slicejs-cli 4.5.0 → 4.6.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 (48) hide show
  1. package/client.js +162 -83
  2. package/commands/Print.js +158 -164
  3. package/commands/build/build.js +27 -1
  4. package/commands/buildProduction/buildProduction.js +42 -71
  5. package/commands/bundle/bundle.js +65 -60
  6. package/commands/docs/agents.js +260 -0
  7. package/commands/docs/events.js +365 -0
  8. package/commands/docs/index.js +123 -0
  9. package/commands/doctor/doctor.js +43 -9
  10. package/commands/export/checkExport.js +163 -0
  11. package/commands/export/clientRedirects.js +72 -0
  12. package/commands/export/copyDist.js +180 -0
  13. package/commands/export/export.js +236 -0
  14. package/commands/export/files.js +33 -0
  15. package/commands/export/hosts/cloudflare.js +48 -0
  16. package/commands/export/hosts/github.js +31 -0
  17. package/commands/export/hosts/index.js +69 -0
  18. package/commands/export/hosts/netlify.js +42 -0
  19. package/commands/export/hosts/nginx.js +73 -0
  20. package/commands/export/hosts/none.js +23 -0
  21. package/commands/export/hosts/s3.js +24 -0
  22. package/commands/export/hosts/shared.js +62 -0
  23. package/commands/export/hosts/vercel.js +69 -0
  24. package/commands/export/outDir.js +91 -0
  25. package/commands/export/prerender.js +121 -0
  26. package/commands/getComponent/getComponent.js +39 -34
  27. package/commands/init/init.js +32 -22
  28. package/commands/lint/lint.js +2 -2
  29. package/commands/lint/types.js +1 -1
  30. package/commands/listComponents/listComponents.js +205 -172
  31. package/commands/seo/check.js +1 -1
  32. package/commands/seo/images.js +1 -1
  33. package/commands/seo/sitemap.js +1 -1
  34. package/commands/setup/lint.js +1 -1
  35. package/commands/skill/skill.js +2 -2
  36. package/commands/startServer/startServer.js +60 -21
  37. package/commands/startServer/watchServer.js +3 -3
  38. package/commands/translator/check.js +1 -1
  39. package/commands/translator/init.js +1 -1
  40. package/commands/typecheck/typecheck.js +2 -2
  41. package/commands/types/types.js +22 -3
  42. package/commands/utils/VersionChecker.js +14 -14
  43. package/commands/utils/bundling/BundleGenerator.js +45 -27
  44. package/commands/utils/bundling/DependencyAnalyzer.js +38 -17
  45. package/commands/utils/componentCatalog.js +120 -0
  46. package/commands/utils/publicEnv.js +74 -0
  47. package/commands/utils/updateManager.js +12 -12
  48. package/package.json +22 -23
@@ -233,9 +233,27 @@ const mergeCatalog = (registry, catalog, prefix = '') => {
233
233
  };
234
234
 
235
235
  // Scan src/**/*.js for slice.events.register(<catalog>) calls and build the event registry.
236
+ // Source files that participate in the static event graph. Specs, tests and
237
+ // generated artifacts must never be documented as application emitters.
238
+ const isEventSourceFile = (filePath, srcDir) => {
239
+ const name = path.basename(filePath).toLowerCase();
240
+ if (name.endsWith('.spec.js') || name.endsWith('.test.js') || name.endsWith('.generated.js')) return false;
241
+ const relative = path.relative(srcDir, filePath).replace(/\\/g, '/');
242
+ if (relative.startsWith('public/') || relative.startsWith('bundles/')) return false;
243
+ return true;
244
+ };
245
+
246
+ const collectEventSourceFiles = async (srcDir) =>
247
+ (await collectJavaScriptFiles(srcDir)).filter((file) => isEventSourceFile(file, srcDir));
248
+
249
+ const categoryForEventSource = (relFile) => {
250
+ const match = relFile.match(/^src\/Components\/([^/]+)\//);
251
+ return match ? match[1] : null;
252
+ };
253
+
236
254
  const collectEventRegistry = async ({ projectRoot }) => {
237
255
  const srcDir = joinRoot(projectRoot, 'src');
238
- const files = await collectJavaScriptFiles(srcDir);
256
+ const files = await collectEventSourceFiles(srcDir);
239
257
  const registry = {};
240
258
 
241
259
  for (const file of files) {
@@ -342,7 +360,7 @@ const enclosingClassName = (pathRef) => {
342
360
  // Returns { events: { name: { emitters:[], listeners:[] } }, dynamic: { emitters:[], listeners:[] } }.
343
361
  const collectEventGraph = async ({ projectRoot }) => {
344
362
  const srcDir = joinRoot(projectRoot, 'src');
345
- const files = await collectJavaScriptFiles(srcDir);
363
+ const files = await collectEventSourceFiles(srcDir);
346
364
  const events = {};
347
365
  const dynamic = { emitters: [], listeners: [] };
348
366
 
@@ -378,7 +396,8 @@ const collectEventGraph = async ({ projectRoot }) => {
378
396
  const site = {
379
397
  file: relFile,
380
398
  line: pathRef.node.loc?.start?.line || 0,
381
- component: enclosingClassName(pathRef)
399
+ component: enclosingClassName(pathRef),
400
+ category: categoryForEventSource(relFile)
382
401
  };
383
402
 
384
403
  const nameArg = pathRef.node.arguments[0];
@@ -113,19 +113,19 @@ class VersionChecker {
113
113
  if (!silent && (cliStatus === 'outdated' || frameworkStatus === 'outdated')) {
114
114
  const pm = resolvePackageManager(getProjectRoot(import.meta.url)).name;
115
115
  console.log(''); // Line break
116
- Print.warning('📦 Available Updates:');
116
+ Print.subtitle('Available updates');
117
117
 
118
118
  if (cliStatus === 'outdated') {
119
- console.log(` 🔧 CLI: ${current.cli} → ${latest.cli}`);
119
+ console.log(` CLI: ${current.cli} → ${latest.cli}`);
120
120
  console.log(` ${pm} update slicejs-cli`);
121
121
  }
122
122
 
123
123
  if (frameworkStatus === 'outdated') {
124
- console.log(` ⚡ Framework: ${current.framework} → ${latest.framework}`);
124
+ console.log(` Framework: ${current.framework} → ${latest.framework}`);
125
125
  console.log(` ${pm} update slicejs-web-framework`);
126
126
  }
127
127
 
128
- console.log(' 📚 Changelog: https://github.com/VKneider/slice.js/releases');
128
+ console.log(' Changelog: https://github.com/VKneider/slice.js/releases');
129
129
  console.log(''); // Line break
130
130
  }
131
131
 
@@ -144,22 +144,22 @@ class VersionChecker {
144
144
  const current = await this.getCurrentVersions();
145
145
  const latest = await this.getLatestVersions();
146
146
 
147
- console.log('\n📋 Version Information:');
148
- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━');
149
-
147
+ Print.title('Version information');
148
+ Print.separator();
149
+
150
150
  if (current?.cli) {
151
151
  const cliStatus = this.compareVersions(current.cli, latest?.cli);
152
- const statusIcon = cliStatus === 'current' ? '✅' : cliStatus === 'outdated' ? '🔄' : '🆕';
153
- console.log(`${statusIcon} CLI: v${current.cli}${latest?.cli && latest.cli !== current.cli ? ` (latest: v${latest.cli})` : ''}`);
152
+ const status = cliStatus === 'current' ? 'up to date' : cliStatus === 'outdated' ? 'update available' : 'new';
153
+ console.log(`CLI v${current.cli}${latest?.cli && latest.cli !== current.cli ? ` → v${latest.cli}` : ''} (${status})`);
154
154
  }
155
-
155
+
156
156
  if (current?.framework) {
157
157
  const frameworkStatus = this.compareVersions(current.framework, latest?.framework);
158
- const statusIcon = frameworkStatus === 'current' ? '✅' : frameworkStatus === 'outdated' ? '🔄' : '🆕';
159
- console.log(`${statusIcon} Framework: v${current.framework}${latest?.framework && latest.framework !== current.framework ? ` (latest: v${latest.framework})` : ''}`);
158
+ const status = frameworkStatus === 'current' ? 'up to date' : frameworkStatus === 'outdated' ? 'update available' : 'new';
159
+ console.log(`Framework v${current.framework}${latest?.framework && latest.framework !== current.framework ? ` → v${latest.framework}` : ''} (${status})`);
160
160
  }
161
-
162
- console.log('━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━\n');
161
+
162
+ Print.separator();
163
163
  }
164
164
  }
165
165
 
@@ -35,6 +35,10 @@ export default class BundleGenerator {
35
35
  this.srcPath = getSrcPath(moduleUrl);
36
36
  this.distPath = getDistPath(moduleUrl);
37
37
  this.output = options.output || 'dist';
38
+ this.verbose = !!options.verbose;
39
+ // Import warnings are deduped: the same missing import can be reached from
40
+ // several bundled modules, and each occurrence is not a new problem.
41
+ this.warningMessages = new Set();
38
42
  this.bundlesPath = this.output === 'dist'
39
43
  ? path.join(this.distPath, 'bundles')
40
44
  : path.join(this.srcPath, 'bundles');
@@ -170,8 +174,6 @@ export default class BundleGenerator {
170
174
  * Generates all bundles
171
175
  */
172
176
  async generate() {
173
- console.log('🔨 Generating bundles...');
174
-
175
177
  // 0. Create bundles directory
176
178
  await fs.ensureDir(this.bundlesPath);
177
179
  if (this.output === 'dist') {
@@ -214,8 +216,6 @@ export default class BundleGenerator {
214
216
  console.warn(`Warning: emitted bundle(s) never referenced by any route: ${integrity.orphans.join(', ')}`);
215
217
  }
216
218
 
217
- console.log('✅ Bundles generated successfully');
218
-
219
219
  return {
220
220
  bundles: this.bundles,
221
221
  config,
@@ -233,13 +233,13 @@ export default class BundleGenerator {
233
233
  // Strategy based on size and usage pattern
234
234
  if (totalComponents < 20 || sharedPercentage > 60) {
235
235
  this.config.strategy = 'global';
236
- console.log('📦 Strategy: Global Bundle (small project or highly shared)');
236
+ if (this.verbose) console.log('Strategy: global bundle (small project or highly shared)');
237
237
  } else if (totalComponents < 100) {
238
238
  this.config.strategy = 'hybrid';
239
- console.log('📦 Strategy: Hybrid (critical + grouped routes)');
239
+ if (this.verbose) console.log('Strategy: hybrid (critical + grouped routes)');
240
240
  } else {
241
241
  this.config.strategy = 'per-route';
242
- console.log('📦 Strategy: Per Route (large project)');
242
+ if (this.verbose) console.log('Strategy: per route (large project)');
243
243
  }
244
244
  }
245
245
 
@@ -307,7 +307,7 @@ export default class BundleGenerator {
307
307
  this.bundles.critical.size = this.componentsBudgetSize(this.bundles.critical.components);
308
308
  }
309
309
 
310
- console.log(`✓ Critical bundle: ${this.bundles.critical.components.length} components, ${(this.bundles.critical.size / 1024).toFixed(1)} KB`);
310
+ if (this.verbose) console.log(`✔ Critical bundle: ${this.bundles.critical.components.length} components, ${(this.bundles.critical.size / 1024).toFixed(1)} KB`);
311
311
  }
312
312
 
313
313
  /**
@@ -368,7 +368,7 @@ export default class BundleGenerator {
368
368
  file: `slice-bundle.${routeKey}.js`
369
369
  };
370
370
 
371
- console.log(`✓ Bundle ${routeKey}: ${uniqueComponents.length} components, ${(totalSize / 1024).toFixed(1)} KB`);
371
+ if (this.verbose) console.log(`✔ Bundle ${routeKey}: ${uniqueComponents.length} components, ${(totalSize / 1024).toFixed(1)} KB`);
372
372
  }
373
373
  }
374
374
 
@@ -439,7 +439,7 @@ export default class BundleGenerator {
439
439
  file: `slice-bundle.${this.routeToFileName(groupKey)}.js`
440
440
  };
441
441
 
442
- console.log(`✓ Bundle ${groupKey}: ${uniqueComponents.length} components, ${(totalSize / 1024).toFixed(1)} KB (${groupData.routes.length} routes)`);
442
+ if (this.verbose) console.log(`✔ Bundle ${groupKey}: ${uniqueComponents.length} components, ${(totalSize / 1024).toFixed(1)} KB (${groupData.routes.length} routes)`);
443
443
  }
444
444
  }
445
445
  }
@@ -496,7 +496,7 @@ export default class BundleGenerator {
496
496
  file: `slice-bundle.${this.routeToFileName(category)}.js`
497
497
  };
498
498
 
499
- console.log(`✓ Bundle ${category}: ${uniqueComponents.length} components, ${(totalSize / 1024).toFixed(1)} KB (${routes.length} routes)`);
499
+ if (this.verbose) console.log(`✔ Bundle ${category}: ${uniqueComponents.length} components, ${(totalSize / 1024).toFixed(1)} KB (${routes.length} routes)`);
500
500
  }
501
501
  }
502
502
 
@@ -1584,14 +1584,14 @@ export default class BundleGenerator {
1584
1584
 
1585
1585
  if (needsDefault.size === 0) return;
1586
1586
 
1587
- console.log(`📦 Resolving ${needsDefault.size} external dependenc${needsDefault.size === 1 ? 'y' : 'ies'} from node_modules...`);
1587
+ if (this.verbose) console.log(`Resolving ${needsDefault.size} external dependenc${needsDefault.size === 1 ? 'y' : 'ies'} from node_modules...`);
1588
1588
 
1589
1589
  for (const [name, nd] of needsDefault) {
1590
1590
  try {
1591
1591
  const { expression, warnings } = await this.getExternalBundler().bundle(name, { needsDefault: nd });
1592
1592
  this.externalModulesByName.set(name, expression);
1593
1593
  warnings.forEach((w) => console.warn(`Warning: [external:${name}] ${w}`));
1594
- console.log(` ✓ ${name}`);
1594
+ if (this.verbose) console.log(` ✔ ${name}`);
1595
1595
  } catch (error) {
1596
1596
  this.externalResolutionErrors.set(name, error.message);
1597
1597
  console.warn(`Warning: ${error.message}`);
@@ -2730,10 +2730,10 @@ if (window.slice && window.slice.controller) {
2730
2730
  && options.handledSpecifiers.has(specifier);
2731
2731
 
2732
2732
  if (!handled && !options.silent) {
2733
- console.warn(this.buildImportWarningMessage(
2733
+ this.recordImportWarning(
2734
2734
  `Warning: Stripping unsupported import inside bundled dependency: ${specifier}`,
2735
2735
  moduleName
2736
- ));
2736
+ );
2737
2737
  }
2738
2738
  return '';
2739
2739
  }
@@ -2744,10 +2744,10 @@ if (window.slice && window.slice.controller) {
2744
2744
  // object. The source module is registered earlier by the topological order.
2745
2745
  const depExpr = this.reexportDependencyExpression(moduleName, node.source?.value, preferShared, specifierToKey);
2746
2746
  if (!depExpr) {
2747
- console.warn(this.buildImportWarningMessage(
2747
+ this.recordImportWarning(
2748
2748
  `Warning: Dropping unresolvable 'export *' inside bundled dependency: ${node.source?.value}`,
2749
2749
  moduleName
2750
- ));
2750
+ );
2751
2751
  return '';
2752
2752
  }
2753
2753
  const tmp = `__sliceReexportAll_${node.start}`;
@@ -2774,10 +2774,10 @@ if (window.slice && window.slice.controller) {
2774
2774
  // the corresponding member of the resolved module's exports object.
2775
2775
  const depExpr = this.reexportDependencyExpression(moduleName, node.source.value, preferShared, specifierToKey);
2776
2776
  if (!depExpr) {
2777
- console.warn(this.buildImportWarningMessage(
2777
+ this.recordImportWarning(
2778
2778
  `Warning: Dropping unresolvable re-export inside bundled dependency: ${node.source.value}`,
2779
2779
  moduleName
2780
- ));
2780
+ );
2781
2781
  return '';
2782
2782
  }
2783
2783
  const tmp = `__sliceReexport_${node.start}`;
@@ -3275,8 +3275,26 @@ if (window.slice && window.slice.controller) {
3275
3275
  }
3276
3276
 
3277
3277
  buildImportWarningMessage(baseMessage, sourceContext) {
3278
- if (!sourceContext) return baseMessage;
3279
- return `${baseMessage} [${sourceContext}]`;
3278
+ const message = String(baseMessage).replace(/^Warning:\s*/, '');
3279
+ if (!sourceContext) return `! ${message}`;
3280
+ // Keep warnings readable: the full absolute path of a framework dependency
3281
+ // adds noise without helping identify the file. Two trailing segments are
3282
+ // enough (`Controller/Controller.js`).
3283
+ const short = sourceContext.includes(path.sep)
3284
+ ? sourceContext.split(path.sep).slice(-2).join('/')
3285
+ : sourceContext;
3286
+ return `! ${message} (${short})`;
3287
+ }
3288
+
3289
+ /**
3290
+ * Prints one `!` warning per unique import problem. Duplicates are common when
3291
+ * the same module is reached from several bundles.
3292
+ */
3293
+ recordImportWarning(baseMessage, sourceContext) {
3294
+ const message = this.buildImportWarningMessage(baseMessage, sourceContext);
3295
+ if (this.warningMessages.has(message)) return;
3296
+ this.warningMessages.add(message);
3297
+ console.warn(message);
3280
3298
  }
3281
3299
 
3282
3300
  extractLocalBindingsFromImportStatement(statement) {
@@ -3437,7 +3455,7 @@ if (window.slice && window.slice.controller) {
3437
3455
  cleanedCode += statement;
3438
3456
  }
3439
3457
  } else if (classification.warning) {
3440
- console.warn(this.buildImportWarningMessage(classification.warning, sourceContext));
3458
+ this.recordImportWarning(classification.warning, sourceContext);
3441
3459
  }
3442
3460
  cursor = end;
3443
3461
  }
@@ -3474,7 +3492,7 @@ if (window.slice && window.slice.controller) {
3474
3492
  cleaned += statement;
3475
3493
  }
3476
3494
  } else if (classification.warning) {
3477
- console.warn(this.buildImportWarningMessage(classification.warning, sourceContext));
3495
+ this.recordImportWarning(classification.warning, sourceContext);
3478
3496
  }
3479
3497
 
3480
3498
  cursor = node.end;
@@ -3574,10 +3592,10 @@ if (window.slice && window.slice.controller) {
3574
3592
  // attach one to. Dropping it costs nothing inside the bundle, but it means
3575
3593
  // this file is acting as a barrel — worth saying so out loud.
3576
3594
  if (node.source) {
3577
- console.warn(this.buildImportWarningMessage(
3595
+ this.recordImportWarning(
3578
3596
  `Warning: Dropping re-export '${code.slice(node.start, node.end).split('\n')[0].trim()}' from a component file (not supported in bundles)`,
3579
3597
  sourceContext
3580
- ));
3598
+ );
3581
3599
  return '';
3582
3600
  }
3583
3601
 
@@ -3699,8 +3717,8 @@ if (window.slice && window.slice.controller) {
3699
3717
  const jsConfig = this.generateBundleConfigJS(config);
3700
3718
  await fs.writeFile(jsConfigPath, jsConfig, 'utf-8');
3701
3719
 
3702
- console.log(`✓ Configuration saved to ${configPath}`);
3703
- console.log(`✓ JavaScript config generated: ${jsConfigPath}`);
3720
+ if (this.verbose) console.log(`✔ Configuration saved to ${configPath}`);
3721
+ if (this.verbose) console.log(`✔ JavaScript config generated: ${jsConfigPath}`);
3704
3722
  }
3705
3723
 
3706
3724
  /**
@@ -16,13 +16,17 @@ export default class DependencyAnalyzer {
16
16
  this.components = new Map();
17
17
  this.routes = new Map();
18
18
  this.dependencyGraph = new Map();
19
+
20
+ // Dynamic slice.build() calls found while parsing component files. They are
21
+ // collected and reported as one line instead of one warning per call.
22
+ this.dynamicBuildCalls = [];
23
+ this.dynamicBuildKeys = new Set();
19
24
  }
20
25
 
21
26
  /**
22
27
  * Executes complete project analysis
23
28
  */
24
29
  async analyze() {
25
- console.log('🔍 Analyzing project...');
26
30
 
27
31
  // 1. Load component configuration
28
32
  await this.loadComponentsConfig();
@@ -40,8 +44,6 @@ export default class DependencyAnalyzer {
40
44
  // 5. Calculate metrics
41
45
  const metrics = this.calculateMetrics();
42
46
 
43
- console.log('✅ Analysis completed');
44
-
45
47
  return {
46
48
  components: Array.from(this.components.values()),
47
49
  routes: Array.from(this.routes.values()),
@@ -51,6 +53,26 @@ export default class DependencyAnalyzer {
51
53
  };
52
54
  }
53
55
 
56
+ /**
57
+ * Reports every dynamic `slice.build()` call as one line. They are valid at
58
+ * runtime but cannot be linked into a bundle, so they used to produce one long
59
+ * warning per call and drown the build result.
60
+ */
61
+ reportDynamicBuildWarnings() {
62
+ if (this.dynamicBuildCalls.length === 0) return;
63
+
64
+ const count = this.dynamicBuildCalls.length;
65
+ const plural = count === 1 ? '' : 's';
66
+ const locations = this.dynamicBuildCalls
67
+ .map(({ file, line }) => `${file}${line ? `:${line}` : ''}`)
68
+ .join(', ');
69
+
70
+ console.warn(
71
+ `! ${count} dynamic slice.build() call${plural} cannot be bundled (runtime-only): ${locations}. ` +
72
+ 'Use a string literal or a resolvable constant to bundle them.'
73
+ );
74
+ }
75
+
54
76
  /**
55
77
  * Loads component configuration from components.js
56
78
  */
@@ -363,7 +385,8 @@ export default class DependencyAnalyzer {
363
385
  // `path` is shadowed by the Babel NodePath param inside visitors, so derive
364
386
  // the label here where `path` is still the node module.
365
387
  const componentLabel = componentFilePath ? path.basename(componentFilePath) : '';
366
- const warnedDynamicBuilds = new Set();
388
+ // Babel visitor methods are plain functions, so `this` is not the analyzer.
389
+ const analyzer = this;
367
390
 
368
391
  const resolveRoutesArray = (node, scope) => {
369
392
  if (!node) return null;
@@ -526,7 +549,7 @@ export default class DependencyAnalyzer {
526
549
  const baseDir = path.dirname(fromFilePath);
527
550
  const resolvedPath = resolveImportPath(importPath, baseDir);
528
551
  if (!resolvedPath) {
529
- console.warn(`⚠️ Cannot resolve import for MultiRoute routes: ${importPath}`);
552
+ console.warn(`Cannot resolve import for MultiRoute routes: ${importPath}`);
530
553
  return null;
531
554
  }
532
555
 
@@ -591,7 +614,7 @@ export default class DependencyAnalyzer {
591
614
  resolveImportedValue.cache.set(cacheKey, exportNode || null);
592
615
  return exportNode || null;
593
616
  } catch (error) {
594
- console.warn(`⚠️ Error resolving import ${importPath}: ${error.message}`);
617
+ console.warn(`Error resolving import ${importPath}: ${error.message}`);
595
618
  resolveImportedValue.cache.set(cacheKey, null);
596
619
  return null;
597
620
  }
@@ -738,12 +761,10 @@ export default class DependencyAnalyzer {
738
761
  ? code.slice(args[0].start, args[0].end)
739
762
  : '<expr>';
740
763
  const line = args[0].loc?.start?.line;
741
- const key = `${snippet}@${line ?? '?'}`;
742
- if (!warnedDynamicBuilds.has(key)) {
743
- warnedDynamicBuilds.add(key);
744
- const where = componentLabel ? ` in ${componentLabel}` : '';
745
- const at = line ? `:${line}` : '';
746
- console.warn(`⚠️ Dynamic slice.build(${snippet})${where}${at} — the component name is computed at runtime, so it can't be linked into a bundle. It will still load individually at runtime (no bundle optimization). Use a string literal or a resolvable constant to bundle it.`);
764
+ const key = `${componentFilePath || componentLabel}:${line ?? '?'}:${snippet}`;
765
+ if (!analyzer.dynamicBuildKeys.has(key)) {
766
+ analyzer.dynamicBuildKeys.add(key);
767
+ analyzer.dynamicBuildCalls.push({ file: componentLabel || 'unknown', line, snippet });
747
768
  }
748
769
  }
749
770
  }
@@ -759,7 +780,7 @@ export default class DependencyAnalyzer {
759
780
  }
760
781
  });
761
782
  } catch (error) {
762
- console.warn(`⚠️ Error parsing component: ${error.message}`);
783
+ console.warn(`Error parsing component: ${error.message}`);
763
784
  }
764
785
 
765
786
  return dependencies;
@@ -815,7 +836,7 @@ export default class DependencyAnalyzer {
815
836
  this.routeGroups = this.detectRouteGroups();
816
837
 
817
838
  } catch (error) {
818
- console.warn(`⚠️ Error parsing routes at ${this.routesPath}: ${error.message}`);
839
+ console.warn(`Error parsing routes at ${this.routesPath}: ${error.message}`);
819
840
  }
820
841
  }
821
842
 
@@ -966,19 +987,19 @@ export default class DependencyAnalyzer {
966
987
  * Generates a visual report of the analysis
967
988
  */
968
989
  generateReport(metrics) {
969
- console.log('\n📊 PROJECT ANALYSIS\n');
990
+ console.log('\nProject analysis\n');
970
991
  console.log(`Total components: ${metrics.totalComponents}`);
971
992
  console.log(`Total routes: ${metrics.totalRoutes}`);
972
993
  console.log(`Shared components: ${metrics.sharedComponentsCount} (${metrics.sharedPercentage}%)`);
973
994
  console.log(`Total size: ${(metrics.totalSize / 1024).toFixed(1)} KB`);
974
995
  console.log(`Average size: ${(metrics.averageSize / 1024).toFixed(1)} KB per component`);
975
996
 
976
- console.log('\n📦 By category:');
997
+ console.log('\nBy category:');
977
998
  for (const [category, count] of Object.entries(metrics.byCategory)) {
978
999
  console.log(` ${category}: ${count} components`);
979
1000
  }
980
1001
 
981
- console.log('\n🔥 Top 10 most used components:');
1002
+ console.log('\nTop 10 most used components:');
982
1003
  metrics.topByUsage.forEach((comp, i) => {
983
1004
  console.log(` ${i + 1}. ${comp.name} - ${comp.routes} routes - ${(comp.size / 1024).toFixed(1)} KB`);
984
1005
  });
@@ -0,0 +1,120 @@
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+
4
+ const cleanCategoryPath = (value) =>
5
+ String(value || '').replace(/^[/\\]+/, '').replace(/[/\\]+$/, '');
6
+
7
+ export function getComponentCategories(config) {
8
+ const entries = Object.entries(config?.paths?.components || {});
9
+ return entries
10
+ .map(([name, meta]) => ({
11
+ name,
12
+ type: meta?.type || 'Visual',
13
+ path: meta?.path || `/Components/${name}`,
14
+ description: typeof meta?.description === 'string' ? meta.description : '',
15
+ }))
16
+ .sort((a, b) => a.name.localeCompare(b.name));
17
+ }
18
+
19
+ export async function loadProjectConfig(projectRoot) {
20
+ const configPath = path.join(projectRoot, 'src', 'sliceConfig.json');
21
+ if (!(await fs.pathExists(configPath))) {
22
+ throw new Error(`sliceConfig.json not found at ${configPath}`);
23
+ }
24
+ return fs.readJson(configPath);
25
+ }
26
+
27
+ export async function scanComponentCatalog({ projectRoot, config }) {
28
+ const categories = [];
29
+
30
+ for (const category of getComponentCategories(config)) {
31
+ const relativePath = path.posix.join('src', cleanCategoryPath(category.path));
32
+ const directory = path.join(projectRoot, 'src', cleanCategoryPath(category.path));
33
+ const components = [];
34
+
35
+ if (await fs.pathExists(directory)) {
36
+ const entries = await fs.readdir(directory, { withFileTypes: true });
37
+ for (const entry of entries) {
38
+ if (!entry.isDirectory() || entry.name.startsWith('.')) continue;
39
+ const componentDir = path.join(directory, entry.name);
40
+ const files = await fs.readdir(componentDir, { withFileTypes: true });
41
+ const fileNames = files
42
+ .filter((file) => file.isFile())
43
+ .map((file) => file.name)
44
+ .sort((a, b) => a.localeCompare(b));
45
+ components.push({
46
+ name: entry.name,
47
+ category: category.name,
48
+ type: category.type,
49
+ directory: componentDir,
50
+ relativePath: path.posix.join(relativePath, entry.name),
51
+ fileCount: fileNames.length,
52
+ files: fileNames,
53
+ readme: fileNames.includes('README.md'),
54
+ spec: fileNames.some((name) => name.endsWith('.spec.js')),
55
+ });
56
+ }
57
+ }
58
+
59
+ components.sort((a, b) => a.name.localeCompare(b.name));
60
+ categories.push({ ...category, relativePath, directory, components });
61
+ }
62
+
63
+ const components = categories.flatMap((category) => category.components);
64
+ return { config, categories, components };
65
+ }
66
+
67
+ export function buildComponentsRegistry(catalog) {
68
+ const registry = {};
69
+ for (const component of catalog.components) registry[component.name] = component.category;
70
+ return Object.fromEntries(Object.entries(registry).sort(([a], [b]) => a.localeCompare(b)));
71
+ }
72
+
73
+ export function serializeComponentsRegistry(catalog) {
74
+ return `const components = ${JSON.stringify(buildComponentsRegistry(catalog), null, 2)};\n\nexport default components;\n`;
75
+ }
76
+
77
+ export async function writeComponentsRegistry(projectRoot, catalog) {
78
+ const outputPath = path.join(projectRoot, 'src', 'Components', 'components.js');
79
+ await fs.ensureDir(path.dirname(outputPath));
80
+ await fs.writeFile(outputPath, serializeComponentsRegistry(catalog), 'utf8');
81
+ return outputPath;
82
+ }
83
+
84
+ export async function syncComponentsRegistry(projectRoot) {
85
+ const config = await loadProjectConfig(projectRoot);
86
+ const catalog = await scanComponentCatalog({ projectRoot, config });
87
+ await writeComponentsRegistry(projectRoot, catalog);
88
+ return catalog;
89
+ }
90
+
91
+ export async function readComponentsRegistry(projectRoot) {
92
+ const registryPath = path.join(projectRoot, 'src', 'Components', 'components.js');
93
+ if (!(await fs.pathExists(registryPath))) return null;
94
+ const source = await fs.readFile(registryPath, 'utf8');
95
+ const match = source.match(/const components = ({[\s\S]*?});/);
96
+ if (!match) return null;
97
+ try {
98
+ return JSON.parse(match[1]);
99
+ } catch {
100
+ return null;
101
+ }
102
+ }
103
+
104
+ export function componentDocCommand(component) {
105
+ // Only the registry-owned categories publish component docs remotely.
106
+ // App categories (Domain, Core, Providers, AppComponents, DataDisplay…) are
107
+ // local and document themselves in a README next to the component.
108
+ if (!['Visual', 'Service'].includes(component.category)) return null;
109
+ const id = component.name
110
+ .replace(/([a-z0-9])([A-Z])/g, '$1-$2')
111
+ .replace(/[_\s]+/g, '-')
112
+ .toLowerCase();
113
+ return `slice docs get components:${id}`;
114
+ }
115
+
116
+ export function componentDocCell(component) {
117
+ if (component.readme) return `[README](./${component.name}/README.md)`;
118
+ const command = componentDocCommand(component);
119
+ return command ? `\`${command}\`` : '—';
120
+ }
@@ -0,0 +1,74 @@
1
+ // commands/utils/publicEnv.js
2
+ //
3
+ // One place for the build-time public environment. `slice build` writes both
4
+ // dist/slice-env.json (shared, auditable) and dist/slice-env.generated.js (the
5
+ // ESM shim the runtime imports). `slice export` copies them and `slice start`
6
+ // serves them as static files; no dynamic env endpoint is needed in production.
7
+ import fs from 'fs-extra';
8
+ import path from 'path';
9
+ import { createRequire } from 'node:module';
10
+ import { pathToFileURL } from 'node:url';
11
+
12
+ let resolverPromise;
13
+
14
+ /**
15
+ * Prefer the framework package export, but fall back to the package file path so
16
+ * an older framework release still works.
17
+ */
18
+ export async function loadPublicEnvResolver() {
19
+ if (!resolverPromise) {
20
+ resolverPromise = (async () => {
21
+ try {
22
+ return await import('slicejs-web-framework/api/framework/publicEnvResolver.js');
23
+ } catch {
24
+ const require = createRequire(import.meta.url);
25
+ const entry = require.resolve('slicejs-web-framework');
26
+ const packageRoot = path.resolve(path.dirname(entry), '..');
27
+ return import(pathToFileURL(path.join(packageRoot, 'api', 'framework', 'publicEnvResolver.js')).href);
28
+ }
29
+ })();
30
+ }
31
+ return resolverPromise;
32
+ }
33
+
34
+ export async function resolvePublicEnvPayload(projectRoot) {
35
+ const { resolvePublicEnv } = await loadPublicEnvResolver();
36
+ return resolvePublicEnv({
37
+ mode: 'production',
38
+ envFilePath: path.join(projectRoot, '.env')
39
+ });
40
+ }
41
+
42
+ /**
43
+ * Writes both env artifacts into `<outDir>` and returns the number of public keys.
44
+ * The JSON is the shared source of truth; the ESM shim exists because native JSON
45
+ * modules are not available in every browser/webview Slice supports.
46
+ */
47
+ export async function writeSliceEnv(outDir, projectRoot) {
48
+ const payload = await resolvePublicEnvPayload(projectRoot);
49
+ await writeSliceEnvPayload(outDir, payload);
50
+ return Object.keys(payload.env || {}).length;
51
+ }
52
+
53
+ export function renderSliceEnvModule(payload) {
54
+ return [
55
+ '// Generated by slice build. Do not edit.',
56
+ `const env = ${JSON.stringify(payload, null, 2)};`,
57
+ 'export default env;',
58
+ ''
59
+ ].join('\n');
60
+ }
61
+
62
+ export async function writeSliceEnvPayload(outDir, payload) {
63
+ await fs.ensureDir(outDir);
64
+ await fs.writeFile(
65
+ path.join(outDir, 'slice-env.json'),
66
+ `${JSON.stringify(payload, null, 2)}\n`,
67
+ 'utf8'
68
+ );
69
+ await fs.writeFile(
70
+ path.join(outDir, 'slice-env.generated.js'),
71
+ renderSliceEnvModule(payload),
72
+ 'utf8'
73
+ );
74
+ }