forked from multiplegeorges/vue-cli-plugin-s3-deploy
-
Notifications
You must be signed in to change notification settings - Fork 4
/
deployer.js
291 lines (240 loc) · 11.5 KB
/
deployer.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
"use strict";
Object.defineProperty(exports, "__esModule", {
value: true
});
exports.default = void 0;
var _path = _interopRequireDefault(require("path"));
var _globby = _interopRequireDefault(require("globby"));
var _fs = _interopRequireDefault(require("fs"));
var _cliSharedUtils = require("@vue/cli-shared-utils");
var _awsSdk = _interopRequireDefault(require("aws-sdk"));
var _es6PromisePool = _interopRequireDefault(require("es6-promise-pool"));
var _bucket = _interopRequireDefault(require("./bucket"));
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
function asyncGeneratorStep(gen, resolve, reject, _next, _throw, key, arg) { try { var info = gen[key](arg); var value = info.value; } catch (error) { reject(error); return; } if (info.done) { resolve(value); } else { Promise.resolve(value).then(_next, _throw); } }
function _asyncToGenerator(fn) { return function () { var self = this, args = arguments; return new Promise(function (resolve, reject) { var gen = fn.apply(self, args); function _next(value) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "next", value); } function _throw(err) { asyncGeneratorStep(gen, resolve, reject, _next, _throw, "throw", err); } _next(undefined); }); }; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } }
function _createClass(Constructor, protoProps, staticProps) { if (protoProps) _defineProperties(Constructor.prototype, protoProps); if (staticProps) _defineProperties(Constructor, staticProps); return Constructor; }
var Deployer =
/*#__PURE__*/
function () {
function Deployer(config) {
_classCallCheck(this, Deployer);
if (!config) throw new TypeError('Configuration is required.');
config.awsConfig = {
region: config.options.region,
httpOptions: {
connectTimeout: 30 * 1000,
timeout: 120 * 1000
}
};
if (config.options.overrideEndpoint) {
config.awsConfig.endpoint = config.options.endpoint;
} // path.sep appends a trailing / or \ depending on platform.
config.fullAssetPath = _path.default.join(process.cwd(), config.options.assetPath) + _path.default.sep;
config.deployPath = this.deployPath(config.options.deployPath);
config.fileList = _globby.default.sync(config.options.assetMatch, {
cwd: config.fullAssetPath
}).map(function (file) {
return _path.default.join(config.fullAssetPath, file);
});
config.remotePath = config.options.staticHosting ? "https://s3-".concat(config.options.region, ".amazonaws.com/").concat(config.options.bucket, "/") : "https://".concat(config.options.bucket, ".s3-website-").concat(config.options.region, ".amazonaws.com/");
this.config = config;
}
_createClass(Deployer, [{
key: "openConnection",
value: function () {
var _openConnection = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee() {
var credentials;
return regeneratorRuntime.wrap(function _callee$(_context) {
while (1) {
switch (_context.prev = _context.next) {
case 0:
if (this.config.options.awsProfile !== 'default') {
credentials = new _awsSdk.default.SharedIniFileCredentials({
profile: this.config.options.awsProfile
});
this.config.awsConfig.credentials = credentials;
}
_awsSdk.default.config.update(this.config.awsConfig);
this.connection = new _awsSdk.default.S3();
(0, _cliSharedUtils.info)('Connection to S3 created.');
case 4:
case "end":
return _context.stop();
}
}
}, _callee, this);
}));
function openConnection() {
return _openConnection.apply(this, arguments);
}
return openConnection;
}()
}, {
key: "run",
value: function () {
var _run = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee2() {
var uploadPool;
return regeneratorRuntime.wrap(function _callee2$(_context2) {
while (1) {
switch (_context2.prev = _context2.next) {
case 0:
this.bucket = new _bucket.default(this.config.options.bucket, {
fullAssetPath: this.config.fullAssetPath,
deployPath: this.config.deployPath,
createBucket: this.config.options.createBucket,
acl: this.config.options.acl,
staticErrorPage: this.config.options.staticErrorPage,
staticIndexPage: this.config.options.staticIndexPage,
staticWebsiteConfiguration: this.config.options.staticWebsiteConfiguration
}, this.connection);
_context2.prev = 1;
_context2.next = 4;
return this.bucket.validate();
case 4:
_context2.next = 13;
break;
case 6:
_context2.prev = 6;
_context2.t0 = _context2["catch"](1);
_context2.next = 10;
return this.bucket.createBucket();
case 10:
if (!this.options.staticHosting) {
_context2.next = 13;
break;
}
_context2.next = 13;
return bucket.enableHosting();
case 13:
(0, _cliSharedUtils.info)("Deploying ".concat(this.config.fileList.length, " assets from ").concat(this.config.fullAssetPath, " to ").concat(this.config.remotePath));
this.uploadCount = 0;
this.uploadTotal = this.config.fileList.length;
uploadPool = new _es6PromisePool.default(this.uploadNextFile.bind(this), parseInt(this.config.options.uploadConcurrency, 10));
_context2.prev = 17;
_context2.next = 20;
return uploadPool.start();
case 20:
(0, _cliSharedUtils.info)('Deployment complete.');
if (this.config.options.enableCloudfront) {
this.invalidateDistribution();
}
_context2.next = 28;
break;
case 24:
_context2.prev = 24;
_context2.t1 = _context2["catch"](17);
(0, _cliSharedUtils.error)("Deployment encountered errors.");
throw new Error("Upload error: ".concat(_context2.t1.toString()));
case 28:
case "end":
return _context2.stop();
}
}
}, _callee2, this, [[1, 6], [17, 24]]);
}));
function run() {
return _run.apply(this, arguments);
}
return run;
}()
}, {
key: "uploadNextFile",
value: function uploadNextFile() {
var _this = this;
if (this.config.fileList.length === 0) {
return null;
}
var filename = this.config.fileList.pop();
var fileStream = _fs.default.readFileSync(filename);
var fileKey = filename.replace(this.config.fullAssetPath, '').replace(/\\/g, '/');
var fullFileKey = "".concat(this.config.deployPath).concat(fileKey);
var pwaSupportForFile = this.config.options.pwa && this.config.options.pwaFiles.split(',').indexOf(fileKey) > -1;
try {
return this.bucket.uploadFile(fullFileKey, fileStream, {
pwa: pwaSupportForFile
}).then(function () {
_this.uploadCount++;
var pwaMessage = pwaSupportForFile ? ' with cache disabled for PWA' : '';
(0, _cliSharedUtils.info)("(".concat(_this.uploadCount, "/").concat(_this.uploadTotal, ") Uploaded ").concat(fullFileKey).concat(pwaMessage));
});
} catch (uploadError) {
throw new Error("(".concat(this.uploadCount, "/").concat(this.uploadTotal, ") Upload failed: ").concat(fullFileKey, ". AWS Error: ").concat(uploadError.toString(), "."));
}
}
}, {
key: "deployPath",
value: function deployPath(path) {
var fixedPath; // We don't need a leading slash for root deploys on S3.
if (path.startsWith('/')) fixedPath = path.slice(1, path.length); // But we do need to make sure there's a trailing one on the path.
if (!path.endsWith('/') && path.length > 0) fixedPath = path + '/';
return fixedPath;
}
}, {
key: "invalidateDistribution",
value: function () {
var _invalidateDistribution = _asyncToGenerator(
/*#__PURE__*/
regeneratorRuntime.mark(function _callee3() {
var cloudfront, invalidationItems, params, data;
return regeneratorRuntime.wrap(function _callee3$(_context3) {
while (1) {
switch (_context3.prev = _context3.next) {
case 0:
cloudfront = new _awsSdk.default.CloudFront();
invalidationItems = this.config.options.cloudfrontMatchers.split(',');
params = {
DistributionId: this.config.options.cloudfrontId,
InvalidationBatch: {
CallerReference: "vue-cli-plugin-s3-deploy-".concat(Date.now().toString()),
Paths: {
Quantity: invalidationItems.length,
Items: invalidationItems
}
}
};
_context3.prev = 3;
(0, _cliSharedUtils.logWithSpinner)("Invalidating CloudFront distribution: ".concat(this.config.options.cloudfrontId));
_context3.next = 7;
return cloudfront.createInvalidation(params).promise();
case 7:
data = _context3.sent;
(0, _cliSharedUtils.info)("Invalidation ID: ".concat(data['Invalidation']['Id']));
(0, _cliSharedUtils.info)("Status: ".concat(data['Invalidation']['Status']));
(0, _cliSharedUtils.info)("Call Reference: ".concat(data['Invalidation']['InvalidationBatch']['CallerReference']));
(0, _cliSharedUtils.info)("See your AWS console for on-going status on this invalidation.");
(0, _cliSharedUtils.stopSpinner)();
_context3.next = 23;
break;
case 15:
_context3.prev = 15;
_context3.t0 = _context3["catch"](3);
(0, _cliSharedUtils.stopSpinner)(false);
(0, _cliSharedUtils.error)('Cloudfront Error!!');
(0, _cliSharedUtils.error)("Code: ".concat(_context3.t0.code));
(0, _cliSharedUtils.error)("Message: ".concat(_context3.t0.message));
(0, _cliSharedUtils.error)("AWS Request ID: ".concat(_context3.t0.requestId));
throw new Error('Cloudfront invalidation failed!');
case 23:
case "end":
return _context3.stop();
}
}
}, _callee3, this, [[3, 15]]);
}));
function invalidateDistribution() {
return _invalidateDistribution.apply(this, arguments);
}
return invalidateDistribution;
}()
}]);
return Deployer;
}();
var _default = Deployer;
exports.default = _default;