-
Notifications
You must be signed in to change notification settings - Fork 359
/
build.mjs
639 lines (559 loc) · 17.4 KB
/
build.mjs
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
import * as esbuild from "esbuild";
import fs from "fs/promises";
import { createRequire } from "module";
import path from "path";
const require = createRequire(import.meta.url);
process.env.NODE_PATH = ".";
const TMP_DIR = `.tmp-llrt-aws-sdk`;
const SRC_DIR = path.join("llrt_core", "src", "modules", "js");
const TESTS_DIR = "tests";
const OUT_DIR = "bundle/js";
const SHIMS = new Map();
const SDK_BUNDLE_MODE = process.env.SDK_BUNDLE_MODE || "NONE"; // "FULL" or "STD" or "NONE"
async function readFilesRecursive(dir, filePredicate) {
const dirents = await fs.readdir(dir, { withFileTypes: true });
const files = await Promise.all(
dirents.map((dirent) => {
const filePath = path.join(dir, dirent.name);
if (dirent.isDirectory()) {
return readFilesRecursive(filePath, filePredicate);
} else {
return filePredicate(filePath) ? filePath : [];
}
})
);
return Array.prototype.concat(...files);
}
const TEST_FILES = await readFilesRecursive(
TESTS_DIR,
(filePath) => filePath.endsWith(".test.ts") || filePath.endsWith(".spec.ts")
);
const AWS_JSON_SHARED_COMMAND_REGEX =
/{\s*const\s*headers\s*=\s*sharedHeaders\(("\w+")\);\s*let body;\s*body\s*=\s*JSON.stringify\(_json\(input\)\);\s*return buildHttpRpcRequest\(context,\s*headers,\s*"\/",\s*undefined,\s*body\);\s*}/gm;
const AWS_JSON_SHARED_COMMAND_REGEX2 =
/{\s*const\s*headers\s*=\s*sharedHeaders\(("\w+")\);\s*let body;\s*body\s*=\s*JSON.stringify\((\w+)\(input,\s*context\)\);\s*return buildHttpRpcRequest\(context,\s*headers,\s*"\/",\s*undefined,\s*body\);\s*}/gm;
const MINIFY_JS = process.env.JS_MINIFY !== "0";
const SDK_UTILS_PACKAGE = "sdk-utils";
const ENTRYPOINTS = ["stream", "@llrt/test/index", "@llrt/test/worker"];
const ES_BUILD_OPTIONS = {
splitting: MINIFY_JS,
minify: MINIFY_JS,
sourcemap: true,
target: "es2023",
outdir: OUT_DIR,
bundle: true,
logLevel: "info",
platform: "browser",
format: "esm",
external: [
"assert",
"console",
"node:console",
"crypto",
"os",
"fs",
"child_process",
"process",
"timers",
"stream",
"path",
"events",
"buffer",
"net",
"util",
"url",
"zlib",
"llrt:hex",
"llrt:uuid",
"llrt:xml",
"perf_hooks",
],
};
const SDK_DATA = await parseSdkData();
const ADDITIONAL_PACKAGES = [
"@aws-sdk/core",
"@aws-sdk/credential-providers",
"@aws-sdk/s3-presigned-post",
"@aws-sdk/s3-request-presigner",
"@aws-sdk/util-dynamodb",
"@aws-sdk/util-user-agent-browser",
"@smithy/config-resolver",
"@smithy/core",
"@smithy/eventstream-codec",
"@smithy/eventstream-serde-browser",
"@smithy/eventstream-serde-config-resolver",
"@smithy/eventstream-serde-universal",
"@smithy/fetch-http-handler",
"@smithy/invalid-dependency",
"@smithy/is-array-buffer",
"@smithy/middleware-compression",
"@smithy/middleware-content-length",
"@smithy/middleware-endpoint",
"@smithy/middleware-retry",
"@smithy/middleware-serde",
"@smithy/middleware-stack",
"@smithy/property-provider",
"@smithy/protocol-http",
"@smithy/querystring-builder",
"@smithy/querystring-parser",
"@smithy/service-error-classification",
"@smithy/signature-v4",
"@smithy/smithy-client",
"@smithy/types",
"@smithy/url-parser",
"@smithy/util-base64",
"@smithy/util-body-length-browser",
"@smithy/util-config-provider",
"@smithy/util-defaults-mode-browser",
"@smithy/util-endpoints",
"@smithy/util-hex-encoding",
"@smithy/util-middleware",
"@smithy/util-retry",
"@smithy/util-stream",
"@smithy/util-uri-escape",
"@smithy/util-utf8",
"@smithy/util-waiter",
];
const REPLACEMENT_PACKAGES = {
"@aws-crypto/sha1-browser": "shims/@aws-crypto/sha1-browser.js",
"@aws-crypto/sha256-browser": "shims/@aws-crypto/sha256-browser.js",
"@aws-crypto/crc32": "shims/@aws-crypto/crc32.js",
"@aws-crypto/crc32c": "shims/@aws-crypto/crc32c.js",
"@smithy/abort-controller": "shims/@smithy/abort-controller.js",
};
const SERVICE_ENDPOINTS_BY_PACKAGE = {};
const CLIENTS_BY_SDK = {};
const SDKS_BY_SDK_PACKAGES = {};
const SDK_PACKAGES = [...ADDITIONAL_PACKAGES];
Object.keys(SDK_DATA).forEach((sdk) => {
const [clientName, serviceEndpoints, fullSdkOnly] = SDK_DATA[sdk] || [];
if (SDK_BUNDLE_MODE == "FULL" || (SDK_BUNDLE_MODE == "STD" && !fullSdkOnly)) {
const sdkPackage = `@aws-sdk/${sdk}`;
SDK_PACKAGES.push(sdkPackage);
SDKS_BY_SDK_PACKAGES[sdkPackage] = sdk;
SERVICE_ENDPOINTS_BY_PACKAGE[sdk] = serviceEndpoints;
CLIENTS_BY_SDK[sdk] = clientName;
}
});
async function parseSdkData() {
const cfgData = await fs.readFile("sdk.cfg");
const cfgLines = cfgData.toString().split("\n");
const sdkData = {};
for (let line of cfgLines) {
line = line.trim();
if (line.startsWith("#") || line == "") {
continue;
}
// Parse the line
const parts = line.split(",");
//get and remove the item at 0
const packageName = parts.shift();
const clientName = parts.shift();
//get and remove the last item
const fullSdkOnly = parts.pop() == 1;
const endpoints = parts;
// Log or store parsed information
sdkData[packageName] = [clientName, endpoints, fullSdkOnly];
}
return sdkData;
}
function resolveDefaultsModeConfigWrapper(config) {
if (!config.credentials) {
config.credentials = {
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
sessionToken: process.env.AWS_SESSION_TOKEN,
};
}
if (!config.region) {
config.region = process.env.AWS_REGION;
}
return resolveDefaultsModeConfig(config);
}
const awsJsonSharedCommand = (name, input, context, request) => {
const headers = sharedHeaders(name);
const body = JSON.stringify(request ? request(input, context) : _json(input));
return buildHttpRpcRequest(context, headers, "/", undefined, body);
};
function defaultEndpointResolver(endpointParams, context = {}) {
const paramsKey = calculateEndpointCacheKey(endpointParams);
let endpoint = ENDPOINT_CACHE[paramsKey];
if (!endpoint) {
endpoint = resolveEndpoint(ruleSet, {
endpointParams,
logger: context.logger,
serviceName,
});
ENDPOINT_CACHE[paramsKey] = endpoint;
}
if (serviceName === "s3") {
const { hostname, protocol, pathname, search } = endpoint.url;
const [bucket, host] = hostname.split(".s3.");
if (host) {
const newHref = `${protocol}//s3.${host}/${bucket}${pathname}${
search ? `?${search}` : ""
}`;
endpoint.url.href = newHref;
}
}
return endpoint;
}
const WRAPPERS = [
{
name: "resolveDefaultsModeConfig",
filter: /resolveDefaultsModeConfig.js$/,
wrapper: resolveDefaultsModeConfigWrapper,
},
];
function executeClientCommand(command, optionsOrCb, cb) {
if (typeof optionsOrCb === "function") {
this.send(command, optionsOrCb);
} else if (typeof cb === "function") {
if (typeof optionsOrCb !== "object")
throw new Error(`Expect http options but get ${typeof optionsOrCb}`);
this.send(command, optionsOrCb || {}, cb);
} else {
return this.send(command, optionsOrCb);
}
}
const ENDPOINT_CACHE_KEY_LOOKUP = {
Bucket: "b",
ForcePathStyle: "f",
UseArnRegion: "n",
DisableMultiRegionAccessPoints: "m",
Accelerate: "a",
UseGlobalEndpoint: "g",
UseFIPS: "i",
Endpoint: "e",
Region: "r",
UseDualStack: "d",
};
const ENDPOINT_CACHE_KEY_LOOKUP_NAME = Object.keys({
ENDPOINT_CACHE_KEY_LOOKUP,
})[0];
function calculateEndpointCacheKey(obj) {
let str = "";
for (const key in obj) {
if (obj[key] === true) {
str += ENDPOINT_CACHE_KEY_LOOKUP[key];
} else if (typeof obj[key] === "string") {
str += obj[key];
}
}
return str;
}
function codeToRegex(fn, includeSignature = false) {
return new RegExp(
fn
.toString()
.split("\n")
.reduce((acc, line, index, array) => {
if (includeSignature || (index > 0 && index < array.length - 1)) {
acc.push(line.trim());
}
return acc;
}, [])
.join("\n")
.replace(/\s+/g, "\\s*")
.replace(/\(/g, "\\(")
.replace(/\)/g, "\\)")
.replace(/\./g, "\\.")
.replace(/\?,/g, "\\?")
.replace(/\,/g, ",?")
.replace(/\$/g, "\\$")
.replace(/\{/g, "\\s*{")
.replace(/\}/g, "}\\s*")
.replace(/\|/g, "\\|"),
"g"
);
}
const AWS_SDK_PLUGIN = {
name: "aws-sdk-plugin",
setup(build) {
const tslib = require.resolve("tslib/tslib.es6.js");
const executeClientCommandRegex = codeToRegex(executeClientCommand);
build.onResolve({ filter: /^tslib$/ }, () => {
return { path: tslib };
});
//load replace shims
for (const [filter, contents] of SHIMS) {
build.onLoad({ filter }, () => ({
contents,
}));
}
for (const sdk in CLIENTS_BY_SDK) {
const clientClass = CLIENTS_BY_SDK[sdk];
build.onLoad(
{ filter: new RegExp(`@aws-sdk\\/${sdk}\\/dist-es/${clientClass}.js`) },
async ({ path: filePath }) => {
const source = (await fs.readFile(filePath)).toString();
const name = path.parse(filePath).name;
console.log("Optimized:", name);
let contents = `import { ${executeClientCommand.name} } from "${SDK_UTILS_PACKAGE}"\n`;
contents += source.replace(
executeClientCommandRegex,
`return ${executeClientCommand.name}.call(this, command, optionsOrCb, cb)`
);
return {
contents,
};
}
);
}
build.onLoad(
{ filter: /protocols\/Aws_json1_1\.js$/ },
async ({ path: filePath }) => {
const name = path.parse(filePath).name;
let source = (await fs.readFile(filePath)).toString();
const sourceLength = source.length;
source = source.replace(
AWS_JSON_SHARED_COMMAND_REGEX,
(_, name) => `${awsJsonSharedCommand.name}(${name}, input, context)`
);
source = source.replace(
AWS_JSON_SHARED_COMMAND_REGEX2,
(_, name, request) =>
`${awsJsonSharedCommand.name}(${name}, input, context, ${request})`
);
if (sourceLength === source.length) {
throw new Error(`Failed to optimize: ${name}`);
}
console.log("Optimized:", name);
source = `const ${
awsJsonSharedCommand.name
} = ${awsJsonSharedCommand.toString()}\n\n${source}`;
return {
contents: source,
};
}
);
build.onResolve({ filter: /^sdk-utils$/ }, (args) => ({
path: args.path,
namespace: "sdk-utils-ns",
}));
build.onLoad({ filter: /.*/, namespace: "sdk-utils-ns" }, (args) => {
let contents = "";
contents += `import { Command as $Command } from "@smithy/smithy-client";\n`;
contents += `import { getEndpointPlugin } from "@smithy/middleware-endpoint";\n`;
contents += `import { getSerdePlugin } from "@smithy/middleware-serde";\n`;
contents += `import { SMITHY_CONTEXT_KEY } from "@smithy/types";\n`;
contents += `export ${executeClientCommand.toString()}\n`;
contents += `const ${ENDPOINT_CACHE_KEY_LOOKUP_NAME} = ${JSON.stringify(
ENDPOINT_CACHE_KEY_LOOKUP
)};\n`;
contents += `export const cloneModel = (obj) => ({...obj})\n`;
contents += `export ${calculateEndpointCacheKey.toString()}\n`;
return {
contents,
resolveDir: path.dirname(args.path),
};
});
build.onLoad(
{ filter: /endpoint\/endpointResolver\.js$/ },
async ({ path: filePath }) => {
let source = (await fs.readFile(filePath)).toString();
source = source.replace(
/export const defaultEndpointResolver =.*?};/s,
""
);
let contents = `import { ${calculateEndpointCacheKey.name} } from "${SDK_UTILS_PACKAGE}"\n`;
contents += source;
const serviceName = path
.resolve(filePath, "../../../")
.split("/")
.pop()
.substring("client-".length);
contents += `const serviceName = "${serviceName}";\n`;
contents += `const ENDPOINT_CACHE = {};\n`;
contents += `export ${defaultEndpointResolver.toString()}`;
return {
contents,
};
}
);
for (const { filter, wrapper, name } of WRAPPERS) {
build.onLoad({ filter }, async ({ path }) => {
let source = (await fs.readFile(path)).toString();
let replaced = false;
let contents = "";
source = source.replace(
RegExp(`export\\s*(const\\s*${name})`),
(_, replacement) => {
replaced = true;
return replacement;
}
);
if (!replaced) {
contents += source;
} else {
const wrapperName = `${name}Wrapper`;
contents += `${source}\n`;
contents += `const ${wrapperName} = ${wrapper.toString()}\n`;
contents += `export {${wrapperName} as ${name}}`;
}
return {
contents,
};
});
}
build.onLoad({ filter: /package\.json$/ }, async ({ path }) => {
let packageJson = JSON.parse(await fs.readFile(path));
let { version } = packageJson;
const data = {
version,
};
return {
contents: `export default ${JSON.stringify(data)}`,
};
});
},
};
function esbuildShimPlugin(shims) {
return {
name: "esbuild-shim",
setup(build) {
shims.forEach(([filter, value], index) => {
build.onResolve(
{
filter,
},
(args) => ({
path: args.path,
namespace: `esbuild-shim-${index}-ns`,
})
);
build.onLoad(
{ filter: /.*/, namespace: `esbuild-shim-${index}-ns` },
() => {
const contents = value || "export default {}";
return {
contents,
};
}
);
});
},
};
}
const requireProcessPlugin = {
name: "require-process",
setup(build) {
build.onResolve({ filter: /^process\/$/ }, () => {
return { path: "process", external: true };
});
},
};
async function rmTmpDir() {
await fs.rm(TMP_DIR, {
recursive: true,
force: true,
});
}
async function createOutputDirectories() {
await fs.rm(OUT_DIR, { recursive: true, force: true });
await fs.mkdir(OUT_DIR, { recursive: true });
await rmTmpDir();
await fs.mkdir(TMP_DIR, { recursive: true });
}
async function loadShims() {
const loadShim = async (filter, filename) => {
const bytes = await fs.readFile(path.join("shims", filename));
SHIMS.set(filter, bytes.toString());
};
await Promise.all([
loadShim(/@aws-crypto/, "@aws-crypto/index.js"),
loadShim(/@smithy\/util-hex-encoding/, "@smithy/util-hex-encoding.js"),
loadShim(/@smithy\/util-utf8/, "@smithy/util-utf8.js"),
loadShim(/@smithy\/util-base64/, "@smithy/util-base64.js"),
loadShim(/mnemonist\/lru-cache\.js/, "mnemonist/lru-cache.js"),
loadShim(/collect-stream-body\.js/, "collect-stream-body.js"),
loadShim(/sdk-stream-mixin.browser\.js/, "sdk-stream-mixin.js"),
loadShim(/stream-collector\.js/, "stream-collector.js"),
loadShim(/splitStream.browser\.js/, "@smithy/split-stream.js"),
]);
}
async function buildLibrary() {
const defaultLibEsBuildOption = {
chunkNames: "llrt-[name]-runtime-[hash]",
...ES_BUILD_OPTIONS,
splitting: false,
keepNames: true,
nodePaths: ["."],
};
// Build lib
const entryPoints = {};
ENTRYPOINTS.forEach((entry) => {
entryPoints[entry] = path.join(SRC_DIR, entry);
});
await esbuild.build({
...defaultLibEsBuildOption,
entryPoints,
plugins: [requireProcessPlugin],
});
// Build tests
const testEntryPoints = TEST_FILES.reduce((acc, entry) => {
const { name, dir } = path.parse(entry);
const parentDir = path.basename(dir);
acc[path.join("__tests__", parentDir, name)] = entry;
return acc;
}, {});
await esbuild.build({
...defaultLibEsBuildOption,
entryPoints: testEntryPoints,
external: [...ES_BUILD_OPTIONS.external, "@aws-sdk", "@smithy"],
});
}
async function buildSdks() {
const sdkEntryList = await Promise.all(
SDK_PACKAGES.map(async (pkg) => {
const packagePath = path.join(TMP_DIR, pkg);
const sdk = SDKS_BY_SDK_PACKAGES[pkg];
const sdkIndexFile = path.join(packagePath, "index.js");
await fs.mkdir(packagePath, { recursive: true });
let sdkContents = `export * from "${pkg}";`;
await fs.writeFile(sdkIndexFile, sdkContents);
return [pkg, sdkIndexFile];
})
);
const sdkEntryPoints = Object.fromEntries(sdkEntryList);
await Promise.all([
esbuild.build({
entryPoints: sdkEntryPoints,
plugins: [AWS_SDK_PLUGIN, esbuildShimPlugin([[/^bowser$/]])],
alias: {
"@aws-sdk/util-utf8-browser": "@smithy/util-utf8",
"@aws-sdk/util-utf8": "@smithy/util-utf8",
"@smithy/md5-js": "crypto",
"fast-xml-parser": "llrt:xml",
uuid: "llrt:uuid",
},
chunkNames: "llrt-[name]-sdk-[hash]",
metafile: true,
...ES_BUILD_OPTIONS,
}),
esbuild.build({
entryPoints: REPLACEMENT_PACKAGES,
...ES_BUILD_OPTIONS,
sourcemap: false,
}),
]);
//console.log(await esbuild.analyzeMetafile(result.metafile));
}
console.log("Building...");
await createOutputDirectories();
let error;
try {
if (SDK_BUNDLE_MODE != "NONE") {
await loadShims();
}
await buildLibrary();
if (SDK_BUNDLE_MODE != "NONE") {
await buildSdks();
}
} catch (e) {
error = e;
}
await rmTmpDir();
if (error) {
throw error;
}