forked from anomalyco/sst
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathstart.js
More file actions
1110 lines (972 loc) · 31 KB
/
Copy pathstart.js
File metadata and controls
1110 lines (972 loc) · 31 KB
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
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
"use strict";
const path = require("path");
const fs = require("fs-extra");
const chalk = require("chalk");
const WebSocket = require("ws");
const esbuild = require("esbuild");
const chokidar = require("chokidar");
const spawn = require("cross-spawn");
const allSettled = require("promise.allsettled");
const { logger } = require("@serverless-stack/core");
const sstDeploy = require("./deploy");
const sstBuild = require("./build");
const paths = require("./util/paths");
const {
getBinPath,
prepareCdk,
applyConfig,
deploy: cdkDeploy,
bootstrap: cdkBootstrap,
} = require("./util/cdkHelpers");
const array = require("../lib/array");
// Setup logger
const clientLogger = logger.child({ label: "client" });
const builderLogger = logger.child({ label: "builder" });
// Create Promise.allSettled shim
allSettled.shim();
const chokidarOptions = {
persistent: true,
ignoreInitial: true,
followSymlinks: false,
disableGlobbing: false,
awaitWriteFinish: {
pollInterval: 100,
stabilityThreshold: 20,
},
};
const WEBSOCKET_CLOSE_CODE = {
NEW_CLIENT_CONNECTED: 4901,
};
let watcher;
let esbuildService;
const builderState = {
isRebuilding: false,
entryPointsData: {}, // KEY: $srcPath/$entry/$handler
srcPathsData: {}, // KEY: $srcPath
watchedFilesIndex: {}, // KEY: /path/to/lambda.js VALUE: [ entryPoint ]
watchedCdkFilesIndex: {}, // KEY: /path/to//MyStack.js VALUE: true
};
const entryPointDataTemplateObject = {
srcPath: null,
handler: null,
tsconfig: null,
hasError: false,
esbuilder: null,
inputFiles: null,
outEntryPoint: null,
transpilePromise: null,
needsReTranspile: false,
pendingRequestCallbacks: [],
};
const srcPathDataTemplateObject = {
srcPath: null,
tsconfig: null,
inputFiles: null,
lintProcess: null,
needsReCheck: false,
typeCheckProcess: null,
};
const clientState = {
ws: null,
wsKeepAliveTimer: null,
};
const MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS = 0;
const IS_TEST = process.env.__TEST__ === "true";
module.exports = async function (argv, cliInfo) {
const config = await applyConfig(argv);
// Deploy debug stack
config.debugEndpoint = await deployDebugStack(argv, cliInfo, config);
// Deploy app
const cdkInputFiles = await deployApp(argv, cliInfo, config);
// Start builder
await startBuilder(cdkInputFiles);
// Start client
startClient(config.debugEndpoint);
};
async function deployDebugStack(argv, cliInfo, config) {
// Do not deploy if running test
if (IS_TEST) {
return "ws://test-endpoint";
}
const stackName = `${config.stage}-${config.name}-debug-stack`;
logger.info("");
logger.info("=======================");
logger.info(" Deploying debug stack");
logger.info("=======================");
logger.info("");
const debugAppArgs = [stackName, config.stage, config.region];
// Note: When deploying the debug stack, the current working directory is user's app.
// Setting the current working directory to debug stack cdk app directory to allow
// Lambda Function construct be able to reference code with relative path.
process.chdir(path.join(paths.ownPath, "assets", "debug-stack"));
let debugStackRet;
try {
const cdkOptions = {
...cliInfo.cdkOptions,
app: `node bin/index.js ${debugAppArgs.join(" ")}`,
output: "cdk.out",
};
await cdkBootstrap(cdkOptions);
debugStackRet = await cdkDeploy(cdkOptions);
} catch (e) {
logger.error(e);
}
// Note: Restore working directory
process.chdir(paths.appPath);
// Get WebSocket endpoint
if (
!debugStackRet ||
!debugStackRet.outputs ||
!debugStackRet.outputs.Endpoint
) {
throw new Error(
`Failed to get the endpoint from the deployed debug stack ${stackName}`
);
}
return debugStackRet.outputs.Endpoint;
}
async function deployApp(argv, cliInfo, config) {
logger.info("");
logger.info("===============");
logger.info(" Deploying app");
logger.info("===============");
logger.info("");
const { inputFiles } = await prepareCdk(argv, cliInfo, config);
// When testing, we will do a build call to generate the lambda-handler.json
if (IS_TEST) {
await sstBuild(argv, config, cliInfo);
} else {
const stacks = await sstDeploy(argv, config, cliInfo);
// Check all stacks deployed successfully
if (stacks.some((stack) => stack.status === "failed")) {
throw new Error(`Failed to deploy the app`);
}
}
return inputFiles;
}
///////////////////////
// Builder functions //
///////////////////////
async function startBuilder(cdkInputFiles) {
builderLogger.info("");
builderLogger.info("===================");
builderLogger.info(" Starting debugger");
builderLogger.info("===================");
builderLogger.info("");
// Load Lambda handlers to watch
// ie. { srcPath: "src/api", handler: "api.main" },
const lambdaHandlersPath = path.join(
paths.appPath,
paths.appBuildDir,
"lambda-handlers.json"
);
const entryPoints = await fs.readJson(lambdaHandlersPath);
if (!(await checkFileExists(lambdaHandlersPath))) {
throw new Error(`Failed to get the Lambda handlers info from the app`);
}
// Initialize state
initializeBuilderState(entryPoints, cdkInputFiles);
// Run transpiler
builderLogger.info(chalk.grey("Transpiling Lambda code..."));
esbuildService = await esbuild.startService();
const results = await Promise.allSettled(
entryPoints.map(({ srcPath, handler }) =>
// Not catching esbuild errors
// Letting it handle the error messages for now
transpile(srcPath, handler)
)
);
const hasError = results.some((result) => result.status === "rejected");
if (hasError) {
stopBuilder();
throw new Error("Error transpiling");
}
// Running inside test => stop builder
if (IS_TEST) {
const testOutputPath = path.join(
paths.appPath,
paths.appBuildDir,
"test-output.json"
);
fs.writeFileSync(testOutputPath, JSON.stringify(builderState));
stopBuilder();
return;
}
// Validate transpiled
const srcPaths = getAllSrcPaths();
if (srcPaths.length === 0) {
builderLogger.info("Nothing has been transpiled");
return;
}
srcPaths.forEach((srcPath) => {
const lintProcess = lint(srcPath);
const typeCheckProcess = typeCheck(srcPath);
onLintAndTypeCheckStarted({ srcPath, lintProcess, typeCheckProcess });
});
// Run watcher
const allInputFiles = getAllWatchedFiles();
watcher = chokidar
.watch(allInputFiles, chokidarOptions)
.on("all", onFileChange)
.on("error", (error) => builderLogger.info(`Watch ${error}`))
.on("ready", () => {
builderLogger.debug(`Watcher ready for ${allInputFiles.length} files...`);
});
}
function stopBuilder() {
// Stop esbuild rebuild processes
Object.keys(builderState.entryPointsData).forEach((key) => {
if (builderState.entryPointsData[key].esbuilder !== null) {
builderState.entryPointsData[key].esbuilder.rebuild.dispose();
}
});
// Stop esbuild service
if (esbuildService) {
esbuildService.stop();
}
}
async function updateBuilder() {
builderLogger.silly(serializeState());
const { entryPointsData, srcPathsData } = builderState;
// Run transpiler
Object.keys(entryPointsData).forEach((key) => {
let {
srcPath,
handler,
transpilePromise,
needsReTranspile,
} = entryPointsData[key];
if (!transpilePromise && needsReTranspile) {
const transpilePromise = reTranspiler(srcPath, handler);
onReTranspileStarted({ srcPath, handler, transpilePromise });
}
});
// Check all entrypoints transpiled, if not => wait
const isTranspiling = Object.keys(entryPointsData).some(
(key) => entryPointsData[key].transpilePromise
);
if (isTranspiling) {
return;
}
// Check all entrypoints successfully transpiled, if not => do not run lint and checker
const hasError = Object.keys(entryPointsData).some(
(key) => entryPointsData[key].hasError
);
if (hasError) {
return;
}
// Run linter and type checker
Object.keys(srcPathsData).forEach((srcPath) => {
let { lintProcess, typeCheckProcess, needsReCheck } = srcPathsData[srcPath];
if (needsReCheck) {
// stop existing linter & type checker
lintProcess && lintProcess.kill();
typeCheckProcess && typeCheckProcess.kill();
// start new linter & type checker
lintProcess = lint(srcPath);
typeCheckProcess = typeCheck(srcPath);
onLintAndTypeCheckStarted({ srcPath, lintProcess, typeCheckProcess });
}
});
}
async function onFileChange(ev, file) {
builderLogger.debug(`File change: ${file}`);
// Handle CDK code changed
if (builderState.watchedCdkFilesIndex[file]) {
builderLogger.info(
"Detected a change in your CDK constructs. Restart the debugger to deploy the changes."
);
return;
}
// Get entrypoints changed
const entryPointKeys = builderState.watchedFilesIndex[file];
if (!entryPointKeys) {
builderLogger.debug("File is not linked to the entry points");
return;
}
// Mark changed entrypoints
entryPointKeys.map((key) => {
builderState.entryPointsData[key].needsReTranspile = true;
});
await updateBuilder();
}
function onTranspileSucceeded(
srcPath,
handler,
{ tsconfig, esbuilder, outEntryPoint, inputFiles }
) {
const key = buildEntryPointKey(srcPath, handler);
// Update entryPointsData
builderState.entryPointsData[key] = {
...builderState.entryPointsData[key],
tsconfig,
esbuilder,
inputFiles,
outEntryPoint,
};
// Update srcPath index
builderState.srcPathsData[srcPath] = {
...srcPathDataTemplateObject,
srcPath,
tsconfig,
inputFiles,
};
// Update inputFiles
inputFiles.forEach((file) => {
builderState.watchedFilesIndex[file] =
builderState.watchedFilesIndex[file] || [];
builderState.watchedFilesIndex[file].push(key);
});
}
function onReTranspileStarted({ srcPath, handler, transpilePromise }) {
const key = buildEntryPointKey(srcPath, handler);
// Print rebuilding message
if (!builderState.isRebuilding) {
builderState.isRebuilding = true;
builderLogger.info("Rebuilding...");
}
// Update entryPointsData
builderState.entryPointsData[key] = {
...builderState.entryPointsData[key],
needsReTranspile: false,
transpilePromise,
};
}
async function onReTranspileSucceeded(srcPath, handler, { inputFiles }) {
const key = buildEntryPointKey(srcPath, handler);
// Note: If the handler included new files, while re-transpiling, the new files
// might have been updated. And because the new files has not been added to
// the watcher yet, onFileChange() wouldn't get called. We need to re-transpile
// again.
const oldInputFiles = builderState.entryPointsData[key].inputFiles;
const inputFilesDiff = diffInputFiles(oldInputFiles, inputFiles);
const hasNewInputFiles = inputFilesDiff.add.length > 0;
// Update entryPointsData
builderState.entryPointsData[key] = {
...builderState.entryPointsData[key],
inputFiles,
hasError: false,
transpilePromise: null,
needsReTranspile:
builderState.entryPointsData[key].needsReTranspile || hasNewInputFiles,
};
// Update srcPathsData
const srcPathInputFiles = Object.keys(builderState.entryPointsData)
.filter((key) => builderState.entryPointsData[key].srcPath === srcPath)
.map((key) => builderState.entryPointsData[key].inputFiles)
.flat();
builderState.srcPathsData[srcPath] = {
...builderState.srcPathsData[srcPath],
inputFiles: array.unique(srcPathInputFiles),
needsReCheck: true,
};
// Update watched files index
inputFilesDiff.add.forEach((file) => {
builderState.watchedFilesIndex[file] =
builderState.watchedFilesIndex[file] || [];
builderState.watchedFilesIndex[file].push(key);
});
inputFilesDiff.remove.forEach((file) => {
const index = builderState.watchedFilesIndex[file].indexOf(key);
if (index > -1) {
builderState.watchedFilesIndex[file].splice(index, 1);
}
if (builderState.watchedFilesIndex[file] === 0) {
delete builderState.watchedFilesIndex[file];
}
});
// Update watcher
if (inputFilesDiff.add.length > 0) {
watcher.add(inputFilesDiff.add);
}
if (inputFilesDiff.remove.length > 0) {
await watcher.unwatch(inputFilesDiff.remove);
}
// Fullfil pending requests
if (!builderState.entryPointsData[key].needsReTranspile) {
builderState.entryPointsData[key].pendingRequestCallbacks.forEach(
({ resolve }) => {
resolve();
}
);
}
await updateBuilder();
}
async function onReTranspileFailed(srcPath, handler) {
const key = buildEntryPointKey(srcPath, handler);
// Update entryPointsData
builderState.entryPointsData[key] = {
...builderState.entryPointsData[key],
hasError: true,
transpilePromise: null,
};
// Fullfil pending requests
if (!builderState.entryPointsData[key].needsReTranspile) {
builderState.entryPointsData[key].pendingRequestCallbacks.forEach(
({ reject }) => {
reject(`Failed to transpile srcPath ${srcPath} handler ${handler}`);
}
);
}
await updateBuilder();
}
function onLintAndTypeCheckStarted({ srcPath, lintProcess, typeCheckProcess }) {
// Update srcPath index
builderState.srcPathsData[srcPath] = {
...builderState.srcPathsData[srcPath],
lintProcess,
typeCheckProcess,
needsReCheck: false,
};
}
async function onLintDone(srcPath) {
builderState.srcPathsData[srcPath] = {
...builderState.srcPathsData[srcPath],
lintProcess: null,
};
// Print rebuilding message
const isChecking = Object.keys(builderState.srcPathsData).some(
(key) =>
builderState.srcPathsData[key].lintProcess ||
builderState.srcPathsData[key].typeCheckProcess
);
if (!isChecking && builderState.isRebuilding) {
builderState.isRebuilding = false;
builderLogger.info("Done building");
}
await updateBuilder();
}
async function onTypeCheckDone(srcPath) {
builderState.srcPathsData[srcPath] = {
...builderState.srcPathsData[srcPath],
typeCheckProcess: null,
};
// Print rebuilding message
const isChecking = Object.keys(builderState.srcPathsData).some(
(key) =>
builderState.srcPathsData[key].lintProcess ||
builderState.srcPathsData[key].typeCheckProcess
);
if (!isChecking && builderState.isRebuilding) {
builderState.isRebuilding = false;
builderLogger.info("Done building");
}
await updateBuilder();
}
async function transpile(srcPath, handler) {
const metafile = getEsbuildMetafilePath(srcPath, handler);
const outSrcPath = path.join(srcPath, paths.appBuildDir);
const fullPath = await getHandlerFilePath(srcPath, handler);
const tsconfigPath = path.join(paths.appPath, srcPath, "tsconfig.json");
const isTs = await checkFileExists(tsconfigPath);
const tsconfig = isTs ? tsconfigPath : undefined;
const external = await getAllExternalsForHandler(srcPath);
const esbuildOptions = {
external,
metafile,
tsconfig,
bundle: true,
format: "cjs",
sourcemap: true,
platform: "node",
incremental: true,
entryPoints: [fullPath],
color: process.env.NO_COLOR !== "true",
outdir: path.join(paths.appPath, outSrcPath),
};
builderLogger.debug(`Transpiling ${handler}...`);
const esbuilder = await esbuildService.build(esbuildOptions);
const handlerParts = path.basename(handler).split(".");
const outHandler = handlerParts.pop();
const outEntry = `${handlerParts.join(".")}.js`;
return onTranspileSucceeded(srcPath, handler, {
tsconfig,
esbuilder,
outEntryPoint: {
entry: outEntry,
handler: outHandler,
srcPath: outSrcPath,
},
inputFiles: await getInputFilesFromEsbuildMetafile(metafile),
});
}
async function reTranspiler(srcPath, handler) {
try {
const key = buildEntryPointKey(srcPath, handler);
const { esbuilder } = builderState.entryPointsData[key];
await esbuilder.rebuild();
// Mock esbuild taking long to rebuild
if (MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS) {
builderLogger.debug(
`Mock rebuild wait (${MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS}ms)...`
);
await sleep(MOCK_SLOW_ESBUILD_RETRANSPILE_IN_MS);
builderLogger.debug(`Mock rebuild wait done`);
}
const metafile = getEsbuildMetafilePath(srcPath, handler);
const inputFiles = await getInputFilesFromEsbuildMetafile(metafile);
await onReTranspileSucceeded(srcPath, handler, { inputFiles });
} catch (e) {
builderLogger.error("reTranspiler error", e);
await onReTranspileFailed(srcPath, handler);
}
}
function lint(srcPath) {
let { inputFiles } = builderState.srcPathsData[srcPath];
inputFiles = inputFiles.filter(
(file) =>
file.indexOf("node_modules") === -1 &&
(file.endsWith(".ts") || file.endsWith(".js"))
);
const cp = spawn(
getBinPath("eslint"),
[
"--no-error-on-unmatched-pattern",
process.env.NO_COLOR === "true" ? "--no-color" : "--color",
"--config",
path.join(paths.appBuildPath, ".eslintrc.internal.js"),
path.join(paths.ownPath, "scripts", "util", ".eslintrc.internal.js"),
"--fix",
// Handling nested ESLint projects in Yarn Workspaces
// https://github.com/serverless-stack/serverless-stack/issues/11
"--resolve-plugins-relative-to",
".",
...inputFiles,
],
{ stdio: "inherit", cwd: path.join(paths.appPath, srcPath) }
);
cp.on("close", (code) => {
builderLogger.debug(`linter exited with code ${code}`);
onLintDone(srcPath);
});
return cp;
}
function typeCheck(srcPath) {
const { inputFiles } = builderState.srcPathsData[srcPath];
const tsFiles = inputFiles.filter((file) => file.endsWith(".ts"));
if (tsFiles.length === 0) {
return null;
}
const cp = spawn(
getBinPath("typescript", "tsc"),
[
"--noEmit",
"--pretty",
process.env.NO_COLOR === "true" ? "false" : "true",
],
{
stdio: "inherit",
cwd: path.join(paths.appPath, srcPath),
}
);
cp.on("close", (code) => {
builderLogger.debug(`type checker exited with code ${code}`);
onTypeCheckDone(srcPath);
});
return cp;
}
/////////////////////////////
// Builder State functions //
/////////////////////////////
function initializeBuilderState(entryPoints, cdkInputFiles) {
// Initialize 'entryPointsData' state
entryPoints.forEach(({ srcPath, handler }) => {
const key = buildEntryPointKey(srcPath, handler);
builderState.entryPointsData[key] = {
...entryPointDataTemplateObject,
srcPath,
handler,
};
});
// Initialize 'watchedCdkFilesIndex' state
cdkInputFiles.forEach((file) => {
builderState.watchedCdkFilesIndex[file] = true;
});
}
function buildEntryPointKey(srcPath, handler) {
return `${srcPath}/${handler}`;
}
function getAllWatchedFiles() {
return [
...Object.keys(builderState.watchedFilesIndex),
...Object.keys(builderState.watchedCdkFilesIndex),
];
}
function getAllSrcPaths() {
return Object.keys(builderState.srcPathsData);
}
function serializeState() {
const {
isRebuilding,
entryPointsData,
srcPathsData,
watchedFilesIndex,
} = builderState;
return JSON.stringify(
{
isRebuilding,
entryPointsData: Object.keys(entryPointsData).reduce(
(acc, key) => ({
...acc,
[key]: {
hasError: entryPointsData[key].hasError,
inputFiles: entryPointsData[key].inputFiles,
transpilePromise:
entryPointsData[key].transpilePromise && "<Promise>",
needsReTranspile: entryPointsData[key].needsReTranspile,
},
//[key]: { ...entryPointsData[key],
// transpilePromise: entryPointsData[key].transpilePromise && '<Promise>'
//},
}),
{}
),
srcPathsData: Object.keys(srcPathsData).reduce(
(acc, key) => ({
...acc,
[key]: {
inputFiles: srcPathsData[key].inputFiles,
lintProcess: srcPathsData[key].lintProcess && "<ChildProcess>",
typeCheckProcess:
srcPathsData[key].typeCheckProcess && "<ChildProcess>",
needsReCheck: srcPathsData[key].needsReCheck,
},
//[key]: { ...srcPathsData[key],
// lintProcess: srcPathsData[key].lintProcess && '<ChildProcess>',
// typeCheckProcess: srcPathsData[key].typeCheckProcess && '<ChildProcess>',
//},
}),
{}
),
watchedFilesIndex,
},
null,
2
);
}
////////////////////////////
// Builder Util functions //
////////////////////////////
async function checkFileExists(file) {
return fs.promises
.access(file, fs.constants.F_OK)
.then(() => true)
.catch(() => false);
}
async function getHandlerFilePath(srcPath, handler) {
const parts = handler.split(".");
const name = parts[0];
const tsFile = path.join(paths.appPath, srcPath, `${name}.ts`);
if (await checkFileExists(tsFile)) {
return tsFile;
}
return path.join(paths.appPath, srcPath, `${name}.js`);
}
async function getAllExternalsForHandler(srcPath) {
let externals;
try {
const packageJson = await fs.readJson(path.join(srcPath, "package.json"));
externals = Object.keys({
...(packageJson.dependencies || {}),
...(packageJson.devDependencies || {}),
...(packageJson.peerDependencies || {}),
});
} catch (e) {
builderLogger.warn(`No package.json found in ${srcPath}`);
externals = [];
}
return externals;
}
async function getTranspiledHandler(srcPath, handler) {
const key = buildEntryPointKey(srcPath, handler);
const entryPointData = builderState.entryPointsData[key];
if (entryPointData.transpilePromise || entryPointData.needsReTranspile) {
builderLogger.debug(`Waiting for re-transpiler output for ${handler}...`);
await new Promise((resolve, reject) =>
entryPointData.pendingRequestCallbacks.push({ resolve, reject })
);
builderLogger.debug(`Waited for re-transpiler output for ${handler}`);
}
return entryPointData.outEntryPoint;
}
function getEsbuildMetafilePath(srcPath, handler) {
const key = `${srcPath}/${handler}`.replace(/[/.]/g, "-");
const outSrcFullPath = path.join(paths.appPath, srcPath, paths.appBuildDir);
return path.join(outSrcFullPath, `.esbuild.${key}.json`);
}
async function getInputFilesFromEsbuildMetafile(file) {
let metaJson;
try {
metaJson = await fs.readJson(file);
} catch (e) {
builderLogger.error("There was a problem reading the build metafile", e);
}
return Object.keys(metaJson.inputs).map((input) => path.resolve(input));
}
function diffInputFiles(oldList, newList) {
const remove = [];
const add = [];
oldList.forEach((item) => newList.indexOf(item) === -1 && remove.push(item));
newList.forEach((item) => oldList.indexOf(item) === -1 && add.push(item));
return { add, remove };
}
function sleep(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
///////////////////////////////
// Websocke Client functions //
///////////////////////////////
function startClient(debugEndpoint) {
// Do not deploy if running test
if (IS_TEST) {
return;
}
clientState.ws = new WebSocket(debugEndpoint);
clientState.ws.on("open", () => {
clientLogger.debug("WebSocket connection opened");
clientState.ws.send(JSON.stringify({ action: "client.register" }));
startKeepAliveMonitor();
});
clientState.ws.on("close", (code, reason) => {
clientLogger.debug("Websocket connection closed", { code, reason });
// Case: disconnected due to new client connected => do not reconnect
if (code === WEBSOCKET_CLOSE_CODE.NEW_CLIENT_CONNECTED) {
return;
}
// Case: disconnected due to 10min idle or 2hr WebSocket connection limit => reconnect
clientLogger.debug("Reconnecting to websocket server...");
startClient(debugEndpoint);
});
clientState.ws.on("error", (e) => {
clientLogger.error("WebSocket connection error", e);
});
clientState.ws.on("message", onClientMessage);
}
function startKeepAliveMonitor() {
// Cancel existing keep-alive timer
if (clientState.wsKeepAliveTimer) {
clientLogger.debug("Clearing existing keep-alive timer...");
clearTimeout(clientState.wsKeepAliveTimer);
}
// Create keep-alive timer
clientLogger.debug("Creating keep-alive timer...");
clientState.ws.send(JSON.stringify({ action: "client.heartbeat" }));
clientState.wsKeepAliveTimer = setInterval(() => {
if (clientState.ws) {
clientLogger.debug("Sending keep-alive call");
clientState.ws.send(JSON.stringify({ action: "client.keepAlive" }));
}
}, 60000);
}
async function onClientMessage(message) {
clientLogger.debug(`Websocket message received: ${message}`);
const data = JSON.parse(message);
// Handle actions
if (data.action === "server.clientRegistered") {
clientLogger.info("Debug session started. Listening for requests...");
clientLogger.debug(`Client connection id: ${data.clientConnectionId}`);
return;
}
if (data.action === "server.clientDisconnectedDueToNewClient") {
clientLogger.warn(
"A new debug session has been started. This session will be closed..."
);
clientState.ws.close(WEBSOCKET_CLOSE_CODE.NEW_CLIENT_CONNECTED);
return;
}
if (data.action === "server.failedToSendResponseDueToStubDisconnected") {
// TODO help user find out why the stub function was disconnected. Maybe pull up
// CloudWatch logs for websocket server and the stub.
clientLogger.error(
chalk.grey(data.debugRequestId) +
" Failed to send response because the Lambda function is disconnected"
);
return;
}
if (data.action === "server.failedToSendResponseDueToUnknown") {
// TODO help user find out why the stub function was disconnected. Maybe pull up
// CloudWatch logs for websocket server and the stub.
clientLogger.error(
chalk.grey(data.debugRequestId) +
" Failed to send response to the Lambda function"
);
return;
}
if (data.action !== "stub.lambdaRequest") {
clientLogger.debug("Unkonwn websocket message received.");
return;
}
const {
stubConnectionId,
event,
context,
env,
debugRequestId,
debugRequestTimeoutInMs,
debugSrcPath,
debugSrcHandler,
} = data;
// Print request info
const eventSource = parseEventSource(event);
const eventSourceDesc =
eventSource === null
? " invoked"
: ` invoked by ${chalk.cyan(eventSource)}`;
clientLogger.info(
chalk.grey(
`${context.awsRequestId} REQUEST ${chalk.cyan(
env.AWS_LAMBDA_FUNCTION_NAME
)} [${debugSrcPath}/${debugSrcHandler}]${eventSourceDesc}`
)
);
clientLogger.debug(chalk.grey(JSON.stringify(event)));
// From Lambda /var/runtime/bootstrap
// https://link.medium.com/7ir11kKjwbb
const newSpace = Math.floor(context.memoryLimitInMB / 10);
const semiSpace = Math.floor(newSpace / 2);
const oldSpace = context.memoryLimitInMB - newSpace;
let transpiledHandler;
try {
transpiledHandler = await getTranspiledHandler(
debugSrcPath,
debugSrcHandler
);
} catch (e) {
clientLogger.error("Get transspiler handler error", e);
// TODO: Handle esbuild transpilation error
return;
}
let lambdaResponse;
const lambda = spawn(
"node",
[
`--max-old-space-size=${oldSpace}`,
`--max-semi-space-size=${semiSpace}`,
"--max-http-header-size=81920", // HTTP header limit of 8KB
path.join(paths.ownPath, "assets", "lambda-invoke", "bootstrap.js"),
JSON.stringify(event),
JSON.stringify(context),
//"./src/index.js", // Local path to the Lambda functions
`${transpiledHandler.srcPath}/${transpiledHandler.entry}`,
//"handler", // Function name of the handler function
transpiledHandler.handler,
],
{
stdio: ["inherit", "inherit", "inherit", "ipc"],
cwd: paths.appPath,
env: { ...process.env, ...env },
}
);
const timer = setLambdaTimeoutTimer(
lambda,
handleResponse,
debugRequestTimeoutInMs
);
function parseEventSource(event) {
try {
// HTTP
if (
["2.0", "1.0"].includes(event.version) &&
event.requestContext.apiId
) {