slicejs-cli 3.8.1 → 4.0.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.
@@ -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.size + dependencies.reduce((sum, dep) => sum + dep.size, 0);
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.size;
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.size;
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.reduce((sum, comp) => sum + comp.size, 0);
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 = sortedComponents.reduce((sum, component) => sum + component.size, 0);
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.size;
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.size;
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 = mergedComponents.reduce((sum, component) => sum + component.size, 0);
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
- const criticalIntegrity = this.computeBundleIntegrity(
740
- this.bundles.critical.components,
741
- 'critical',
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);
@@ -759,13 +850,9 @@ export default class BundleGenerator {
759
850
  'route',
760
851
  routeIdentifier
761
852
  );
762
- const routeIntegrity = `sha256:${routeFile.hash}`;
763
- const matchingBundle = Object.values(this.bundles.routes)
764
- .find((entry) => entry.file === routeFile.file);
765
- if (matchingBundle) {
766
- matchingBundle.hash = routeFile.hash;
767
- matchingBundle.integrity = routeIntegrity;
768
- }
853
+ bundle.file = routeFile.file;
854
+ bundle.hash = routeFile.hash;
855
+ bundle.integrity = `sha256:${routeFile.hash}`;
769
856
  files.push(routeFile);
770
857
  }
771
858
 
@@ -780,6 +867,7 @@ export default class BundleGenerator {
780
867
  this.vendorShared.dependencyUsage = usageIndex;
781
868
  this.vendorShared.sharedDependencySet = sharedDependencySet;
782
869
  this.vendorShared.bundleKeysUsingSharedDependencies = new Set();
870
+ this.vendorShared.criticalUsesShared = false;
783
871
 
784
872
  if (sharedDependencySet.size === 0) {
785
873
  return;
@@ -792,6 +880,10 @@ export default class BundleGenerator {
792
880
  }
793
881
  }
794
882
 
883
+ // The critical bundle participates in sharing too: if it uses a shared dep,
884
+ // it must load vendor-shared first and resolve from it (no inline copy).
885
+ this.vendorShared.criticalUsesShared = this.vendorShared.bundleKeysUsingSharedDependencies.has('critical');
886
+
795
887
  for (const bundleKey of this.vendorShared.bundleKeysUsingSharedDependencies) {
796
888
  const bundle = this.bundles.routes[bundleKey];
797
889
  if (!bundle) continue;
@@ -802,7 +894,15 @@ export default class BundleGenerator {
802
894
  async collectRouteExternalDependencyIndex() {
803
895
  const routeDependencyIndex = {};
804
896
 
805
- for (const [bundleKey, bundle] of Object.entries(this.bundles.routes)) {
897
+ // The critical bundle participates in shared-dependency detection alongside
898
+ // the route bundles: a package used by critical AND a route is extracted
899
+ // once into vendor-shared instead of being inlined in both.
900
+ const indexedBundles = [
901
+ ...Object.entries(this.bundles.routes),
902
+ ['critical', { components: this.bundles.critical.components || [] }]
903
+ ];
904
+
905
+ for (const [bundleKey, bundle] of indexedBundles) {
806
906
  routeDependencyIndex[bundleKey] = {};
807
907
  const uniqueComponents = this.dedupeComponentsByName(bundle.components || []);
808
908
 
@@ -811,15 +911,28 @@ export default class BundleGenerator {
811
911
  const jsPath = path.join(comp.path, `${fileBaseName}.js`);
812
912
  if (!await fs.pathExists(jsPath)) continue;
813
913
  const jsContent = await fs.readFile(jsPath, 'utf-8');
914
+ // Relative helper modules (inline content) + bare node_modules imports
915
+ // (pre-bundled esbuild expression), discovered in the component and its
916
+ // relative helpers. Both are candidates for extraction into the shared
917
+ // vendor bundle when used across multiple routes.
814
918
  const dependencies = await this.buildDependencyContents(jsContent, comp.path);
815
919
  for (const [depName, depEntry] of Object.entries(dependencies || {})) {
920
+ const isExternal = !!(depEntry && typeof depEntry === 'object' && depEntry.external);
921
+ // For external deps the shareable payload is the pre-bundled
922
+ // expression; skip any that failed to resolve (no expression).
923
+ const content = isExternal
924
+ ? (this.externalModulesByName.get(depName) || '')
925
+ : (depEntry?.content || '');
926
+ if (isExternal && !content) continue;
927
+
816
928
  if (!routeDependencyIndex[bundleKey][depName]) {
817
- routeDependencyIndex[bundleKey][depName] = depEntry;
929
+ routeDependencyIndex[bundleKey][depName] = { content, external: isExternal };
818
930
  }
819
931
  if (!this.vendorShared.dependencyModules.has(depName)) {
820
932
  this.vendorShared.dependencyModules.set(depName, {
821
933
  name: depName,
822
- content: depEntry?.content || ''
934
+ content,
935
+ external: isExternal
823
936
  });
824
937
  }
825
938
  }
@@ -839,7 +952,8 @@ export default class BundleGenerator {
839
952
  name: dependencyName,
840
953
  bundleKeys: new Set(),
841
954
  bundleCount: 0,
842
- content: dependencyEntry?.content || ''
955
+ content: dependencyEntry?.content || '',
956
+ external: !!dependencyEntry?.external
843
957
  });
844
958
  }
845
959
  const entry = usage.get(dependencyName);
@@ -856,13 +970,16 @@ export default class BundleGenerator {
856
970
 
857
971
  for (const [dependencyName, entry] of usageIndex.entries()) {
858
972
  if ((entry?.bundleCount || 0) < this.config.minVendorSharedUsage) continue;
859
- const transformedContent = this.transformDependencyContent(
860
- entry?.content || '',
861
- '__sliceVendorSharedProbe',
862
- dependencyName
863
- );
864
- const transformedSize = Buffer.byteLength(transformedContent, 'utf-8');
865
- if (transformedSize < this.config.minVendorSharedTransformedSize) continue;
973
+ // External deps are already fully-bundled esbuild expressions — measure
974
+ // them directly. Relative helper modules are measured after the export
975
+ // rewrite, matching how they will actually be emitted.
976
+ const measuredSize = entry?.external
977
+ ? Buffer.byteLength(entry?.content || '', 'utf-8')
978
+ : Buffer.byteLength(
979
+ this.transformDependencyContent(entry?.content || '', '__sliceVendorSharedProbe', dependencyName),
980
+ 'utf-8'
981
+ );
982
+ if (measuredSize < this.config.minVendorSharedTransformedSize) continue;
866
983
  shared.add(dependencyName);
867
984
  }
868
985
 
@@ -873,10 +990,14 @@ export default class BundleGenerator {
873
990
  const selectedModules = Array.from(sharedDependencySet)
874
991
  .sort((a, b) => a.localeCompare(b))
875
992
  .map((dependencyName) => {
876
- const fromUsage = this.vendorShared.dependencyUsage.get(dependencyName)?.content;
877
- const fromCollected = this.vendorShared.dependencyModules.get(dependencyName)?.content;
878
- const content = fromUsage || fromCollected || '';
879
- return { name: dependencyName, content };
993
+ const usageEntry = this.vendorShared.dependencyUsage.get(dependencyName);
994
+ const collectedEntry = this.vendorShared.dependencyModules.get(dependencyName);
995
+ const content = usageEntry?.content || collectedEntry?.content || '';
996
+ // External modules are emitted from their pre-bundled expression (looked
997
+ // up by name in buildV2DependencyModuleBlockFromModules), so the flag
998
+ // must survive here.
999
+ const external = !!(usageEntry?.external || collectedEntry?.external);
1000
+ return { name: dependencyName, content, external };
880
1001
  })
881
1002
  .filter((entry) => !!entry.content);
882
1003
 
@@ -894,20 +1015,15 @@ export default class BundleGenerator {
894
1015
  }
895
1016
 
896
1017
  async createVendorSharedDependencyBundleFile(sharedDependencySet) {
897
- const fileName = this.vendorShared.file;
898
- const filePath = path.join(this.bundlesPath, fileName);
1018
+ const baseFileName = this.vendorShared.file;
899
1019
  const bundleContent = this.generateVendorSharedDependencyBundleContent(sharedDependencySet);
900
- const finalContent = await this.applyBundleTransforms(bundleContent, fileName);
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');
1020
+ const { file, path: filePath, hash, rawSize } = await this.emitBundleArtifact(baseFileName, bundleContent);
905
1021
 
906
1022
  return {
907
1023
  name: 'vendor-shared',
908
- file: fileName,
1024
+ file,
909
1025
  path: filePath,
910
- size: Buffer.byteLength(bundleContent, 'utf-8'),
1026
+ size: rawSize,
911
1027
  hash,
912
1028
  integrity: `sha256:${hash}`,
913
1029
  componentCount: 0
@@ -919,39 +1035,41 @@ export default class BundleGenerator {
919
1035
  */
920
1036
  async createBundleFile(components, type, routePath) {
921
1037
  const routeKey = routePath ? this.routeToFileName(routePath) : 'critical';
922
- const fileName = `slice-bundle.${routeKey}.js`;
923
- const filePath = path.join(this.bundlesPath, fileName);
1038
+ const baseFileName = `slice-bundle.${routeKey}.js`;
924
1039
 
925
1040
  const bundleContent = await this.generateBundleContent(
926
1041
  components,
927
1042
  type,
928
1043
  routePath,
929
1044
  routeKey,
930
- fileName
1045
+ baseFileName
931
1046
  );
932
1047
 
933
- const finalContent = await this.applyBundleTransforms(bundleContent, fileName);
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');
1048
+ const { file, path: filePath, hash, rawSize } = await this.emitBundleArtifact(baseFileName, bundleContent);
939
1049
 
940
1050
  return {
941
1051
  name: routeKey,
942
- file: fileName,
1052
+ file,
943
1053
  path: filePath,
944
- size: Buffer.byteLength(bundleContent, 'utf-8'),
1054
+ size: rawSize,
945
1055
  hash,
946
1056
  componentCount: components.length
947
1057
  };
948
1058
  }
949
1059
 
1060
+ /**
1061
+ * Minifies/obfuscates a bundle and (when `--sourcemap` is on) produces a
1062
+ * source map. Returns `{ code, map }`; `map` is the raw source-map JSON string
1063
+ * or null. The `//# sourceMappingURL` comment is NOT appended here — the
1064
+ * caller does that once it knows the final (possibly hashed) filename.
1065
+ * @returns {Promise<{ code: string, map: string|null }>}
1066
+ */
950
1067
  async applyBundleTransforms(bundleContent, fileName) {
951
1068
  if (!this.options.minify && !this.options.obfuscate) {
952
- return bundleContent;
1069
+ return { code: bundleContent, map: null };
953
1070
  }
954
1071
 
1072
+ const wantMap = !!this.options.sourcemap;
955
1073
  const options = {
956
1074
  parse: {
957
1075
  ecma: 2022
@@ -970,7 +1088,11 @@ export default class BundleGenerator {
970
1088
  format: {
971
1089
  comments: false,
972
1090
  ecma: 2022
973
- }
1091
+ },
1092
+ // Map the minified output back to the readable pre-minified bundle
1093
+ // (embedded via includeSources so DevTools shows it without a sidecar
1094
+ // source). The URL comment is appended by the caller.
1095
+ ...(wantMap ? { sourceMap: { includeSources: true, filename: fileName } } : {})
974
1096
  };
975
1097
 
976
1098
  let result;
@@ -1003,9 +1125,311 @@ export default class BundleGenerator {
1003
1125
  throw new Error(`Terser failed for ${fileName}: ${result.error.message}. Saved bundle to ${tmpPath}`);
1004
1126
  }
1005
1127
 
1006
- return result.code || bundleContent;
1128
+ return { code: result.code || bundleContent, map: wantMap ? (result.map || null) : null };
1129
+ }
1130
+
1131
+ /**
1132
+ * Inserts an 8-char content hash into a bundle filename for cache-busting
1133
+ * (`slice-bundle.home.js` → `slice-bundle.home.a1b2c3d4.js`), matching how
1134
+ * traditional bundlers name immutable assets. Only active under `--hash-filenames`.
1135
+ */
1136
+ hashBundleFileName(baseFileName, code) {
1137
+ if (!this.options.hashFilenames) return baseFileName;
1138
+ const hash = crypto.createHash('sha256').update(code).digest('hex').slice(0, 8);
1139
+ return baseFileName.replace(/\.js$/, `.${hash}.js`);
1140
+ }
1141
+
1142
+ /**
1143
+ * Central bundle writer: transforms the raw content, resolves the final
1144
+ * (optionally content-hashed) filename, appends the source-map URL + writes the
1145
+ * `.map` when enabled, writes the `.js`, and returns the emitted name + paths +
1146
+ * integrity hash. Every bundle file (route, critical, vendor-shared, framework)
1147
+ * goes through here so cache-busting and source maps apply uniformly.
1148
+ * @returns {Promise<{ file: string, path: string, hash: string, rawSize: number }>}
1149
+ */
1150
+ async emitBundleArtifact(baseFileName, rawContent) {
1151
+ const { code, map } = await this.applyBundleTransforms(rawContent, baseFileName);
1152
+ const fileName = this.hashBundleFileName(baseFileName, code);
1153
+ let finalCode = code;
1154
+ if (map) {
1155
+ finalCode += `\n//# sourceMappingURL=${fileName}.map\n`;
1156
+ }
1157
+ const filePath = path.join(this.bundlesPath, fileName);
1158
+ await fs.ensureDir(path.dirname(filePath));
1159
+ await fs.writeFile(filePath, finalCode, 'utf-8');
1160
+ if (map) {
1161
+ await fs.writeFile(path.join(this.bundlesPath, `${fileName}.map`), map, 'utf-8');
1162
+ }
1163
+ const hash = crypto.createHash('sha256').update(finalCode).digest('hex');
1164
+ return { file: fileName, path: filePath, hash, rawSize: Buffer.byteLength(rawContent, 'utf-8') };
1165
+ }
1166
+
1167
+
1168
+ /**
1169
+ * Bare-package (node_modules) imports are always resolved and bundled — no
1170
+ * configuration needed, mirroring how a React/Vite project imports npm
1171
+ * packages. Kept as a method so call sites read intently.
1172
+ */
1173
+ isExternalDependenciesEnabled() {
1174
+ return true;
1175
+ }
1176
+
1177
+ /**
1178
+ * Every resolvable bare specifier is allowed. Retained so call sites are
1179
+ * uniform; there is no allowlist to configure.
1180
+ */
1181
+ isExternalAllowed() {
1182
+ return true;
1183
+ }
1184
+
1185
+ getExternalBundler() {
1186
+ if (!this.externalBundler) {
1187
+ this.externalBundler = new ExternalModuleBundler({
1188
+ resolveDir: getProjectRoot(this.moduleUrl),
1189
+ minify: this.options.minify
1190
+ });
1191
+ }
1192
+ return this.externalBundler;
1193
+ }
1194
+
1195
+ /**
1196
+ * Extracts bare-package imports from a component's source. Returns one entry
1197
+ * per unique bare specifier with the merged local bindings and whether any
1198
+ * consumer needs the default export (default import or namespace import).
1199
+ * @param {string} code
1200
+ * @returns {Array<{ name: string, bindings: Array, needsDefault: boolean }>}
1201
+ */
1202
+ analyzeBareImports(code) {
1203
+ const byName = new Map();
1204
+
1205
+ const record = (name, bindings, needsDefault) => {
1206
+ if (!ExternalModuleBundler.isBareSpecifier(name)) return;
1207
+ if (!this.isExternalAllowed(name)) return;
1208
+ if (!byName.has(name)) {
1209
+ byName.set(name, { name, bindings: [], needsDefault: false });
1210
+ }
1211
+ const entry = byName.get(name);
1212
+ entry.bindings.push(...bindings);
1213
+ entry.needsDefault = entry.needsDefault || needsDefault;
1214
+ };
1215
+
1216
+ try {
1217
+ const ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
1218
+ traverse.default(ast, {
1219
+ ImportDeclaration(pathNode) {
1220
+ const source = pathNode.node.source?.value;
1221
+ if (typeof source !== 'string') return;
1222
+
1223
+ const bindings = [];
1224
+ let needsDefault = false;
1225
+
1226
+ for (const spec of pathNode.node.specifiers || []) {
1227
+ if (spec.type === 'ImportDefaultSpecifier') {
1228
+ bindings.push({ type: 'default', importedName: 'default', localName: spec.local.name });
1229
+ needsDefault = true;
1230
+ } else if (spec.type === 'ImportNamespaceSpecifier') {
1231
+ bindings.push({ type: 'namespace', localName: spec.local.name });
1232
+ needsDefault = true; // namespace may read `.default`
1233
+ } else if (spec.type === 'ImportSpecifier') {
1234
+ bindings.push({
1235
+ type: 'named',
1236
+ importedName: spec.imported?.name ?? spec.imported?.value,
1237
+ localName: spec.local.name
1238
+ });
1239
+ }
1240
+ }
1241
+
1242
+ record(source, bindings, needsDefault);
1243
+ },
1244
+
1245
+ // Re-exports from a bare package (`export * from 'pkg'`,
1246
+ // `export { default as X } from 'pkg'`). record() ignores relative
1247
+ // sources, so this only registers the package for bundling; the emission
1248
+ // is handled in transformDependencyStatement.
1249
+ ExportAllDeclaration(pathNode) {
1250
+ const source = pathNode.node.source?.value;
1251
+ if (typeof source === 'string') record(source, [], false);
1252
+ },
1253
+
1254
+ ExportNamedDeclaration(pathNode) {
1255
+ const source = pathNode.node.source?.value;
1256
+ if (typeof source !== 'string') return;
1257
+ // `export { default as X } from 'pkg'` needs the package default built.
1258
+ const needsDefault = (pathNode.node.specifiers || []).some((s) => s.local?.name === 'default');
1259
+ record(source, [], needsDefault);
1260
+ },
1261
+
1262
+ // Dynamic `import('pkg')` — resolves to a module namespace at runtime, so
1263
+ // register it (no static bindings) and request the default so the
1264
+ // namespace exposes `.default` when the package has one.
1265
+ CallExpression(pathNode) {
1266
+ const node = pathNode.node;
1267
+ if (node.callee?.type === 'Import' && node.arguments?.[0]?.type === 'StringLiteral') {
1268
+ record(node.arguments[0].value, [], true);
1269
+ }
1270
+ }
1271
+ });
1272
+ } catch (error) {
1273
+ console.warn(`Warning: Could not analyze bare imports: ${error.message}`);
1274
+ }
1275
+
1276
+ return Array.from(byName.values());
1277
+ }
1278
+
1279
+ /**
1280
+ * Rewrites dynamic `import('pkg')` of bare packages to resolve from the
1281
+ * bundle's registered dependencies (vendor-shared first, then the local
1282
+ * SLICE_BUNDLE_DEPENDENCIES). Relative/absolute dynamic imports are left
1283
+ * untouched.
1284
+ * @param {string} code
1285
+ * @returns {string}
1286
+ */
1287
+ rewriteDynamicExternalImports(code) {
1288
+ if (!this.isExternalDependenciesEnabled()) return code;
1289
+
1290
+ let ast;
1291
+ try {
1292
+ ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
1293
+ } catch {
1294
+ return code;
1295
+ }
1296
+
1297
+ const edits = [];
1298
+ const isAllowedBare = (spec) =>
1299
+ ExternalModuleBundler.isBareSpecifier(spec) && this.isExternalAllowed(spec);
1300
+
1301
+ traverse.default(ast, {
1302
+ CallExpression: (pathNode) => {
1303
+ const node = pathNode.node;
1304
+ if (
1305
+ node.callee?.type === 'Import' &&
1306
+ node.arguments?.[0]?.type === 'StringLiteral' &&
1307
+ typeof node.start === 'number' &&
1308
+ typeof node.end === 'number'
1309
+ ) {
1310
+ const spec = node.arguments[0].value;
1311
+ if (isAllowedBare(spec)) {
1312
+ edits.push({ start: node.start, end: node.end, spec });
1313
+ }
1314
+ }
1315
+ }
1316
+ });
1317
+
1318
+ if (edits.length === 0) return code;
1319
+
1320
+ // Apply from the end so earlier offsets stay valid.
1321
+ edits.sort((a, b) => b.start - a.start);
1322
+ let out = code;
1323
+ for (const { start, end, spec } of edits) {
1324
+ const key = JSON.stringify(spec);
1325
+ const replacement =
1326
+ `Promise.resolve((typeof window!=="undefined"&&window.__SLICE_SHARED_DEPS__&&${key} in window.__SLICE_SHARED_DEPS__)` +
1327
+ `?window.__SLICE_SHARED_DEPS__[${key}]:SLICE_BUNDLE_DEPENDENCIES[${key}])`;
1328
+ out = out.slice(0, start) + replacement + out.slice(end);
1329
+ }
1330
+ return out;
1331
+ }
1332
+
1333
+ /**
1334
+ * Builds the per-component external-dependency map for bare imports, keyed by
1335
+ * bare specifier. Shaped to slot alongside the relative-dependency map so the
1336
+ * existing binding/registration machinery treats both uniformly.
1337
+ * @param {string} code
1338
+ * @returns {Record<string, { external: true, bindings: Array, needsDefault: boolean }>}
1339
+ */
1340
+ collectComponentBareDependencies(code) {
1341
+ if (!this.isExternalDependenciesEnabled()) return {};
1342
+ const out = {};
1343
+ for (const imp of this.analyzeBareImports(code)) {
1344
+ out[imp.name] = { external: true, bindings: imp.bindings, needsDefault: imp.needsDefault };
1345
+ }
1346
+ return out;
1347
+ }
1348
+
1349
+ /**
1350
+ * Collects every bare (node_modules) import reachable from an entry file,
1351
+ * following relative helper imports transitively. Returns a map of
1352
+ * packageName -> needsDefault (aggregated across all reachable sites).
1353
+ * @param {string} entryPath absolute path to the component's entry .js
1354
+ * @returns {Promise<Map<string, boolean>>}
1355
+ */
1356
+ async collectReachableBareImports(entryPath) {
1357
+ const found = new Map();
1358
+ const visited = new Set();
1359
+
1360
+ const walk = async (filePath) => {
1361
+ if (visited.has(filePath)) return;
1362
+ visited.add(filePath);
1363
+
1364
+ let code;
1365
+ try {
1366
+ code = await fs.readFile(filePath, 'utf-8');
1367
+ } catch {
1368
+ return;
1369
+ }
1370
+
1371
+ for (const imp of this.analyzeBareImports(code)) {
1372
+ found.set(imp.name, (found.get(imp.name) || false) || imp.needsDefault);
1373
+ }
1374
+ // Follow relative helper modules so packages imported only by a helper
1375
+ // are discovered too.
1376
+ for (const dep of this.analyzeDependencies(code, path.dirname(filePath))) {
1377
+ await walk(dep.path);
1378
+ }
1379
+ };
1380
+
1381
+ await walk(entryPath);
1382
+ return found;
1007
1383
  }
1008
1384
 
1385
+ /**
1386
+ * Resolves and bundles every bare import used across the app's components with
1387
+ * esbuild, once per package, before bundle files are emitted. needsDefault is
1388
+ * aggregated globally so a package default-imported anywhere is always built
1389
+ * with its default export available. Bare imports inside relative helper
1390
+ * modules are discovered transitively.
1391
+ */
1392
+ async prepareExternalModules() {
1393
+ if (!this.isExternalDependenciesEnabled()) return;
1394
+
1395
+ const needsDefault = new Map();
1396
+ for (const comp of this.analysisData.components || []) {
1397
+ const fileBaseName = comp.fileName || comp.name;
1398
+ const jsPath = path.join(comp.path, `${fileBaseName}.js`);
1399
+ if (!await fs.pathExists(jsPath)) continue;
1400
+ const reachable = await this.collectReachableBareImports(jsPath);
1401
+ for (const [name, nd] of reachable) {
1402
+ needsDefault.set(name, (needsDefault.get(name) || false) || nd);
1403
+ }
1404
+ }
1405
+
1406
+ if (needsDefault.size === 0) return;
1407
+
1408
+ console.log(`📦 Resolving ${needsDefault.size} external dependenc${needsDefault.size === 1 ? 'y' : 'ies'} from node_modules...`);
1409
+
1410
+ for (const [name, nd] of needsDefault) {
1411
+ try {
1412
+ const { expression, warnings } = await this.getExternalBundler().bundle(name, { needsDefault: nd });
1413
+ this.externalModulesByName.set(name, expression);
1414
+ warnings.forEach((w) => console.warn(`Warning: [external:${name}] ${w}`));
1415
+ console.log(` ✓ ${name}`);
1416
+ } catch (error) {
1417
+ this.externalResolutionErrors.set(name, error.message);
1418
+ console.warn(`Warning: ${error.message}`);
1419
+ console.warn(` Components importing "${name}" will fail at runtime unless it is provided another way (a file under src/public/).`);
1420
+ }
1421
+ }
1422
+
1423
+ // In strict mode, any unresolved dependency fails the build so a broken
1424
+ // bundle never ships silently.
1425
+ if (this.strictExternal && this.externalResolutionErrors.size > 0) {
1426
+ const names = Array.from(this.externalResolutionErrors.keys()).sort().join(', ');
1427
+ throw new Error(
1428
+ `Strict external dependencies: ${this.externalResolutionErrors.size} package(s) could not be resolved from node_modules: ${names}. ` +
1429
+ `Install them or remove the imports.`
1430
+ );
1431
+ }
1432
+ }
1009
1433
 
1010
1434
  /**
1011
1435
  * Analyzes dependencies of a JavaScript file using simple regex
@@ -1077,8 +1501,28 @@ export default class BundleGenerator {
1077
1501
 
1078
1502
  dependencies.push({
1079
1503
  path: resolvedPath,
1080
- bindings
1504
+ bindings,
1505
+ specifier: importPath
1081
1506
  });
1507
+ },
1508
+
1509
+ // Re-export edges to a RELATIVE module (`export * from './x'`,
1510
+ // `export { a, b as c } from './x'`). These must inline + register the
1511
+ // target so the re-export can resolve at eval time; the exact binding
1512
+ // mapping is read back from the statement in transformDependencyStatement,
1513
+ // so no bindings need to be carried here.
1514
+ ExportNamedDeclaration(pathNode) {
1515
+ const src = pathNode.node.source?.value;
1516
+ if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
1517
+ const resolvedPath = resolveImportPath(src);
1518
+ if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
1519
+ },
1520
+
1521
+ ExportAllDeclaration(pathNode) {
1522
+ const src = pathNode.node.source?.value;
1523
+ if (typeof src !== 'string' || (!src.startsWith('./') && !src.startsWith('../'))) return;
1524
+ const resolvedPath = resolveImportPath(src);
1525
+ if (resolvedPath) dependencies.push({ path: resolvedPath, bindings: [], specifier: src });
1082
1526
  }
1083
1527
  });
1084
1528
  } catch (error) {
@@ -1116,6 +1560,11 @@ export default class BundleGenerator {
1116
1560
 
1117
1561
  const cleanedJavaScript = this.cleanJavaScript(jsContent, comp.name, jsPath);
1118
1562
 
1563
+ // buildDependencyContents returns both relative helper modules (keyed by
1564
+ // src-relative path) and bare node_modules imports (keyed by bare
1565
+ // specifier, discovered in the component and its relative helpers).
1566
+ const externalDependencies = await this.buildDependencyContents(jsContent, comp.path);
1567
+
1119
1568
  bundleComponents.push({
1120
1569
  name: comp.name,
1121
1570
  category: comp.category,
@@ -1124,7 +1573,7 @@ export default class BundleGenerator {
1124
1573
  hoistedImports: cleanedJavaScript.hoistedImports,
1125
1574
  html: htmlContent,
1126
1575
  css: cssContent,
1127
- externalDependencies: await this.buildDependencyContents(jsContent, comp.path),
1576
+ externalDependencies,
1128
1577
  size: comp.size
1129
1578
  });
1130
1579
  }
@@ -1154,9 +1603,13 @@ export default class BundleGenerator {
1154
1603
 
1155
1604
  const dependencyModules = this.collectDependencyModulesFromComponents(uniqueComponents);
1156
1605
  const isRouteBundle = type === 'route';
1606
+ // The critical bundle also resolves from vendor-shared when it uses a shared
1607
+ // dependency (see prepareVendorSharedDependencies): it loads vendor-shared
1608
+ // first and omits its own inline copy, exactly like a route bundle.
1609
+ const usesVendorShared = isRouteBundle || (type === 'critical' && this.vendorShared.criticalUsesShared);
1157
1610
  const dependencyModuleBlock = this.buildV2DependencyModuleBlock(uniqueComponents, {
1158
- includeSharedResolver: isRouteBundle,
1159
- omittedDependencies: isRouteBundle ? this.vendorShared.sharedDependencySet : null
1611
+ includeSharedResolver: usesVendorShared,
1612
+ omittedDependencies: usesVendorShared ? this.vendorShared.sharedDependencySet : null
1160
1613
  });
1161
1614
  const rawHoistedImports = uniqueComponents
1162
1615
  .flatMap((component) => component.hoistedImports || [])
@@ -1177,7 +1630,7 @@ export default class BundleGenerator {
1177
1630
  .map((component) => {
1178
1631
  const factoryName = this.classFactoryName(component.name);
1179
1632
  const dependencyBindings = this.buildDependencyBindings(component.externalDependencies || {}, {
1180
- preferShared: isRouteBundle
1633
+ preferShared: usesVendorShared
1181
1634
  });
1182
1635
  const body = component.js && component.js.trim()
1183
1636
  ? component.js
@@ -1263,12 +1716,41 @@ export default class BundleGenerator {
1263
1716
  lines.push(...this.getBundleDependencyResolverLines());
1264
1717
  }
1265
1718
  filteredModules.forEach((module, index) => {
1719
+ // External (node_modules) modules are emitted from their pre-bundled
1720
+ // esbuild expression, which already yields a module-namespace-like object
1721
+ // (named exports + a `default` key). No Babel export-rewriting needed.
1722
+ if (module.external) {
1723
+ const expression = this.externalModulesByName.get(module.name);
1724
+ lines.push(`// External dependency: ${module.name}`);
1725
+ if (expression) {
1726
+ lines.push(`SLICE_BUNDLE_DEPENDENCIES[${JSON.stringify(module.name)}] = ${expression};`);
1727
+ } else {
1728
+ // Resolution failed earlier (already warned). Emit an empty namespace
1729
+ // so the bundle still evaluates; the binding resolves to undefined.
1730
+ lines.push(`SLICE_BUNDLE_DEPENDENCIES[${JSON.stringify(module.name)}] = {};`);
1731
+ }
1732
+ return;
1733
+ }
1734
+
1266
1735
  const exportVar = `__sliceDepExports${index}`;
1267
1736
  // Evaluate each dependency inside its own IIFE so its private,
1268
1737
  // non-exported top-level bindings stay local and cannot collide with
1269
1738
  // another dependency's (or the bundle's) identifiers. Only the exports
1270
1739
  // object escapes the closure.
1271
- const transformedContent = this.transformDependencyContent(module.content, '__sliceExports', module.name);
1740
+ // Map each relative import/re-export specifier this module used to the
1741
+ // src-relative key it was registered under, so a re-export resolves its
1742
+ // source without touching the filesystem.
1743
+ const specifierToKey = new Map(
1744
+ (module.moduleImports || [])
1745
+ .filter((mi) => mi.specifier && mi.depName)
1746
+ .map((mi) => [mi.specifier, mi.depName])
1747
+ );
1748
+ const transformedContent = this.transformDependencyContent(module.content, '__sliceExports', module.name, {
1749
+ // A re-export inside this helper must resolve its source through the same
1750
+ // shared resolver the bundle uses, since the source may live in vendor-shared.
1751
+ preferShared: !!options.includeSharedResolver,
1752
+ specifierToKey
1753
+ });
1272
1754
  // Bind this module's own (transitive) imports inside its IIFE — they were
1273
1755
  // registered by earlier modules in the topological order.
1274
1756
  const importBindings = this.buildDependencyBindings(
@@ -1321,9 +1803,25 @@ export default class BundleGenerator {
1321
1803
  const resolveModule = async (content, basePath) => {
1322
1804
  const consumerImports = [];
1323
1805
 
1806
+ // Bare (node_modules) imports of THIS module. They become moduleImports of
1807
+ // the consumer (so a helper's IIFE binds them from SLICE_BUNDLE_DEPENDENCIES)
1808
+ // and are registered once as external modules keyed by bare name.
1809
+ if (this.isExternalDependenciesEnabled()) {
1810
+ for (const bare of this.analyzeBareImports(content)) {
1811
+ consumerImports.push({ depName: bare.name, bindings: bare.bindings || [], external: true });
1812
+ if (!dependencyContents[bare.name]) {
1813
+ dependencyContents[bare.name] = { external: true, bindings: [], needsDefault: false };
1814
+ }
1815
+ dependencyContents[bare.name].needsDefault =
1816
+ dependencyContents[bare.name].needsDefault || bare.needsDefault;
1817
+ }
1818
+ }
1819
+
1324
1820
  for (const dep of this.analyzeDependencies(content, basePath)) {
1325
1821
  const depName = path.relative(this.srcPath, dep.path).replace(/\\/g, '/');
1326
- consumerImports.push({ depName, bindings: dep.bindings || [] });
1822
+ // Carry the original specifier so a re-export (`export … from './x'`) can
1823
+ // map it back to the registered key without touching the filesystem.
1824
+ consumerImports.push({ depName, bindings: dep.bindings || [], specifier: dep.specifier });
1327
1825
 
1328
1826
  if (visited.has(depName)) continue;
1329
1827
  visited.add(depName);
@@ -1342,10 +1840,17 @@ export default class BundleGenerator {
1342
1840
  };
1343
1841
 
1344
1842
  const directImports = await resolveModule(jsContent, componentPath);
1345
- // The component's direct imports drive its class-factory bindings.
1346
- for (const { depName, bindings } of directImports) {
1347
- if (dependencyContents[depName]) {
1348
- dependencyContents[depName].bindings = bindings;
1843
+ // The component's direct imports drive its class-factory bindings. For a
1844
+ // package the component imports directly, those bindings belong on the
1845
+ // external entry; helper-only packages keep empty component-level bindings
1846
+ // (their bindings live in the helper's moduleImports).
1847
+ for (const { depName, bindings, external } of directImports) {
1848
+ const entry = dependencyContents[depName];
1849
+ if (!entry) continue;
1850
+ if (external) {
1851
+ entry.bindings = (entry.bindings || []).concat(bindings || []);
1852
+ } else {
1853
+ entry.bindings = bindings;
1349
1854
  }
1350
1855
  }
1351
1856
 
@@ -1367,6 +1872,11 @@ export default class BundleGenerator {
1367
1872
  const hoistedImports = stripped.hoistedImports || [];
1368
1873
  code = stripped.code;
1369
1874
 
1875
+ // Rewrite dynamic `import('pkg')` of bare packages so they resolve from the
1876
+ // registered dependency at runtime (native dynamic import of a bare
1877
+ // specifier has no resolver in the built output).
1878
+ code = this.rewriteDynamicExternalImports(code);
1879
+
1370
1880
  // Guard customElements.define to avoid duplicate registrations
1371
1881
  code = code.replace(
1372
1882
  /customElements\.define\(([^)]+)\);?/g,
@@ -1523,6 +2033,12 @@ if (window.slice && window.slice.controller) {
1523
2033
  const externalDependencies = component.externalDependencies || {};
1524
2034
  for (const [moduleName, entry] of Object.entries(externalDependencies)) {
1525
2035
  if (modules.has(moduleName)) continue;
2036
+ // External (node_modules) modules carry no inline content — they are
2037
+ // emitted from the pre-bundled esbuild expression keyed by bare name.
2038
+ if (entry && typeof entry === 'object' && entry.external) {
2039
+ modules.set(moduleName, { name: moduleName, external: true, content: null, moduleImports: [] });
2040
+ continue;
2041
+ }
1526
2042
  const content = typeof entry === 'string' ? entry : entry?.content;
1527
2043
  if (!content) continue;
1528
2044
  const moduleImports = (entry && typeof entry === 'object' ? entry.moduleImports : null) || [];
@@ -1536,7 +2052,35 @@ if (window.slice && window.slice.controller) {
1536
2052
  return (dependencyModules || []).map((_, index) => `__sliceDepExports${index}`);
1537
2053
  }
1538
2054
 
1539
- transformDependencyContent(content, exportVar, moduleName) {
2055
+ /**
2056
+ * A relative `.json` dependency (`import cfg from './data.json'`) is data, not
2057
+ * a JS module. Embed it as a literal (JSON is a subset of JS expression
2058
+ * syntax): the whole document as the `default` export, plus each top-level key
2059
+ * as a named export (matching how Vite/webpack expose JSON).
2060
+ */
2061
+ transformJsonModule(content, exportVar) {
2062
+ const trimmed = String(content).trim();
2063
+ try {
2064
+ JSON.parse(trimmed || 'null');
2065
+ } catch (error) {
2066
+ console.warn(`Warning: Invalid JSON dependency: ${error.message}. Emitting empty exports.`);
2067
+ return `${exportVar}.default = {};`;
2068
+ }
2069
+ const literal = trimmed || 'null';
2070
+ return [
2071
+ `const __sliceJson = ${literal};`,
2072
+ `${exportVar}.default = __sliceJson;`,
2073
+ `if (__sliceJson && typeof __sliceJson === "object" && !Array.isArray(__sliceJson)) { for (const __k in __sliceJson) { if (__k !== "default") ${exportVar}[__k] = __sliceJson[__k]; } }`
2074
+ ].join('\n');
2075
+ }
2076
+
2077
+ transformDependencyContent(content, exportVar, moduleName, options = {}) {
2078
+ // A `.json` dependency is data — embed it directly instead of parsing it as
2079
+ // a JS module (which would drop its contents).
2080
+ if (typeof moduleName === 'string' && moduleName.endsWith('.json')) {
2081
+ return this.transformJsonModule(content, exportVar);
2082
+ }
2083
+
1540
2084
  let ast;
1541
2085
  try {
1542
2086
  ast = parse(content, { sourceType: 'module', plugins: ['jsx'] });
@@ -1555,13 +2099,69 @@ if (window.slice && window.slice.controller) {
1555
2099
  let output = '';
1556
2100
  for (const node of statements) {
1557
2101
  output += content.slice(cursor, node.start);
1558
- output += this.transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey);
2102
+ output += this.transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey, options);
1559
2103
  cursor = node.end;
1560
2104
  }
1561
2105
  output += content.slice(cursor);
1562
2106
  return output;
1563
2107
  }
1564
2108
 
2109
+ /** RHS member access on a resolved dependency object: `.name` or `["weird-name"]`. */
2110
+ describeMemberAccess(name) {
2111
+ return /^[A-Za-z_$][\w$]*$/.test(name) ? `.${name}` : `[${JSON.stringify(name)}]`;
2112
+ }
2113
+
2114
+ /**
2115
+ * Resolves a relative import specifier written inside a bundled helper module
2116
+ * to the src-relative key it was registered under (matching analyzeDependencies'
2117
+ * depName computation), so a re-export can look it up in SLICE_BUNDLE_DEPENDENCIES.
2118
+ * @param {string} moduleName the helper's own src-relative path
2119
+ * @param {string} spec relative specifier (e.g. './x', '../lib/y.js')
2120
+ * @returns {string|null}
2121
+ */
2122
+ resolveRelativeModuleKey(moduleName, spec) {
2123
+ try {
2124
+ const moduleDir = path.dirname(path.join(this.srcPath, moduleName));
2125
+ let resolved = path.resolve(moduleDir, spec);
2126
+ if (!path.extname(resolved)) {
2127
+ for (const ext of ['.js', '.json', '.mjs']) {
2128
+ if (fs.existsSync(resolved + ext)) { resolved = resolved + ext; break; }
2129
+ }
2130
+ }
2131
+ if (!fs.existsSync(resolved)) return null;
2132
+ return path.relative(this.srcPath, resolved).replace(/\\/g, '/');
2133
+ } catch {
2134
+ return null;
2135
+ }
2136
+ }
2137
+
2138
+ /**
2139
+ * JS expression that yields the exports object of a re-export source, or null
2140
+ * if it can't be resolved (absolute/URL source, or a missing relative file).
2141
+ * Bare packages resolve by name; relative helpers resolve to their registered
2142
+ * key. Honors the shared resolver when the bundle uses vendor-shared.
2143
+ * @param {string} moduleName re-exporting helper's src-relative path
2144
+ * @param {string} src the re-export source specifier
2145
+ * @param {boolean} preferShared
2146
+ * @returns {string|null}
2147
+ */
2148
+ reexportDependencyExpression(moduleName, src, preferShared, specifierToKey = null) {
2149
+ if (typeof src !== 'string') return null;
2150
+ const keyFor = (name) => preferShared
2151
+ ? `__sliceResolveBundleDependency(${JSON.stringify(name)})`
2152
+ : `SLICE_BUNDLE_DEPENDENCIES[${JSON.stringify(name)}]`;
2153
+ if (ExternalModuleBundler.isBareSpecifier(src)) {
2154
+ return keyFor(src);
2155
+ }
2156
+ if (src.startsWith('.')) {
2157
+ // Prefer the already-resolved key recorded on the module's import edges
2158
+ // (fs-free, exact match); fall back to resolving against the filesystem.
2159
+ const key = (specifierToKey && specifierToKey.get(src)) || this.resolveRelativeModuleKey(moduleName, src);
2160
+ return key ? keyFor(key) : null;
2161
+ }
2162
+ return null; // absolute / URL re-export is unsupported
2163
+ }
2164
+
1565
2165
  describeExportTarget(exportVar, name) {
1566
2166
  return /^[A-Za-z_$][\w$]*$/.test(name)
1567
2167
  ? `${exportVar}.${name}`
@@ -1628,8 +2228,10 @@ if (window.slice && window.slice.controller) {
1628
2228
  return sourceOf(decl);
1629
2229
  }
1630
2230
 
1631
- transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey) {
2231
+ transformDependencyStatement(node, content, exportVar, moduleName, fallbackKey, options = {}) {
1632
2232
  const sourceOf = (n) => content.slice(n.start, n.end);
2233
+ const preferShared = !!options.preferShared;
2234
+ const specifierToKey = options.specifierToKey || null;
1633
2235
 
1634
2236
  if (node.type === 'ImportDeclaration') {
1635
2237
  // Transitive imports of a bundled dependency cannot be resolved at
@@ -1642,11 +2244,22 @@ if (window.slice && window.slice.controller) {
1642
2244
  }
1643
2245
 
1644
2246
  if (node.type === 'ExportAllDeclaration') {
1645
- console.warn(this.buildImportWarningMessage(
1646
- `Warning: Dropping unsupported 'export *' inside bundled dependency: ${node.source?.value}`,
1647
- moduleName
1648
- ));
1649
- return '';
2247
+ // `export * from './x'` (or 'pkg') — copy every own enumerable export of
2248
+ // the resolved module except `default` (per the ESM spec) onto the exports
2249
+ // object. The source module is registered earlier by the topological order.
2250
+ const depExpr = this.reexportDependencyExpression(moduleName, node.source?.value, preferShared, specifierToKey);
2251
+ if (!depExpr) {
2252
+ console.warn(this.buildImportWarningMessage(
2253
+ `Warning: Dropping unresolvable 'export *' inside bundled dependency: ${node.source?.value}`,
2254
+ moduleName
2255
+ ));
2256
+ return '';
2257
+ }
2258
+ const tmp = `__sliceReexportAll_${node.start}`;
2259
+ return [
2260
+ `const ${tmp} = ${depExpr};`,
2261
+ `for (const __k of Object.keys(${tmp})) { if (__k !== "default") ${exportVar}[__k] = ${tmp}[__k]; }`
2262
+ ].join('\n');
1650
2263
  }
1651
2264
 
1652
2265
  if (node.type === 'ExportDefaultDeclaration') {
@@ -1662,11 +2275,27 @@ if (window.slice && window.slice.controller) {
1662
2275
 
1663
2276
  if (node.type === 'ExportNamedDeclaration') {
1664
2277
  if (node.source) {
1665
- console.warn(this.buildImportWarningMessage(
1666
- `Warning: Dropping unsupported re-export inside bundled dependency: ${node.source.value}`,
1667
- moduleName
1668
- ));
1669
- return '';
2278
+ // `export { a, b as c } from './x'` (or 'pkg') — map each PUBLIC name to
2279
+ // the corresponding member of the resolved module's exports object.
2280
+ const depExpr = this.reexportDependencyExpression(moduleName, node.source.value, preferShared, specifierToKey);
2281
+ if (!depExpr) {
2282
+ console.warn(this.buildImportWarningMessage(
2283
+ `Warning: Dropping unresolvable re-export inside bundled dependency: ${node.source.value}`,
2284
+ moduleName
2285
+ ));
2286
+ return '';
2287
+ }
2288
+ const tmp = `__sliceReexport_${node.start}`;
2289
+ const lines = [`const ${tmp} = ${depExpr};`];
2290
+ for (const spec of node.specifiers || []) {
2291
+ // ExportSpecifier: `local` is the name in the source module, `exported`
2292
+ // is the public name. `export { default as X }` maps X <- tmp.default.
2293
+ const localName = spec.local?.name ?? spec.local?.value;
2294
+ const exportedName = spec.exported?.name ?? spec.exported?.value;
2295
+ if (!localName || !exportedName) continue;
2296
+ lines.push(`${this.describeExportTarget(exportVar, exportedName)} = ${tmp}${this.describeMemberAccess(localName)};`);
2297
+ }
2298
+ return lines.join('\n');
1670
2299
  }
1671
2300
 
1672
2301
  if (node.declaration) {
@@ -1841,7 +2470,7 @@ if (window.slice && window.slice.controller) {
1841
2470
  minified: this.options.minify,
1842
2471
  obfuscated: this.options.obfuscate,
1843
2472
  production: true,
1844
- generated: new Date().toISOString(),
2473
+ generated: resolveBuildTimestamp(),
1845
2474
 
1846
2475
  stats: {
1847
2476
  totalComponents: metrics.totalComponents || 0,
@@ -1868,7 +2497,7 @@ if (window.slice && window.slice.controller) {
1868
2497
  ? {
1869
2498
  bundleKey: 'vendor-shared',
1870
2499
  type: 'vendor-shared',
1871
- file: this.vendorShared.file,
2500
+ file: this.vendorShared.bundle?.file || this.vendorShared.file,
1872
2501
  size: this.vendorShared.bundle?.size || 0,
1873
2502
  hash: this.vendorShared.bundle?.hash || null,
1874
2503
  integrity: this.vendorShared.bundle?.integrity || null,
@@ -1882,7 +2511,10 @@ if (window.slice && window.slice.controller) {
1882
2511
  size: this.bundles.critical.size,
1883
2512
  hash: this.bundles.critical.hash || null,
1884
2513
  integrity: this.bundles.critical.integrity || null,
1885
- components: this.bundles.critical.components.map(c => c.name)
2514
+ components: this.bundles.critical.components.map(c => c.name),
2515
+ // When critical uses a shared dependency it must load vendor-shared
2516
+ // first so the shared resolver finds it at registration time.
2517
+ ...(this.vendorShared.criticalUsesShared ? { dependencies: ['vendor-shared'] } : {})
1886
2518
  },
1887
2519
  routes: {}
1888
2520
  },
@@ -1903,7 +2535,9 @@ if (window.slice && window.slice.controller) {
1903
2535
 
1904
2536
  config.bundles.routes[key] = {
1905
2537
  path: bundle.path || bundle.paths || key, // Support both single path and array of paths, fallback to key
1906
- file: `slice-bundle.${this.routeToFileName(routeIdentifier)}.js`,
2538
+ // Prefer the emitted (possibly content-hashed) filename; fall back to the
2539
+ // deterministic name when the bundle wasn't emitted through the writer.
2540
+ file: bundle.file || `slice-bundle.${this.routeToFileName(routeIdentifier)}.js`,
1907
2541
  size: bundle.size,
1908
2542
  hash: bundle.hash || null,
1909
2543
  integrity: bundle.integrity || null,
@@ -1964,6 +2598,39 @@ if (window.slice && window.slice.controller) {
1964
2598
  return config;
1965
2599
  }
1966
2600
 
2601
+ /**
2602
+ * Checks that the generated config is self-consistent: every bundle key
2603
+ * referenced (in `routeBundles` or a bundle's `dependencies`) is actually
2604
+ * emitted, and no emitted route bundle is orphaned (referenced by nothing).
2605
+ * Guards against the class of bug where splitting/merging a bundle leaves
2606
+ * dangling by-key references or dead files.
2607
+ * @returns {{ dangling: string[], orphans: string[] }}
2608
+ */
2609
+ collectBundleReferentialIssues(config) {
2610
+ const valid = new Set(['critical', 'framework']);
2611
+ if (config?.bundles?.vendorShared) valid.add('vendor-shared');
2612
+ for (const key of Object.keys(config?.bundles?.routes || {})) valid.add(key);
2613
+
2614
+ const dangling = new Set();
2615
+ const referenced = new Set();
2616
+ const note = (key) => {
2617
+ if (!key) return;
2618
+ if (key !== 'critical') referenced.add(key);
2619
+ if (!valid.has(key)) dangling.add(key);
2620
+ };
2621
+
2622
+ for (const list of Object.values(config?.routeBundles || {})) {
2623
+ for (const key of list || []) note(key);
2624
+ }
2625
+ for (const entry of Object.values(config?.bundles?.routes || {})) {
2626
+ for (const dep of entry?.dependencies || []) note(dep);
2627
+ }
2628
+ for (const dep of config?.bundles?.critical?.dependencies || []) note(dep);
2629
+
2630
+ const orphans = Object.keys(config?.bundles?.routes || {}).filter((key) => !referenced.has(key));
2631
+ return { dangling: [...dangling].sort(), orphans: orphans.sort() };
2632
+ }
2633
+
1967
2634
  collectFrameworkComponents() {
1968
2635
  return this.analysisData.components.filter((comp) => comp.isFramework);
1969
2636
  }
@@ -1983,7 +2650,7 @@ if (window.slice && window.slice.controller) {
1983
2650
  route: null,
1984
2651
  bundleKey: 'framework',
1985
2652
  file: fileName,
1986
- generated: new Date().toISOString(),
2653
+ generated: resolveBuildTimestamp(),
1987
2654
  totalSize: components.reduce((sum, c) => sum + c.size, 0),
1988
2655
  componentCount: components.length,
1989
2656
  strategy: this.config.strategy,
@@ -2020,17 +2687,13 @@ if (window.slice && window.slice.controller) {
2020
2687
 
2021
2688
  const prelude = `const components = ${JSON.stringify(componentsMap)};`;
2022
2689
  const bundleContent = `${prelude}\n${this.formatBundleFile(componentsData, metadata)}`;
2023
- const finalContent = await this.applyBundleTransforms(bundleContent, fileName);
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');
2690
+ const { file, hash, rawSize } = await this.emitBundleArtifact(fileName, bundleContent);
2028
2691
  const integrity = `sha256:${hash}`;
2029
2692
 
2030
2693
  return {
2031
2694
  name: 'framework',
2032
- file: fileName,
2033
- size: Buffer.byteLength(bundleContent, 'utf-8'),
2695
+ file,
2696
+ size: rawSize,
2034
2697
  hash,
2035
2698
  integrity,
2036
2699
  componentCount: components.length,
@@ -2061,33 +2724,6 @@ if (window.slice && window.slice.controller) {
2061
2724
  return dependencyContents;
2062
2725
  }
2063
2726
 
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
2727
  normalizeImportPath(importPath) {
2092
2728
  if (typeof importPath !== 'string') return '';
2093
2729
  const cleanPath = importPath.split(/[?#]/)[0];
@@ -2102,12 +2738,20 @@ if (window.slice && window.slice.controller) {
2102
2738
  return importPath.startsWith('/');
2103
2739
  }
2104
2740
 
2105
- isImportInPublicFolders(importPath, publicFolders) {
2106
- const normalizedImport = this.normalizeImportPath(importPath);
2107
- return publicFolders.some((folder) => normalizedImport === folder || normalizedImport.startsWith(`${folder}/`));
2741
+ // True when an absolute import resolves to a real file under `src/public/`.
2742
+ // Anything served at the root URL from public/ can be imported by its
2743
+ // absolute path.
2744
+ isImportInPublicDir(importPath) {
2745
+ const normalizedImport = this.normalizeImportPath(importPath).replace(/^\/+/, '');
2746
+ if (!normalizedImport) return false;
2747
+ try {
2748
+ return fs.existsSync(path.join(this.srcPath, 'public', normalizedImport));
2749
+ } catch {
2750
+ return false;
2751
+ }
2108
2752
  }
2109
2753
 
2110
- classifyImport(importPath, publicFolders) {
2754
+ classifyImport(importPath) {
2111
2755
  if (typeof importPath !== 'string' || !importPath) {
2112
2756
  return { keep: false, warning: 'Warning: Removing bare import: <unknown>' };
2113
2757
  }
@@ -2117,20 +2761,21 @@ if (window.slice && window.slice.controller) {
2117
2761
  }
2118
2762
 
2119
2763
  if (this.isAbsoluteImport(importPath)) {
2120
- if (this.isImportInPublicFolders(importPath, publicFolders)) {
2764
+ // Kept only if the file exists under src/public/ (served at the root URL).
2765
+ if (this.isImportInPublicDir(importPath)) {
2121
2766
  return { keep: true, warning: null };
2122
2767
  }
2123
2768
 
2124
2769
  return {
2125
2770
  keep: false,
2126
- warning: `Warning: Removing absolute import outside publicFolders: ${importPath}`
2771
+ warning: `Warning: Removing absolute import not found under public/: ${importPath}`
2127
2772
  };
2128
2773
  }
2129
2774
 
2130
- return {
2131
- keep: false,
2132
- warning: `Warning: Removing bare import: ${importPath}`
2133
- };
2775
+ // Bare specifier (node_modules package). Strip it silently from the
2776
+ // component body: it is resolved + bundled separately and re-bound in the
2777
+ // component's class-factory prologue via SLICE_BUNDLE_DEPENDENCIES.
2778
+ return { keep: false, warning: null, external: true };
2134
2779
  }
2135
2780
 
2136
2781
  buildImportWarningMessage(baseMessage, sourceContext) {
@@ -2276,7 +2921,7 @@ if (window.slice && window.slice.controller) {
2276
2921
  return entries;
2277
2922
  }
2278
2923
 
2279
- stripImportsWithFallbackRegex(code, publicFolders, sourceContext, collectHoistedImports) {
2924
+ stripImportsWithFallbackRegex(code, sourceContext, collectHoistedImports) {
2280
2925
  const hoistedImports = [];
2281
2926
  const importEntries = this.parseImportsWithFallbackScanner(code);
2282
2927
  if (importEntries.length === 0) {
@@ -2287,7 +2932,7 @@ if (window.slice && window.slice.controller) {
2287
2932
  let cursor = 0;
2288
2933
  for (const entry of importEntries) {
2289
2934
  const { start, end, statement, importPath } = entry;
2290
- const classification = this.classifyImport(importPath, publicFolders);
2935
+ const classification = this.classifyImport(importPath);
2291
2936
  cleanedCode += code.slice(cursor, start);
2292
2937
  if (classification.keep) {
2293
2938
  if (collectHoistedImports) {
@@ -2308,7 +2953,6 @@ if (window.slice && window.slice.controller) {
2308
2953
 
2309
2954
  stripImports(code, options = {}) {
2310
2955
  const { sourceContext = null, collectHoistedImports = false } = options;
2311
- const publicFolders = this.getConfiguredPublicFolders();
2312
2956
  const hoistedImports = [];
2313
2957
 
2314
2958
  try {
@@ -2323,7 +2967,7 @@ if (window.slice && window.slice.controller) {
2323
2967
 
2324
2968
  for (const node of importNodes) {
2325
2969
  const importPath = node.source?.value;
2326
- const classification = this.classifyImport(importPath, publicFolders);
2970
+ const classification = this.classifyImport(importPath);
2327
2971
  const statement = code.slice(node.start, node.end);
2328
2972
 
2329
2973
  cleaned += code.slice(cursor, node.start);
@@ -2345,7 +2989,7 @@ if (window.slice && window.slice.controller) {
2345
2989
  ? { code: cleaned, hoistedImports }
2346
2990
  : cleaned;
2347
2991
  } catch (error) {
2348
- const fallback = this.stripImportsWithFallbackRegex(code, publicFolders, sourceContext, collectHoistedImports);
2992
+ const fallback = this.stripImportsWithFallbackRegex(code, sourceContext, collectHoistedImports);
2349
2993
  return collectHoistedImports ? fallback : fallback.code;
2350
2994
  }
2351
2995
  }
@@ -2488,7 +3132,7 @@ export const SLICE_BUNDLE_CONFIG = null;
2488
3132
  generateBundleConfigJS(config) {
2489
3133
  return `/**
2490
3134
  * Slice.js Bundle Configuration
2491
- * Generated: ${new Date().toISOString()}
3135
+ * Generated: ${resolveBuildTimestamp()}
2492
3136
  * Strategy: ${config.strategy}
2493
3137
  */
2494
3138
 
@@ -2513,7 +3157,9 @@ if (typeof window !== 'undefined' && window.slice && window.slice.controller) {
2513
3157
  }
2514
3158
  }
2515
3159
 
2516
- import('./slice-bundle.critical.js').catch(err =>
3160
+ // Load by the config's filename (which carries the content hash under
3161
+ // --hash-filenames) rather than a hardcoded name.
3162
+ import(bundlePath).catch(err =>
2517
3163
  console.warn('Failed to load critical bundle:', err)
2518
3164
  );
2519
3165
  window.slice.controller.criticalBundleLoaded = true;