slicejs-web-framework 3.4.4 → 3.5.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.
Files changed (101) hide show
  1. package/Slice/Components/Structural/Controller/Controller.js +135 -0
  2. package/Slice/Components/Structural/EventManager/EventManager.js +289 -4
  3. package/Slice/Components/Structural/EventManager/EventManagerDebugger.js +368 -30
  4. package/Slice/Components/Structural/LeakInspector/LeakInspector.js +296 -0
  5. package/Slice/Slice.js +14 -1
  6. package/Slice/tests/event-emitters.test.js +79 -0
  7. package/Slice/tests/event-registry.test.js +141 -0
  8. package/Slice/tests/leak-orphans.test.js +131 -0
  9. package/api/index.js +35 -8
  10. package/package.json +1 -1
  11. package/sliceConfig.schema.json +10 -1
  12. package/src/sliceConfig.json +5 -1
  13. package/types/index.d.ts +12 -0
  14. package/slicejs-cli/.github/workflows/ci.yml +0 -43
  15. package/slicejs-cli/LICENSE +0 -21
  16. package/slicejs-cli/assets/Slice.js-logo.png +0 -0
  17. package/slicejs-cli/client.js +0 -740
  18. package/slicejs-cli/commands/Print.js +0 -164
  19. package/slicejs-cli/commands/Validations.js +0 -92
  20. package/slicejs-cli/commands/build/build.js +0 -40
  21. package/slicejs-cli/commands/buildProduction/buildProduction.js +0 -577
  22. package/slicejs-cli/commands/bundle/bundle.js +0 -236
  23. package/slicejs-cli/commands/createComponent/VisualComponentTemplate.js +0 -55
  24. package/slicejs-cli/commands/createComponent/createComponent.js +0 -128
  25. package/slicejs-cli/commands/deleteComponent/deleteComponent.js +0 -81
  26. package/slicejs-cli/commands/doctor/doctor.js +0 -516
  27. package/slicejs-cli/commands/getComponent/getComponent.js +0 -695
  28. package/slicejs-cli/commands/init/init.js +0 -473
  29. package/slicejs-cli/commands/listComponents/listComponents.js +0 -172
  30. package/slicejs-cli/commands/startServer/startServer.js +0 -240
  31. package/slicejs-cli/commands/startServer/watchServer.js +0 -66
  32. package/slicejs-cli/commands/types/types.js +0 -583
  33. package/slicejs-cli/commands/utils/LocalCliDelegation.js +0 -53
  34. package/slicejs-cli/commands/utils/PackageManager.js +0 -148
  35. package/slicejs-cli/commands/utils/PathHelper.js +0 -75
  36. package/slicejs-cli/commands/utils/VersionChecker.js +0 -169
  37. package/slicejs-cli/commands/utils/bundling/BundleGenerator.js +0 -2525
  38. package/slicejs-cli/commands/utils/bundling/DependencyAnalyzer.js +0 -933
  39. package/slicejs-cli/commands/utils/loadConfig.js +0 -31
  40. package/slicejs-cli/commands/utils/sliceScripts.js +0 -48
  41. package/slicejs-cli/commands/utils/updateManager.js +0 -471
  42. package/slicejs-cli/package.json +0 -71
  43. package/slicejs-cli/playwright.config.js +0 -51
  44. package/slicejs-cli/pnpm-lock.yaml +0 -1629
  45. package/slicejs-cli/tests/build-command-integration.test.js +0 -87
  46. package/slicejs-cli/tests/build-mangling-e2e.test.js +0 -290
  47. package/slicejs-cli/tests/build-production-e2e.test.js +0 -140
  48. package/slicejs-cli/tests/builder-edge-cases.test.js +0 -322
  49. package/slicejs-cli/tests/bundle-generate-e2e.test.js +0 -115
  50. package/slicejs-cli/tests/bundle-generator.test.js +0 -691
  51. package/slicejs-cli/tests/bundle-v2-register-output.test.js +0 -470
  52. package/slicejs-cli/tests/bundling-dependency-edges.test.js +0 -127
  53. package/slicejs-cli/tests/bundling-imports-unit.test.js +0 -267
  54. package/slicejs-cli/tests/client-launcher-contract.test.js +0 -211
  55. package/slicejs-cli/tests/commands-component-crud.test.js +0 -128
  56. package/slicejs-cli/tests/commands-doctor.test.js +0 -152
  57. package/slicejs-cli/tests/commands-version-checker.test.js +0 -37
  58. package/slicejs-cli/tests/component-registry-parse.test.js +0 -34
  59. package/slicejs-cli/tests/dependency-analyzer.test.js +0 -24
  60. package/slicejs-cli/tests/e2e/bundles.spec.js +0 -91
  61. package/slicejs-cli/tests/e2e/dependency-scenarios.spec.js +0 -56
  62. package/slicejs-cli/tests/e2e/fixtures/components/Service/FetchManager/FetchManager.js +0 -136
  63. package/slicejs-cli/tests/e2e/fixtures/components/Service/IndexedDbManager/IndexedDbManager.js +0 -149
  64. package/slicejs-cli/tests/e2e/fixtures/components/Service/LocalStorageManager/LocalStorageManager.js +0 -45
  65. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Button/Button.css +0 -106
  66. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Button/Button.html +0 -5
  67. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Button/Button.js +0 -158
  68. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Link/Link.js +0 -33
  69. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Loading/Loading.css +0 -56
  70. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Loading/Loading.html +0 -83
  71. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Loading/Loading.js +0 -164
  72. package/slicejs-cli/tests/e2e/fixtures/components/Visual/MultiRoute/MultiRoute.js +0 -167
  73. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Navbar/Navbar.css +0 -116
  74. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Navbar/Navbar.html +0 -44
  75. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Navbar/Navbar.js +0 -180
  76. package/slicejs-cli/tests/e2e/fixtures/components/Visual/NotFound/NotFound.js +0 -20
  77. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Route/Route.js +0 -181
  78. package/slicejs-cli/tests/e2e/fixtures/components/registry.json +0 -12
  79. package/slicejs-cli/tests/e2e/fixtures/vendor-components.mjs +0 -65
  80. package/slicejs-cli/tests/e2e/navigation.spec.js +0 -44
  81. package/slicejs-cli/tests/e2e/render.spec.js +0 -34
  82. package/slicejs-cli/tests/e2e/serve.mjs +0 -264
  83. package/slicejs-cli/tests/e2e/shared-deps.spec.js +0 -61
  84. package/slicejs-cli/tests/e2e/unminified.spec.js +0 -33
  85. package/slicejs-cli/tests/e2e-serve.test.js +0 -148
  86. package/slicejs-cli/tests/fixtures/components.js +0 -8
  87. package/slicejs-cli/tests/fixtures/sliceConfig.json +0 -74
  88. package/slicejs-cli/tests/getcomponent.test.js +0 -435
  89. package/slicejs-cli/tests/helpers/setup.js +0 -102
  90. package/slicejs-cli/tests/init-command-contract.test.js +0 -101
  91. package/slicejs-cli/tests/init-e2e.test.js +0 -82
  92. package/slicejs-cli/tests/init-project-isolation.test.js +0 -98
  93. package/slicejs-cli/tests/local-cli-delegation.test.js +0 -81
  94. package/slicejs-cli/tests/package-manager.test.js +0 -127
  95. package/slicejs-cli/tests/path-helper.test.js +0 -206
  96. package/slicejs-cli/tests/perf-budget.test.js +0 -84
  97. package/slicejs-cli/tests/postinstall-command.test.js +0 -103
  98. package/slicejs-cli/tests/property-mangling-regression.test.js +0 -182
  99. package/slicejs-cli/tests/types-breakage.test.js +0 -491
  100. package/slicejs-cli/tests/types-generator-errors.test.js +0 -361
  101. package/slicejs-cli/tests/types-generator.test.js +0 -348
@@ -1,691 +0,0 @@
1
- import { test } from 'node:test';
2
- import assert from 'node:assert/strict';
3
- import fs from 'fs-extra';
4
- import os from 'node:os';
5
- import path from 'node:path';
6
- import BundleGenerator from '../commands/utils/bundling/BundleGenerator.js';
7
- import { withTestProject } from './helpers/setup.js';
8
-
9
- const createComponent = (name, deps = []) => ({
10
- name,
11
- category: 'Visual',
12
- categoryType: 'Visual',
13
- dependencies: new Set(deps),
14
- size: 10,
15
- path: `/tmp/${name}`
16
- });
17
-
18
- test('computeBundleIntegrity returns sha256 hash', () => {
19
- // Arrange
20
- const generator = new BundleGenerator(import.meta.url, { components: [], routes: [], metrics: {} });
21
- const components = [createComponent('Button', ['Input']), createComponent('Input')];
22
-
23
- // Act
24
- const integrity = generator.computeBundleIntegrity(components, 'critical', null, 'critical', 'slice-bundle.critical.js');
25
-
26
- // Assert
27
- assert.match(integrity, /^sha256:[a-f0-9]{64}$/);
28
- });
29
-
30
- test('computeBundleIntegrity changes with component dependencies', () => {
31
- // Arrange
32
- const generator = new BundleGenerator(import.meta.url, { components: [], routes: [], metrics: {} });
33
- const baseComponents = [createComponent('Button', ['Input']), createComponent('Input')];
34
- const changedComponents = [createComponent('Button', ['Input', 'Icon']), createComponent('Input'), createComponent('Icon')];
35
-
36
- // Act
37
- const baseIntegrity = generator.computeBundleIntegrity(baseComponents, 'critical', null, 'critical', 'slice-bundle.critical.js');
38
- const changedIntegrity = generator.computeBundleIntegrity(changedComponents, 'critical', null, 'critical', 'slice-bundle.critical.js');
39
-
40
- // Assert
41
- assert.notEqual(baseIntegrity, changedIntegrity);
42
- });
43
-
44
- test('generateBundleConfig outputs V2 manifest fields', () => {
45
- const generator = new BundleGenerator(import.meta.url, {
46
- components: [],
47
- routes: [],
48
- metrics: {
49
- totalComponents: 0,
50
- totalRoutes: 0,
51
- sharedPercentage: 0,
52
- totalSize: 0
53
- }
54
- });
55
-
56
- const config = generator.generateBundleConfig(null);
57
-
58
- assert.equal(config.format, 'v2');
59
- assert.ok(config.generated);
60
- assert.ok(config.bundles);
61
- assert.ok(['enabled', 'disabled'].includes(config.loadingPolicy));
62
- });
63
-
64
- test('loading policy is enabled when sliceConfig loading.enabled is true', () => {
65
- const generator = new BundleGenerator(import.meta.url, {
66
- components: [],
67
- routes: [],
68
- metrics: {
69
- totalComponents: 0,
70
- totalRoutes: 0,
71
- sharedPercentage: 0,
72
- totalSize: 0
73
- },
74
- sliceConfig: { loading: { enabled: true } }
75
- });
76
-
77
- const config = generator.generateBundleConfig(null);
78
- assert.equal(config.loadingPolicy, 'enabled');
79
- });
80
-
81
- test('loading policy falls back to project sliceConfig when analysisData lacks sliceConfig', async () => {
82
- await withTestProject(async () => {
83
- const generator = new BundleGenerator(import.meta.url, {
84
- components: [],
85
- routes: [],
86
- metrics: {
87
- totalComponents: 0,
88
- totalRoutes: 0,
89
- sharedPercentage: 0,
90
- totalSize: 0
91
- }
92
- });
93
-
94
- const config = generator.generateBundleConfig(null);
95
- assert.equal(config.loadingPolicy, 'enabled');
96
- });
97
- });
98
-
99
- test('loading enabled always includes Loading component in critical bundle', () => {
100
- const loading = {
101
- ...createComponent('Loading'),
102
- routes: new Set(),
103
- size: 100000
104
- };
105
- const home = {
106
- ...createComponent('HomePage'),
107
- routes: new Set(['/'])
108
- };
109
-
110
- const generator = new BundleGenerator(import.meta.url, {
111
- components: [loading, home],
112
- routes: [{ path: '/', component: 'HomePage' }],
113
- metrics: {
114
- totalComponents: 2,
115
- totalRoutes: 1,
116
- sharedPercentage: 0,
117
- totalSize: 100010
118
- },
119
- sliceConfig: { loading: { enabled: true } }
120
- });
121
-
122
- generator.identifyCriticalComponents();
123
-
124
- assert.ok(generator.bundles.critical.components.some((component) => component.name === 'Loading'));
125
- assert.equal(generator.generateBundleConfig().loadingPolicy, 'enabled');
126
- });
127
-
128
- test('shared-core is wired as dependency for affected route bundles', () => {
129
- const generator = new BundleGenerator(import.meta.url, {
130
- components: [],
131
- routes: [],
132
- metrics: {
133
- totalComponents: 0,
134
- totalRoutes: 0,
135
- sharedPercentage: 0,
136
- totalSize: 0
137
- }
138
- });
139
-
140
- generator.config.minSharedUsage = 2;
141
-
142
- generator.bundles.routes = {
143
- alpha: {
144
- path: '/alpha',
145
- components: [createComponent('SharedWidget'), createComponent('AlphaOnly')],
146
- size: 20,
147
- file: 'slice-bundle.alpha.js'
148
- },
149
- beta: {
150
- path: '/beta',
151
- components: [createComponent('SharedWidget'), createComponent('BetaOnly')],
152
- size: 20,
153
- file: 'slice-bundle.beta.js'
154
- }
155
- };
156
-
157
- generator.extractSharedComponents(new Set());
158
- const config = generator.generateBundleConfig();
159
-
160
- assert.ok(config.bundles.routes['shared-core']);
161
- assert.deepEqual(config.bundles.routes.alpha.dependencies, ['critical', 'shared-core']);
162
- assert.deepEqual(config.bundles.routes.beta.dependencies, ['critical', 'shared-core']);
163
- assert.deepEqual(config.routeBundles['/alpha'], ['critical', 'shared-core', 'alpha']);
164
- assert.deepEqual(config.routeBundles['/beta'], ['critical', 'shared-core', 'beta']);
165
- });
166
-
167
- test('rebalance merge preserves and merges route path metadata deterministically', () => {
168
- const generator = new BundleGenerator(import.meta.url, {
169
- components: [],
170
- routes: [],
171
- metrics: {
172
- totalComponents: 0,
173
- totalRoutes: 0,
174
- sharedPercentage: 0,
175
- totalSize: 0
176
- }
177
- });
178
-
179
- const bundles = {
180
- alpha: { path: '/alpha', components: [createComponent('Alpha')], size: 10, file: 'slice-bundle.alpha.js' },
181
- beta: { paths: ['/beta', '/beta-alt'], components: [createComponent('Beta')], size: 10, file: 'slice-bundle.beta.js' },
182
- gamma: { path: '/gamma', components: [createComponent('Gamma')], size: 10, file: 'slice-bundle.gamma.js' }
183
- };
184
-
185
- generator.rebalanceBundlesByBudget(bundles, { maxBundleSize: 99999, maxRequests: 2 });
186
-
187
- assert.equal(Object.keys(bundles).length, 2);
188
- assert.deepEqual(bundles.beta.paths, ['/beta', '/beta-alt', '/gamma']);
189
- });
190
-
191
- test('stripImports preserves absolute imports from configured publicFolders', () => {
192
- const generator = new BundleGenerator(import.meta.url, {
193
- components: [],
194
- routes: [],
195
- metrics: {},
196
- sliceConfig: {
197
- publicFolders: ['/public', '/assets']
198
- }
199
- });
200
-
201
- const source = "import logo from '/public/logo.js';\nimport hero from '/assets/hero.js';\nclass Demo {}\n";
202
- const cleaned = generator.stripImports(source);
203
-
204
- assert.match(cleaned, /import\s+logo\s+from\s+'\/public\/logo\.js';/);
205
- assert.match(cleaned, /import\s+hero\s+from\s+'\/assets\/hero\.js';/);
206
- });
207
-
208
- test('stripImports removes relative imports', () => {
209
- const generator = new BundleGenerator(import.meta.url, {
210
- components: [],
211
- routes: [],
212
- metrics: {},
213
- sliceConfig: {
214
- publicFolders: ['/public']
215
- }
216
- });
217
-
218
- const source = "import localDep from './local.js';\nimport parentDep from '../parent.js';\nclass Demo {}\n";
219
- const cleaned = generator.stripImports(source);
220
-
221
- assert.doesNotMatch(cleaned, /\.\/local\.js/);
222
- assert.doesNotMatch(cleaned, /\.\.\/parent\.js/);
223
- assert.match(cleaned, /class Demo \{\}/);
224
- });
225
-
226
- test('stripImports warns on bare imports', () => {
227
- const generator = new BundleGenerator(import.meta.url, {
228
- components: [],
229
- routes: [],
230
- metrics: {},
231
- sliceConfig: {
232
- publicFolders: ['/public']
233
- }
234
- });
235
-
236
- const warnings = [];
237
- const originalWarn = console.warn;
238
- console.warn = (...args) => warnings.push(args.join(' '));
239
-
240
- try {
241
- const source = "import { html } from 'lit';\nclass Demo {}\n";
242
- const cleaned = generator.stripImports(source);
243
-
244
- assert.doesNotMatch(cleaned, /from\s+'lit'/);
245
- assert.ok(warnings.some((msg) => msg.includes('bare import') && msg.includes('lit')));
246
- } finally {
247
- console.warn = originalWarn;
248
- }
249
- });
250
-
251
- test('stripImports warns on absolute imports outside publicFolders', () => {
252
- const generator = new BundleGenerator(import.meta.url, {
253
- components: [],
254
- routes: [],
255
- metrics: {},
256
- sliceConfig: {
257
- publicFolders: ['/public']
258
- }
259
- });
260
-
261
- const warnings = [];
262
- const originalWarn = console.warn;
263
- console.warn = (...args) => warnings.push(args.join(' '));
264
-
265
- try {
266
- const source = "import secret from '/private/secret.js';\nclass Demo {}\n";
267
- const cleaned = generator.stripImports(source);
268
-
269
- assert.doesNotMatch(cleaned, /\/private\/secret\.js/);
270
- assert.ok(warnings.some((msg) => msg.includes('outside publicFolders') && msg.includes('/private/secret.js')));
271
- } finally {
272
- console.warn = originalWarn;
273
- }
274
- });
275
-
276
- test('stripImports supports side-effect and multiline imports in fallback mode', () => {
277
- const generator = new BundleGenerator(import.meta.url, {
278
- components: [],
279
- routes: [],
280
- metrics: {},
281
- sliceConfig: {
282
- publicFolders: ['/public']
283
- }
284
- });
285
-
286
- const warnings = [];
287
- const originalWarn = console.warn;
288
- console.warn = (...args) => warnings.push(args.join(' '));
289
-
290
- const originalParse = generator.parseImportsFromCode;
291
- generator.parseImportsFromCode = () => {
292
- throw new Error('forced parser failure');
293
- };
294
-
295
- try {
296
- const source = [
297
- "import '/public/effects.js';",
298
- "import '/private/effects.js';",
299
- "import {",
300
- ' html,',
301
- ' css',
302
- "} from 'lit';",
303
- 'class Demo {}'
304
- ].join('\n');
305
- const cleaned = generator.stripImports(source, { sourceContext: 'DemoComponent' });
306
-
307
- assert.match(cleaned, /import '\/public\/effects\.js';/);
308
- assert.doesNotMatch(cleaned, /\/private\/effects\.js/);
309
- assert.doesNotMatch(cleaned, /from 'lit'/);
310
- assert.ok(warnings.some((msg) => msg.includes('outside publicFolders') && msg.includes('/private/effects.js') && msg.includes('[DemoComponent]')));
311
- assert.ok(warnings.some((msg) => msg.includes('bare import') && msg.includes('lit') && msg.includes('[DemoComponent]')));
312
- } finally {
313
- generator.parseImportsFromCode = originalParse;
314
- console.warn = originalWarn;
315
- }
316
- });
317
-
318
- test('cleanJavaScript hoists allowed absolute imports and removes them from component code', () => {
319
- const generator = new BundleGenerator(import.meta.url, {
320
- components: [],
321
- routes: [],
322
- metrics: {},
323
- sliceConfig: {
324
- publicFolders: ['/public']
325
- }
326
- });
327
-
328
- const source = [
329
- "import hero from '/public/hero.js';",
330
- 'class Demo extends HTMLElement {}',
331
- 'customElements.define("x-demo", Demo);'
332
- ].join('\n');
333
-
334
- const result = generator.cleanJavaScript(source, 'Demo', 'DemoPath.js');
335
-
336
- assert.doesNotMatch(result.code, /import hero from '\/public\/hero\.js';/);
337
- assert.ok(result.hoistedImports.includes("import hero from '/public/hero.js';"));
338
- });
339
-
340
- test('formatBundleFile emits hoisted imports for framework-compatible output', () => {
341
- const generator = new BundleGenerator(import.meta.url, {
342
- components: [],
343
- routes: [],
344
- metrics: {}
345
- });
346
-
347
- const source = generator.formatBundleFile({
348
- 'Framework/Structural/Bootstrap': {
349
- name: 'Bootstrap',
350
- category: 'Framework',
351
- categoryType: 'Structural',
352
- componentDependencies: [],
353
- externalDependencies: {},
354
- hoistedImports: ["import boot from '/public/bootstrap.js';"],
355
- js: 'class Bootstrap extends HTMLElement {}\nreturn Bootstrap;',
356
- html: '',
357
- css: '',
358
- size: 10,
359
- isFramework: true
360
- }
361
- }, {
362
- type: 'framework',
363
- generated: new Date().toISOString(),
364
- strategy: 'hybrid',
365
- componentCount: 1,
366
- totalSize: 10
367
- });
368
-
369
- assert.match(source, /import boot from '\/public\/bootstrap\.js';/);
370
- assert.match(source, /const SLICE_BUNDLE_DEPENDENCIES = \{\};/);
371
- });
372
-
373
- test('default dependency binding resolves transformed default key over named exports', () => {
374
- const generator = new BundleGenerator(import.meta.url, {
375
- components: [],
376
- routes: [],
377
- metrics: {}
378
- });
379
-
380
- const externalDependencies = {
381
- 'App/purify.js': {
382
- content: 'export default () => "DEFAULT"; export const purify = () => "NAMED";',
383
- bindings: [{ type: 'default', importedName: 'default', localName: 'purify' }]
384
- }
385
- };
386
-
387
- const resolverSource = generator.getDefaultExportResolverLines().join('\n');
388
- const bindingsSource = generator.buildDependencyBindings(externalDependencies);
389
- const resolveBoundValue = new Function(
390
- `${resolverSource}\n` +
391
- 'const SLICE_BUNDLE_DEPENDENCIES = {"App/purify.js": { purifyData: "DEFAULT", purify: "NAMED" }};\n' +
392
- `${bindingsSource}\n` +
393
- 'return purify;'
394
- );
395
-
396
- assert.equal(resolveBoundValue(), 'DEFAULT');
397
- });
398
-
399
- const evaluateDefaultResolver = ({ dep, depName = 'App/dep.js', preferredKey = null, calls = 1 }) => {
400
- const generator = new BundleGenerator(import.meta.url, {
401
- components: [],
402
- routes: [],
403
- metrics: {}
404
- });
405
-
406
- const resolverSource = generator.getDefaultExportResolverLines().join('\n');
407
- const resolve = new Function(
408
- '__dep',
409
- '__depName',
410
- '__preferredKey',
411
- '__calls',
412
- `${resolverSource}\n` +
413
- 'const __capturedWarnings = [];' +
414
- 'const __originalWarn = console.warn;' +
415
- 'console.warn = (...args) => __capturedWarnings.push(args.join(" "));' +
416
- 'let __result;' +
417
- 'try {' +
418
- ' for (let __i = 0; __i < __calls; __i += 1) {' +
419
- ' __result = __sliceResolveDefaultExport(__dep, __depName, __preferredKey);' +
420
- ' }' +
421
- '} finally {' +
422
- ' console.warn = __originalWarn;' +
423
- '}' +
424
- 'return { result: __result, warnings: __capturedWarnings };'
425
- );
426
-
427
- return resolve(dep, depName, preferredKey, calls);
428
- };
429
-
430
- test('default resolver returns default when present', () => {
431
- const { result, warnings } = evaluateDefaultResolver({
432
- dep: { default: 'DEFAULT', alpha: 'ALPHA' }
433
- });
434
-
435
- assert.equal(result, 'DEFAULT');
436
- assert.equal(warnings.length, 0);
437
- });
438
-
439
- test('default resolver preserves falsy default values', () => {
440
- const falsyValues = [0, '', false, null];
441
-
442
- for (const value of falsyValues) {
443
- const { result, warnings } = evaluateDefaultResolver({ dep: { default: value, alt: 'fallback' } });
444
- assert.equal(result, value);
445
- assert.equal(warnings.length, 0);
446
- }
447
- });
448
-
449
- test('default resolver falls back to single non-default key', () => {
450
- const { result, warnings } = evaluateDefaultResolver({ dep: { onlyKey: 42 } });
451
-
452
- assert.equal(result, 42);
453
- assert.equal(warnings.length, 0);
454
- });
455
-
456
- test('default resolver respects preferred key hint when present', () => {
457
- const { result, warnings } = evaluateDefaultResolver({
458
- dep: { purifyData: 'PREFERRED', purify: 'OTHER' },
459
- depName: 'App/purify.js',
460
- preferredKey: 'purifyData'
461
- });
462
-
463
- assert.equal(result, 'PREFERRED');
464
- assert.equal(warnings.length, 0);
465
- });
466
-
467
- test('default resolver prefers known keys module/exports/purify when unambiguous', () => {
468
- const moduleResult = evaluateDefaultResolver({ dep: { module: 'MODULE', alpha: 'A' } });
469
- const exportsResult = evaluateDefaultResolver({ dep: { exports: 'EXPORTS', beta: 'B' } });
470
- const purifyResult = evaluateDefaultResolver({ dep: { purify: 'PURIFY', gamma: 'C' } });
471
-
472
- assert.equal(moduleResult.result, 'MODULE');
473
- assert.equal(exportsResult.result, 'EXPORTS');
474
- assert.equal(purifyResult.result, 'PURIFY');
475
- assert.equal(moduleResult.warnings.length, 0);
476
- assert.equal(exportsResult.warnings.length, 0);
477
- assert.equal(purifyResult.warnings.length, 0);
478
- });
479
-
480
- test('default resolver uses deterministic alphabetical fallback on ambiguous keys', () => {
481
- const { result } = evaluateDefaultResolver({ dep: { zebra: 'Z', alpha: 'A', middle: 'M' } });
482
- assert.equal(result, 'A');
483
- });
484
-
485
- test('default resolver source uses locale-independent comparator and named preferred keys constant', () => {
486
- const generator = new BundleGenerator(import.meta.url, {
487
- components: [],
488
- routes: [],
489
- metrics: {}
490
- });
491
-
492
- const resolverSource = generator.getDefaultExportResolverLines().join('\n');
493
-
494
- assert.match(resolverSource, /const __sliceDefaultExportPreferredKeys = \['module', 'exports', 'purify'\];/);
495
- assert.match(resolverSource, /const __sliceDeterministicKeyCompare = \(a, b\) => \(a < b \? -1 : a > b \? 1 : 0\);/);
496
- assert.doesNotMatch(resolverSource, /localeCompare/);
497
- });
498
-
499
- test('default resolver warning includes dependency path keys and chosen key', () => {
500
- const { warnings } = evaluateDefaultResolver({
501
- dep: { zebra: 'Z', alpha: 'A', middle: 'M' },
502
- depName: 'App/ambiguous.js'
503
- });
504
-
505
- assert.equal(warnings.length, 1);
506
- assert.match(warnings[0], /App\/ambiguous\.js/);
507
- assert.match(warnings[0], /Falling back to "alpha"/);
508
- assert.match(warnings[0], /Keys: alpha, middle, zebra/);
509
- });
510
-
511
- test('default resolver deduplicates ambiguous warning per dependency in one evaluation', () => {
512
- const { warnings } = evaluateDefaultResolver({
513
- dep: { c: 3, a: 1, b: 2 },
514
- depName: 'App/repeat-warning.js',
515
- calls: 3
516
- });
517
-
518
- assert.equal(warnings.length, 1);
519
- });
520
-
521
- test('default resolver evaluation restores console.warn when resolver throws', () => {
522
- const originalWarn = console.warn;
523
-
524
- assert.throws(() => {
525
- evaluateDefaultResolver({
526
- dep: new Proxy({}, {
527
- ownKeys() {
528
- throw new Error('kaboom');
529
- }
530
- })
531
- });
532
- }, /kaboom/);
533
-
534
- assert.equal(console.warn, originalWarn);
535
- });
536
-
537
- test('default resolver passes through non-object values and null/undefined', () => {
538
- const fn = () => 'ok';
539
- const functionResult = evaluateDefaultResolver({ dep: fn });
540
- const stringResult = evaluateDefaultResolver({ dep: 'value' });
541
- const numberResult = evaluateDefaultResolver({ dep: 7 });
542
- const nullResult = evaluateDefaultResolver({ dep: null });
543
- const undefinedResult = evaluateDefaultResolver({ dep: undefined });
544
-
545
- assert.equal(functionResult.result, fn);
546
- assert.equal(stringResult.result, 'value');
547
- assert.equal(numberResult.result, 7);
548
- assert.equal(nullResult.result, null);
549
- assert.equal(undefinedResult.result, undefined);
550
- });
551
-
552
- test('analyzeDependencies resolves extensionless imports across js json and mjs', async () => {
553
- const tempRoot = await fs.mkdtemp(path.join(os.tmpdir(), 'slice-deps-ext-'));
554
- const componentDir = path.join(tempRoot, 'Component');
555
-
556
- await fs.ensureDir(componentDir);
557
- await fs.writeFile(path.join(componentDir, 'dep-js.js'), 'export const value = 1;', 'utf-8');
558
- await fs.writeFile(path.join(componentDir, 'dep-json.json'), '{"ok":true}', 'utf-8');
559
- await fs.writeFile(path.join(componentDir, 'dep-mjs.mjs'), 'export const ok = true;', 'utf-8');
560
-
561
- const generator = new BundleGenerator(import.meta.url, {
562
- components: [],
563
- routes: [],
564
- metrics: {}
565
- });
566
-
567
- try {
568
- const jsDeps = generator.analyzeDependencies("import dep from './dep-js';", componentDir);
569
- const jsonDeps = generator.analyzeDependencies("import cfg from './dep-json';", componentDir);
570
- const mjsDeps = generator.analyzeDependencies("import mod from './dep-mjs';", componentDir);
571
-
572
- assert.equal(jsDeps.length, 1);
573
- assert.equal(path.basename(jsDeps[0].path), 'dep-js.js');
574
- assert.equal(jsonDeps.length, 1);
575
- assert.equal(path.basename(jsonDeps[0].path), 'dep-json.json');
576
- assert.equal(mjsDeps.length, 1);
577
- assert.equal(path.basename(mjsDeps[0].path), 'dep-mjs.mjs');
578
- } finally {
579
- await fs.remove(tempRoot);
580
- }
581
- });
582
-
583
- test('named and namespace dependency bindings remain unchanged', () => {
584
- const generator = new BundleGenerator(import.meta.url, {
585
- components: [],
586
- routes: [],
587
- metrics: {}
588
- });
589
-
590
- const externalDependencies = {
591
- 'App/named.js': {
592
- content: 'export const alpha = 1;',
593
- bindings: [
594
- { type: 'named', importedName: 'alpha', localName: 'localAlpha' },
595
- { type: 'namespace', localName: 'namedNamespace' }
596
- ]
597
- }
598
- };
599
-
600
- const resolverSource = generator.getDefaultExportResolverLines().join('\n');
601
- const bindingsSource = generator.buildDependencyBindings(externalDependencies);
602
- const evaluate = new Function(
603
- `${resolverSource}\n` +
604
- 'const SLICE_BUNDLE_DEPENDENCIES = {"App/named.js": { alpha: 99, other: 1 }};' +
605
- `${bindingsSource}\n` +
606
- 'return { localAlpha, namedNamespace };'
607
- );
608
-
609
- const values = evaluate();
610
- assert.equal(values.localAlpha, 99);
611
- assert.deepEqual(values.namedNamespace, { alpha: 99, other: 1 });
612
- });
613
-
614
- test('indexExternalDependencyUsage tracks unique route-bundle usage counts', () => {
615
- const generator = new BundleGenerator(import.meta.url, {
616
- components: [],
617
- routes: [],
618
- metrics: {}
619
- });
620
-
621
- const routeDependencyIndex = {
622
- alpha: {
623
- 'deps/shared.js': { content: 'export const shared = true;' },
624
- 'deps/alpha.js': { content: 'export const alpha = true;' }
625
- },
626
- beta: {
627
- 'deps/shared.js': { content: 'export const shared = true;' },
628
- 'deps/beta.js': { content: 'export const beta = true;' }
629
- }
630
- };
631
-
632
- const usageIndex = generator.indexExternalDependencyUsage(routeDependencyIndex);
633
-
634
- assert.equal(usageIndex.get('deps/shared.js').bundleCount, 2);
635
- assert.equal(usageIndex.get('deps/alpha.js').bundleCount, 1);
636
- assert.deepEqual(Array.from(usageIndex.get('deps/shared.js').bundleKeys).sort(), ['alpha', 'beta']);
637
- });
638
-
639
- test('computeSharedDependencySet enforces usage and transformed-size thresholds', () => {
640
- const generator = new BundleGenerator(import.meta.url, {
641
- components: [],
642
- routes: [],
643
- metrics: {}
644
- });
645
-
646
- const largePayload = 'x'.repeat(2100);
647
- const routeDependencyIndex = {
648
- alpha: {
649
- 'deps/shared-large.js': { content: `export const payload = '${largePayload}';` },
650
- 'deps/shared-small.js': { content: 'export const tiny = 1;' }
651
- },
652
- beta: {
653
- 'deps/shared-large.js': { content: `export const payload = '${largePayload}';` },
654
- 'deps/shared-small.js': { content: 'export const tiny = 1;' }
655
- },
656
- gamma: {
657
- 'deps/shared-small.js': { content: 'export const tiny = 1;' }
658
- }
659
- };
660
-
661
- const usageIndex = generator.indexExternalDependencyUsage(routeDependencyIndex);
662
- const sharedSet = generator.computeSharedDependencySet(usageIndex);
663
-
664
- assert.ok(sharedSet.has('deps/shared-large.js'));
665
- assert.ok(!sharedSet.has('deps/shared-small.js'));
666
- });
667
-
668
- test('generateVendorSharedDependencyBundleContent emits shared dependency module once', () => {
669
- const generator = new BundleGenerator(import.meta.url, {
670
- components: [],
671
- routes: [],
672
- metrics: {}
673
- });
674
-
675
- const routeDependencyIndex = {
676
- alpha: {
677
- 'deps/shared.js': { content: `export const payload = '${'y'.repeat(2200)}';` }
678
- },
679
- beta: {
680
- 'deps/shared.js': { content: `export const payload = '${'y'.repeat(2200)}';` }
681
- }
682
- };
683
-
684
- const usageIndex = generator.indexExternalDependencyUsage(routeDependencyIndex);
685
- const sharedSet = generator.computeSharedDependencySet(usageIndex);
686
- generator.vendorShared.dependencyUsage = usageIndex;
687
- const content = generator.generateVendorSharedDependencyBundleContent(sharedSet);
688
- const assignmentMatches = content.match(/SLICE_BUNDLE_DEPENDENCIES\["deps\/shared\.js"\]/g) || [];
689
-
690
- assert.equal(assignmentMatches.length, 1);
691
- });