slicejs-cli 4.1.1 → 4.2.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/client.js +16 -2
- package/commands/build/build.js +18 -1
- package/commands/buildProduction/buildProduction.js +82 -81
- package/commands/types/types.js +116 -7
- package/commands/utils/JsMinifier.js +230 -0
- package/commands/utils/SourceDiagnostics.js +201 -0
- package/commands/utils/bundling/BundleGenerator.js +622 -59
- package/package.json +1 -1
|
@@ -4,7 +4,8 @@ import path from 'path';
|
|
|
4
4
|
import crypto from 'crypto';
|
|
5
5
|
import { parse } from '@babel/parser';
|
|
6
6
|
import traverse from '@babel/traverse';
|
|
7
|
-
import {
|
|
7
|
+
import { minifyJs, bundleOptions } from '../JsMinifier.js';
|
|
8
|
+
import { describeSyntaxError } from '../SourceDiagnostics.js';
|
|
8
9
|
import { getSrcPath, getComponentsJsPath, getDistPath, getConfigPath, getProjectRoot } from '../PathHelper.js';
|
|
9
10
|
import ExternalModuleBundler from './ExternalModuleBundler.js';
|
|
10
11
|
|
|
@@ -54,7 +55,12 @@ export default class BundleGenerator {
|
|
|
54
55
|
|
|
55
56
|
// When true, an unresolved node_modules dependency fails the build instead
|
|
56
57
|
// of warning + emitting an empty module. Driven by `slice build --strict-external`.
|
|
57
|
-
|
|
58
|
+
// Unresolved bare imports fail the build unless explicitly allowed. They
|
|
59
|
+
// used to only warn, and the warning said the components "will fail at
|
|
60
|
+
// runtime" — which is a build error described in prose. `--no-strict-external`
|
|
61
|
+
// keeps the old behaviour for the one legitimate case: a package provided
|
|
62
|
+
// some other way (a shim under src/public/).
|
|
63
|
+
this.strictExternal = options.strictExternal !== false;
|
|
58
64
|
|
|
59
65
|
// Bare-package (node_modules) import support is always on. Bare imports are
|
|
60
66
|
// resolved+bundled with esbuild (see ExternalModuleBundler) and registered
|
|
@@ -993,6 +999,61 @@ export default class BundleGenerator {
|
|
|
993
999
|
shared.add(dependencyName);
|
|
994
1000
|
}
|
|
995
1001
|
|
|
1002
|
+
this.expandSharedSetWithDependencyClosure(shared);
|
|
1003
|
+
|
|
1004
|
+
return shared;
|
|
1005
|
+
}
|
|
1006
|
+
|
|
1007
|
+
/**
|
|
1008
|
+
* Grows the shared set to the full dependency closure of everything in it.
|
|
1009
|
+
*
|
|
1010
|
+
* The usage/size thresholds decide which modules are worth extracting, but
|
|
1011
|
+
* they must not decide the closure. A helper that clears
|
|
1012
|
+
* minVendorSharedTransformedSize is emitted into vendor-shared and omitted
|
|
1013
|
+
* from the route bundles; if a module it imports fell under the threshold, it
|
|
1014
|
+
* stayed inlined in the route bundles instead, and the helper's IIFE inside
|
|
1015
|
+
* vendor-shared bound a key vendor-shared never registered. Since
|
|
1016
|
+
* vendor-shared evaluates before anything renders, that surfaced as the whole
|
|
1017
|
+
* app failing to boot with `Cannot read properties of undefined`.
|
|
1018
|
+
*
|
|
1019
|
+
* Pulling a small module in is also the cheaper outcome: it stops being
|
|
1020
|
+
* duplicated across every route bundle that used it.
|
|
1021
|
+
*
|
|
1022
|
+
* Mutates `shared` in place, following moduleImports transitively and
|
|
1023
|
+
* tolerating cycles.
|
|
1024
|
+
*
|
|
1025
|
+
* @param {Set<string>} shared
|
|
1026
|
+
* @returns {Set<string>} the same set
|
|
1027
|
+
*/
|
|
1028
|
+
expandSharedSetWithDependencyClosure(shared) {
|
|
1029
|
+
const pending = Array.from(shared);
|
|
1030
|
+
const visited = new Set(pending);
|
|
1031
|
+
|
|
1032
|
+
while (pending.length > 0) {
|
|
1033
|
+
const dependencyName = pending.pop();
|
|
1034
|
+
const entry = this.vendorShared.dependencyModules.get(dependencyName)
|
|
1035
|
+
|| this.vendorShared.dependencyUsage.get(dependencyName);
|
|
1036
|
+
|
|
1037
|
+
for (const moduleImport of entry?.moduleImports || []) {
|
|
1038
|
+
const importedName = moduleImport?.depName;
|
|
1039
|
+
if (!importedName || visited.has(importedName)) continue;
|
|
1040
|
+
visited.add(importedName);
|
|
1041
|
+
|
|
1042
|
+
// Only modules the vendor-shared bundle can actually emit. Anything
|
|
1043
|
+
// unresolvable has no content to register, so adding it would omit it
|
|
1044
|
+
// from the route bundles and register nothing in its place — the very
|
|
1045
|
+
// failure this closure exists to prevent.
|
|
1046
|
+
const collected = this.vendorShared.dependencyModules.get(importedName);
|
|
1047
|
+
const emittable = collected?.external
|
|
1048
|
+
? !!this.externalModulesByName.get(importedName)
|
|
1049
|
+
: !!collected?.content;
|
|
1050
|
+
if (!emittable) continue;
|
|
1051
|
+
|
|
1052
|
+
shared.add(importedName);
|
|
1053
|
+
pending.push(importedName);
|
|
1054
|
+
}
|
|
1055
|
+
}
|
|
1056
|
+
|
|
996
1057
|
return shared;
|
|
997
1058
|
}
|
|
998
1059
|
|
|
@@ -1087,34 +1148,18 @@ export default class BundleGenerator {
|
|
|
1087
1148
|
}
|
|
1088
1149
|
|
|
1089
1150
|
const wantMap = !!this.options.sourcemap;
|
|
1090
|
-
const
|
|
1091
|
-
|
|
1092
|
-
|
|
1093
|
-
|
|
1094
|
-
|
|
1095
|
-
|
|
1096
|
-
drop_console: false,
|
|
1097
|
-
drop_debugger: true,
|
|
1098
|
-
passes: 1
|
|
1099
|
-
} : false,
|
|
1100
|
-
mangle: this.options.obfuscate ? {
|
|
1101
|
-
properties: false
|
|
1102
|
-
} : false,
|
|
1103
|
-
keep_fnames: true,
|
|
1104
|
-
keep_classnames: true,
|
|
1105
|
-
format: {
|
|
1106
|
-
comments: false,
|
|
1107
|
-
ecma: 2022
|
|
1108
|
-
},
|
|
1109
|
-
// Map the minified output back to the readable pre-minified bundle
|
|
1110
|
-
// (embedded via includeSources so DevTools shows it without a sidecar
|
|
1111
|
-
// source). The URL comment is appended by the caller.
|
|
1112
|
-
...(wantMap ? { sourceMap: { includeSources: true, filename: fileName } } : {})
|
|
1113
|
-
};
|
|
1151
|
+
const createOptions = () => bundleOptions({
|
|
1152
|
+
minify: this.options.minify,
|
|
1153
|
+
obfuscate: this.options.obfuscate,
|
|
1154
|
+
sourcemap: wantMap,
|
|
1155
|
+
fileName
|
|
1156
|
+
});
|
|
1114
1157
|
|
|
1115
1158
|
let result;
|
|
1116
1159
|
try {
|
|
1117
|
-
result
|
|
1160
|
+
// minifyJs normalizes a reported `result.error` into a throw, so both
|
|
1161
|
+
// failure shapes land here and the bundle is dumped once.
|
|
1162
|
+
result = await minifyJs(bundleContent, createOptions);
|
|
1118
1163
|
} catch (error) {
|
|
1119
1164
|
const tmpDir = path.resolve(process.cwd(), '.tmp');
|
|
1120
1165
|
const safeName = fileName.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
@@ -1129,19 +1174,6 @@ export default class BundleGenerator {
|
|
|
1129
1174
|
throw new Error(`Terser failed for ${fileName}: ${message} Saved bundle to ${tmpPath}`);
|
|
1130
1175
|
}
|
|
1131
1176
|
|
|
1132
|
-
if (result.error) {
|
|
1133
|
-
const tmpDir = path.resolve(process.cwd(), '.tmp');
|
|
1134
|
-
const safeName = fileName.replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
1135
|
-
const tmpPath = path.join(tmpDir, `terser-fail-${safeName}`);
|
|
1136
|
-
try {
|
|
1137
|
-
await fs.ensureDir(tmpDir);
|
|
1138
|
-
await fs.writeFile(tmpPath, bundleContent, 'utf-8');
|
|
1139
|
-
} catch (writeError) {
|
|
1140
|
-
console.warn(`Warning: Failed to write ${tmpPath}:`, writeError.message);
|
|
1141
|
-
}
|
|
1142
|
-
throw new Error(`Terser failed for ${fileName}: ${result.error.message}. Saved bundle to ${tmpPath}`);
|
|
1143
|
-
}
|
|
1144
|
-
|
|
1145
1177
|
return { code: result.code || bundleContent, map: wantMap ? (result.map || null) : null };
|
|
1146
1178
|
}
|
|
1147
1179
|
|
|
@@ -1165,6 +1197,7 @@ export default class BundleGenerator {
|
|
|
1165
1197
|
* @returns {Promise<{ file: string, path: string, hash: string, rawSize: number }>}
|
|
1166
1198
|
*/
|
|
1167
1199
|
async emitBundleArtifact(baseFileName, rawContent) {
|
|
1200
|
+
await this.validateGeneratedBundle(rawContent, baseFileName);
|
|
1168
1201
|
const { code, map } = await this.applyBundleTransforms(rawContent, baseFileName);
|
|
1169
1202
|
const fileName = this.hashBundleFileName(baseFileName, code);
|
|
1170
1203
|
let finalCode = code;
|
|
@@ -1182,6 +1215,134 @@ export default class BundleGenerator {
|
|
|
1182
1215
|
}
|
|
1183
1216
|
|
|
1184
1217
|
|
|
1218
|
+
/**
|
|
1219
|
+
* Asserts a generated bundle parses as an ES module, before it is transformed
|
|
1220
|
+
* or written.
|
|
1221
|
+
*
|
|
1222
|
+
* This is a guard on the generator's own output, not on user code. Every
|
|
1223
|
+
* bundler bug found so far had the same shape: valid source in, invalid
|
|
1224
|
+
* JavaScript out, and nothing checking. Terser used to be the accidental
|
|
1225
|
+
* gatekeeper, which made for two bad failure modes — its error named the
|
|
1226
|
+
* generated file instead of the source, and with `--minify` off
|
|
1227
|
+
* applyBundleTransforms returns early, so the broken bundle was written
|
|
1228
|
+
* silently and only failed once a browser tried to parse it.
|
|
1229
|
+
*
|
|
1230
|
+
* Runs unconditionally for that reason: the check is worth more precisely when
|
|
1231
|
+
* minification is off.
|
|
1232
|
+
*
|
|
1233
|
+
* @param {string} bundleContent
|
|
1234
|
+
* @param {string} fileName
|
|
1235
|
+
* @returns {Promise<void>}
|
|
1236
|
+
* @throws {Error} naming the bundle, the source it came from, and a saved copy
|
|
1237
|
+
*/
|
|
1238
|
+
async validateGeneratedBundle(bundleContent, fileName) {
|
|
1239
|
+
try {
|
|
1240
|
+
parse(bundleContent, { sourceType: 'module', plugins: ['jsx'] });
|
|
1241
|
+
return;
|
|
1242
|
+
} catch (error) {
|
|
1243
|
+
const position = typeof error.pos === 'number' ? error.pos : 0;
|
|
1244
|
+
const owner = this.describeBundleOwner(bundleContent, position);
|
|
1245
|
+
const savedPath = await this.saveFailedBundle(bundleContent, fileName, 'invalid-bundle');
|
|
1246
|
+
|
|
1247
|
+
const where = owner ? ` The invalid code comes from ${owner}.` : '';
|
|
1248
|
+
const detail = error.message || 'unknown parse error';
|
|
1249
|
+
throw new Error(
|
|
1250
|
+
`Generated bundle "${fileName}" is not valid JavaScript: ${detail}.${where}`
|
|
1251
|
+
+ ` This is a bundler bug, not a problem with your source. Saved bundle to ${savedPath}`
|
|
1252
|
+
);
|
|
1253
|
+
}
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
/**
|
|
1257
|
+
* Writes a bundle that could not be processed to `.tmp/` so it can be read.
|
|
1258
|
+
* @param {string} bundleContent
|
|
1259
|
+
* @param {string} fileName
|
|
1260
|
+
* @param {string} prefix
|
|
1261
|
+
* @returns {Promise<string>} the path written (or attempted)
|
|
1262
|
+
*/
|
|
1263
|
+
async saveFailedBundle(bundleContent, fileName, prefix) {
|
|
1264
|
+
const tmpDir = path.resolve(process.cwd(), '.tmp');
|
|
1265
|
+
const safeName = String(fileName).replace(/[^a-zA-Z0-9_.-]/g, '_');
|
|
1266
|
+
const tmpPath = path.join(tmpDir, `${prefix}-${safeName}`);
|
|
1267
|
+
try {
|
|
1268
|
+
await fs.ensureDir(tmpDir);
|
|
1269
|
+
await fs.writeFile(tmpPath, bundleContent, 'utf-8');
|
|
1270
|
+
} catch (writeError) {
|
|
1271
|
+
console.warn(`Warning: Failed to write ${tmpPath}:`, writeError.message);
|
|
1272
|
+
}
|
|
1273
|
+
return tmpPath;
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
/**
|
|
1277
|
+
* Maps an offset in a generated bundle back to whatever produced that region:
|
|
1278
|
+
* a component's class factory, or a dependency module's IIFE. Turns "bundle X
|
|
1279
|
+
* is broken" into "component Y emitted invalid code", which is the difference
|
|
1280
|
+
* between a usable error and a scavenger hunt.
|
|
1281
|
+
*
|
|
1282
|
+
* @param {string} bundleContent
|
|
1283
|
+
* @param {number} position
|
|
1284
|
+
* @returns {string|null}
|
|
1285
|
+
*/
|
|
1286
|
+
describeBundleOwner(bundleContent, position) {
|
|
1287
|
+
const regions = [];
|
|
1288
|
+
|
|
1289
|
+
// Dependency modules: `const __sliceDepExportsN = (() => {` ... then
|
|
1290
|
+
// `SLICE_BUNDLE_DEPENDENCIES["key"] = __sliceDepExportsN;` closes it, which
|
|
1291
|
+
// is also where the key becomes known.
|
|
1292
|
+
const depAssignment = /SLICE_BUNDLE_DEPENDENCIES\[("(?:[^"\\]|\\.)*")\]\s*=\s*(__sliceDepExports\d+)\s*;/g;
|
|
1293
|
+
for (let match = depAssignment.exec(bundleContent); match; match = depAssignment.exec(bundleContent)) {
|
|
1294
|
+
const [, quotedKey, exportVar] = match;
|
|
1295
|
+
const openIndex = bundleContent.indexOf(`const ${exportVar} = (() => {`);
|
|
1296
|
+
if (openIndex === -1) continue;
|
|
1297
|
+
let key = quotedKey;
|
|
1298
|
+
try { key = JSON.parse(quotedKey); } catch { /* keep the raw form */ }
|
|
1299
|
+
regions.push({ start: openIndex, end: match.index + match[0].length, label: `dependency "${key}"` });
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
// Component factories: from `const SLICE_CLASS_FACTORY_x = ` up to the next
|
|
1303
|
+
// factory or the template declarations that follow the whole block.
|
|
1304
|
+
const factoryStarts = [];
|
|
1305
|
+
const factory = /const (SLICE_CLASS_FACTORY_\S+) = \(\) => \{/g;
|
|
1306
|
+
for (let match = factory.exec(bundleContent); match; match = factory.exec(bundleContent)) {
|
|
1307
|
+
factoryStarts.push({ start: match.index, identifier: match[1] });
|
|
1308
|
+
}
|
|
1309
|
+
for (const [index, entry] of factoryStarts.entries()) {
|
|
1310
|
+
const next = factoryStarts[index + 1]?.start;
|
|
1311
|
+
const templates = bundleContent.indexOf('const __templateElement_', entry.start);
|
|
1312
|
+
const candidates = [next, templates === -1 ? undefined : templates, bundleContent.length]
|
|
1313
|
+
.filter((value) => typeof value === 'number');
|
|
1314
|
+
regions.push({
|
|
1315
|
+
start: entry.start,
|
|
1316
|
+
end: Math.min(...candidates),
|
|
1317
|
+
label: `component "${this.componentNameFromFactory(entry.identifier)}"`
|
|
1318
|
+
});
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
// Innermost match wins, so a dependency IIFE nested in a factory is named
|
|
1322
|
+
// rather than the factory around it.
|
|
1323
|
+
const containing = regions
|
|
1324
|
+
.filter((region) => position >= region.start && position <= region.end)
|
|
1325
|
+
.sort((a, b) => (a.end - a.start) - (b.end - b.start));
|
|
1326
|
+
|
|
1327
|
+
return containing[0]?.label || null;
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
/**
|
|
1331
|
+
* Reverses toSafeIdentifier() so an error can name the component as the
|
|
1332
|
+
* developer wrote it. The encoding is injective, so this is exact.
|
|
1333
|
+
* @param {string} factoryIdentifier
|
|
1334
|
+
* @returns {string}
|
|
1335
|
+
*/
|
|
1336
|
+
componentNameFromFactory(factoryIdentifier) {
|
|
1337
|
+
const encoded = String(factoryIdentifier)
|
|
1338
|
+
.replace(/^SLICE_CLASS_FACTORY_/, '')
|
|
1339
|
+
.replace(/^SliceComponent_/, '');
|
|
1340
|
+
return encoded.replace(/_([0-9a-f]+)_/g, (match, hex) => {
|
|
1341
|
+
const codePoint = Number.parseInt(hex, 16);
|
|
1342
|
+
return Number.isFinite(codePoint) ? String.fromCharCode(codePoint) : match;
|
|
1343
|
+
});
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1185
1346
|
/**
|
|
1186
1347
|
* Bare-package (node_modules) imports are always resolved and bundled — no
|
|
1187
1348
|
* configuration needed, mirroring how a React/Vite project imports npm
|
|
@@ -1390,7 +1551,7 @@ export default class BundleGenerator {
|
|
|
1390
1551
|
}
|
|
1391
1552
|
// Follow relative helper modules so packages imported only by a helper
|
|
1392
1553
|
// are discovered too.
|
|
1393
|
-
for (const dep of this.analyzeDependencies(code, path.dirname(filePath))) {
|
|
1554
|
+
for (const dep of this.analyzeDependencies(code, path.dirname(filePath), filePath)) {
|
|
1394
1555
|
await walk(dep.path);
|
|
1395
1556
|
}
|
|
1396
1557
|
};
|
|
@@ -1437,13 +1598,15 @@ export default class BundleGenerator {
|
|
|
1437
1598
|
}
|
|
1438
1599
|
}
|
|
1439
1600
|
|
|
1440
|
-
//
|
|
1441
|
-
//
|
|
1601
|
+
// A package that cannot be resolved is emitted as an empty namespace, so
|
|
1602
|
+
// every binding from it is undefined — a guaranteed runtime failure. Fail
|
|
1603
|
+
// here instead, unless the caller opted out.
|
|
1442
1604
|
if (this.strictExternal && this.externalResolutionErrors.size > 0) {
|
|
1443
1605
|
const names = Array.from(this.externalResolutionErrors.keys()).sort().join(', ');
|
|
1444
1606
|
throw new Error(
|
|
1445
|
-
|
|
1446
|
-
|
|
1607
|
+
`${this.externalResolutionErrors.size} package(s) could not be resolved from node_modules: ${names}. `
|
|
1608
|
+
+ 'Install them, remove the imports, or pass --no-strict-external if they are provided '
|
|
1609
|
+
+ 'another way (a shim under src/public/).'
|
|
1447
1610
|
);
|
|
1448
1611
|
}
|
|
1449
1612
|
}
|
|
@@ -1451,8 +1614,17 @@ export default class BundleGenerator {
|
|
|
1451
1614
|
/**
|
|
1452
1615
|
* Analyzes dependencies of a JavaScript file using simple regex
|
|
1453
1616
|
*/
|
|
1454
|
-
|
|
1617
|
+
/**
|
|
1618
|
+
* Extensions resolveImportPath() will try. A relative import of one of these
|
|
1619
|
+
* (or of nothing, meaning extensionless) points at a JavaScript module that is
|
|
1620
|
+
* expected to exist in the repo — so failing to resolve it is a typo, not a
|
|
1621
|
+
* supported pattern. Anything else (an asset, say) is left alone.
|
|
1622
|
+
*/
|
|
1623
|
+
static RESOLVABLE_MODULE_EXTENSIONS = ['.js', '.json', '.mjs'];
|
|
1624
|
+
|
|
1625
|
+
analyzeDependencies(jsContent, componentPath, sourceFile = null) {
|
|
1455
1626
|
const dependencies = [];
|
|
1627
|
+
const unresolved = [];
|
|
1456
1628
|
|
|
1457
1629
|
const resolveImportPath = (importPath) => {
|
|
1458
1630
|
const resolvedPath = path.resolve(componentPath, importPath);
|
|
@@ -1486,6 +1658,7 @@ export default class BundleGenerator {
|
|
|
1486
1658
|
|
|
1487
1659
|
const resolvedPath = resolveImportPath(importPath);
|
|
1488
1660
|
if (!resolvedPath) {
|
|
1661
|
+
unresolved.push(importPath);
|
|
1489
1662
|
return;
|
|
1490
1663
|
}
|
|
1491
1664
|
|
|
@@ -1533,6 +1706,7 @@ export default class BundleGenerator {
|
|
|
1533
1706
|
if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
|
|
1534
1707
|
const resolvedPath = resolveImportPath(src);
|
|
1535
1708
|
if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
|
|
1709
|
+
else unresolved.push(src);
|
|
1536
1710
|
},
|
|
1537
1711
|
|
|
1538
1712
|
ExportAllDeclaration(pathNode) {
|
|
@@ -1540,15 +1714,55 @@ export default class BundleGenerator {
|
|
|
1540
1714
|
if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
|
|
1541
1715
|
const resolvedPath = resolveImportPath(src);
|
|
1542
1716
|
if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
|
|
1717
|
+
else unresolved.push(src);
|
|
1543
1718
|
}
|
|
1544
1719
|
});
|
|
1545
1720
|
} catch (error) {
|
|
1546
1721
|
console.warn(`Warning: Could not analyze dependencies for ${componentPath}:`, error.message);
|
|
1547
1722
|
}
|
|
1548
1723
|
|
|
1724
|
+
this.assertRelativeImportsResolve(unresolved, componentPath, sourceFile);
|
|
1725
|
+
|
|
1549
1726
|
return dependencies;
|
|
1550
1727
|
}
|
|
1551
1728
|
|
|
1729
|
+
/**
|
|
1730
|
+
* Fails the build on a relative import that points at nothing.
|
|
1731
|
+
*
|
|
1732
|
+
* These used to be dropped silently: `import { x } from './typo.js'` produced
|
|
1733
|
+
* a bundle where `x` was simply undefined, with no warning at build time and
|
|
1734
|
+
* no clue at runtime. A relative specifier names a file in the repo, so an
|
|
1735
|
+
* unresolved one is a typo or a deleted file — there is no legitimate "it will
|
|
1736
|
+
* be provided some other way" story, unlike a bare package (which
|
|
1737
|
+
* --strict-external governs, and which can be shimmed from src/public/).
|
|
1738
|
+
*
|
|
1739
|
+
* Only specifiers that name a JavaScript module are enforced: an extensionless
|
|
1740
|
+
* one, or .js/.json/.mjs. A relative asset import is left alone.
|
|
1741
|
+
*
|
|
1742
|
+
* @param {string[]} specifiers
|
|
1743
|
+
* @param {string} componentPath directory the import was resolved against
|
|
1744
|
+
* @param {string|null} sourceFile importing file, when the caller knows it
|
|
1745
|
+
* @throws {Error} listing every unresolved specifier
|
|
1746
|
+
*/
|
|
1747
|
+
assertRelativeImportsResolve(specifiers, componentPath, sourceFile = null) {
|
|
1748
|
+
const moduleLike = specifiers.filter((specifier) => {
|
|
1749
|
+
const ext = path.extname(specifier);
|
|
1750
|
+
return ext === '' || BundleGenerator.RESOLVABLE_MODULE_EXTENSIONS.includes(ext);
|
|
1751
|
+
});
|
|
1752
|
+
if (moduleLike.length === 0) return;
|
|
1753
|
+
|
|
1754
|
+
const where = sourceFile || componentPath;
|
|
1755
|
+
const details = moduleLike
|
|
1756
|
+
.map((specifier) => ` "${specifier}" -> ${path.resolve(componentPath, specifier)}`)
|
|
1757
|
+
.join('\n');
|
|
1758
|
+
|
|
1759
|
+
throw new Error(
|
|
1760
|
+
`Cannot resolve ${moduleLike.length} import(s) in ${where}:\n${details}\n`
|
|
1761
|
+
+ `Checked those paths plus ${BundleGenerator.RESOLVABLE_MODULE_EXTENSIONS.join(', ')} for extensionless specifiers. `
|
|
1762
|
+
+ 'Fix the path or create the file — an unresolved relative import silently becomes `undefined` at runtime.'
|
|
1763
|
+
);
|
|
1764
|
+
}
|
|
1765
|
+
|
|
1552
1766
|
/**
|
|
1553
1767
|
* Generates the content of a bundle
|
|
1554
1768
|
*/
|
|
@@ -1588,6 +1802,7 @@ export default class BundleGenerator {
|
|
|
1588
1802
|
categoryType: comp.categoryType,
|
|
1589
1803
|
js: cleanedJavaScript.code,
|
|
1590
1804
|
hoistedImports: cleanedJavaScript.hoistedImports,
|
|
1805
|
+
hasTopLevelAwait: cleanedJavaScript.hasTopLevelAwait,
|
|
1591
1806
|
html: htmlContent,
|
|
1592
1807
|
css: cssContent,
|
|
1593
1808
|
externalDependencies,
|
|
@@ -1657,11 +1872,17 @@ export default class BundleGenerator {
|
|
|
1657
1872
|
});
|
|
1658
1873
|
const body = component.js && component.js.trim()
|
|
1659
1874
|
? component.js
|
|
1660
|
-
: `
|
|
1875
|
+
// Bracket-keyed: a registered name like `my-btn` is a valid key but
|
|
1876
|
+
// not a valid identifier.
|
|
1877
|
+
: `return window[${JSON.stringify(component.name)}];`;
|
|
1661
1878
|
const bodyWithBindings = dependencyBindings
|
|
1662
1879
|
? `${dependencyBindings}\n${body}`
|
|
1663
1880
|
: body;
|
|
1664
|
-
|
|
1881
|
+
// A component module may legitimately use top-level await. Its code ends
|
|
1882
|
+
// up inside this factory, so the factory has to be async for that to be
|
|
1883
|
+
// valid — and only then, to keep every other bundle byte-identical.
|
|
1884
|
+
const arrow = component.hasTopLevelAwait ? 'async () =>' : '() =>';
|
|
1885
|
+
return `const ${factoryName} = ${arrow} {\n${this.indentCodeBlock(bodyWithBindings, 2)}\n};`;
|
|
1665
1886
|
})
|
|
1666
1887
|
.join('\n\n');
|
|
1667
1888
|
|
|
@@ -1675,7 +1896,13 @@ export default class BundleGenerator {
|
|
|
1675
1896
|
const classRegistrations = uniqueComponents
|
|
1676
1897
|
.map((component) => {
|
|
1677
1898
|
const componentName = JSON.stringify(component.name);
|
|
1678
|
-
|
|
1899
|
+
// An async factory returns a promise; registerAll is already async and
|
|
1900
|
+
// the framework awaits it (Controller.loadBundleWithDependencies), so
|
|
1901
|
+
// awaiting here keeps `classes` holding the class itself, never a promise.
|
|
1902
|
+
const call = component.hasTopLevelAwait
|
|
1903
|
+
? `await ${this.classFactoryName(component.name)}()`
|
|
1904
|
+
: `${this.classFactoryName(component.name)}()`;
|
|
1905
|
+
return ` if (!controller.classes.has(${componentName})) {\n controller.classes.set(${componentName}, ${call});\n }`;
|
|
1679
1906
|
})
|
|
1680
1907
|
.join('\n');
|
|
1681
1908
|
|
|
@@ -1725,11 +1952,15 @@ export default class BundleGenerator {
|
|
|
1725
1952
|
const omittedDependencies = options.omittedDependencies instanceof Set
|
|
1726
1953
|
? options.omittedDependencies
|
|
1727
1954
|
: new Set(options.omittedDependencies || []);
|
|
1955
|
+
const emittedModules = modules.filter((module) => !omittedDependencies.has(module.name));
|
|
1956
|
+
|
|
1957
|
+
// A cycle has no topological order, and this emission strategy cannot
|
|
1958
|
+
// reproduce ESM's live bindings, so it must be reported rather than emitted.
|
|
1959
|
+
this.assertNoDependencyCycles(emittedModules);
|
|
1960
|
+
|
|
1728
1961
|
// Emit in topological order so a module is registered before any module
|
|
1729
1962
|
// that depends on it (its transitive imports resolve at IIFE-eval time).
|
|
1730
|
-
const filteredModules = this.sortDependencyModulesTopologically(
|
|
1731
|
-
modules.filter((module) => !omittedDependencies.has(module.name))
|
|
1732
|
-
);
|
|
1963
|
+
const filteredModules = this.sortDependencyModulesTopologically(emittedModules);
|
|
1733
1964
|
|
|
1734
1965
|
const lines = [
|
|
1735
1966
|
'const SLICE_BUNDLE_DEPENDENCIES = {};',
|
|
@@ -1807,6 +2038,83 @@ export default class BundleGenerator {
|
|
|
1807
2038
|
return lines.join('\n');
|
|
1808
2039
|
}
|
|
1809
2040
|
|
|
2041
|
+
/**
|
|
2042
|
+
* Fails the build when the helper modules about to be emitted import each
|
|
2043
|
+
* other in a cycle.
|
|
2044
|
+
*
|
|
2045
|
+
* Each dependency is emitted as an eagerly-evaluated IIFE, and its imports are
|
|
2046
|
+
* bound by *copying* values out of the modules registered before it
|
|
2047
|
+
* (`const B = SLICE_BUNDLE_DEPENDENCIES["b.js"].B`). That is sound for a DAG,
|
|
2048
|
+
* emitted in topological order. A cycle has no such order: whichever module
|
|
2049
|
+
* runs first copies from an object that is not populated yet.
|
|
2050
|
+
*
|
|
2051
|
+
* There is no safe way to paper over this. Registering the exports objects up
|
|
2052
|
+
* front would stop the crash, but the copied binding would stay `undefined`
|
|
2053
|
+
* forever — trading a loud failure for a silent wrong value, which is worse.
|
|
2054
|
+
* Reproducing ESM's live bindings would mean rewriting every reference into a
|
|
2055
|
+
* member access, with full scope analysis.
|
|
2056
|
+
*
|
|
2057
|
+
* Cycles work in `slice dev`, where each file is a real ES module, so this has
|
|
2058
|
+
* to be reported at build time or it becomes a dev/production divergence.
|
|
2059
|
+
*
|
|
2060
|
+
* @param {Array<{name: string, moduleImports?: Array<{depName: string}>}>} modules
|
|
2061
|
+
* @throws {Error} naming the modules in the cycle
|
|
2062
|
+
*/
|
|
2063
|
+
assertNoDependencyCycles(modules = []) {
|
|
2064
|
+
const cycle = this.findDependencyCycle(modules);
|
|
2065
|
+
if (!cycle) return;
|
|
2066
|
+
|
|
2067
|
+
throw new Error(
|
|
2068
|
+
`Circular import between bundled modules: ${cycle.join(' -> ')}. `
|
|
2069
|
+
+ 'Bundled helper modules are evaluated in dependency order and cannot reproduce '
|
|
2070
|
+
+ "ES module live bindings, so whichever module runs first would read the other's "
|
|
2071
|
+
+ 'exports before they exist. This works in `slice dev` (real ES modules) but not in a build. '
|
|
2072
|
+
+ 'Break the cycle — usually by moving what both files share into a third module they each import.'
|
|
2073
|
+
);
|
|
2074
|
+
}
|
|
2075
|
+
|
|
2076
|
+
/**
|
|
2077
|
+
* Finds one import cycle, if any, and returns it as a readable path.
|
|
2078
|
+
* @param {Array<object>} modules
|
|
2079
|
+
* @returns {string[]|null} e.g. ['a.js', 'b.js', 'a.js']
|
|
2080
|
+
*/
|
|
2081
|
+
findDependencyCycle(modules = []) {
|
|
2082
|
+
const byName = new Map(modules.map((module) => [module.name, module]));
|
|
2083
|
+
const visited = new Set();
|
|
2084
|
+
const stack = [];
|
|
2085
|
+
const onStack = new Set();
|
|
2086
|
+
|
|
2087
|
+
const walk = (module) => {
|
|
2088
|
+
if (visited.has(module.name)) return null;
|
|
2089
|
+
|
|
2090
|
+
stack.push(module.name);
|
|
2091
|
+
onStack.add(module.name);
|
|
2092
|
+
|
|
2093
|
+
for (const imported of module.moduleImports || []) {
|
|
2094
|
+
const next = byName.get(imported?.depName);
|
|
2095
|
+
if (!next) continue;
|
|
2096
|
+
|
|
2097
|
+
if (onStack.has(next.name)) {
|
|
2098
|
+
// Report from the first occurrence so the path reads as a loop.
|
|
2099
|
+
return [...stack.slice(stack.indexOf(next.name)), next.name];
|
|
2100
|
+
}
|
|
2101
|
+
const found = walk(next);
|
|
2102
|
+
if (found) return found;
|
|
2103
|
+
}
|
|
2104
|
+
|
|
2105
|
+
onStack.delete(module.name);
|
|
2106
|
+
stack.pop();
|
|
2107
|
+
visited.add(module.name);
|
|
2108
|
+
return null;
|
|
2109
|
+
};
|
|
2110
|
+
|
|
2111
|
+
for (const module of modules) {
|
|
2112
|
+
const found = walk(module);
|
|
2113
|
+
if (found) return found;
|
|
2114
|
+
}
|
|
2115
|
+
return null;
|
|
2116
|
+
}
|
|
2117
|
+
|
|
1810
2118
|
sortDependencyModulesTopologically(modules = []) {
|
|
1811
2119
|
const byName = new Map(modules.map((module) => [module.name, module]));
|
|
1812
2120
|
const visited = new Set();
|
|
@@ -1893,9 +2201,57 @@ export default class BundleGenerator {
|
|
|
1893
2201
|
/**
|
|
1894
2202
|
* Cleans JavaScript code by removing imports/exports and ensuring class is available globally
|
|
1895
2203
|
*/
|
|
2204
|
+
/**
|
|
2205
|
+
* Fails the build on a component whose source is not valid JavaScript, before
|
|
2206
|
+
* anything tries to transform it.
|
|
2207
|
+
*
|
|
2208
|
+
* Without this the broken source flowed through every transform (each of which
|
|
2209
|
+
* silently falls back to a regex when it cannot parse) and into the bundle,
|
|
2210
|
+
* where the generated-bundle validation reported a position in the *generated*
|
|
2211
|
+
* file and said "this is a bundler bug" — actively misleading when the mistake
|
|
2212
|
+
* is a missing brace in the developer's own component. The real position was
|
|
2213
|
+
* only ever visible in warnings nobody reads.
|
|
2214
|
+
*
|
|
2215
|
+
* @param {string} code
|
|
2216
|
+
* @param {string} componentName
|
|
2217
|
+
* @param {string} sourceContext file path shown in the error
|
|
2218
|
+
* @throws {Error} with the file, line, column and a source frame
|
|
2219
|
+
*/
|
|
2220
|
+
assertComponentSourceParses(code, componentName, sourceContext) {
|
|
2221
|
+
const diagnosis = describeSyntaxError(code, sourceContext);
|
|
2222
|
+
if (diagnosis.ok) return;
|
|
2223
|
+
|
|
2224
|
+
throw new Error(
|
|
2225
|
+
`Syntax error in component "${componentName}" at ${diagnosis.message}`
|
|
2226
|
+
+ '\nFix the source above — the build cannot bundle a file it cannot parse.'
|
|
2227
|
+
);
|
|
2228
|
+
}
|
|
2229
|
+
|
|
1896
2230
|
cleanJavaScript(code, componentName, sourceContext = componentName) {
|
|
1897
|
-
//
|
|
1898
|
-
|
|
2231
|
+
// Before any transform: a file that does not parse cannot be bundled, and
|
|
2232
|
+
// every downstream step degrades to regex fallbacks that hide the real cause.
|
|
2233
|
+
this.assertComponentSourceParses(code, componentName, sourceContext);
|
|
2234
|
+
|
|
2235
|
+
// Detect this on the pristine source: the transforms below append a
|
|
2236
|
+
// top-level `return`, after which the code no longer parses as a module.
|
|
2237
|
+
const hasTopLevelAwait = this.hasModuleTopLevelAwait(code);
|
|
2238
|
+
|
|
2239
|
+
// Resolve what the module actually default-exports, while the source is
|
|
2240
|
+
// still pristine. The factory has to return *that* binding: a component's
|
|
2241
|
+
// registered name and its class name need not match, and the registered name
|
|
2242
|
+
// may not even be a legal identifier (`my-btn`).
|
|
2243
|
+
const defaultExport = this.resolveDefaultExportBinding(code, componentName, sourceContext);
|
|
2244
|
+
|
|
2245
|
+
// Drop module-level `export` keywords before anything else, while the
|
|
2246
|
+
// source is still pristine enough to parse as a module.
|
|
2247
|
+
code = this.stripModuleExports(code, sourceContext);
|
|
2248
|
+
|
|
2249
|
+
// Remove export default. An anonymous one (`export default class {}`) has no
|
|
2250
|
+
// binding to return, so give it one instead of leaving a bare class
|
|
2251
|
+
// expression, which is not a valid statement.
|
|
2252
|
+
code = defaultExport.anonymous
|
|
2253
|
+
? code.replace(/export\s+default\s+/, `const ${defaultExport.name} = `)
|
|
2254
|
+
: code.replace(/export\s+default\s+/g, '');
|
|
1899
2255
|
|
|
1900
2256
|
// Remove only unsupported imports (relative always removed, allowed absolute kept)
|
|
1901
2257
|
const stripped = this.stripImports(code, {
|
|
@@ -1922,11 +2278,16 @@ export default class BundleGenerator {
|
|
|
1922
2278
|
}
|
|
1923
2279
|
);
|
|
1924
2280
|
|
|
1925
|
-
// Make sure the class is available globally for bundle evaluation
|
|
2281
|
+
// Make sure the class is available globally for bundle evaluation.
|
|
2282
|
+
// Keyed by component name as a *string*: a registered name like `my-btn` is
|
|
2283
|
+
// a perfectly good key but not a valid identifier, so `window.my-btn = ...`
|
|
2284
|
+
// would be a syntax error.
|
|
2285
|
+
const globalKey = `window[${JSON.stringify(componentName)}]`;
|
|
2286
|
+
|
|
1926
2287
|
// Preserve original customElements.define if it exists
|
|
1927
2288
|
if (code.includes('customElements.define')) {
|
|
1928
2289
|
// Add global assignment before guarded or direct customElements.define
|
|
1929
|
-
const globalAssignment =
|
|
2290
|
+
const globalAssignment = `${globalKey} = ${defaultExport.name};\n`;
|
|
1930
2291
|
const guardedDefineRegex = /if\s*\(\s*!\s*customElements\.get\([^)]*\)\s*\)\s*\{\s*customElements\.define\([^;]+\);?\s*\}\s*$/;
|
|
1931
2292
|
const directDefineRegex = /customElements\.define\([^;]+\);?\s*$/;
|
|
1932
2293
|
if (guardedDefineRegex.test(code)) {
|
|
@@ -1936,18 +2297,109 @@ export default class BundleGenerator {
|
|
|
1936
2297
|
}
|
|
1937
2298
|
} else {
|
|
1938
2299
|
// If no customElements.define found, just assign to global
|
|
1939
|
-
code += `\
|
|
2300
|
+
code += `\n${globalKey} = ${defaultExport.name};`;
|
|
1940
2301
|
}
|
|
1941
2302
|
|
|
1942
2303
|
// Add return statement for bundle evaluation compatibility
|
|
1943
|
-
code += `\nreturn ${
|
|
2304
|
+
code += `\nreturn ${defaultExport.name};`;
|
|
1944
2305
|
|
|
1945
2306
|
return {
|
|
1946
2307
|
code,
|
|
1947
|
-
hoistedImports
|
|
2308
|
+
hoistedImports,
|
|
2309
|
+
hasTopLevelAwait
|
|
1948
2310
|
};
|
|
1949
2311
|
}
|
|
1950
2312
|
|
|
2313
|
+
/**
|
|
2314
|
+
* Works out which binding a component module default-exports.
|
|
2315
|
+
*
|
|
2316
|
+
* The bundle wraps the component's code in a factory that has to end with
|
|
2317
|
+
* `return <the class>`, and register it on `window` for bundle evaluation.
|
|
2318
|
+
* Both used to be written as the *component name*, which assumed two things
|
|
2319
|
+
* that are not true: that the registered name matches the class name, and that
|
|
2320
|
+
* it is a valid JavaScript identifier. A component registered as `my-btn`
|
|
2321
|
+
* produced `window.my-btn = my-btn; return my-btn;` — a syntax error.
|
|
2322
|
+
*
|
|
2323
|
+
* A component with no default export is a source error, not a bundler one:
|
|
2324
|
+
* the runtime loads components with `const { default: myClass } = await
|
|
2325
|
+
* import(...)` (Slice.getClass), so such a component could never be built at
|
|
2326
|
+
* all. It fails the build here, with the file named and the fix spelled out,
|
|
2327
|
+
* rather than emitting a bundle that dies later.
|
|
2328
|
+
*
|
|
2329
|
+
* @param {string} code component source, before any transform
|
|
2330
|
+
* @param {string} componentName registered name
|
|
2331
|
+
* @param {string} sourceContext path, used in the error
|
|
2332
|
+
* @returns {{name: string, anonymous: boolean}}
|
|
2333
|
+
* @throws {Error} when the module has no default export
|
|
2334
|
+
*/
|
|
2335
|
+
resolveDefaultExportBinding(code, componentName, sourceContext) {
|
|
2336
|
+
const anonymousBinding = `__sliceComponent_${this.toSafeIdentifier(componentName)}`;
|
|
2337
|
+
|
|
2338
|
+
let ast;
|
|
2339
|
+
try {
|
|
2340
|
+
ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
2341
|
+
} catch (error) {
|
|
2342
|
+
// Unparseable source. Don't guess a binding — the generated bundle is
|
|
2343
|
+
// validated before it is written, and that reports the real problem.
|
|
2344
|
+
return { name: anonymousBinding, anonymous: false };
|
|
2345
|
+
}
|
|
2346
|
+
|
|
2347
|
+
for (const node of ast.program.body) {
|
|
2348
|
+
if (node.type !== 'ExportDefaultDeclaration') continue;
|
|
2349
|
+
const declaration = node.declaration;
|
|
2350
|
+
|
|
2351
|
+
if ((declaration.type === 'ClassDeclaration' || declaration.type === 'FunctionDeclaration')
|
|
2352
|
+
&& declaration.id?.name) {
|
|
2353
|
+
return { name: declaration.id.name, anonymous: false };
|
|
2354
|
+
}
|
|
2355
|
+
if (declaration.type === 'Identifier') {
|
|
2356
|
+
return { name: declaration.name, anonymous: false };
|
|
2357
|
+
}
|
|
2358
|
+
// `export default class {}`, `export default function () {}`, or any
|
|
2359
|
+
// expression: nothing to reference, so bind it on the way out.
|
|
2360
|
+
return { name: anonymousBinding, anonymous: true };
|
|
2361
|
+
}
|
|
2362
|
+
|
|
2363
|
+
throw new Error(
|
|
2364
|
+
`Component "${componentName}" has no default export (${sourceContext}). `
|
|
2365
|
+
+ 'Slice loads a component with `const { default: myClass } = await import(...)`, '
|
|
2366
|
+
+ `so ${componentName}.js must end with \`export default class ${componentName.replace(/[^A-Za-z0-9]/g, '')} { ... }\`.`
|
|
2367
|
+
);
|
|
2368
|
+
}
|
|
2369
|
+
|
|
2370
|
+
/**
|
|
2371
|
+
* True when a component module awaits at its own top level (rather than inside
|
|
2372
|
+
* a function). Such a module is valid ESM, but its code is emitted inside the
|
|
2373
|
+
* class factory — so the factory must be declared async.
|
|
2374
|
+
*
|
|
2375
|
+
* @param {string} code component source, before any transform
|
|
2376
|
+
* @returns {boolean}
|
|
2377
|
+
*/
|
|
2378
|
+
hasModuleTopLevelAwait(code) {
|
|
2379
|
+
let ast;
|
|
2380
|
+
try {
|
|
2381
|
+
ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
2382
|
+
} catch (error) {
|
|
2383
|
+
// Unparseable source: assume no top-level await. The bundle validation in
|
|
2384
|
+
// emitBundleArtifact is what catches whatever is actually wrong.
|
|
2385
|
+
return false;
|
|
2386
|
+
}
|
|
2387
|
+
|
|
2388
|
+
let found = false;
|
|
2389
|
+
traverse.default(ast, {
|
|
2390
|
+
// `for await (...)` counts too — it is only legal in an async context.
|
|
2391
|
+
'AwaitExpression|ForOfStatement': (pathNode) => {
|
|
2392
|
+
if (found) return;
|
|
2393
|
+
if (pathNode.node.type === 'ForOfStatement' && !pathNode.node.await) return;
|
|
2394
|
+
if (pathNode.getFunctionParent()) return; // awaits inside a function are fine
|
|
2395
|
+
found = true;
|
|
2396
|
+
pathNode.stop();
|
|
2397
|
+
}
|
|
2398
|
+
});
|
|
2399
|
+
|
|
2400
|
+
return found;
|
|
2401
|
+
}
|
|
2402
|
+
|
|
1951
2403
|
/**
|
|
1952
2404
|
* Formats the bundle file
|
|
1953
2405
|
*/
|
|
@@ -2715,6 +3167,7 @@ if (window.slice && window.slice.controller) {
|
|
|
2715
3167
|
isFramework: true,
|
|
2716
3168
|
js: cleanedJavaScript.code,
|
|
2717
3169
|
hoistedImports: cleanedJavaScript.hoistedImports,
|
|
3170
|
+
hasTopLevelAwait: cleanedJavaScript.hasTopLevelAwait,
|
|
2718
3171
|
externalDependencies: dependencyContents,
|
|
2719
3172
|
componentDependencies: Array.from(comp.dependencies),
|
|
2720
3173
|
html: fs.existsSync(path.join(comp.path, `${fileBaseName}.html`))
|
|
@@ -3036,6 +3489,116 @@ if (window.slice && window.slice.controller) {
|
|
|
3036
3489
|
}
|
|
3037
3490
|
}
|
|
3038
3491
|
|
|
3492
|
+
/**
|
|
3493
|
+
* Removes module-level `export` keywords from a component's own source.
|
|
3494
|
+
*
|
|
3495
|
+
* A component file is a real ES module, so `export const` / `export function`
|
|
3496
|
+
* / `export class` are valid there and work in dev (each file is loaded as a
|
|
3497
|
+
* module). The bundle, however, embeds this code inside
|
|
3498
|
+
* `SLICE_CLASS_FACTORY_* = () => { ... }`, and `export` is only legal at the
|
|
3499
|
+
* top level of a module — so the emitted bundle is a syntax error. With
|
|
3500
|
+
* minification on that surfaces as `Terser failed for slice-bundle.*.js:
|
|
3501
|
+
* "Export" statement may only appear at the top level`, which names the
|
|
3502
|
+
* generated file rather than the source; with minification off
|
|
3503
|
+
* applyBundleTransforms returns early, so the broken bundle ships and the
|
|
3504
|
+
* browser rejects it at parse time instead.
|
|
3505
|
+
*
|
|
3506
|
+
* Only the keyword is removed — the declaration stays, so references to the
|
|
3507
|
+
* name from elsewhere in the same file keep working. Nothing can consume
|
|
3508
|
+
* these names through the bundle anyway: the Bundling V2 contract reads
|
|
3509
|
+
* exactly SLICE_BUNDLE_META and registerAll (Controller.validateBundleModule),
|
|
3510
|
+
* and another component that imports `{ NAME }` from this file resolves it
|
|
3511
|
+
* from the separate copy emitted on the dependency path
|
|
3512
|
+
* (buildDependencyContents), where transformDependencyContent rewrites named
|
|
3513
|
+
* exports onto an exports object properly.
|
|
3514
|
+
*
|
|
3515
|
+
* `export default` is handled by the caller's own strip, which also appends
|
|
3516
|
+
* the `return <ComponentName>;` the factory needs.
|
|
3517
|
+
*
|
|
3518
|
+
* @param {string} code component source
|
|
3519
|
+
* @param {string|null} sourceContext path used in warnings
|
|
3520
|
+
* @returns {string}
|
|
3521
|
+
*/
|
|
3522
|
+
stripModuleExports(code, sourceContext = null) {
|
|
3523
|
+
let exportNodes;
|
|
3524
|
+
try {
|
|
3525
|
+
exportNodes = this.parseModuleExportsFromCode(code);
|
|
3526
|
+
} catch (error) {
|
|
3527
|
+
// Unparseable (e.g. TS syntax): fall back to a conservative keyword strip
|
|
3528
|
+
// rather than emitting a bundle that cannot be parsed at all.
|
|
3529
|
+
return this.stripModuleExportsWithFallbackRegex(code);
|
|
3530
|
+
}
|
|
3531
|
+
|
|
3532
|
+
if (exportNodes.length === 0) return code;
|
|
3533
|
+
|
|
3534
|
+
let cleaned = '';
|
|
3535
|
+
let cursor = 0;
|
|
3536
|
+
for (const node of exportNodes) {
|
|
3537
|
+
cleaned += code.slice(cursor, node.start);
|
|
3538
|
+
cleaned += this.rewriteModuleExportStatement(node, code, sourceContext);
|
|
3539
|
+
cursor = node.end;
|
|
3540
|
+
}
|
|
3541
|
+
cleaned += code.slice(cursor);
|
|
3542
|
+
|
|
3543
|
+
return cleaned;
|
|
3544
|
+
}
|
|
3545
|
+
|
|
3546
|
+
/**
|
|
3547
|
+
* Top-level named/star export statements, in source order. Exports are only
|
|
3548
|
+
* valid at the top level, so program.body is the whole search space.
|
|
3549
|
+
* @param {string} code
|
|
3550
|
+
* @returns {Array<object>}
|
|
3551
|
+
*/
|
|
3552
|
+
parseModuleExportsFromCode(code) {
|
|
3553
|
+
const ast = parse(code, {
|
|
3554
|
+
sourceType: 'module',
|
|
3555
|
+
plugins: ['jsx']
|
|
3556
|
+
});
|
|
3557
|
+
|
|
3558
|
+
return ast.program.body
|
|
3559
|
+
.filter((node) => node.type === 'ExportNamedDeclaration' || node.type === 'ExportAllDeclaration')
|
|
3560
|
+
.filter((node) => typeof node.start === 'number' && typeof node.end === 'number')
|
|
3561
|
+
.sort((a, b) => a.start - b.start);
|
|
3562
|
+
}
|
|
3563
|
+
|
|
3564
|
+
rewriteModuleExportStatement(node, code, sourceContext) {
|
|
3565
|
+
// `export const X = 1` / `export function f() {}` / `export class C {}`
|
|
3566
|
+
// become the bare declaration.
|
|
3567
|
+
if (node.type === 'ExportNamedDeclaration' && node.declaration) {
|
|
3568
|
+
return code.slice(node.declaration.start, node.declaration.end);
|
|
3569
|
+
}
|
|
3570
|
+
|
|
3571
|
+
// A re-export (`export { x } from './y'`, `export * from './y'`) has no
|
|
3572
|
+
// local declaration to keep, and the factory has no exports object to
|
|
3573
|
+
// attach one to. Dropping it costs nothing inside the bundle, but it means
|
|
3574
|
+
// this file is acting as a barrel — worth saying so out loud.
|
|
3575
|
+
if (node.source) {
|
|
3576
|
+
console.warn(this.buildImportWarningMessage(
|
|
3577
|
+
`Warning: Dropping re-export '${code.slice(node.start, node.end).split('\n')[0].trim()}' from a component file (not supported in bundles)`,
|
|
3578
|
+
sourceContext
|
|
3579
|
+
));
|
|
3580
|
+
return '';
|
|
3581
|
+
}
|
|
3582
|
+
|
|
3583
|
+
// Plain `export { a, b }` — the declarations of a and b stay in the file,
|
|
3584
|
+
// so removing the statement loses nothing.
|
|
3585
|
+
return '';
|
|
3586
|
+
}
|
|
3587
|
+
|
|
3588
|
+
/**
|
|
3589
|
+
* Last-resort strip for sources Babel cannot parse. Anchored to the start of
|
|
3590
|
+
* a line and required to be followed by a declaration keyword, so `export`
|
|
3591
|
+
* inside a string, a comment or a longer identifier is left alone.
|
|
3592
|
+
* @param {string} code
|
|
3593
|
+
* @returns {string}
|
|
3594
|
+
*/
|
|
3595
|
+
stripModuleExportsWithFallbackRegex(code) {
|
|
3596
|
+
return code.replace(
|
|
3597
|
+
/^([ \t]*)export[ \t]+(?=(?:const|let|var|class|function|async[ \t]+function)\b)/gm,
|
|
3598
|
+
'$1'
|
|
3599
|
+
);
|
|
3600
|
+
}
|
|
3601
|
+
|
|
3039
3602
|
async loadComponentsMap() {
|
|
3040
3603
|
const componentsConfigPath = path.join(this.componentsPath, 'components.js');
|
|
3041
3604
|
if (!await fs.pathExists(componentsConfigPath)) {
|