slicejs-cli 3.8.1 → 4.0.1
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 +5 -0
- package/commands/build/build.js +38 -1
- package/commands/bundle/bundle.js +4 -1
- package/commands/doctor/doctor.js +115 -68
- package/commands/getComponent/getComponent.js +11 -1
- package/commands/types/types.js +86 -22
- package/commands/utils/analyzeSource.js +18 -10
- package/commands/utils/bundling/BundleGenerator.js +837 -157
- package/commands/utils/bundling/DependencyAnalyzer.js +42 -7
- package/commands/utils/bundling/ExternalModuleBundler.js +298 -0
- package/commands/utils/compressAssets.js +103 -0
- package/package.json +2 -1
|
@@ -5,7 +5,27 @@ import crypto from 'crypto';
|
|
|
5
5
|
import { parse } from '@babel/parser';
|
|
6
6
|
import traverse from '@babel/traverse';
|
|
7
7
|
import { minify as terserMinify } from 'terser';
|
|
8
|
-
import { getSrcPath, getComponentsJsPath, getDistPath, getConfigPath } from '../PathHelper.js';
|
|
8
|
+
import { getSrcPath, getComponentsJsPath, getDistPath, getConfigPath, getProjectRoot } from '../PathHelper.js';
|
|
9
|
+
import ExternalModuleBundler from './ExternalModuleBundler.js';
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Build timestamp honoring SOURCE_DATE_EPOCH for reproducible builds. When the
|
|
13
|
+
* env var is set (integer seconds since the Unix epoch — the reproducible-builds
|
|
14
|
+
* convention), every build embeds the same timestamp, so bundle content and its
|
|
15
|
+
* integrity hash are byte-identical across runs. Otherwise the current time is
|
|
16
|
+
* used.
|
|
17
|
+
* @returns {string} ISO-8601 timestamp
|
|
18
|
+
*/
|
|
19
|
+
export function resolveBuildTimestamp() {
|
|
20
|
+
const raw = process.env.SOURCE_DATE_EPOCH;
|
|
21
|
+
if (raw != null && String(raw).trim() !== '') {
|
|
22
|
+
const seconds = Number(raw);
|
|
23
|
+
if (Number.isFinite(seconds) && seconds >= 0) {
|
|
24
|
+
return new Date(seconds * 1000).toISOString();
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
return new Date().toISOString();
|
|
28
|
+
}
|
|
9
29
|
|
|
10
30
|
export default class BundleGenerator {
|
|
11
31
|
constructor(moduleUrl, analysisData, options = {}) {
|
|
@@ -20,12 +40,30 @@ export default class BundleGenerator {
|
|
|
20
40
|
this.componentsPath = path.dirname(getComponentsJsPath(moduleUrl));
|
|
21
41
|
this.options = {
|
|
22
42
|
minify: !!options.minify,
|
|
23
|
-
obfuscate: !!options.obfuscate
|
|
43
|
+
obfuscate: !!options.obfuscate,
|
|
44
|
+
// Emit a source map next to each minified bundle (`--sourcemap`). Off by
|
|
45
|
+
// default so production source isn't shipped unless asked (matches Vite).
|
|
46
|
+
sourcemap: !!options.sourcemap,
|
|
47
|
+
// Insert a content hash into each bundle filename (`--hash-filenames`) for
|
|
48
|
+
// immutable CDN caching. Off by default to keep stable bundle names.
|
|
49
|
+
hashFilenames: !!options.hashFilenames
|
|
24
50
|
};
|
|
25
51
|
this.format = 'v2';
|
|
26
52
|
this.sliceConfig = this.resolveSliceConfig();
|
|
27
53
|
this.loadingPolicy = this.resolveLoadingPolicy();
|
|
28
54
|
|
|
55
|
+
// When true, an unresolved node_modules dependency fails the build instead
|
|
56
|
+
// of warning + emitting an empty module. Driven by `slice build --strict-external`.
|
|
57
|
+
this.strictExternal = !!options.strictExternal;
|
|
58
|
+
|
|
59
|
+
// Bare-package (node_modules) import support is always on. Bare imports are
|
|
60
|
+
// resolved+bundled with esbuild (see ExternalModuleBundler) and registered
|
|
61
|
+
// under SLICE_BUNDLE_DEPENDENCIES keyed by the bare specifier, mirroring the
|
|
62
|
+
// relative-dependency runtime contract.
|
|
63
|
+
this.externalBundler = null; // lazily constructed
|
|
64
|
+
this.externalModulesByName = new Map(); // bareName -> wrapped module expression
|
|
65
|
+
this.externalResolutionErrors = new Map(); // bareName -> error message
|
|
66
|
+
|
|
29
67
|
// Configuration
|
|
30
68
|
this.config = {
|
|
31
69
|
maxCriticalSize: 50 * 1024, // 50KB
|
|
@@ -44,6 +82,10 @@ export default class BundleGenerator {
|
|
|
44
82
|
dependencyUsage: new Map(),
|
|
45
83
|
sharedDependencySet: new Set(),
|
|
46
84
|
bundleKeysUsingSharedDependencies: new Set(),
|
|
85
|
+
// True when the critical bundle itself uses a shared dependency, so it
|
|
86
|
+
// resolves it from the vendor-shared bundle (loaded first) instead of
|
|
87
|
+
// inlining its own copy.
|
|
88
|
+
criticalUsesShared: false,
|
|
47
89
|
bundle: null
|
|
48
90
|
};
|
|
49
91
|
|
|
@@ -133,6 +175,9 @@ export default class BundleGenerator {
|
|
|
133
175
|
// 1. Determine optimal strategy
|
|
134
176
|
this.determineStrategy();
|
|
135
177
|
|
|
178
|
+
// 1b. Resolve external (node_modules) dependencies up front, once per package.
|
|
179
|
+
await this.prepareExternalModules();
|
|
180
|
+
|
|
136
181
|
// 2. Identify critical components
|
|
137
182
|
this.identifyCriticalComponents();
|
|
138
183
|
|
|
@@ -153,6 +198,16 @@ export default class BundleGenerator {
|
|
|
153
198
|
// 6. Generate configuration
|
|
154
199
|
const config = this.generateBundleConfig(frameworkBundle);
|
|
155
200
|
|
|
201
|
+
// 6b. Fail loudly on a self-inconsistent config (dangling refs / orphan
|
|
202
|
+
// bundles) instead of silently shipping dead files or broken references.
|
|
203
|
+
const integrity = this.collectBundleReferentialIssues(config);
|
|
204
|
+
if (integrity.dangling.length > 0) {
|
|
205
|
+
console.warn(`Warning: bundle config references missing bundle(s): ${integrity.dangling.join(', ')}`);
|
|
206
|
+
}
|
|
207
|
+
if (integrity.orphans.length > 0) {
|
|
208
|
+
console.warn(`Warning: emitted bundle(s) never referenced by any route: ${integrity.orphans.join(', ')}`);
|
|
209
|
+
}
|
|
210
|
+
|
|
156
211
|
console.log('✅ Bundles generated successfully');
|
|
157
212
|
|
|
158
213
|
return {
|
|
@@ -219,7 +274,7 @@ export default class BundleGenerator {
|
|
|
219
274
|
// Fill critical bundle up to limit
|
|
220
275
|
for (const comp of candidates) {
|
|
221
276
|
const dependencies = this.getComponentDependencies(comp);
|
|
222
|
-
const totalSize = comp
|
|
277
|
+
const totalSize = this.budgetSizeOf(comp) + dependencies.reduce((sum, dep) => sum + this.budgetSizeOf(dep), 0);
|
|
223
278
|
const totalCount = 1 + dependencies.length;
|
|
224
279
|
|
|
225
280
|
const wouldExceedSize = this.bundles.critical.size + totalSize > this.config.maxCriticalSize;
|
|
@@ -230,20 +285,20 @@ export default class BundleGenerator {
|
|
|
230
285
|
// Add component and its dependencies
|
|
231
286
|
if (!this.bundles.critical.components.find(c => c.name === comp.name)) {
|
|
232
287
|
this.bundles.critical.components.push(comp);
|
|
233
|
-
this.bundles.critical.size += comp
|
|
288
|
+
this.bundles.critical.size += this.budgetSizeOf(comp);
|
|
234
289
|
}
|
|
235
290
|
|
|
236
291
|
for (const dep of dependencies) {
|
|
237
292
|
if (!this.bundles.critical.components.find(c => c.name === dep.name)) {
|
|
238
293
|
this.bundles.critical.components.push(dep);
|
|
239
|
-
this.bundles.critical.size += dep
|
|
294
|
+
this.bundles.critical.size += this.budgetSizeOf(dep);
|
|
240
295
|
}
|
|
241
296
|
}
|
|
242
297
|
}
|
|
243
298
|
|
|
244
299
|
if (this.loadingPolicy === 'disabled') {
|
|
245
300
|
this.bundles.critical.components = this.bundles.critical.components.filter((comp) => comp.name !== 'Loading');
|
|
246
|
-
this.bundles.critical.size = this.bundles.critical.components
|
|
301
|
+
this.bundles.critical.size = this.componentsBudgetSize(this.bundles.critical.components);
|
|
247
302
|
}
|
|
248
303
|
|
|
249
304
|
console.log(`✓ Critical bundle: ${this.bundles.critical.components.length} components, ${(this.bundles.critical.size / 1024).toFixed(1)} KB`);
|
|
@@ -264,7 +319,10 @@ export default class BundleGenerator {
|
|
|
264
319
|
this.extractSharedComponents(criticalNames);
|
|
265
320
|
this.rebalanceBundlesByBudget(this.bundles.routes, {
|
|
266
321
|
maxBundleSize: this.config.maxRouteBundleSize,
|
|
267
|
-
maxRequests: this.config.maxRouteRequests
|
|
322
|
+
maxRequests: this.config.maxRouteRequests,
|
|
323
|
+
// shared-core is referenced by route bundles via `dependencies: ['shared-core']`;
|
|
324
|
+
// pin it so the rebalancer never splits/merges it and breaks those references.
|
|
325
|
+
pinnedKeys: new Set(['shared-core'])
|
|
268
326
|
});
|
|
269
327
|
}
|
|
270
328
|
|
|
@@ -566,16 +624,50 @@ export default class BundleGenerator {
|
|
|
566
624
|
}
|
|
567
625
|
}
|
|
568
626
|
|
|
627
|
+
/**
|
|
628
|
+
* Size a component contributes to a bundle. Uses the bundled-code size
|
|
629
|
+
* (js+html+css) so a sidecar asset in the component folder can't inflate the
|
|
630
|
+
* budget; falls back to the folder size for synthetic components (tests).
|
|
631
|
+
*/
|
|
632
|
+
budgetSizeOf(component) {
|
|
633
|
+
if (!component) return 0;
|
|
634
|
+
return typeof component.codeSize === 'number' ? component.codeSize : (component.size || 0);
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
componentsBudgetSize(components = []) {
|
|
638
|
+
return components.reduce((sum, component) => sum + this.budgetSizeOf(component), 0);
|
|
639
|
+
}
|
|
640
|
+
|
|
569
641
|
rebalanceBundlesByBudget(bundles, limits = {}) {
|
|
570
642
|
const maxBundleSize = limits.maxBundleSize || this.config.maxRouteBundleSize;
|
|
571
643
|
const maxRequests = limits.maxRequests || this.config.maxRouteRequests;
|
|
644
|
+
// Bundles other bundles reference by key (e.g. `shared-core`) must NOT be
|
|
645
|
+
// split or merged: splitting orphans the `--pN` parts and leaves every
|
|
646
|
+
// referrer pointing at a bundle key that no longer exists; merging would
|
|
647
|
+
// delete the key entirely. They pass through untouched (only their size is
|
|
648
|
+
// recomputed on the code metric).
|
|
649
|
+
const pinnedKeys = limits.pinnedKeys instanceof Set
|
|
650
|
+
? limits.pinnedKeys
|
|
651
|
+
: new Set(limits.pinnedKeys || []);
|
|
572
652
|
const orderedEntries = Object.entries(bundles)
|
|
573
653
|
.sort(([a], [b]) => a.localeCompare(b));
|
|
574
654
|
const rebalanced = {};
|
|
655
|
+
const pinned = {};
|
|
575
656
|
|
|
576
657
|
for (const [key, bundle] of orderedEntries) {
|
|
577
658
|
const sortedComponents = this.dedupeComponentsByName(bundle.components || []);
|
|
578
|
-
const totalSize =
|
|
659
|
+
const totalSize = this.componentsBudgetSize(sortedComponents);
|
|
660
|
+
|
|
661
|
+
if (pinnedKeys.has(key)) {
|
|
662
|
+
pinned[key] = {
|
|
663
|
+
...bundle,
|
|
664
|
+
components: sortedComponents,
|
|
665
|
+
size: totalSize,
|
|
666
|
+
file: `slice-bundle.${this.routeToFileName(key)}.js`
|
|
667
|
+
};
|
|
668
|
+
continue;
|
|
669
|
+
}
|
|
670
|
+
|
|
579
671
|
if (totalSize <= maxBundleSize || sortedComponents.length <= 1) {
|
|
580
672
|
rebalanced[key] = {
|
|
581
673
|
...bundle,
|
|
@@ -591,7 +683,7 @@ export default class BundleGenerator {
|
|
|
591
683
|
let currentSize = 0;
|
|
592
684
|
|
|
593
685
|
for (const component of sortedComponents) {
|
|
594
|
-
const nextSize = currentSize + component
|
|
686
|
+
const nextSize = currentSize + this.budgetSizeOf(component);
|
|
595
687
|
const shouldFlush = currentChunk.length > 0 && nextSize > maxBundleSize;
|
|
596
688
|
|
|
597
689
|
if (shouldFlush) {
|
|
@@ -608,7 +700,7 @@ export default class BundleGenerator {
|
|
|
608
700
|
}
|
|
609
701
|
|
|
610
702
|
currentChunk.push(component);
|
|
611
|
-
currentSize += component
|
|
703
|
+
currentSize += this.budgetSizeOf(component);
|
|
612
704
|
}
|
|
613
705
|
|
|
614
706
|
if (currentChunk.length > 0) {
|
|
@@ -622,8 +714,11 @@ export default class BundleGenerator {
|
|
|
622
714
|
}
|
|
623
715
|
}
|
|
624
716
|
|
|
717
|
+
// Merge only among non-pinned bundles, but count pinned ones toward the
|
|
718
|
+
// request budget. Never merge below one non-pinned bundle.
|
|
719
|
+
const pinnedCount = Object.keys(pinned).length;
|
|
625
720
|
const keys = Object.keys(rebalanced).sort((a, b) => a.localeCompare(b));
|
|
626
|
-
while (keys.length > maxRequests) {
|
|
721
|
+
while (keys.length + pinnedCount > maxRequests && keys.length > 1) {
|
|
627
722
|
const lastKey = keys.pop();
|
|
628
723
|
const targetKey = keys[keys.length - 1];
|
|
629
724
|
if (!lastKey || !targetKey) break;
|
|
@@ -641,14 +736,14 @@ export default class BundleGenerator {
|
|
|
641
736
|
);
|
|
642
737
|
|
|
643
738
|
rebalanced[targetKey].components = mergedComponents;
|
|
644
|
-
rebalanced[targetKey].size =
|
|
739
|
+
rebalanced[targetKey].size = this.componentsBudgetSize(mergedComponents);
|
|
645
740
|
rebalanced[targetKey].dependencies = mergedDependencies;
|
|
646
741
|
this.setBundlePaths(rebalanced[targetKey], mergedPaths);
|
|
647
742
|
delete rebalanced[lastKey];
|
|
648
743
|
}
|
|
649
744
|
|
|
650
745
|
Object.keys(bundles).forEach((key) => delete bundles[key]);
|
|
651
|
-
for (const [key, bundle] of Object.entries(rebalanced).sort(([a], [b]) => a.localeCompare(b))) {
|
|
746
|
+
for (const [key, bundle] of Object.entries({ ...pinned, ...rebalanced }).sort(([a], [b]) => a.localeCompare(b))) {
|
|
652
747
|
bundles[key] = bundle;
|
|
653
748
|
}
|
|
654
749
|
|
|
@@ -736,13 +831,9 @@ export default class BundleGenerator {
|
|
|
736
831
|
'critical',
|
|
737
832
|
null
|
|
738
833
|
);
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
null,
|
|
743
|
-
'critical',
|
|
744
|
-
criticalFile.file
|
|
745
|
-
);
|
|
834
|
+
// Store the emitted (possibly content-hashed) filename so the config and
|
|
835
|
+
// the runtime loader reference the file that was actually written.
|
|
836
|
+
this.bundles.critical.file = criticalFile.file;
|
|
746
837
|
this.bundles.critical.integrity = `sha256:${criticalFile.hash}`;
|
|
747
838
|
this.bundles.critical.hash = criticalFile.hash;
|
|
748
839
|
files.push(criticalFile);
|
|
@@ -757,15 +848,12 @@ export default class BundleGenerator {
|
|
|
757
848
|
const routeFile = await this.createBundleFile(
|
|
758
849
|
bundle.components,
|
|
759
850
|
'route',
|
|
760
|
-
routeIdentifier
|
|
851
|
+
routeIdentifier,
|
|
852
|
+
routeKey
|
|
761
853
|
);
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
if (matchingBundle) {
|
|
766
|
-
matchingBundle.hash = routeFile.hash;
|
|
767
|
-
matchingBundle.integrity = routeIntegrity;
|
|
768
|
-
}
|
|
854
|
+
bundle.file = routeFile.file;
|
|
855
|
+
bundle.hash = routeFile.hash;
|
|
856
|
+
bundle.integrity = `sha256:${routeFile.hash}`;
|
|
769
857
|
files.push(routeFile);
|
|
770
858
|
}
|
|
771
859
|
|
|
@@ -780,6 +868,7 @@ export default class BundleGenerator {
|
|
|
780
868
|
this.vendorShared.dependencyUsage = usageIndex;
|
|
781
869
|
this.vendorShared.sharedDependencySet = sharedDependencySet;
|
|
782
870
|
this.vendorShared.bundleKeysUsingSharedDependencies = new Set();
|
|
871
|
+
this.vendorShared.criticalUsesShared = false;
|
|
783
872
|
|
|
784
873
|
if (sharedDependencySet.size === 0) {
|
|
785
874
|
return;
|
|
@@ -792,6 +881,10 @@ export default class BundleGenerator {
|
|
|
792
881
|
}
|
|
793
882
|
}
|
|
794
883
|
|
|
884
|
+
// The critical bundle participates in sharing too: if it uses a shared dep,
|
|
885
|
+
// it must load vendor-shared first and resolve from it (no inline copy).
|
|
886
|
+
this.vendorShared.criticalUsesShared = this.vendorShared.bundleKeysUsingSharedDependencies.has('critical');
|
|
887
|
+
|
|
795
888
|
for (const bundleKey of this.vendorShared.bundleKeysUsingSharedDependencies) {
|
|
796
889
|
const bundle = this.bundles.routes[bundleKey];
|
|
797
890
|
if (!bundle) continue;
|
|
@@ -802,7 +895,15 @@ export default class BundleGenerator {
|
|
|
802
895
|
async collectRouteExternalDependencyIndex() {
|
|
803
896
|
const routeDependencyIndex = {};
|
|
804
897
|
|
|
805
|
-
|
|
898
|
+
// The critical bundle participates in shared-dependency detection alongside
|
|
899
|
+
// the route bundles: a package used by critical AND a route is extracted
|
|
900
|
+
// once into vendor-shared instead of being inlined in both.
|
|
901
|
+
const indexedBundles = [
|
|
902
|
+
...Object.entries(this.bundles.routes),
|
|
903
|
+
['critical', { components: this.bundles.critical.components || [] }]
|
|
904
|
+
];
|
|
905
|
+
|
|
906
|
+
for (const [bundleKey, bundle] of indexedBundles) {
|
|
806
907
|
routeDependencyIndex[bundleKey] = {};
|
|
807
908
|
const uniqueComponents = this.dedupeComponentsByName(bundle.components || []);
|
|
808
909
|
|
|
@@ -811,15 +912,28 @@ export default class BundleGenerator {
|
|
|
811
912
|
const jsPath = path.join(comp.path, `${fileBaseName}.js`);
|
|
812
913
|
if (!await fs.pathExists(jsPath)) continue;
|
|
813
914
|
const jsContent = await fs.readFile(jsPath, 'utf-8');
|
|
915
|
+
// Relative helper modules (inline content) + bare node_modules imports
|
|
916
|
+
// (pre-bundled esbuild expression), discovered in the component and its
|
|
917
|
+
// relative helpers. Both are candidates for extraction into the shared
|
|
918
|
+
// vendor bundle when used across multiple routes.
|
|
814
919
|
const dependencies = await this.buildDependencyContents(jsContent, comp.path);
|
|
815
920
|
for (const [depName, depEntry] of Object.entries(dependencies || {})) {
|
|
921
|
+
const isExternal = !!(depEntry && typeof depEntry === 'object' && depEntry.external);
|
|
922
|
+
// For external deps the shareable payload is the pre-bundled
|
|
923
|
+
// expression; skip any that failed to resolve (no expression).
|
|
924
|
+
const content = isExternal
|
|
925
|
+
? (this.externalModulesByName.get(depName) || '')
|
|
926
|
+
: (depEntry?.content || '');
|
|
927
|
+
if (isExternal && !content) continue;
|
|
928
|
+
|
|
816
929
|
if (!routeDependencyIndex[bundleKey][depName]) {
|
|
817
|
-
routeDependencyIndex[bundleKey][depName] =
|
|
930
|
+
routeDependencyIndex[bundleKey][depName] = { content, external: isExternal };
|
|
818
931
|
}
|
|
819
932
|
if (!this.vendorShared.dependencyModules.has(depName)) {
|
|
820
933
|
this.vendorShared.dependencyModules.set(depName, {
|
|
821
934
|
name: depName,
|
|
822
|
-
content
|
|
935
|
+
content,
|
|
936
|
+
external: isExternal
|
|
823
937
|
});
|
|
824
938
|
}
|
|
825
939
|
}
|
|
@@ -839,7 +953,8 @@ export default class BundleGenerator {
|
|
|
839
953
|
name: dependencyName,
|
|
840
954
|
bundleKeys: new Set(),
|
|
841
955
|
bundleCount: 0,
|
|
842
|
-
content: dependencyEntry?.content || ''
|
|
956
|
+
content: dependencyEntry?.content || '',
|
|
957
|
+
external: !!dependencyEntry?.external
|
|
843
958
|
});
|
|
844
959
|
}
|
|
845
960
|
const entry = usage.get(dependencyName);
|
|
@@ -856,13 +971,18 @@ export default class BundleGenerator {
|
|
|
856
971
|
|
|
857
972
|
for (const [dependencyName, entry] of usageIndex.entries()) {
|
|
858
973
|
if ((entry?.bundleCount || 0) < this.config.minVendorSharedUsage) continue;
|
|
859
|
-
|
|
860
|
-
|
|
861
|
-
|
|
862
|
-
|
|
863
|
-
|
|
864
|
-
|
|
865
|
-
|
|
974
|
+
// External deps are already fully-bundled esbuild expressions — measure
|
|
975
|
+
// them directly. Relative helper modules are measured after the export
|
|
976
|
+
// rewrite, matching how they will actually be emitted.
|
|
977
|
+
const measuredSize = entry?.external
|
|
978
|
+
? Buffer.byteLength(entry?.content || '', 'utf-8')
|
|
979
|
+
: Buffer.byteLength(
|
|
980
|
+
// Size probe only — nothing here is emitted, so it must stay quiet
|
|
981
|
+
// rather than double-report warnings the real emit already covers.
|
|
982
|
+
this.transformDependencyContent(entry?.content || '', '__sliceVendorSharedProbe', dependencyName, { silent: true }),
|
|
983
|
+
'utf-8'
|
|
984
|
+
);
|
|
985
|
+
if (measuredSize < this.config.minVendorSharedTransformedSize) continue;
|
|
866
986
|
shared.add(dependencyName);
|
|
867
987
|
}
|
|
868
988
|
|
|
@@ -873,10 +993,14 @@ export default class BundleGenerator {
|
|
|
873
993
|
const selectedModules = Array.from(sharedDependencySet)
|
|
874
994
|
.sort((a, b) => a.localeCompare(b))
|
|
875
995
|
.map((dependencyName) => {
|
|
876
|
-
const
|
|
877
|
-
const
|
|
878
|
-
const content =
|
|
879
|
-
|
|
996
|
+
const usageEntry = this.vendorShared.dependencyUsage.get(dependencyName);
|
|
997
|
+
const collectedEntry = this.vendorShared.dependencyModules.get(dependencyName);
|
|
998
|
+
const content = usageEntry?.content || collectedEntry?.content || '';
|
|
999
|
+
// External modules are emitted from their pre-bundled expression (looked
|
|
1000
|
+
// up by name in buildV2DependencyModuleBlockFromModules), so the flag
|
|
1001
|
+
// must survive here.
|
|
1002
|
+
const external = !!(usageEntry?.external || collectedEntry?.external);
|
|
1003
|
+
return { name: dependencyName, content, external };
|
|
880
1004
|
})
|
|
881
1005
|
.filter((entry) => !!entry.content);
|
|
882
1006
|
|
|
@@ -894,20 +1018,15 @@ export default class BundleGenerator {
|
|
|
894
1018
|
}
|
|
895
1019
|
|
|
896
1020
|
async createVendorSharedDependencyBundleFile(sharedDependencySet) {
|
|
897
|
-
const
|
|
898
|
-
const filePath = path.join(this.bundlesPath, fileName);
|
|
1021
|
+
const baseFileName = this.vendorShared.file;
|
|
899
1022
|
const bundleContent = this.generateVendorSharedDependencyBundleContent(sharedDependencySet);
|
|
900
|
-
const
|
|
901
|
-
await fs.ensureDir(path.dirname(filePath));
|
|
902
|
-
await fs.writeFile(filePath, finalContent, 'utf-8');
|
|
903
|
-
|
|
904
|
-
const hash = crypto.createHash('sha256').update(finalContent).digest('hex');
|
|
1023
|
+
const { file, path: filePath, hash, rawSize } = await this.emitBundleArtifact(baseFileName, bundleContent);
|
|
905
1024
|
|
|
906
1025
|
return {
|
|
907
1026
|
name: 'vendor-shared',
|
|
908
|
-
file
|
|
1027
|
+
file,
|
|
909
1028
|
path: filePath,
|
|
910
|
-
size:
|
|
1029
|
+
size: rawSize,
|
|
911
1030
|
hash,
|
|
912
1031
|
integrity: `sha256:${hash}`,
|
|
913
1032
|
componentCount: 0
|
|
@@ -917,41 +1036,49 @@ export default class BundleGenerator {
|
|
|
917
1036
|
/**
|
|
918
1037
|
* Creates a bundle file
|
|
919
1038
|
*/
|
|
920
|
-
async createBundleFile(components, type, routePath) {
|
|
921
|
-
|
|
922
|
-
|
|
923
|
-
|
|
1039
|
+
async createBundleFile(components, type, routePath, bundleKey = null) {
|
|
1040
|
+
// The key — not the route path — names the file. Size-split parts of one
|
|
1041
|
+
// route (`playground--p1`, `--p2`) share a `path`, so deriving the name from
|
|
1042
|
+
// the path makes every part collide on `slice-bundle.playground.js` and the
|
|
1043
|
+
// last one written wins, silently dropping the other parts' components.
|
|
1044
|
+
const routeKey = bundleKey
|
|
1045
|
+
? this.routeToFileName(bundleKey)
|
|
1046
|
+
: (routePath ? this.routeToFileName(routePath) : 'critical');
|
|
1047
|
+
const baseFileName = `slice-bundle.${routeKey}.js`;
|
|
924
1048
|
|
|
925
1049
|
const bundleContent = await this.generateBundleContent(
|
|
926
1050
|
components,
|
|
927
1051
|
type,
|
|
928
1052
|
routePath,
|
|
929
1053
|
routeKey,
|
|
930
|
-
|
|
1054
|
+
baseFileName
|
|
931
1055
|
);
|
|
932
1056
|
|
|
933
|
-
const
|
|
934
|
-
|
|
935
|
-
await fs.ensureDir(path.dirname(filePath));
|
|
936
|
-
await fs.writeFile(filePath, finalContent, 'utf-8');
|
|
937
|
-
|
|
938
|
-
const hash = crypto.createHash('sha256').update(finalContent).digest('hex');
|
|
1057
|
+
const { file, path: filePath, hash, rawSize } = await this.emitBundleArtifact(baseFileName, bundleContent);
|
|
939
1058
|
|
|
940
1059
|
return {
|
|
941
1060
|
name: routeKey,
|
|
942
|
-
file
|
|
1061
|
+
file,
|
|
943
1062
|
path: filePath,
|
|
944
|
-
size:
|
|
1063
|
+
size: rawSize,
|
|
945
1064
|
hash,
|
|
946
1065
|
componentCount: components.length
|
|
947
1066
|
};
|
|
948
1067
|
}
|
|
949
1068
|
|
|
1069
|
+
/**
|
|
1070
|
+
* Minifies/obfuscates a bundle and (when `--sourcemap` is on) produces a
|
|
1071
|
+
* source map. Returns `{ code, map }`; `map` is the raw source-map JSON string
|
|
1072
|
+
* or null. The `//# sourceMappingURL` comment is NOT appended here — the
|
|
1073
|
+
* caller does that once it knows the final (possibly hashed) filename.
|
|
1074
|
+
* @returns {Promise<{ code: string, map: string|null }>}
|
|
1075
|
+
*/
|
|
950
1076
|
async applyBundleTransforms(bundleContent, fileName) {
|
|
951
1077
|
if (!this.options.minify && !this.options.obfuscate) {
|
|
952
|
-
return bundleContent;
|
|
1078
|
+
return { code: bundleContent, map: null };
|
|
953
1079
|
}
|
|
954
1080
|
|
|
1081
|
+
const wantMap = !!this.options.sourcemap;
|
|
955
1082
|
const options = {
|
|
956
1083
|
parse: {
|
|
957
1084
|
ecma: 2022
|
|
@@ -970,7 +1097,11 @@ export default class BundleGenerator {
|
|
|
970
1097
|
format: {
|
|
971
1098
|
comments: false,
|
|
972
1099
|
ecma: 2022
|
|
973
|
-
}
|
|
1100
|
+
},
|
|
1101
|
+
// Map the minified output back to the readable pre-minified bundle
|
|
1102
|
+
// (embedded via includeSources so DevTools shows it without a sidecar
|
|
1103
|
+
// source). The URL comment is appended by the caller.
|
|
1104
|
+
...(wantMap ? { sourceMap: { includeSources: true, filename: fileName } } : {})
|
|
974
1105
|
};
|
|
975
1106
|
|
|
976
1107
|
let result;
|
|
@@ -1003,10 +1134,312 @@ export default class BundleGenerator {
|
|
|
1003
1134
|
throw new Error(`Terser failed for ${fileName}: ${result.error.message}. Saved bundle to ${tmpPath}`);
|
|
1004
1135
|
}
|
|
1005
1136
|
|
|
1006
|
-
return result.code || bundleContent;
|
|
1137
|
+
return { code: result.code || bundleContent, map: wantMap ? (result.map || null) : null };
|
|
1138
|
+
}
|
|
1139
|
+
|
|
1140
|
+
/**
|
|
1141
|
+
* Inserts an 8-char content hash into a bundle filename for cache-busting
|
|
1142
|
+
* (`slice-bundle.home.js` → `slice-bundle.home.a1b2c3d4.js`), matching how
|
|
1143
|
+
* traditional bundlers name immutable assets. Only active under `--hash-filenames`.
|
|
1144
|
+
*/
|
|
1145
|
+
hashBundleFileName(baseFileName, code) {
|
|
1146
|
+
if (!this.options.hashFilenames) return baseFileName;
|
|
1147
|
+
const hash = crypto.createHash('sha256').update(code).digest('hex').slice(0, 8);
|
|
1148
|
+
return baseFileName.replace(/\.js$/, `.${hash}.js`);
|
|
1149
|
+
}
|
|
1150
|
+
|
|
1151
|
+
/**
|
|
1152
|
+
* Central bundle writer: transforms the raw content, resolves the final
|
|
1153
|
+
* (optionally content-hashed) filename, appends the source-map URL + writes the
|
|
1154
|
+
* `.map` when enabled, writes the `.js`, and returns the emitted name + paths +
|
|
1155
|
+
* integrity hash. Every bundle file (route, critical, vendor-shared, framework)
|
|
1156
|
+
* goes through here so cache-busting and source maps apply uniformly.
|
|
1157
|
+
* @returns {Promise<{ file: string, path: string, hash: string, rawSize: number }>}
|
|
1158
|
+
*/
|
|
1159
|
+
async emitBundleArtifact(baseFileName, rawContent) {
|
|
1160
|
+
const { code, map } = await this.applyBundleTransforms(rawContent, baseFileName);
|
|
1161
|
+
const fileName = this.hashBundleFileName(baseFileName, code);
|
|
1162
|
+
let finalCode = code;
|
|
1163
|
+
if (map) {
|
|
1164
|
+
finalCode += `\n//# sourceMappingURL=${fileName}.map\n`;
|
|
1165
|
+
}
|
|
1166
|
+
const filePath = path.join(this.bundlesPath, fileName);
|
|
1167
|
+
await fs.ensureDir(path.dirname(filePath));
|
|
1168
|
+
await fs.writeFile(filePath, finalCode, 'utf-8');
|
|
1169
|
+
if (map) {
|
|
1170
|
+
await fs.writeFile(path.join(this.bundlesPath, `${fileName}.map`), map, 'utf-8');
|
|
1171
|
+
}
|
|
1172
|
+
const hash = crypto.createHash('sha256').update(finalCode).digest('hex');
|
|
1173
|
+
return { file: fileName, path: filePath, hash, rawSize: Buffer.byteLength(rawContent, 'utf-8') };
|
|
1007
1174
|
}
|
|
1008
1175
|
|
|
1009
1176
|
|
|
1177
|
+
/**
|
|
1178
|
+
* Bare-package (node_modules) imports are always resolved and bundled — no
|
|
1179
|
+
* configuration needed, mirroring how a React/Vite project imports npm
|
|
1180
|
+
* packages. Kept as a method so call sites read intently.
|
|
1181
|
+
*/
|
|
1182
|
+
isExternalDependenciesEnabled() {
|
|
1183
|
+
return true;
|
|
1184
|
+
}
|
|
1185
|
+
|
|
1186
|
+
/**
|
|
1187
|
+
* Every resolvable bare specifier is allowed. Retained so call sites are
|
|
1188
|
+
* uniform; there is no allowlist to configure.
|
|
1189
|
+
*/
|
|
1190
|
+
isExternalAllowed() {
|
|
1191
|
+
return true;
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
getExternalBundler() {
|
|
1195
|
+
if (!this.externalBundler) {
|
|
1196
|
+
this.externalBundler = new ExternalModuleBundler({
|
|
1197
|
+
resolveDir: getProjectRoot(this.moduleUrl),
|
|
1198
|
+
minify: this.options.minify
|
|
1199
|
+
});
|
|
1200
|
+
}
|
|
1201
|
+
return this.externalBundler;
|
|
1202
|
+
}
|
|
1203
|
+
|
|
1204
|
+
/**
|
|
1205
|
+
* Extracts bare-package imports from a component's source. Returns one entry
|
|
1206
|
+
* per unique bare specifier with the merged local bindings and whether any
|
|
1207
|
+
* consumer needs the default export (default import or namespace import).
|
|
1208
|
+
* @param {string} code
|
|
1209
|
+
* @returns {Array<{ name: string, bindings: Array, needsDefault: boolean }>}
|
|
1210
|
+
*/
|
|
1211
|
+
analyzeBareImports(code) {
|
|
1212
|
+
const byName = new Map();
|
|
1213
|
+
|
|
1214
|
+
const record = (name, bindings, needsDefault) => {
|
|
1215
|
+
if (!ExternalModuleBundler.isBareSpecifier(name)) return;
|
|
1216
|
+
if (!this.isExternalAllowed(name)) return;
|
|
1217
|
+
if (!byName.has(name)) {
|
|
1218
|
+
byName.set(name, { name, bindings: [], needsDefault: false });
|
|
1219
|
+
}
|
|
1220
|
+
const entry = byName.get(name);
|
|
1221
|
+
entry.bindings.push(...bindings);
|
|
1222
|
+
entry.needsDefault = entry.needsDefault || needsDefault;
|
|
1223
|
+
};
|
|
1224
|
+
|
|
1225
|
+
try {
|
|
1226
|
+
const ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
1227
|
+
traverse.default(ast, {
|
|
1228
|
+
ImportDeclaration(pathNode) {
|
|
1229
|
+
const source = pathNode.node.source?.value;
|
|
1230
|
+
if (typeof source !== 'string') return;
|
|
1231
|
+
|
|
1232
|
+
const bindings = [];
|
|
1233
|
+
let needsDefault = false;
|
|
1234
|
+
|
|
1235
|
+
for (const spec of pathNode.node.specifiers || []) {
|
|
1236
|
+
if (spec.type === 'ImportDefaultSpecifier') {
|
|
1237
|
+
bindings.push({ type: 'default', importedName: 'default', localName: spec.local.name });
|
|
1238
|
+
needsDefault = true;
|
|
1239
|
+
} else if (spec.type === 'ImportNamespaceSpecifier') {
|
|
1240
|
+
bindings.push({ type: 'namespace', localName: spec.local.name });
|
|
1241
|
+
needsDefault = true; // namespace may read `.default`
|
|
1242
|
+
} else if (spec.type === 'ImportSpecifier') {
|
|
1243
|
+
bindings.push({
|
|
1244
|
+
type: 'named',
|
|
1245
|
+
importedName: spec.imported?.name ?? spec.imported?.value,
|
|
1246
|
+
localName: spec.local.name
|
|
1247
|
+
});
|
|
1248
|
+
}
|
|
1249
|
+
}
|
|
1250
|
+
|
|
1251
|
+
record(source, bindings, needsDefault);
|
|
1252
|
+
},
|
|
1253
|
+
|
|
1254
|
+
// Re-exports from a bare package (`export * from 'pkg'`,
|
|
1255
|
+
// `export { default as X } from 'pkg'`). record() ignores relative
|
|
1256
|
+
// sources, so this only registers the package for bundling; the emission
|
|
1257
|
+
// is handled in transformDependencyStatement.
|
|
1258
|
+
ExportAllDeclaration(pathNode) {
|
|
1259
|
+
const source = pathNode.node.source?.value;
|
|
1260
|
+
if (typeof source === 'string') record(source, [], false);
|
|
1261
|
+
},
|
|
1262
|
+
|
|
1263
|
+
ExportNamedDeclaration(pathNode) {
|
|
1264
|
+
const source = pathNode.node.source?.value;
|
|
1265
|
+
if (typeof source !== 'string') return;
|
|
1266
|
+
// `export { default as X } from 'pkg'` needs the package default built.
|
|
1267
|
+
const needsDefault = (pathNode.node.specifiers || []).some((s) => s.local?.name === 'default');
|
|
1268
|
+
record(source, [], needsDefault);
|
|
1269
|
+
},
|
|
1270
|
+
|
|
1271
|
+
// Dynamic `import('pkg')` — resolves to a module namespace at runtime, so
|
|
1272
|
+
// register it (no static bindings) and request the default so the
|
|
1273
|
+
// namespace exposes `.default` when the package has one.
|
|
1274
|
+
CallExpression(pathNode) {
|
|
1275
|
+
const node = pathNode.node;
|
|
1276
|
+
if (node.callee?.type === 'Import' && node.arguments?.[0]?.type === 'StringLiteral') {
|
|
1277
|
+
record(node.arguments[0].value, [], true);
|
|
1278
|
+
}
|
|
1279
|
+
}
|
|
1280
|
+
});
|
|
1281
|
+
} catch (error) {
|
|
1282
|
+
console.warn(`Warning: Could not analyze bare imports: ${error.message}`);
|
|
1283
|
+
}
|
|
1284
|
+
|
|
1285
|
+
return Array.from(byName.values());
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
/**
|
|
1289
|
+
* Rewrites dynamic `import('pkg')` of bare packages to resolve from the
|
|
1290
|
+
* bundle's registered dependencies (vendor-shared first, then the local
|
|
1291
|
+
* SLICE_BUNDLE_DEPENDENCIES). Relative/absolute dynamic imports are left
|
|
1292
|
+
* untouched.
|
|
1293
|
+
* @param {string} code
|
|
1294
|
+
* @returns {string}
|
|
1295
|
+
*/
|
|
1296
|
+
rewriteDynamicExternalImports(code) {
|
|
1297
|
+
if (!this.isExternalDependenciesEnabled()) return code;
|
|
1298
|
+
|
|
1299
|
+
let ast;
|
|
1300
|
+
try {
|
|
1301
|
+
ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
|
|
1302
|
+
} catch {
|
|
1303
|
+
return code;
|
|
1304
|
+
}
|
|
1305
|
+
|
|
1306
|
+
const edits = [];
|
|
1307
|
+
const isAllowedBare = (spec) =>
|
|
1308
|
+
ExternalModuleBundler.isBareSpecifier(spec) && this.isExternalAllowed(spec);
|
|
1309
|
+
|
|
1310
|
+
traverse.default(ast, {
|
|
1311
|
+
CallExpression: (pathNode) => {
|
|
1312
|
+
const node = pathNode.node;
|
|
1313
|
+
if (
|
|
1314
|
+
node.callee?.type === 'Import' &&
|
|
1315
|
+
node.arguments?.[0]?.type === 'StringLiteral' &&
|
|
1316
|
+
typeof node.start === 'number' &&
|
|
1317
|
+
typeof node.end === 'number'
|
|
1318
|
+
) {
|
|
1319
|
+
const spec = node.arguments[0].value;
|
|
1320
|
+
if (isAllowedBare(spec)) {
|
|
1321
|
+
edits.push({ start: node.start, end: node.end, spec });
|
|
1322
|
+
}
|
|
1323
|
+
}
|
|
1324
|
+
}
|
|
1325
|
+
});
|
|
1326
|
+
|
|
1327
|
+
if (edits.length === 0) return code;
|
|
1328
|
+
|
|
1329
|
+
// Apply from the end so earlier offsets stay valid.
|
|
1330
|
+
edits.sort((a, b) => b.start - a.start);
|
|
1331
|
+
let out = code;
|
|
1332
|
+
for (const { start, end, spec } of edits) {
|
|
1333
|
+
const key = JSON.stringify(spec);
|
|
1334
|
+
const replacement =
|
|
1335
|
+
`Promise.resolve((typeof window!=="undefined"&&window.__SLICE_SHARED_DEPS__&&${key} in window.__SLICE_SHARED_DEPS__)` +
|
|
1336
|
+
`?window.__SLICE_SHARED_DEPS__[${key}]:SLICE_BUNDLE_DEPENDENCIES[${key}])`;
|
|
1337
|
+
out = out.slice(0, start) + replacement + out.slice(end);
|
|
1338
|
+
}
|
|
1339
|
+
return out;
|
|
1340
|
+
}
|
|
1341
|
+
|
|
1342
|
+
/**
|
|
1343
|
+
* Builds the per-component external-dependency map for bare imports, keyed by
|
|
1344
|
+
* bare specifier. Shaped to slot alongside the relative-dependency map so the
|
|
1345
|
+
* existing binding/registration machinery treats both uniformly.
|
|
1346
|
+
* @param {string} code
|
|
1347
|
+
* @returns {Record<string, { external: true, bindings: Array, needsDefault: boolean }>}
|
|
1348
|
+
*/
|
|
1349
|
+
collectComponentBareDependencies(code) {
|
|
1350
|
+
if (!this.isExternalDependenciesEnabled()) return {};
|
|
1351
|
+
const out = {};
|
|
1352
|
+
for (const imp of this.analyzeBareImports(code)) {
|
|
1353
|
+
out[imp.name] = { external: true, bindings: imp.bindings, needsDefault: imp.needsDefault };
|
|
1354
|
+
}
|
|
1355
|
+
return out;
|
|
1356
|
+
}
|
|
1357
|
+
|
|
1358
|
+
/**
|
|
1359
|
+
* Collects every bare (node_modules) import reachable from an entry file,
|
|
1360
|
+
* following relative helper imports transitively. Returns a map of
|
|
1361
|
+
* packageName -> needsDefault (aggregated across all reachable sites).
|
|
1362
|
+
* @param {string} entryPath absolute path to the component's entry .js
|
|
1363
|
+
* @returns {Promise<Map<string, boolean>>}
|
|
1364
|
+
*/
|
|
1365
|
+
async collectReachableBareImports(entryPath) {
|
|
1366
|
+
const found = new Map();
|
|
1367
|
+
const visited = new Set();
|
|
1368
|
+
|
|
1369
|
+
const walk = async (filePath) => {
|
|
1370
|
+
if (visited.has(filePath)) return;
|
|
1371
|
+
visited.add(filePath);
|
|
1372
|
+
|
|
1373
|
+
let code;
|
|
1374
|
+
try {
|
|
1375
|
+
code = await fs.readFile(filePath, 'utf-8');
|
|
1376
|
+
} catch {
|
|
1377
|
+
return;
|
|
1378
|
+
}
|
|
1379
|
+
|
|
1380
|
+
for (const imp of this.analyzeBareImports(code)) {
|
|
1381
|
+
found.set(imp.name, (found.get(imp.name) || false) || imp.needsDefault);
|
|
1382
|
+
}
|
|
1383
|
+
// Follow relative helper modules so packages imported only by a helper
|
|
1384
|
+
// are discovered too.
|
|
1385
|
+
for (const dep of this.analyzeDependencies(code, path.dirname(filePath))) {
|
|
1386
|
+
await walk(dep.path);
|
|
1387
|
+
}
|
|
1388
|
+
};
|
|
1389
|
+
|
|
1390
|
+
await walk(entryPath);
|
|
1391
|
+
return found;
|
|
1392
|
+
}
|
|
1393
|
+
|
|
1394
|
+
/**
|
|
1395
|
+
* Resolves and bundles every bare import used across the app's components with
|
|
1396
|
+
* esbuild, once per package, before bundle files are emitted. needsDefault is
|
|
1397
|
+
* aggregated globally so a package default-imported anywhere is always built
|
|
1398
|
+
* with its default export available. Bare imports inside relative helper
|
|
1399
|
+
* modules are discovered transitively.
|
|
1400
|
+
*/
|
|
1401
|
+
async prepareExternalModules() {
|
|
1402
|
+
if (!this.isExternalDependenciesEnabled()) return;
|
|
1403
|
+
|
|
1404
|
+
const needsDefault = new Map();
|
|
1405
|
+
for (const comp of this.analysisData.components || []) {
|
|
1406
|
+
const fileBaseName = comp.fileName || comp.name;
|
|
1407
|
+
const jsPath = path.join(comp.path, `${fileBaseName}.js`);
|
|
1408
|
+
if (!await fs.pathExists(jsPath)) continue;
|
|
1409
|
+
const reachable = await this.collectReachableBareImports(jsPath);
|
|
1410
|
+
for (const [name, nd] of reachable) {
|
|
1411
|
+
needsDefault.set(name, (needsDefault.get(name) || false) || nd);
|
|
1412
|
+
}
|
|
1413
|
+
}
|
|
1414
|
+
|
|
1415
|
+
if (needsDefault.size === 0) return;
|
|
1416
|
+
|
|
1417
|
+
console.log(`📦 Resolving ${needsDefault.size} external dependenc${needsDefault.size === 1 ? 'y' : 'ies'} from node_modules...`);
|
|
1418
|
+
|
|
1419
|
+
for (const [name, nd] of needsDefault) {
|
|
1420
|
+
try {
|
|
1421
|
+
const { expression, warnings } = await this.getExternalBundler().bundle(name, { needsDefault: nd });
|
|
1422
|
+
this.externalModulesByName.set(name, expression);
|
|
1423
|
+
warnings.forEach((w) => console.warn(`Warning: [external:${name}] ${w}`));
|
|
1424
|
+
console.log(` ✓ ${name}`);
|
|
1425
|
+
} catch (error) {
|
|
1426
|
+
this.externalResolutionErrors.set(name, error.message);
|
|
1427
|
+
console.warn(`Warning: ${error.message}`);
|
|
1428
|
+
console.warn(` Components importing "${name}" will fail at runtime unless it is provided another way (a file under src/public/).`);
|
|
1429
|
+
}
|
|
1430
|
+
}
|
|
1431
|
+
|
|
1432
|
+
// In strict mode, any unresolved dependency fails the build so a broken
|
|
1433
|
+
// bundle never ships silently.
|
|
1434
|
+
if (this.strictExternal && this.externalResolutionErrors.size > 0) {
|
|
1435
|
+
const names = Array.from(this.externalResolutionErrors.keys()).sort().join(', ');
|
|
1436
|
+
throw new Error(
|
|
1437
|
+
`Strict external dependencies: ${this.externalResolutionErrors.size} package(s) could not be resolved from node_modules: ${names}. ` +
|
|
1438
|
+
`Install them or remove the imports.`
|
|
1439
|
+
);
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1010
1443
|
/**
|
|
1011
1444
|
* Analyzes dependencies of a JavaScript file using simple regex
|
|
1012
1445
|
*/
|
|
@@ -1077,8 +1510,28 @@ export default class BundleGenerator {
|
|
|
1077
1510
|
|
|
1078
1511
|
dependencies.push({
|
|
1079
1512
|
path: resolvedPath,
|
|
1080
|
-
bindings
|
|
1513
|
+
bindings,
|
|
1514
|
+
specifier: importPath
|
|
1081
1515
|
});
|
|
1516
|
+
},
|
|
1517
|
+
|
|
1518
|
+
// Re-export edges to a RELATIVE module (`export * from './x'`,
|
|
1519
|
+
// `export { a, b as c } from './x'`). These must inline + register the
|
|
1520
|
+
// target so the re-export can resolve at eval time; the exact binding
|
|
1521
|
+
// mapping is read back from the statement in transformDependencyStatement,
|
|
1522
|
+
// so no bindings need to be carried here.
|
|
1523
|
+
ExportNamedDeclaration(pathNode) {
|
|
1524
|
+
const src = pathNode.node.source?.value;
|
|
1525
|
+
if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
|
|
1526
|
+
const resolvedPath = resolveImportPath(src);
|
|
1527
|
+
if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
|
|
1528
|
+
},
|
|
1529
|
+
|
|
1530
|
+
ExportAllDeclaration(pathNode) {
|
|
1531
|
+
const src = pathNode.node.source?.value;
|
|
1532
|
+
if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
|
|
1533
|
+
const resolvedPath = resolveImportPath(src);
|
|
1534
|
+
if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
|
|
1082
1535
|
}
|
|
1083
1536
|
});
|
|
1084
1537
|
} catch (error) {
|
|
@@ -1116,6 +1569,11 @@ export default class BundleGenerator {
|
|
|
1116
1569
|
|
|
1117
1570
|
const cleanedJavaScript = this.cleanJavaScript(jsContent, comp.name, jsPath);
|
|
1118
1571
|
|
|
1572
|
+
// buildDependencyContents returns both relative helper modules (keyed by
|
|
1573
|
+
// src-relative path) and bare node_modules imports (keyed by bare
|
|
1574
|
+
// specifier, discovered in the component and its relative helpers).
|
|
1575
|
+
const externalDependencies = await this.buildDependencyContents(jsContent, comp.path);
|
|
1576
|
+
|
|
1119
1577
|
bundleComponents.push({
|
|
1120
1578
|
name: comp.name,
|
|
1121
1579
|
category: comp.category,
|
|
@@ -1124,12 +1582,12 @@ export default class BundleGenerator {
|
|
|
1124
1582
|
hoistedImports: cleanedJavaScript.hoistedImports,
|
|
1125
1583
|
html: htmlContent,
|
|
1126
1584
|
css: cssContent,
|
|
1127
|
-
externalDependencies
|
|
1585
|
+
externalDependencies,
|
|
1128
1586
|
size: comp.size
|
|
1129
1587
|
});
|
|
1130
1588
|
}
|
|
1131
1589
|
|
|
1132
|
-
return this.generateBundleFileContent(fileName, type, this.sortComponentsByName(bundleComponents), routePath);
|
|
1590
|
+
return this.generateBundleFileContent(fileName, type, this.sortComponentsByName(bundleComponents), routePath, bundleKey);
|
|
1133
1591
|
}
|
|
1134
1592
|
|
|
1135
1593
|
classFactoryName(componentName) {
|
|
@@ -1144,19 +1602,29 @@ export default class BundleGenerator {
|
|
|
1144
1602
|
.join('\n');
|
|
1145
1603
|
}
|
|
1146
1604
|
|
|
1147
|
-
generateBundleFileContent(fileName, type, components, routePath = null) {
|
|
1605
|
+
generateBundleFileContent(fileName, type, components, routePath = null, bundleKeyOverride = null) {
|
|
1148
1606
|
const uniqueComponents = this.dedupeComponentsByName(components || []);
|
|
1607
|
+
// `bundleKeyOverride` carries the split-aware key (`playground--p1`) so the
|
|
1608
|
+
// emitted META matches the key the runtime looks up in `routeBundles`.
|
|
1149
1609
|
const bundleKey = type === 'critical'
|
|
1150
1610
|
? 'critical'
|
|
1151
1611
|
: type === 'framework'
|
|
1152
1612
|
? 'framework'
|
|
1153
|
-
: this.routeToFileName(
|
|
1613
|
+
: this.routeToFileName(
|
|
1614
|
+
bundleKeyOverride
|
|
1615
|
+
|| routePath
|
|
1616
|
+
|| fileName.replace('slice-bundle.', '').replace('.js', '')
|
|
1617
|
+
);
|
|
1154
1618
|
|
|
1155
1619
|
const dependencyModules = this.collectDependencyModulesFromComponents(uniqueComponents);
|
|
1156
1620
|
const isRouteBundle = type === 'route';
|
|
1621
|
+
// The critical bundle also resolves from vendor-shared when it uses a shared
|
|
1622
|
+
// dependency (see prepareVendorSharedDependencies): it loads vendor-shared
|
|
1623
|
+
// first and omits its own inline copy, exactly like a route bundle.
|
|
1624
|
+
const usesVendorShared = isRouteBundle || (type === 'critical' && this.vendorShared.criticalUsesShared);
|
|
1157
1625
|
const dependencyModuleBlock = this.buildV2DependencyModuleBlock(uniqueComponents, {
|
|
1158
|
-
includeSharedResolver:
|
|
1159
|
-
omittedDependencies:
|
|
1626
|
+
includeSharedResolver: usesVendorShared,
|
|
1627
|
+
omittedDependencies: usesVendorShared ? this.vendorShared.sharedDependencySet : null
|
|
1160
1628
|
});
|
|
1161
1629
|
const rawHoistedImports = uniqueComponents
|
|
1162
1630
|
.flatMap((component) => component.hoistedImports || [])
|
|
@@ -1177,7 +1645,7 @@ export default class BundleGenerator {
|
|
|
1177
1645
|
.map((component) => {
|
|
1178
1646
|
const factoryName = this.classFactoryName(component.name);
|
|
1179
1647
|
const dependencyBindings = this.buildDependencyBindings(component.externalDependencies || {}, {
|
|
1180
|
-
preferShared:
|
|
1648
|
+
preferShared: usesVendorShared
|
|
1181
1649
|
});
|
|
1182
1650
|
const body = component.js && component.js.trim()
|
|
1183
1651
|
? component.js
|
|
@@ -1263,12 +1731,51 @@ export default class BundleGenerator {
|
|
|
1263
1731
|
lines.push(...this.getBundleDependencyResolverLines());
|
|
1264
1732
|
}
|
|
1265
1733
|
filteredModules.forEach((module, index) => {
|
|
1734
|
+
// External (node_modules) modules are emitted from their pre-bundled
|
|
1735
|
+
// esbuild expression, which already yields a module-namespace-like object
|
|
1736
|
+
// (named exports + a `default` key). No Babel export-rewriting needed.
|
|
1737
|
+
if (module.external) {
|
|
1738
|
+
const expression = this.externalModulesByName.get(module.name);
|
|
1739
|
+
lines.push(`// External dependency: ${module.name}`);
|
|
1740
|
+
if (expression) {
|
|
1741
|
+
lines.push(`SLICE_BUNDLE_DEPENDENCIES[${JSON.stringify(module.name)}] = ${expression};`);
|
|
1742
|
+
} else {
|
|
1743
|
+
// Resolution failed earlier (already warned). Emit an empty namespace
|
|
1744
|
+
// so the bundle still evaluates; the binding resolves to undefined.
|
|
1745
|
+
lines.push(`SLICE_BUNDLE_DEPENDENCIES[${JSON.stringify(module.name)}] = {};`);
|
|
1746
|
+
}
|
|
1747
|
+
return;
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1266
1750
|
const exportVar = `__sliceDepExports${index}`;
|
|
1267
1751
|
// Evaluate each dependency inside its own IIFE so its private,
|
|
1268
1752
|
// non-exported top-level bindings stay local and cannot collide with
|
|
1269
1753
|
// another dependency's (or the bundle's) identifiers. Only the exports
|
|
1270
1754
|
// object escapes the closure.
|
|
1271
|
-
|
|
1755
|
+
// Map each relative import/re-export specifier this module used to the
|
|
1756
|
+
// src-relative key it was registered under, so a re-export resolves its
|
|
1757
|
+
// source without touching the filesystem.
|
|
1758
|
+
const specifierToKey = new Map(
|
|
1759
|
+
(module.moduleImports || [])
|
|
1760
|
+
.filter((mi) => mi.specifier && mi.depName)
|
|
1761
|
+
.map((mi) => [mi.specifier, mi.depName])
|
|
1762
|
+
);
|
|
1763
|
+
// Every specifier this module's imports were analyzed under — bare ones by
|
|
1764
|
+
// name, relative ones by the specifier as written. Each has its module
|
|
1765
|
+
// emitted in this block and its bindings re-created below, so stripping the
|
|
1766
|
+
// original statement loses nothing and must not warn.
|
|
1767
|
+
const handledSpecifiers = new Set(
|
|
1768
|
+
(module.moduleImports || [])
|
|
1769
|
+
.map((mi) => (mi.external ? mi.depName : mi.specifier))
|
|
1770
|
+
.filter((specifier) => typeof specifier === 'string')
|
|
1771
|
+
);
|
|
1772
|
+
const transformedContent = this.transformDependencyContent(module.content, '__sliceExports', module.name, {
|
|
1773
|
+
// A re-export inside this helper must resolve its source through the same
|
|
1774
|
+
// shared resolver the bundle uses, since the source may live in vendor-shared.
|
|
1775
|
+
preferShared: !!options.includeSharedResolver,
|
|
1776
|
+
specifierToKey,
|
|
1777
|
+
handledSpecifiers
|
|
1778
|
+
});
|
|
1272
1779
|
// Bind this module's own (transitive) imports inside its IIFE — they were
|
|
1273
1780
|
// registered by earlier modules in the topological order.
|
|
1274
1781
|
const importBindings = this.buildDependencyBindings(
|
|
@@ -1321,9 +1828,25 @@ export default class BundleGenerator {
|
|
|
1321
1828
|
const resolveModule = async (content, basePath) => {
|
|
1322
1829
|
const consumerImports = [];
|
|
1323
1830
|
|
|
1831
|
+
// Bare (node_modules) imports of THIS module. They become moduleImports of
|
|
1832
|
+
// the consumer (so a helper's IIFE binds them from SLICE_BUNDLE_DEPENDENCIES)
|
|
1833
|
+
// and are registered once as external modules keyed by bare name.
|
|
1834
|
+
if (this.isExternalDependenciesEnabled()) {
|
|
1835
|
+
for (const bare of this.analyzeBareImports(content)) {
|
|
1836
|
+
consumerImports.push({ depName: bare.name, bindings: bare.bindings || [], external: true });
|
|
1837
|
+
if (!dependencyContents[bare.name]) {
|
|
1838
|
+
dependencyContents[bare.name] = { external: true, bindings: [], needsDefault: false };
|
|
1839
|
+
}
|
|
1840
|
+
dependencyContents[bare.name].needsDefault =
|
|
1841
|
+
dependencyContents[bare.name].needsDefault || bare.needsDefault;
|
|
1842
|
+
}
|
|
1843
|
+
}
|
|
1844
|
+
|
|
1324
1845
|
for (const dep of this.analyzeDependencies(content, basePath)) {
|
|
1325
1846
|
const depName = path.relative(this.srcPath, dep.path).replace(/\\/g, '/');
|
|
1326
|
-
|
|
1847
|
+
// Carry the original specifier so a re-export (`export … from './x'`) can
|
|
1848
|
+
// map it back to the registered key without touching the filesystem.
|
|
1849
|
+
consumerImports.push({ depName, bindings: dep.bindings || [], specifier: dep.specifier });
|
|
1327
1850
|
|
|
1328
1851
|
if (visited.has(depName)) continue;
|
|
1329
1852
|
visited.add(depName);
|
|
@@ -1342,10 +1865,17 @@ export default class BundleGenerator {
|
|
|
1342
1865
|
};
|
|
1343
1866
|
|
|
1344
1867
|
const directImports = await resolveModule(jsContent, componentPath);
|
|
1345
|
-
// The component's direct imports drive its class-factory bindings.
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1868
|
+
// The component's direct imports drive its class-factory bindings. For a
|
|
1869
|
+
// package the component imports directly, those bindings belong on the
|
|
1870
|
+
// external entry; helper-only packages keep empty component-level bindings
|
|
1871
|
+
// (their bindings live in the helper's moduleImports).
|
|
1872
|
+
for (const { depName, bindings, external } of directImports) {
|
|
1873
|
+
const entry = dependencyContents[depName];
|
|
1874
|
+
if (!entry) continue;
|
|
1875
|
+
if (external) {
|
|
1876
|
+
entry.bindings = (entry.bindings || []).concat(bindings || []);
|
|
1877
|
+
} else {
|
|
1878
|
+
entry.bindings = bindings;
|
|
1349
1879
|
}
|
|
1350
1880
|
}
|
|
1351
1881
|
|
|
@@ -1367,6 +1897,11 @@ export default class BundleGenerator {
|
|
|
1367
1897
|
const hoistedImports = stripped.hoistedImports || [];
|
|
1368
1898
|
code = stripped.code;
|
|
1369
1899
|
|
|
1900
|
+
// Rewrite dynamic `import('pkg')` of bare packages so they resolve from the
|
|
1901
|
+
// registered dependency at runtime (native dynamic import of a bare
|
|
1902
|
+
// specifier has no resolver in the built output).
|
|
1903
|
+
code = this.rewriteDynamicExternalImports(code);
|
|
1904
|
+
|
|
1370
1905
|
// Guard customElements.define to avoid duplicate registrations
|
|
1371
1906
|
code = code.replace(
|
|
1372
1907
|
/customElements\.define\(([^)]+)\);?/g,
|
|
@@ -1523,6 +2058,12 @@ if (window.slice && window.slice.controller) {
|
|
|
1523
2058
|
const externalDependencies = component.externalDependencies || {};
|
|
1524
2059
|
for (const [moduleName, entry] of Object.entries(externalDependencies)) {
|
|
1525
2060
|
if (modules.has(moduleName)) continue;
|
|
2061
|
+
// External (node_modules) modules carry no inline content — they are
|
|
2062
|
+
// emitted from the pre-bundled esbuild expression keyed by bare name.
|
|
2063
|
+
if (entry && typeof entry === 'object' && entry.external) {
|
|
2064
|
+
modules.set(moduleName, { name: moduleName, external: true, content: null, moduleImports: [] });
|
|
2065
|
+
continue;
|
|
2066
|
+
}
|
|
1526
2067
|
const content = typeof entry === 'string' ? entry : entry?.content;
|
|
1527
2068
|
if (!content) continue;
|
|
1528
2069
|
const moduleImports = (entry && typeof entry === 'object' ? entry.moduleImports : null) || [];
|
|
@@ -1536,7 +2077,35 @@ if (window.slice && window.slice.controller) {
|
|
|
1536
2077
|
return (dependencyModules || []).map((_, index) => `__sliceDepExports${index}`);
|
|
1537
2078
|
}
|
|
1538
2079
|
|
|
1539
|
-
|
|
2080
|
+
/**
|
|
2081
|
+
* A relative `.json` dependency (`import cfg from './data.json'`) is data, not
|
|
2082
|
+
* a JS module. Embed it as a literal (JSON is a subset of JS expression
|
|
2083
|
+
* syntax): the whole document as the `default` export, plus each top-level key
|
|
2084
|
+
* as a named export (matching how Vite/webpack expose JSON).
|
|
2085
|
+
*/
|
|
2086
|
+
transformJsonModule(content, exportVar) {
|
|
2087
|
+
const trimmed = String(content).trim();
|
|
2088
|
+
try {
|
|
2089
|
+
JSON.parse(trimmed || 'null');
|
|
2090
|
+
} catch (error) {
|
|
2091
|
+
console.warn(`Warning: Invalid JSON dependency: ${error.message}. Emitting empty exports.`);
|
|
2092
|
+
return `${exportVar}.default = {};`;
|
|
2093
|
+
}
|
|
2094
|
+
const literal = trimmed || 'null';
|
|
2095
|
+
return [
|
|
2096
|
+
`const __sliceJson = ${literal};`,
|
|
2097
|
+
`${exportVar}.default = __sliceJson;`,
|
|
2098
|
+
`if (__sliceJson && typeof __sliceJson === "object" && !Array.isArray(__sliceJson)) { for (const __k in __sliceJson) { if (__k !== "default") ${exportVar}[__k] = __sliceJson[__k]; } }`
|
|
2099
|
+
].join('\n');
|
|
2100
|
+
}
|
|
2101
|
+
|
|
2102
|
+
transformDependencyContent(content, exportVar, moduleName, options = {}) {
|
|
2103
|
+
// A `.json` dependency is data — embed it directly instead of parsing it as
|
|
2104
|
+
// a JS module (which would drop its contents).
|
|
2105
|
+
if (typeof moduleName === 'string' && moduleName.endsWith('.json')) {
|
|
2106
|
+
return this.transformJsonModule(content, exportVar);
|
|
2107
|
+
}
|
|
2108
|
+
|
|
1540
2109
|
let ast;
|
|
1541
2110
|
try {
|
|
1542
2111
|
ast = parse(content, { sourceType: 'module', plugins: ['jsx'] });
|
|
@@ -1555,13 +2124,69 @@ if (window.slice && window.slice.controller) {
|
|
|
1555
2124
|
let output = '';
|
|
1556
2125
|
for (const node of statements) {
|
|
1557
2126
|
output += content.slice(cursor, node.start);
|
|
1558
|
-
output += this.transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey);
|
|
2127
|
+
output += this.transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey, options);
|
|
1559
2128
|
cursor = node.end;
|
|
1560
2129
|
}
|
|
1561
2130
|
output += content.slice(cursor);
|
|
1562
2131
|
return output;
|
|
1563
2132
|
}
|
|
1564
2133
|
|
|
2134
|
+
/** RHS member access on a resolved dependency object: `.name` or `["weird-name"]`. */
|
|
2135
|
+
describeMemberAccess(name) {
|
|
2136
|
+
return /^[A-Za-z_$][\w$]*$/.test(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
|
|
2137
|
+
}
|
|
2138
|
+
|
|
2139
|
+
/**
|
|
2140
|
+
* Resolves a relative import specifier written inside a bundled helper module
|
|
2141
|
+
* to the src-relative key it was registered under (matching analyzeDependencies'
|
|
2142
|
+
* depName computation), so a re-export can look it up in SLICE_BUNDLE_DEPENDENCIES.
|
|
2143
|
+
* @param {string} moduleName the helper's own src-relative path
|
|
2144
|
+
* @param {string} spec relative specifier (e.g. './x', '../lib/y.js')
|
|
2145
|
+
* @returns {string|null}
|
|
2146
|
+
*/
|
|
2147
|
+
resolveRelativeModuleKey(moduleName, spec) {
|
|
2148
|
+
try {
|
|
2149
|
+
const moduleDir = path.dirname(path.join(this.srcPath, moduleName));
|
|
2150
|
+
let resolved = path.resolve(moduleDir, spec);
|
|
2151
|
+
if (!path.extname(resolved)) {
|
|
2152
|
+
for (const ext of ['.js', '.json', '.mjs']) {
|
|
2153
|
+
if (fs.existsSync(resolved + ext)) { resolved = resolved + ext; break; }
|
|
2154
|
+
}
|
|
2155
|
+
}
|
|
2156
|
+
if (!fs.existsSync(resolved)) return null;
|
|
2157
|
+
return path.relative(this.srcPath, resolved).replace(/\\/g, '/');
|
|
2158
|
+
} catch {
|
|
2159
|
+
return null;
|
|
2160
|
+
}
|
|
2161
|
+
}
|
|
2162
|
+
|
|
2163
|
+
/**
|
|
2164
|
+
* JS expression that yields the exports object of a re-export source, or null
|
|
2165
|
+
* if it can't be resolved (absolute/URL source, or a missing relative file).
|
|
2166
|
+
* Bare packages resolve by name; relative helpers resolve to their registered
|
|
2167
|
+
* key. Honors the shared resolver when the bundle uses vendor-shared.
|
|
2168
|
+
* @param {string} moduleName re-exporting helper's src-relative path
|
|
2169
|
+
* @param {string} src the re-export source specifier
|
|
2170
|
+
* @param {boolean} preferShared
|
|
2171
|
+
* @returns {string|null}
|
|
2172
|
+
*/
|
|
2173
|
+
reexportDependencyExpression(moduleName, src, preferShared, specifierToKey = null) {
|
|
2174
|
+
if (typeof src !== 'string') return null;
|
|
2175
|
+
const keyFor = (name) => preferShared
|
|
2176
|
+
? `__sliceResolveBundleDependency(${JSON.stringify(name)})`
|
|
2177
|
+
: `SLICE_BUNDLE_DEPENDENCIES[${JSON.stringify(name)}]`;
|
|
2178
|
+
if (ExternalModuleBundler.isBareSpecifier(src)) {
|
|
2179
|
+
return keyFor(src);
|
|
2180
|
+
}
|
|
2181
|
+
if (src.startsWith('.')) {
|
|
2182
|
+
// Prefer the already-resolved key recorded on the module's import edges
|
|
2183
|
+
// (fs-free, exact match); fall back to resolving against the filesystem.
|
|
2184
|
+
const key = (specifierToKey && specifierToKey.get(src)) || this.resolveRelativeModuleKey(moduleName, src);
|
|
2185
|
+
return key ? keyFor(key) : null;
|
|
2186
|
+
}
|
|
2187
|
+
return null; // absolute / URL re-export is unsupported
|
|
2188
|
+
}
|
|
2189
|
+
|
|
1565
2190
|
describeExportTarget(exportVar, name) {
|
|
1566
2191
|
return /^[A-Za-z_$][\w$]*$/.test(name)
|
|
1567
2192
|
? `${exportVar}.${name}`
|
|
@@ -1628,25 +2253,47 @@ if (window.slice && window.slice.controller) {
|
|
|
1628
2253
|
return sourceOf(decl);
|
|
1629
2254
|
}
|
|
1630
2255
|
|
|
1631
|
-
transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey) {
|
|
2256
|
+
transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey, options = {}) {
|
|
1632
2257
|
const sourceOf = (n) => content.slice(n.start, n.end);
|
|
2258
|
+
const preferShared = !!options.preferShared;
|
|
2259
|
+
const specifierToKey = options.specifierToKey || null;
|
|
1633
2260
|
|
|
1634
2261
|
if (node.type === 'ImportDeclaration') {
|
|
1635
|
-
//
|
|
1636
|
-
//
|
|
1637
|
-
|
|
1638
|
-
|
|
1639
|
-
|
|
1640
|
-
|
|
2262
|
+
// An import listed in `handledSpecifiers` is not dropped: the caller
|
|
2263
|
+
// re-emits it as an IIFE-scoped binding (buildDependencyBindings), and
|
|
2264
|
+
// removing the original statement is the second half of that rewrite.
|
|
2265
|
+
// Only an import nothing rebinds is actually lost — warn for that one.
|
|
2266
|
+
const specifier = node.source?.value;
|
|
2267
|
+
const handled = options.handledSpecifiers instanceof Set
|
|
2268
|
+
&& typeof specifier === 'string'
|
|
2269
|
+
&& options.handledSpecifiers.has(specifier);
|
|
2270
|
+
|
|
2271
|
+
if (!handled && !options.silent) {
|
|
2272
|
+
console.warn(this.buildImportWarningMessage(
|
|
2273
|
+
`Warning: Stripping unsupported import inside bundled dependency: ${specifier}`,
|
|
2274
|
+
moduleName
|
|
2275
|
+
));
|
|
2276
|
+
}
|
|
1641
2277
|
return '';
|
|
1642
2278
|
}
|
|
1643
2279
|
|
|
1644
2280
|
if (node.type === 'ExportAllDeclaration') {
|
|
1645
|
-
|
|
1646
|
-
|
|
1647
|
-
|
|
1648
|
-
)
|
|
1649
|
-
|
|
2281
|
+
// `export * from './x'` (or 'pkg') — copy every own enumerable export of
|
|
2282
|
+
// the resolved module except `default` (per the ESM spec) onto the exports
|
|
2283
|
+
// object. The source module is registered earlier by the topological order.
|
|
2284
|
+
const depExpr = this.reexportDependencyExpression(moduleName, node.source?.value, preferShared, specifierToKey);
|
|
2285
|
+
if (!depExpr) {
|
|
2286
|
+
console.warn(this.buildImportWarningMessage(
|
|
2287
|
+
`Warning: Dropping unresolvable 'export *' inside bundled dependency: ${node.source?.value}`,
|
|
2288
|
+
moduleName
|
|
2289
|
+
));
|
|
2290
|
+
return '';
|
|
2291
|
+
}
|
|
2292
|
+
const tmp = `__sliceReexportAll_${node.start}`;
|
|
2293
|
+
return [
|
|
2294
|
+
`const ${tmp} = ${depExpr};`,
|
|
2295
|
+
`for (const __k of Object.keys(${tmp})) { if (__k !== "default") ${exportVar}[__k] = ${tmp}[__k]; }`
|
|
2296
|
+
].join('\n');
|
|
1650
2297
|
}
|
|
1651
2298
|
|
|
1652
2299
|
if (node.type === 'ExportDefaultDeclaration') {
|
|
@@ -1662,11 +2309,27 @@ if (window.slice && window.slice.controller) {
|
|
|
1662
2309
|
|
|
1663
2310
|
if (node.type === 'ExportNamedDeclaration') {
|
|
1664
2311
|
if (node.source) {
|
|
1665
|
-
|
|
1666
|
-
|
|
1667
|
-
|
|
1668
|
-
)
|
|
1669
|
-
|
|
2312
|
+
// `export { a, b as c } from './x'` (or 'pkg') — map each PUBLIC name to
|
|
2313
|
+
// the corresponding member of the resolved module's exports object.
|
|
2314
|
+
const depExpr = this.reexportDependencyExpression(moduleName, node.source.value, preferShared, specifierToKey);
|
|
2315
|
+
if (!depExpr) {
|
|
2316
|
+
console.warn(this.buildImportWarningMessage(
|
|
2317
|
+
`Warning: Dropping unresolvable re-export inside bundled dependency: ${node.source.value}`,
|
|
2318
|
+
moduleName
|
|
2319
|
+
));
|
|
2320
|
+
return '';
|
|
2321
|
+
}
|
|
2322
|
+
const tmp = `__sliceReexport_${node.start}`;
|
|
2323
|
+
const lines = [`const ${tmp} = ${depExpr};`];
|
|
2324
|
+
for (const spec of node.specifiers || []) {
|
|
2325
|
+
// ExportSpecifier: `local` is the name in the source module, `exported`
|
|
2326
|
+
// is the public name. `export { default as X }` maps X <- tmp.default.
|
|
2327
|
+
const localName = spec.local?.name ?? spec.local?.value;
|
|
2328
|
+
const exportedName = spec.exported?.name ?? spec.exported?.value;
|
|
2329
|
+
if (!localName || !exportedName) continue;
|
|
2330
|
+
lines.push(`${this.describeExportTarget(exportVar, exportedName)} = ${tmp}${this.describeMemberAccess(localName)};`);
|
|
2331
|
+
}
|
|
2332
|
+
return lines.join('\n');
|
|
1670
2333
|
}
|
|
1671
2334
|
|
|
1672
2335
|
if (node.declaration) {
|
|
@@ -1841,7 +2504,7 @@ if (window.slice && window.slice.controller) {
|
|
|
1841
2504
|
minified: this.options.minify,
|
|
1842
2505
|
obfuscated: this.options.obfuscate,
|
|
1843
2506
|
production: true,
|
|
1844
|
-
generated:
|
|
2507
|
+
generated: resolveBuildTimestamp(),
|
|
1845
2508
|
|
|
1846
2509
|
stats: {
|
|
1847
2510
|
totalComponents: metrics.totalComponents || 0,
|
|
@@ -1868,7 +2531,7 @@ if (window.slice && window.slice.controller) {
|
|
|
1868
2531
|
? {
|
|
1869
2532
|
bundleKey: 'vendor-shared',
|
|
1870
2533
|
type: 'vendor-shared',
|
|
1871
|
-
file: this.vendorShared.file,
|
|
2534
|
+
file: this.vendorShared.bundle?.file || this.vendorShared.file,
|
|
1872
2535
|
size: this.vendorShared.bundle?.size || 0,
|
|
1873
2536
|
hash: this.vendorShared.bundle?.hash || null,
|
|
1874
2537
|
integrity: this.vendorShared.bundle?.integrity || null,
|
|
@@ -1882,7 +2545,10 @@ if (window.slice && window.slice.controller) {
|
|
|
1882
2545
|
size: this.bundles.critical.size,
|
|
1883
2546
|
hash: this.bundles.critical.hash || null,
|
|
1884
2547
|
integrity: this.bundles.critical.integrity || null,
|
|
1885
|
-
components: this.bundles.critical.components.map(c => c.name)
|
|
2548
|
+
components: this.bundles.critical.components.map(c => c.name),
|
|
2549
|
+
// When critical uses a shared dependency it must load vendor-shared
|
|
2550
|
+
// first so the shared resolver finds it at registration time.
|
|
2551
|
+
...(this.vendorShared.criticalUsesShared ? { dependencies: ['vendor-shared'] } : {})
|
|
1886
2552
|
},
|
|
1887
2553
|
routes: {}
|
|
1888
2554
|
},
|
|
@@ -1903,7 +2569,9 @@ if (window.slice && window.slice.controller) {
|
|
|
1903
2569
|
|
|
1904
2570
|
config.bundles.routes[key] = {
|
|
1905
2571
|
path: bundle.path || bundle.paths || key, // Support both single path and array of paths, fallback to key
|
|
1906
|
-
|
|
2572
|
+
// Prefer the emitted (possibly content-hashed) filename; fall back to the
|
|
2573
|
+
// deterministic name when the bundle wasn't emitted through the writer.
|
|
2574
|
+
file: bundle.file || `slice-bundle.${this.routeToFileName(routeIdentifier)}.js`,
|
|
1907
2575
|
size: bundle.size,
|
|
1908
2576
|
hash: bundle.hash || null,
|
|
1909
2577
|
integrity: bundle.integrity || null,
|
|
@@ -1964,6 +2632,39 @@ if (window.slice && window.slice.controller) {
|
|
|
1964
2632
|
return config;
|
|
1965
2633
|
}
|
|
1966
2634
|
|
|
2635
|
+
/**
|
|
2636
|
+
* Checks that the generated config is self-consistent: every bundle key
|
|
2637
|
+
* referenced (in `routeBundles` or a bundle's `dependencies`) is actually
|
|
2638
|
+
* emitted, and no emitted route bundle is orphaned (referenced by nothing).
|
|
2639
|
+
* Guards against the class of bug where splitting/merging a bundle leaves
|
|
2640
|
+
* dangling by-key references or dead files.
|
|
2641
|
+
* @returns {{ dangling: string[], orphans: string[] }}
|
|
2642
|
+
*/
|
|
2643
|
+
collectBundleReferentialIssues(config) {
|
|
2644
|
+
const valid = new Set(['critical', 'framework']);
|
|
2645
|
+
if (config?.bundles?.vendorShared) valid.add('vendor-shared');
|
|
2646
|
+
for (const key of Object.keys(config?.bundles?.routes || {})) valid.add(key);
|
|
2647
|
+
|
|
2648
|
+
const dangling = new Set();
|
|
2649
|
+
const referenced = new Set();
|
|
2650
|
+
const note = (key) => {
|
|
2651
|
+
if (!key) return;
|
|
2652
|
+
if (key !== 'critical') referenced.add(key);
|
|
2653
|
+
if (!valid.has(key)) dangling.add(key);
|
|
2654
|
+
};
|
|
2655
|
+
|
|
2656
|
+
for (const list of Object.values(config?.routeBundles || {})) {
|
|
2657
|
+
for (const key of list || []) note(key);
|
|
2658
|
+
}
|
|
2659
|
+
for (const entry of Object.values(config?.bundles?.routes || {})) {
|
|
2660
|
+
for (const dep of entry?.dependencies || []) note(dep);
|
|
2661
|
+
}
|
|
2662
|
+
for (const dep of config?.bundles?.critical?.dependencies || []) note(dep);
|
|
2663
|
+
|
|
2664
|
+
const orphans = Object.keys(config?.bundles?.routes || {}).filter((key) => !referenced.has(key));
|
|
2665
|
+
return { dangling: [...dangling].sort(), orphans: orphans.sort() };
|
|
2666
|
+
}
|
|
2667
|
+
|
|
1967
2668
|
collectFrameworkComponents() {
|
|
1968
2669
|
return this.analysisData.components.filter((comp) => comp.isFramework);
|
|
1969
2670
|
}
|
|
@@ -1983,7 +2684,7 @@ if (window.slice && window.slice.controller) {
|
|
|
1983
2684
|
route: null,
|
|
1984
2685
|
bundleKey: 'framework',
|
|
1985
2686
|
file: fileName,
|
|
1986
|
-
generated:
|
|
2687
|
+
generated: resolveBuildTimestamp(),
|
|
1987
2688
|
totalSize: components.reduce((sum, c) => sum + c.size, 0),
|
|
1988
2689
|
componentCount: components.length,
|
|
1989
2690
|
strategy: this.config.strategy,
|
|
@@ -2020,17 +2721,13 @@ if (window.slice && window.slice.controller) {
|
|
|
2020
2721
|
|
|
2021
2722
|
const prelude = `const components = ${JSON.stringify(componentsMap)};`;
|
|
2022
2723
|
const bundleContent = `${prelude}\n${this.formatBundleFile(componentsData, metadata)}`;
|
|
2023
|
-
const
|
|
2024
|
-
await fs.ensureDir(path.dirname(filePath));
|
|
2025
|
-
await fs.writeFile(filePath, finalContent, 'utf-8');
|
|
2026
|
-
|
|
2027
|
-
const hash = crypto.createHash('sha256').update(finalContent).digest('hex');
|
|
2724
|
+
const { file, hash, rawSize } = await this.emitBundleArtifact(fileName, bundleContent);
|
|
2028
2725
|
const integrity = `sha256:${hash}`;
|
|
2029
2726
|
|
|
2030
2727
|
return {
|
|
2031
2728
|
name: 'framework',
|
|
2032
|
-
file
|
|
2033
|
-
size:
|
|
2729
|
+
file,
|
|
2730
|
+
size: rawSize,
|
|
2034
2731
|
hash,
|
|
2035
2732
|
integrity,
|
|
2036
2733
|
componentCount: components.length,
|
|
@@ -2061,33 +2758,6 @@ if (window.slice && window.slice.controller) {
|
|
|
2061
2758
|
return dependencyContents;
|
|
2062
2759
|
}
|
|
2063
2760
|
|
|
2064
|
-
getConfiguredPublicFolders() {
|
|
2065
|
-
const publicFolders = Array.isArray(this.sliceConfig?.publicFolders)
|
|
2066
|
-
? this.sliceConfig.publicFolders
|
|
2067
|
-
: [];
|
|
2068
|
-
|
|
2069
|
-
return publicFolders
|
|
2070
|
-
.map((folder) => this.normalizePublicFolder(folder))
|
|
2071
|
-
.filter(Boolean);
|
|
2072
|
-
}
|
|
2073
|
-
|
|
2074
|
-
normalizePublicFolder(folder) {
|
|
2075
|
-
if (typeof folder !== 'string') return null;
|
|
2076
|
-
let normalized = folder.trim();
|
|
2077
|
-
if (!normalized) return null;
|
|
2078
|
-
|
|
2079
|
-
if (!normalized.startsWith('/')) {
|
|
2080
|
-
normalized = `/${normalized}`;
|
|
2081
|
-
}
|
|
2082
|
-
|
|
2083
|
-
normalized = normalized.replace(/\\+/g, '/').replace(/\/+/g, '/');
|
|
2084
|
-
if (normalized.length > 1 && normalized.endsWith('/')) {
|
|
2085
|
-
normalized = normalized.slice(0, -1);
|
|
2086
|
-
}
|
|
2087
|
-
|
|
2088
|
-
return normalized;
|
|
2089
|
-
}
|
|
2090
|
-
|
|
2091
2761
|
normalizeImportPath(importPath) {
|
|
2092
2762
|
if (typeof importPath !== 'string') return '';
|
|
2093
2763
|
const cleanPath = importPath.split(/[?#]/)[0];
|
|
@@ -2102,12 +2772,20 @@ if (window.slice && window.slice.controller) {
|
|
|
2102
2772
|
return importPath.startsWith('/');
|
|
2103
2773
|
}
|
|
2104
2774
|
|
|
2105
|
-
|
|
2106
|
-
|
|
2107
|
-
|
|
2775
|
+
// True when an absolute import resolves to a real file under `src/public/`.
|
|
2776
|
+
// Anything served at the root URL from public/ can be imported by its
|
|
2777
|
+
// absolute path.
|
|
2778
|
+
isImportInPublicDir(importPath) {
|
|
2779
|
+
const normalizedImport = this.normalizeImportPath(importPath).replace(/^\/+/, '');
|
|
2780
|
+
if (!normalizedImport) return false;
|
|
2781
|
+
try {
|
|
2782
|
+
return fs.existsSync(path.join(this.srcPath, 'public', normalizedImport));
|
|
2783
|
+
} catch {
|
|
2784
|
+
return false;
|
|
2785
|
+
}
|
|
2108
2786
|
}
|
|
2109
2787
|
|
|
2110
|
-
classifyImport(importPath
|
|
2788
|
+
classifyImport(importPath) {
|
|
2111
2789
|
if (typeof importPath !== 'string' || !importPath) {
|
|
2112
2790
|
return { keep: false, warning: 'Warning: Removing bare import: <unknown>' };
|
|
2113
2791
|
}
|
|
@@ -2117,20 +2795,21 @@ if (window.slice && window.slice.controller) {
|
|
|
2117
2795
|
}
|
|
2118
2796
|
|
|
2119
2797
|
if (this.isAbsoluteImport(importPath)) {
|
|
2120
|
-
if (
|
|
2798
|
+
// Kept only if the file exists under src/public/ (served at the root URL).
|
|
2799
|
+
if (this.isImportInPublicDir(importPath)) {
|
|
2121
2800
|
return { keep: true, warning: null };
|
|
2122
2801
|
}
|
|
2123
2802
|
|
|
2124
2803
|
return {
|
|
2125
2804
|
keep: false,
|
|
2126
|
-
warning: `Warning: Removing absolute import
|
|
2805
|
+
warning: `Warning: Removing absolute import not found under public/: ${importPath}`
|
|
2127
2806
|
};
|
|
2128
2807
|
}
|
|
2129
2808
|
|
|
2130
|
-
|
|
2131
|
-
|
|
2132
|
-
|
|
2133
|
-
};
|
|
2809
|
+
// Bare specifier (node_modules package). Strip it silently from the
|
|
2810
|
+
// component body: it is resolved + bundled separately and re-bound in the
|
|
2811
|
+
// component's class-factory prologue via SLICE_BUNDLE_DEPENDENCIES.
|
|
2812
|
+
return { keep: false, warning: null, external: true };
|
|
2134
2813
|
}
|
|
2135
2814
|
|
|
2136
2815
|
buildImportWarningMessage(baseMessage, sourceContext) {
|
|
@@ -2276,7 +2955,7 @@ if (window.slice && window.slice.controller) {
|
|
|
2276
2955
|
return entries;
|
|
2277
2956
|
}
|
|
2278
2957
|
|
|
2279
|
-
stripImportsWithFallbackRegex(code,
|
|
2958
|
+
stripImportsWithFallbackRegex(code, sourceContext, collectHoistedImports) {
|
|
2280
2959
|
const hoistedImports = [];
|
|
2281
2960
|
const importEntries = this.parseImportsWithFallbackScanner(code);
|
|
2282
2961
|
if (importEntries.length === 0) {
|
|
@@ -2287,7 +2966,7 @@ if (window.slice && window.slice.controller) {
|
|
|
2287
2966
|
let cursor = 0;
|
|
2288
2967
|
for (const entry of importEntries) {
|
|
2289
2968
|
const { start, end, statement, importPath } = entry;
|
|
2290
|
-
const classification = this.classifyImport(importPath
|
|
2969
|
+
const classification = this.classifyImport(importPath);
|
|
2291
2970
|
cleanedCode += code.slice(cursor, start);
|
|
2292
2971
|
if (classification.keep) {
|
|
2293
2972
|
if (collectHoistedImports) {
|
|
@@ -2308,7 +2987,6 @@ if (window.slice && window.slice.controller) {
|
|
|
2308
2987
|
|
|
2309
2988
|
stripImports(code, options = {}) {
|
|
2310
2989
|
const { sourceContext = null, collectHoistedImports = false } = options;
|
|
2311
|
-
const publicFolders = this.getConfiguredPublicFolders();
|
|
2312
2990
|
const hoistedImports = [];
|
|
2313
2991
|
|
|
2314
2992
|
try {
|
|
@@ -2323,7 +3001,7 @@ if (window.slice && window.slice.controller) {
|
|
|
2323
3001
|
|
|
2324
3002
|
for (const node of importNodes) {
|
|
2325
3003
|
const importPath = node.source?.value;
|
|
2326
|
-
const classification = this.classifyImport(importPath
|
|
3004
|
+
const classification = this.classifyImport(importPath);
|
|
2327
3005
|
const statement = code.slice(node.start, node.end);
|
|
2328
3006
|
|
|
2329
3007
|
cleaned += code.slice(cursor, node.start);
|
|
@@ -2345,7 +3023,7 @@ if (window.slice && window.slice.controller) {
|
|
|
2345
3023
|
? { code: cleaned, hoistedImports }
|
|
2346
3024
|
: cleaned;
|
|
2347
3025
|
} catch (error) {
|
|
2348
|
-
const fallback = this.stripImportsWithFallbackRegex(code,
|
|
3026
|
+
const fallback = this.stripImportsWithFallbackRegex(code, sourceContext, collectHoistedImports);
|
|
2349
3027
|
return collectHoistedImports ? fallback : fallback.code;
|
|
2350
3028
|
}
|
|
2351
3029
|
}
|
|
@@ -2488,7 +3166,7 @@ export const SLICE_BUNDLE_CONFIG = null;
|
|
|
2488
3166
|
generateBundleConfigJS(config) {
|
|
2489
3167
|
return `/**
|
|
2490
3168
|
* Slice.js Bundle Configuration
|
|
2491
|
-
* Generated: ${
|
|
3169
|
+
* Generated: ${resolveBuildTimestamp()}
|
|
2492
3170
|
* Strategy: ${config.strategy}
|
|
2493
3171
|
*/
|
|
2494
3172
|
|
|
@@ -2513,7 +3191,9 @@ if (typeof window !== 'undefined' && window.slice && window.slice.controller) {
|
|
|
2513
3191
|
}
|
|
2514
3192
|
}
|
|
2515
3193
|
|
|
2516
|
-
|
|
3194
|
+
// Load by the config's filename (which carries the content hash under
|
|
3195
|
+
// --hash-filenames) rather than a hardcoded name.
|
|
3196
|
+
import(bundlePath).catch(err =>
|
|
2517
3197
|
console.warn('Failed to load critical bundle:', err)
|
|
2518
3198
|
);
|
|
2519
3199
|
window.slice.controller.criticalBundleLoaded = true;
|