-
Notifications
You must be signed in to change notification settings - Fork 38
/
index.js
619 lines (532 loc) · 16.5 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
var AWS = require('aws-sdk')
var defaults = require('merge-defaults')
var assert = require('assert')
var util = require('util')
var path = require('path')
var url = require('url')
var cloudfront = require('cloudfront-tls')
var diff = require('deep-diff').diff
var assign = require('object-assign')
var fs = require('graceful-fs')
var mime = require('mime')
require('dotenv').config({ silent: true })
var s3diff = require('s3-diff')
var wildcard = require('wildcard')
var logUpdate = require('log-update')
var array = require('lodash/array')
var defaultConfig = {
index: 'index.html',
region: 'us-east-1',
uploadDir: '.',
prefix: '',
exclude: [],
corsConfiguration: [],
enableCloudfront: false,
retries: 20
}
var templateConfig = Object.assign({},
defaultConfig,
{
domain: 'sample.bucket.name',
corsConfiguration: [{
AllowedMethods: [ /* required */
'STRING_VALUE_REQUIRED'
/* more items */
],
AllowedOrigins: [ /* required */
'STRING_VALUE_REQUIRED'
/* more items */
],
AllowedHeaders: [
'STRING_VALUE'
/* more items */
],
ExposeHeaders: [
'STRING_VALUE'
/* more items */
],
MaxAgeSeconds: 0
}]
}
)
var defaultBucketConfig = {
Bucket: '' /* required */
}
var defaultWebsiteConfig = {
Bucket: '', /* required */
WebsiteConfiguration: { /* required */
IndexDocument: {
Suffix: defaultConfig.index /* required */
}
}
}
// Perform an action on an array of items, action will be invoked again after
// the prior item has finished
function sequentially (s3, config, action, files, cb, results = {done: [], errors: []}) {
const index = results.done.length + results.errors.length
action(s3, config, files[index], function (err, data, file) {
if (err) {
results.errors.push(file)
} else {
results.done.push(file)
}
if (index === files.length - 1) {
return cb(err, data, results)
}
sequentially(s3, config, action, files, cb, results)
})
}
function mergeResults (oldResult, newResult) {
var updated = oldResult.updated.concat(newResult.updated)
var uploaded = oldResult.uploaded.concat(newResult.uploaded)
var removed = oldResult.removed.concat(newResult.removed)
var errors = newResult.errors
return {
updated: array.uniq(updated),
uploaded: array.uniq(uploaded),
removed: array.uniq(removed),
errors: errors
}
}
function retry (s3, config, allFiles, currentResults, cb) {
var results = {
updated: [],
uploaded: [],
removed: [],
errors: []
}
var retryFiles = {
missing: [],
changed: [],
extra: currentResults.errors
}
function deletionDone (err, data, file) {
if (err) {
results.errors.push(file)
} else {
results.removed.push(file)
}
checkDone(retryFiles, results, function (err, results) {
cb(err, mergeResults(currentResults, results))
})
}
function uploadDone (err, data, file) {
if (err) {
results.errors.push(file)
} else {
results.uploaded.push(file)
}
checkDone(retryFiles, results, function (err, results) {
cb(err, mergeResults(currentResults, results))
})
}
logUpdate('Retrying failed actions')
currentResults.errors.forEach(function (error) {
if (allFiles.missing.find(function (file) { return file === error })) {
deleteFile(s3, config, error, deletionDone)
} else {
uploadFile(s3, config, error, uploadDone)
}
})
}
function checkDone (allFiles, results, cb) {
var files = [allFiles.missing, allFiles.changed, allFiles.extra]
var finished = [results.uploaded, results.updated, results.removed, results.errors]
var totalFiles = files.reduce(function (prev, current) {
return prev.concat(current)
}, []).length
var fileResults = finished.reduce(function (prev, current) {
return prev.concat(current)
}, []).length
logUpdate('Finished Uploading ' + fileResults + ' of ' + totalFiles)
if (fileResults >= totalFiles && cb) {
if (results.errors.length > 0) { }
if (totalFiles > 0) { logUpdate('Done Uploading') }
cb(null, results)
}
}
function deleteFile (s3, config, file, cb) {
var params = {
Bucket: config.domain,
Key: normalizeKey(config.prefix, file)
}
logUpdate('Removing: ' + file)
s3.deleteObject(params, function (err, data) {
if (err && cb) { return cb(err, data, file) }
if (cb) { cb(err, data, file) }
})
}
function getExtension (file) {
const spl = file.split('.')
return spl.length > 0 && spl[spl.length - 1]
}
function uploadFile (s3, config, file, cb) {
const ext = getExtension(file)
const contentType = config.contentTypes && config.contentTypes[ext]
var params = {
Bucket: config.domain,
Key: normalizeKey(config.prefix, file),
Body: fs.createReadStream(path.join(config.uploadDir, file)),
ContentType: contentType || mime.lookup(file),
CacheControl: (config.cacheControl != null) ? config.cacheControl : null
}
logUpdate('Uploading: ' + file)
s3.putObject(params, function (err, data) {
if (err && cb) { return cb(err, data, file) }
if (cb) { cb(err, data, file) }
})
}
function chunkedAction (s3, config, action, arr, cb) {
var result = {
done: [],
errors: []
}
var numWorkers = 200
var chunkSize = Math.ceil(arr.length / numWorkers)
var chunks = array.chunk(arr, chunkSize)
chunks.forEach(function (chunk) {
new Promise(function (resolve, reject) {
action(s3, config, chunk, function (err, data, results) {
if (err) { console.error(err) }
result.done = result.done.concat(results.done)
result.errors = result.errors.concat(results.errors)
var numFinished = result.done.length + result.errors.length
if (numFinished === arr.length) { cb(err, data, result) }
resolve()
})
}).catch(function (e) { console.error(e) })
})
return result
}
function s3site (config, cb) {
if (typeof cb !== 'function') cb = function () {}
assert(typeof config === 'object')
assert(typeof config.domain === 'string')
config = defaults(config, defaultConfig)
var bucketConfig = defaults(config.bucketConfig || {}, defaultBucketConfig)
var websiteConfig = defaults(config.websiteConfig || {}, defaultWebsiteConfig)
if (config.domain) {
bucketConfig.Bucket = config.domain
websiteConfig.Bucket = config.domain
}
if (config.region && config.region !== 'us-east-1') { // LocationConstraint for default location is invalid
bucketConfig.CreateBucketConfiguration = { LocationConstraint: config.region }
} else {
config.region = defaultConfig.region
}
if (config.redirectall) {
websiteConfig.WebsiteConfiguration = {
RedirectAllRequestsTo: { HostName: config.redirectall }
}
}
if (config.index && !config.redirectall) {
websiteConfig.WebsiteConfiguration.IndexDocument.Suffix = config.index
}
if (config.error && !config.redirectall) {
websiteConfig.WebsiteConfiguration.ErrorDocument = { Key: config.error }
}
if (config.routes && !config.redirectall) {
websiteConfig.WebsiteConfiguration.RoutingRules = loadRoutes(config.routes)
}
var s3 = new AWS.S3({ region: config.region, maxRetries: config.retries })
s3.createBucket(bucketConfig, function (err, bucket) {
if (err && err.code !== 'BucketAlreadyOwnedByYou') return cb(err)
setPolicy(s3, config.domain, function (err) {
if (err) return cb(err)
createWebsite(s3, websiteConfig, config, function (err, website) {
if (err) return cb(err)
if (config.corsConfiguration.length > 0) {
setCorsRules(s3, config.domain, config.corsConfiguration, function (err, data) {
if (err) console.error(err)
})
}
if (config.enableCloudfront || config.cert || config.certId) {
config.aliases = config.aliases || [ config.domain ]
config.origin = url.parse(website.url).host
cloudfront(config, function (err, distribution) {
if (err) return cb(err)
website.url = 'http://' + distribution.url
website.certId = distribution.certId
website.cloudfront = distribution.distribution
if (config.deploy) {
return putWebsiteContent(s3, config, function (err, uploadResults) {
cb(err, website, uploadResults)
})
}
cb(null, website, {})
})
} else {
if (config.deploy) {
return putWebsiteContent(s3, config, function (err, website, uploadResults) {
cb(err, website, uploadResults)
})
}
cb(null, website, {})
}
})
})
})
}
function parseWebsite (website, modified, config) {
var host
// Some region has a slightly differnt URL scheme :(
var dotEndpointRegions = ['us-east-2', 'ca-central-1', 'ap-south-1', 'ap-northeast-2', 'eu-central-1', 'eu-west-2']
var hasDifferentScheme = dotEndpointRegions.find(function (region) {
return region === config.region
})
if (hasDifferentScheme) {
host = [config.domain, 's3-website', config.region, 'amazonaws.com'].join('.')
} else {
host = [config.domain, 's3-website-' + config.region, 'amazonaws.com'].join('.')
}
var siteUrl = url.format({
protocol: 'http',
host: host
})
return {
url: siteUrl,
config: website,
modified: !!modified
}
}
function createWebsite (s3, websiteConfig, config, cb) {
function putWebsite () {
s3.putBucketWebsite(websiteConfig, function (err, website) {
if (err) return cb(err)
s3.getBucketWebsite({ Bucket: config.domain }, function (err, website) {
if (err) return cb(err)
cb(null, parseWebsite(website, true, config))
})
})
}
s3.getBucketWebsite({ Bucket: config.domain }, function (err, website) { // eslint-disable-line handle-callback-err
var dirty = diff(website || {}, websiteConfig.WebsiteConfiguration)
if (dirty) {
putWebsite()
} else {
cb(null, parseWebsite(website, null, config))
}
})
}
function setCorsRules (s3, bucket, rules, cb) {
var s3Params = {
Bucket: bucket,
CORSConfiguration: {
CORSRules: rules
}
}
s3.putBucketCors(s3Params, function (err, data) {
if (cb) { cb(err, data) }
})
}
// sets up a public-read bucket policy
function setPolicy (s3, bucket, cb) {
var publicRead = {
Sid: 'AddPublicReadPermissions',
Effect: 'Allow',
Principal: '*',
Action: 's3:GetObject',
Resource: 'arn:aws:s3:::' + bucket + '/*'
}
s3.getBucketPolicy({ Bucket: bucket }, function (err, data) {
if (err && err.code !== 'NoSuchBucketPolicy') return cb(err)
var newPolicy = { Statement: [] }
var oldPolicy
try {
oldPolicy = JSON.parse(data.Policy)
} catch (err) {}
var found = false
if (oldPolicy) {
newPolicy.Statement = oldPolicy.Statement.map(function (item) {
if (item.Sid === 'AddPublicReadPermissions') {
found = true
return publicRead
}
return item
})
}
if (!found) newPolicy.Statement.push(publicRead)
var dirty = diff(oldPolicy || {}, newPolicy, function (path, key) {
if (key === 'Version') return true
})
if (dirty) {
var policy = assign(oldPolicy || {}, newPolicy)
s3.putBucketPolicy({ Bucket: bucket, Policy: JSON.stringify(policy) }, cb)
} else {
process.nextTick(cb)
}
})
}
function loadRoutes (routesOrFile) {
var routes
if (typeof routesOrFile === 'string') {
routes = require(path.resolve(__dirname, routesOrFile))
} else {
routes = routesOrFile
}
validateRoutes(routes)
return routes
}
function validateRoutes (routes) {
assert(Array.isArray(routes), 'Routes must be an array')
var validProperties = {
Condition: {
HttpErrorCodeReturnedEquals: true,
KeyPrefixEquals: true
},
Redirect: {
HostName: true,
Protocol: true,
ReplaceKeyPrefixWith: true,
ReplaceKeyWith: true,
HttpRedirectCode: true
}
}
routes.forEach(function (route, idx) {
validateProps(route, validProperties)
validateProps(route.Condition, validProperties.Condition)
validateProps(route.Redirect, validProperties.Redirect)
})
}
function validateProps (obj, props, idx) {
var keys = Object.keys(obj)
assert(keys.length > 0, util.format('Invalid route at index %s', idx))
keys.forEach(function (key) {
assert(props[key], util.format('Invalid route property %s at index %s', key, idx))
})
}
function getConfig (path, fromCL, cb) {
fs.readFile(path, function (err, data) {
var fromFile
try {
fromFile = JSON.parse(data) // Read data from file
} catch (e) {
fromFile = {}
}
var dirty = Object.keys(fromCL).some(function (key) { // Test if anything has changed
return fromFile[key] !== fromCL[key]
})
var config = Object.assign(defaultConfig, fromFile, fromCL) // Merge arguments and file parameters
if (!config.domain) {
console.log('No bucket was specified. Check your config file ' + path)
return
}
if (dirty && !config.lockConfig) { // Something has changed rewrite file, and we are allowed to write config file
fs.writeFile(fromCL.configFile, JSON.stringify(config, null, 3), function (err) {
if (err) console.error(err)
console.log('Updated config file: ' + fromCL.configFile)
cb(err, config)
})
} else { // No change, we're done
cb(err, config)
}
})
}
function normalizePath (path) {
return path.replace(/\\/g, '/')
}
function normalizeKey (prefix, key) {
return normalizePath(prefix ? prefix + '/' + key : key)
}
function deleteFiles (s3, config, files, cb, results = {done: [], errors: []}) {
sequentially(s3, config, deleteFile, files, cb)
}
function uploadFiles (s3, config, files, cb, results = {done: [], errors: []}) {
sequentially(s3, config, uploadFile, files, cb)
}
function putWebsiteContent (s3, config, cb) {
if (typeof cb !== 'function') { cb = function () {} }
config = defaults(config, defaultConfig)
s3diff({
aws: {
signatureVersion: 'v4'
},
local: config.uploadDir || '.',
remote: {
bucket: config.domain,
prefix: config.prefix
},
recursive: true
}, function (err, data) {
if (err) return cb(err)
// exclude files from the diff
config.exclude.forEach(function (excludePattern) {
for (var key in data) {
data[key] = data[key].filter(function (path) {
return !wildcard(excludePattern, path)
})
}
})
var results = {
uploaded: [],
updated: [],
removed: [],
errors: []
}
function logResults (err, results) {
if (err) { return cb(err) }
var params = { Bucket: config.domain }
s3.getBucketWebsite(params, function (err, website) {
if (err) { return cb(err) }
cb(err, parseWebsite(website, null, config), results)
})
}
function handleRetry (err, results) {
if (results.errors.length > 0) {
retry(s3, config, data, results, logResults)
return
}
logResults(err, results)
}
// Delete files that exist on s3, but not locally
chunkedAction(
s3,
config,
deleteFiles,
data.missing,
function (err, eTags, result) {
if (err) { console.error(err) }
results.removed = results.removed.concat(result.done)
results.errors = results.errors.concat(result.errors)
checkDone(data, results, handleRetry)
})
// Upload changed files
chunkedAction(
s3,
config,
uploadFiles,
data.changed,
function (err, eTags, result) {
if (err) { console.error(err) }
results.updated = results.updated.concat(result.done)
results.errors = results.errors.concat(result.errors)
checkDone(data, results, handleRetry)
})
// Upload files that exist locally but not on s3
chunkedAction(
s3,
config,
uploadFiles,
data.extra,
function (err, eTags, result) {
if (err) { console.error(err) }
results.uploaded = results.uploaded.concat(result.done)
results.errors = results.errors.concat(result.errors)
checkDone(data, results, handleRetry)
})
checkDone(data, results, handleRetry)
})
}
var utilities = {
retry: retry,
sequentially: sequentially,
chunkedAction: chunkedAction,
checkDone: checkDone
}
module.exports = {
utils: utilities,
s3site: s3site,
deploy: putWebsiteContent,
config: getConfig,
templateConfig: templateConfig
}