-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
scripts.js
executable file
·591 lines (530 loc) · 15.5 KB
/
scripts.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
#!/usr/bin/env node
"use strict";
process.on("uncaughtException", (err) => {
// Format any uncaught exceptions
console.error("\n" + (err ? err.stack || err : "Uncaught exception") + "\n");
process.exit(1);
});
process.on("unhandledRejection", (err) => {
throw err;
});
require("source-map-support").install();
const path = require("path");
const fs = require("fs-extra");
const yargs = require("yargs");
const chalk = require("chalk");
const spawn = require("cross-spawn");
const readline = require("readline");
const {
logger,
initializeLogger,
Packager,
Update,
State,
Telemetry,
getCdkVersion,
getAwsCredentials,
} = require("@serverless-stack/core");
const packageJson = require("../package.json");
const paths = require("../scripts/util/paths");
const cdkOptions = require("../scripts/util/cdkOptions");
const { prepareCdk } = require("../scripts/util/cdkHelpers");
const sstVersion = packageJson.version;
const cdkVersion = getCdkVersion();
const args = process.argv.slice(2);
const script = args[0];
const scriptArgs = args.slice(1);
const cmd = {
s: "sst",
cdk: "cdk",
diff: "diff",
test: "test",
start: "start",
build: "build",
console: "console",
deploy: "deploy",
remove: "remove",
addCdk: "add-cdk",
update: "update",
telemetry: "telemetry",
};
const internals = {
[cmd.diff]: require("../scripts/diff"),
[cmd.start]: require("../scripts/start"),
[cmd.build]: require("../scripts/build"),
[cmd.deploy]: require("../scripts/deploy"),
[cmd.remove]: require("../scripts/remove"),
[cmd.addCdk]: require("../scripts/add-cdk"),
[cmd.console]: require("../scripts/console"),
};
const DEFAULT_STAGE = "dev";
const DEFAULT_NAME = "my-app";
const DEFAULT_REGION = undefined;
const DEFAULT_LINT = true;
const DEFAULT_TYPE_CHECK = true;
const DEFAULT_ESBUILD_CONFIG = undefined;
function getCliInfo() {
const usingYarn = Packager.getManager(paths.appPath).type === "yarn";
return {
cdkVersion,
yarn: usingYarn,
npm: !usingYarn,
// Options that'll be passed into CDK
cdkOptions: {
...cdkOptions,
rollback: argv.rollback,
roleArn: argv.roleArn,
verbose: argv.verbose ? 2 : 0,
noColor: process.env.NO_COLOR === "true",
},
};
}
function addOptions(currentCmd) {
return function (yargs) {
yargs
.option("stage", {
type: "string",
describe: "The stage you want to deploy to",
})
.option("region", {
type: "string",
describe: "The region you want to deploy to",
})
.option("role-arn", {
type: "string",
describe: "ARN of Role to use when invoking CloudFormation",
})
.option("profile", {
type: "string",
describe: "Use a specific profile from your credential file.",
});
if (currentCmd === cmd.deploy || currentCmd === cmd.remove) {
yargs.positional("stack", {
type: "string",
describe: "Specify a stack, if you have multiple stacks",
});
}
if (currentCmd === cmd.deploy || currentCmd === cmd.start) {
yargs.option("outputs-file", {
type: "string",
describe: "Path to file where the stack outputs will be written",
});
}
if (currentCmd === cmd.deploy) {
yargs.option("rollback", {
type: "boolean",
describe: "Rollback stack to stable state on failure",
default: true,
});
}
if (currentCmd === cmd.start) {
yargs
.option("increase-timeout", {
type: "boolean",
describe:
"Increase the Function timeouts to allow testing with breakpoints",
default: false,
})
.option("console", {
type: "boolean",
describe: "Launch local console on start",
default: false,
})
.option("udp", {
type: "boolean",
describe: "Enable udp communication with AWS Lambda",
default: false,
})
.option("rollback", {
type: "boolean",
describe: "Rollback stack to stable state on failure",
default: true,
});
}
};
}
async function applyConfig(argv) {
const configPath = path.join(paths.appPath, "sst.json");
if (!fs.existsSync(configPath)) {
exitWithMessage(
`\nAdd the ${chalk.bold(
"sst.json"
)} config file in your project root to get started. Or use the ${chalk.bold(
"create-serverless-stack"
)} CLI to create a new project.\n`
);
}
let config;
try {
config = fs.readJsonSync(configPath);
} catch (e) {
exitWithMessage(
`\nThere was a problem reading the ${chalk.bold(
"sst.json"
)} config file. Make sure it is in valid JSON format.\n`
);
}
if (!config.name || config.name.trim() === "") {
exitWithMessage(
`\nGive your Serverless Stack app a ${chalk.bold(
"name"
)} in the ${chalk.bold("sst.json")}.\n\n "name": "my-sst-app"\n`
);
}
State.init(paths.appPath);
config.name = config.name || DEFAULT_NAME;
config.stage = await getStage(argv, config);
config.lint = config.lint === false ? false : DEFAULT_LINT;
config.region = argv.region || config.region || DEFAULT_REGION;
config.typeCheck = config.typeCheck === false ? false : DEFAULT_TYPE_CHECK;
config.main = config.main || getDefaultMainPath();
config.esbuildConfig = config.esbuildConfig || DEFAULT_ESBUILD_CONFIG;
return config;
}
async function loadAwsCredentials(script, argv) {
if (process.env.__TEST__ === "true") return;
if (
![
cmd.diff,
cmd.build,
cmd.deploy,
cmd.remove,
cmd.start,
cmd.console,
cmd.cdk,
].includes(script)
) {
return;
}
// Manually get credentials from credential chain and set as "AWS_"
// environment variables. This is so that when calling the AWS CDK CLI,
// the credentials from the environment variables will be used. So if
// MFA is configured for the AWS profile, SST will prompt for MFA, and
// CDK CLI won't prompt again.
const credentials = await getAwsCredentials({ profile: argv.profile });
process.env.AWS_ACCESS_KEY_ID = credentials.accessKeyId;
process.env.AWS_SECRET_ACCESS_KEY = credentials.secretAccessKey;
if (credentials.sessionToken) {
process.env.AWS_SESSION_TOKEN = credentials.sessionToken;
}
}
async function getStage(argv, config) {
if (argv.stage) return argv.stage;
if (config.stage) {
console.warn(
chalk.yellow(
'Warning: Setting the stage in the "sst.json" will be deprecated soon. Read more about this change here: https://docs.serverless-stack.com/live-lambda-development#deprecating-the-stage-option-in-the-sstjson'
)
);
return config.stage;
}
const fromState = State.getStage(paths.appPath);
if (fromState) return fromState;
if (process.env.__TEST__ === "true") return DEFAULT_STAGE;
if (argv._[0] === "test") return DEFAULT_STAGE;
const suggested = await State.suggestStage();
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
return new Promise((resolve) => {
rl.question(
`Look like you’re running sst for the first time in this directory. Please enter a stage name you’d like to use locally. Or hit enter to use the one based on your AWS credentials (${suggested}): `,
(input) => {
const final = input.trim() || suggested;
State.setStage(paths.appPath, final);
rl.close();
resolve(final);
}
);
});
}
function getDefaultMainPath() {
let mainPath = path.join("lib", "index.ts");
if (!fs.existsSync(path.join(paths.appPath, mainPath))) {
mainPath = path.join("lib", "index.js");
}
return mainPath;
}
/**
* If `npm run` is used to execute these commands, you need to add `--` before
* the options. If it's not used, the command will run but the options will not be
* set correctly. The region or the stage might get set as the stack. This
* function simply checks if the stack is set to a common stage name or a region.
* And shows a warning.
*/
function checkNpmScriptArgs() {
const commonStageAndRegions = [
"qa",
"dev",
"prod",
"stage",
"staging",
"preprod",
"production",
"development",
"eu-west-1",
"eu-west-2",
"sa-east-1",
"us-east-1",
"us-east-2",
"us-west-1",
"us-west-2",
"ap-south-1",
"ca-central-1",
"eu-central-1",
"ap-northeast-2",
"ap-southeast-1",
"ap-southeast-2",
"ap-northeast-1",
];
if (commonStageAndRegions.indexOf(argv.stack) !== -1) {
logger.warn(
chalk.yellow(
`\nWarning: It looks like you might be setting the stack option to "${argv.stack}" by mistake. If you are using "npm run", make sure to add "--" before the options. For example, "npm run deploy -- --stage prod".\n`
)
);
}
}
function exitWithMessage(message) {
// Move newline before message
if (message.indexOf("\n") === 0) {
logger.info("");
}
logger.error(message.trimStart());
process.exit(1);
}
const argv = yargs
.parserConfiguration({ "boolean-negation": false })
.usage(`${cmd.s} <command>`)
.demandCommand(1)
.option("no-color", {
default: false,
type: "boolean",
desc: "Remove colors and other style from console output",
})
.option("verbose", {
default: false,
type: "boolean",
desc: "Show more debug info in the output",
})
.command(cmd.start, "Work on your SST app locally", addOptions(cmd.start))
.command(
`${cmd.diff} [stacks..]`,
"Compares all the stacks in your app with the deployed stacks"
)
.command(
`${cmd.deploy} [stack]`,
"Deploy all your stacks to AWS",
addOptions(cmd.deploy)
)
.command(
`${cmd.remove} [stack]`,
"Remove all your stacks and all of their resources from AWS",
addOptions(cmd.remove)
)
.command(
cmd.build,
"Build your app and synthesize your stacks",
addOptions(cmd.build)
)
.command(cmd.test, "Run your tests", (yargs) =>
yargs.option("stage", {
type: "string",
describe: "The stage you want to test against",
})
)
.command(cmd.cdk, "Access the AWS CDK CLI")
.command(
`${cmd.update} [vsn]`,
"Update SST and CDK packages to a different version",
(yargs) => {
return yargs.positional("vsn", {
type: "string",
description: "Specific version of SST to upgrade to",
default: "latest",
});
}
)
.command(
`${cmd.addCdk} [packages..]`,
"Installs the given CDK package(s) in your app",
{
dev: {
default: false,
type: "boolean",
desc: "Install as a dev dependency",
},
"dry-run": {
default: false,
type: "boolean",
desc: "Do not install, but show the install command",
},
}
)
.command(
`${cmd.telemetry} [enable/disable]`,
"Control SST's telemetry collection",
(yargs) => {
return yargs.positional("enable/disable", {
type: "string",
choices: ["enable", "disable"],
description:
"Specific 'enable' or 'disable' to turn SST's telemetry collection on or off",
});
}
)
.command(`console`, "Start up SST console", (yargs) => {
return yargs.option("stage", {
type: "string",
describe: "The stage you want the console to talk to",
});
})
.example([
[`$0 ${cmd.start}`, "Start using the defaults"],
[`$0 ${cmd.remove} my-s3-stack`, "Remove a specific stack"],
[
`$0 ${cmd.deploy} --stage prod --region us-west-1`,
"Deploy to a stage and region",
],
])
.version(
true,
"Show the version of SST and CDK",
`SST: ${sstVersion}\nCDK: ${cdkVersion}`
)
.alias("version", "v")
.help("help")
.alias("help", "h")
.epilogue("For more information, visit www.serverless-stack.com")
.wrap(yargs.terminalWidth())
.fail((msg, err) => {
if (err) throw err;
console.log(chalk.red(msg) + "\n");
yargs.showHelp();
process.exit(1);
})
.parse();
// Disable color
if (!process.stdout.isTTY || argv.noColor) {
process.env.NO_COLOR = "true";
chalk.level = 0;
}
// Set debug flag
if (argv.verbose) {
process.env.DEBUG = "true";
}
// Cleanup build dir
fs.emptyDirSync(paths.appBuildPath);
// Initialize logger after .build diretory is created, in which the debug log will be written
initializeLogger(paths.appBuildPath);
logger.debug("SST:", sstVersion);
logger.debug("CDK:", cdkVersion);
async function run() {
// Parse cli input and load config
const cliInfo = getCliInfo();
// Do not load config for update
if (script === cmd.update) {
try {
Update.run({
rootDir: process.cwd(),
verbose: argv.verbose,
version: argv.vsn,
});
} catch (e) {
logger.debug(e);
exitWithMessage(e.message);
}
return;
} else if (script === cmd.telemetry) {
if (argv["enable/disable"] === "enable") {
Telemetry.enable();
} else if (argv["enable/disable"] === "disable") {
Telemetry.disable();
}
if (Telemetry.isEnabled()) {
logger.info("\nStatus:", chalk.bold(chalk.green("Enabled")), "\n");
logger.info(
"SST telemetry is completely anonymous. Thank you for participating!\n"
);
} else {
logger.info("\nStatus:", chalk.bold(chalk.red("Disabled")), "\n");
logger.info("You have opted out of SST's anonymous telemetry program.");
logger.info("No data will be collected from your machine.\n");
}
return;
}
const config = await applyConfig(argv);
await loadAwsCredentials(script, argv);
// Track
Telemetry.trackCli(script);
switch (script) {
case cmd.diff:
case cmd.build:
case cmd.deploy:
case cmd.remove: {
logger.info("Using stage:", config.stage);
if (cliInfo.npm) {
checkNpmScriptArgs();
}
// Prepare app
prepareCdk(argv, cliInfo, config)
.then(() => internals[script](argv, config, cliInfo))
.catch((e) => exitWithMessage(e.message));
break;
}
case cmd.start:
case cmd.addCdk: {
if (script === cmd.start) logger.info("Using stage:", config.stage);
internals[script](argv, config, cliInfo).catch((e) => {
logger.debug(e);
exitWithMessage(e.message);
});
break;
}
case cmd.console: {
internals[script](argv, config, cliInfo).catch((e) => {
logger.debug(e);
exitWithMessage(e.message);
});
break;
}
case cmd.cdk:
case cmd.test: {
// Prepare app
prepareCdk(argv, cliInfo, config)
.then(() => {
const result = spawn.sync(
"node",
[require.resolve("../scripts/" + script)].concat(scriptArgs),
{ stdio: "inherit" }
);
if (result.signal) {
if (result.signal === "SIGKILL") {
exitWithMessage(
"The command failed because the process exited too early. " +
"This probably means the system ran out of memory or someone called " +
"`kill -9` on the process."
);
} else if (result.signal === "SIGTERM") {
exitWithMessage(
"The command failed because the process exited too early. " +
"Someone might have called `kill` or `killall`, or the system could " +
"be shutting down."
);
}
exitWithMessage(
"The command failed because the process exited too early."
);
}
process.exit(result.status);
})
.catch((e) => exitWithMessage(e.message));
break;
}
default:
console.log('Unknown script "' + script + '".');
break;
}
}
run();