forked from multiplegeorges/vue-cli-plugin-s3-deploy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy paths3deploy.js
242 lines (198 loc) · 7.13 KB
/
s3deploy.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
const { info, error, logWithSpinner, stopSpinner } = require('@vue/cli-shared-utils')
const path = require('path')
const fs = require('fs')
const mime = require('mime-types')
const globby = require('globby')
const AWS = require('aws-sdk')
const PromisePool = require('es6-promise-pool')
const S3 = new AWS.S3()
function contentTypeFor (filename) {
return mime.lookup(filename) || 'application/octet-stream'
}
async function createBucket (options) {
let createParams = {
Bucket: options.bucket,
ACL: options.acl
}
// Create bucket
try {
await S3.createBucket(createParams).promise()
} catch (createErr) {
error(`Bucket: ${options.bucket} could not be created. AWS Error: ${createErr.toString()}.`)
return false
}
info(`Bucket: ${options.bucket} created.`)
return true
}
async function enableStaticHosting (options) {
let staticParams = {
Bucket: options.bucket,
WebsiteConfiguration: {
ErrorDocument: {
Key: options.staticErrorPage
},
IndexDocument: {
Suffix: options.staticIndexPage
}
}
}
// use custom WebsiteConfiguration if set
if (options.staticWebsiteConfiguration) {
staticParams.WebsiteConfiguration = options.staticWebsiteConfiguration
}
// enable static hosting
try {
await S3.putBucketWebsite(staticParams).promise()
info(`Static Hosting is enabled.`)
} catch (staticErr) {
error(`Static Hosting could not be enabled on bucket: ${options.bucket}. AWS Error: ${staticErr.toString()}.`)
}
}
async function bucketExists (options) {
let headParams = { Bucket: options.bucket }
let bucketExists = false
try {
bucketExists = await S3.headBucket(headParams).promise()
info(`Bucket: ${options.bucket} exists.`)
} catch (headErr) {
let errStr = headErr.toString().toLowerCase()
if (errStr.indexOf('forbidden') > -1) {
error(`Bucket: ${options.bucket} exists, but you do not have permission to access it.`)
} else if (errStr.indexOf('notfound') > -1) {
if (options.createBucket) {
info(`Bucket: ${options.bucket} does not exist, attempting to create.`)
bucketExists = await createBucket(options)
} else {
error(`Bucket: ${options.bucket} does not exist.`)
}
} else {
error(`Could not verify that bucket ${options.bucket} exists. AWS Error: ${headErr}.`)
}
}
if (bucketExists && options.staticHosting) {
await enableStaticHosting(options)
}
return bucketExists
}
function getAllFiles (pattern, assetPath) {
return globby.sync(pattern, { cwd: assetPath }).map(file => path.join(assetPath, file))
}
async function invalidateDistribution (options) {
const cloudfront = new AWS.CloudFront()
const invalidationItems = options.cloudfrontMatchers.split(',')
let params = {
DistributionId: options.cloudfrontId,
InvalidationBatch: {
CallerReference: `vue-cli-plugin-s3-deploy-${Date.now().toString()}`,
Paths: {
Quantity: invalidationItems.length,
Items: invalidationItems
}
}
}
logWithSpinner(`Invalidating CloudFront distribution: ${options.cloudfrontId}`)
try {
let data = await cloudfront.createInvalidation(params).promise()
info(`Invalidation ID: ${data['Invalidation']['Id']}`)
info(`Status: ${data['Invalidation']['Status']}`)
info(`Call Reference: ${data['Invalidation']['InvalidationBatch']['CallerReference']}`)
info(`See your AWS console for on-going status on this invalidation.`)
} catch (err) {
error('Cloudfront Error!')
error(`Code: ${err.code}`)
error(`Message: ${err.message}`)
error(`AWS Request ID: ${err.requestId}`)
}
stopSpinner()
}
async function uploadFile (filename, fileBody, options) {
let fileKey = filename.replace(options.fullAssetPath, '').replace(/\\/g, '/')
let pwaSupport = options.pwa && options.pwaFiles.split(',').indexOf(fileKey) > -1
let fullFileKey = `${options.deployPath}${fileKey}`
let uploadParams = {
Bucket: options.bucket,
Key: fileKey,
ACL: options.acl,
Body: fileBody,
ContentType: contentTypeFor(fileKey)
}
if (pwaSupport) {
uploadParams.CacheControl = 'no-store, no-cache, must-revalidate, proxy-revalidate, max-age=0'
}
try {
await S3.upload(uploadParams, options.uploadOptions).promise()
} catch (uploadResultErr) {
// pass full error with details back to promisePool callback
throw new Error(`(${options.uploadCount}/${options.uploadTotal}) Upload failed: ${fullFileKey}. AWS Error: ${uploadResultErr.toString()}.`)
}
}
module.exports = async (options, api) => {
info(`Options: ${JSON.stringify(options)}`)
let awsConfig = {
region: options.region,
httpOptions: {
connectTimeout: 30 * 1000,
timeout: 120 * 1000
}
}
if (options.awsProfile.toString() !== 'default') {
let credentials = new AWS.SharedIniFileCredentials({ profile: options.awsProfile })
await credentials.get((err) => {
if (err) {
error(err.toString())
}
awsConfig.credentials = credentials
})
}
AWS.config.update(awsConfig)
if (await bucketExists(options) === false) {
error('Deployment terminated.')
return
}
options.uploadOptions = { partSize: (5 * 1024 * 1024), queueSize: 4 }
let fullAssetPath = path.join(process.cwd(), options.assetPath) + path.sep // path.sep appends a trailing / or \ depending on platform.
let fileList = getAllFiles(options.assetMatch, fullAssetPath)
let deployPath = options.deployPath
// We don't need a leading slash for root deploys on S3.
if (deployPath.startsWith('/')) deployPath = deployPath.slice(1, deployPath.length)
// But we do need to make sure there's a trailing one on the path.
if (!deployPath.endsWith('/') && deployPath.length > 0) deployPath = deployPath + '/'
let uploadCount = 0
let uploadTotal = fileList.length
let remotePath = `https://${options.bucket}.s3-website-${options.region}.amazonaws.com/`
if (options.staticHosting) {
remotePath = `https://s3-${options.region}.amazonaws.com/${options.bucket}/`
}
info(`Deploying ${fileList.length} assets from ${fullAssetPath} to ${remotePath}`)
let nextFile = () => {
if (fileList.length === 0) return null
let filename = fileList.pop()
let fileStream = fs.readFileSync(filename)
let fileKey = filename.replace(fullAssetPath, '').replace(/\\/g, '/')
let fullFileKey = `${deployPath}${fileKey}`
return uploadFile(fullFileKey, fileStream, options)
.then(() => {
uploadCount++
let pwaSupport = options.pwa && options.pwaFiles.split(',').indexOf(fileKey) > -1
let pwaStr = pwaSupport ? ' with cache disabled for PWA' : ''
info(`(${uploadCount}/${uploadTotal}) Uploaded ${fullFileKey}${pwaStr}`)
// resolve()
})
.catch((e) => {
error(`Upload failed: ${fullFileKey}`)
error(e.toString())
// reject(e)
})
}
const uploadPool = new PromisePool(nextFile, parseInt(options.uploadConcurrency, 10))
try {
await uploadPool.start()
info('Deployment complete.')
if (options.enableCloudfront) {
invalidateDistribution(options)
}
} catch (uploadErr) {
error(`Deployment completed with errors.`)
error(`${uploadErr.toString()}`)
}
}