slicejs-cli 3.7.2 → 3.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/client.js CHANGED
@@ -520,11 +520,13 @@ registryCommand
520
520
  .description("Download and install components from official repository")
521
521
  .option("-f, --force", "Force overwrite existing components")
522
522
  .option("-s, --service", "Install Service components instead of Visual")
523
+ .option("--no-deps", "Do not resolve and install component dependencies")
523
524
  .action(async (components, options) => {
524
525
  await runWithVersionCheck(async () => {
525
526
  await getComponent(components, {
526
527
  force: options.force,
527
- service: options.service
528
+ service: options.service,
529
+ deps: options.deps
528
530
  });
529
531
  });
530
532
  });
@@ -559,6 +561,7 @@ sliceClient
559
561
  .description("Quick install components from registry")
560
562
  .option("-f, --force", "Force overwrite existing components")
561
563
  .option("-s, --service", "Install Service components instead of Visual")
564
+ .option("--no-deps", "Do not resolve and install component dependencies")
562
565
  .action(async (components, options) => {
563
566
  await runWithVersionCheck(async () => {
564
567
  if (!components || components.length === 0) {
@@ -571,7 +574,8 @@ sliceClient
571
574
 
572
575
  await getComponent(components, {
573
576
  force: options.force,
574
- service: options.service
577
+ service: options.service,
578
+ deps: options.deps
575
579
  });
576
580
  });
577
581
  });
@@ -2,6 +2,7 @@
2
2
 
3
3
  import fs from 'fs-extra';
4
4
  import path from 'path';
5
+ import { createRequire } from 'module';
5
6
  import { minify as terserMinify } from 'terser';
6
7
  import { minify } from 'html-minifier-terser';
7
8
  import CleanCSS from 'clean-css';
@@ -111,6 +112,36 @@ async function copySliceConfig() {
111
112
  }
112
113
  }
113
114
 
115
+ /**
116
+ * Copies the Slice.js framework runtime entry into dist so the production build
117
+ * is self-contained.
118
+ *
119
+ * The app bootstraps with `import Slice from '/Slice/Slice.js'`, which the server
120
+ * serves in production. Reading it from node_modules at runtime is unreliable on
121
+ * serverless platforms (Vercel only ships traced imports + `includeFiles: dist/**`,
122
+ * and pnpm stores the package behind a symlink), so we emit a physical copy into
123
+ * `dist/Slice/Slice.js`. The package's "." export resolves to that single,
124
+ * self-contained bundle; resolution is done from the *project* root so the
125
+ * project's installed framework is used (following pnpm symlinks to the real file).
126
+ */
127
+ async function copyFrameworkRuntime() {
128
+ const projectRoot = getProjectRoot(import.meta.url);
129
+ try {
130
+ const projectRequire = createRequire(path.join(projectRoot, 'package.json'));
131
+ const frameworkEntry = projectRequire.resolve('slicejs-web-framework');
132
+ const distSlice = getDistPath(import.meta.url, 'Slice', 'Slice.js');
133
+
134
+ await fs.ensureDir(path.dirname(distSlice));
135
+ await fs.copy(frameworkEntry, distSlice);
136
+
137
+ const stat = await fs.stat(distSlice);
138
+ Print.info(`Framework runtime bundled to dist/Slice/Slice.js (${(stat.size / 1024).toFixed(1)} KB)`);
139
+ } catch (error) {
140
+ Print.warning(`Could not bundle framework runtime into dist: ${error.message}`);
141
+ Print.warning('Production servers that serve /Slice/Slice.js from dist may 404 until this is resolved.');
142
+ }
143
+ }
144
+
114
145
  /**
115
146
  * Processes a complete directory
116
147
  */
@@ -472,6 +503,10 @@ export default async function buildProduction(options = {}) {
472
503
  await processDirectory(srcDir, distDir, srcDir, options);
473
504
  Print.success('All source files processed and optimized');
474
505
 
506
+ // Make dist self-contained: the framework runtime the app imports at
507
+ // /Slice/Slice.js must live under dist so it ships with serverless deploys.
508
+ await copyFrameworkRuntime();
509
+
475
510
  await verifyBuildIntegrity(distDir);
476
511
  await createOptimizedBundle();
477
512
  await generateBuildStats(srcDir, distDir);
@@ -7,6 +7,7 @@ import validations from "../Validations.js";
7
7
  import Print from "../Print.js";
8
8
  import { getComponentsJsPath, getPath } from "../utils/PathHelper.js";
9
9
  import { loadConfig as sharedLoadConfig } from "../utils/loadConfig.js";
10
+ import { analyzeSource } from "../utils/analyzeSource.js";
10
11
  import ora from "ora";
11
12
 
12
13
  // Base URL of the Slice.js documentation repository
@@ -292,11 +293,29 @@ filterOfficialComponents(allComponents) {
292
293
  }
293
294
  }
294
295
 
295
- async installComponent(componentName, category, force = false) {
296
+ async installComponent(componentName, category, force = false, opts = {}) {
297
+ const seen = opts.seen || new Set();
298
+ const withDeps = opts.withDeps !== false;
299
+ const isDep = opts.isDep === true;
300
+
301
+ // Dedupe within a single run: a component reached through several paths
302
+ // (explicitly requested + pulled in as a shared dependency) installs once.
303
+ // Check-and-add is synchronous (no await between), so concurrent installs
304
+ // from installMultipleComponents can't both pass this guard.
305
+ const seenKey = `comp:${componentName}`;
306
+ if (seen.has(seenKey)) return true;
307
+ seen.add(seenKey);
308
+
296
309
  await this._ensureConfig();
297
310
  const availableComponents = this.getAvailableComponents(category);
298
311
 
299
312
  if (!availableComponents[componentName]) {
313
+ // A dependency that isn't in the official registry (e.g. a project-local or
314
+ // framework-structural component) can't be fetched — skip it, don't abort.
315
+ if (isDep) {
316
+ Print.warning(`Dependency '${componentName}' not found in registry category '${category}' — skipping`);
317
+ return false;
318
+ }
300
319
  throw new Error(`Component '${componentName}' not found in category '${category}' in the official repository`);
301
320
  }
302
321
 
@@ -329,6 +348,13 @@ filterOfficialComponents(allComponents) {
329
348
 
330
349
  // Check if component already exists
331
350
  if (await fs.pathExists(targetPath) && !force) {
351
+ // Dependencies pulled in transitively are never re-downloaded or prompted
352
+ // for: an existing local copy is assumed complete (with its own deps).
353
+ if (isDep) {
354
+ Print.info(`${componentName} already installed — skipping dependency`);
355
+ return true;
356
+ }
357
+
332
358
  const { overwrite } = await inquirer.prompt([
333
359
  {
334
360
  type: 'confirm',
@@ -337,7 +363,7 @@ filterOfficialComponents(allComponents) {
337
363
  default: false
338
364
  }
339
365
  ]);
340
-
366
+
341
367
  if (!overwrite) {
342
368
  Print.info('Installation cancelled by user');
343
369
  return false;
@@ -357,6 +383,20 @@ filterOfficialComponents(allComponents) {
357
383
  console.log(`📁 Location: ${[folderSuffix, categoryPath, componentName].join('/').replace(/\/+/g, '/')}/`);
358
384
  console.log(`📄 Files: ${downloadedFiles.join(', ')}`);
359
385
 
386
+ // Resolve and install what this component pulls in: other components via
387
+ // slice.build('X') or relative imports, and helper .js modules it imports.
388
+ if (withDeps) {
389
+ const mainJsPath = path.join(targetPath, `${componentName}.js`);
390
+ if (await fs.pathExists(mainJsPath)) {
391
+ const jsText = await fs.readFile(mainJsPath, 'utf8');
392
+ // Path of this file relative to the repo's Components root — the anchor
393
+ // for resolving relative imports. category ('Visual'|'Service') matches
394
+ // the repo folder layout used by the download URLs.
395
+ const repoRelPath = `${category}/${componentName}/${componentName}.js`;
396
+ await this.resolveDependencies(jsText, repoRelPath, seen, force);
397
+ }
398
+ }
399
+
360
400
  return true;
361
401
 
362
402
  } catch (error) {
@@ -375,15 +415,109 @@ filterOfficialComponents(allComponents) {
375
415
  }
376
416
  }
377
417
 
378
- async installMultipleComponents(componentNames, category = 'Visual', force = false) {
418
+ // Given the source of a just-installed module, install everything it needs.
419
+ // `repoRelPath` anchors relative-import resolution to the repo's Components root.
420
+ async resolveDependencies(jsText, repoRelPath, seen, force = false) {
421
+ const { builds, imports } = analyzeSource(jsText);
422
+
423
+ // 1) Component dependencies via slice.build('X').
424
+ for (const name of builds) {
425
+ const info = this.findComponentInRegistry(name);
426
+ if (!info) continue; // structural/framework/unknown — nothing to fetch
427
+ if (!seen.has(`comp:${info.name}`)) {
428
+ Print.info(`↳ dependency: ${info.name} (${info.category})`);
429
+ }
430
+ await this.installComponent(info.name, info.category, force, { seen, withDeps: true, isDep: true });
431
+ }
432
+
433
+ // 2) Relative imports: either another component's entrypoint, or a plain
434
+ // helper .js module living inside a component folder.
435
+ for (const spec of imports) {
436
+ const resolved = this.resolveRepoImportPath(repoRelPath, spec);
437
+ if (!resolved) continue;
438
+
439
+ const parts = resolved.split('/');
440
+ const fileBase = parts[parts.length - 1].replace(/\.js$/, '');
441
+ const folder = parts.length >= 2 ? parts[parts.length - 2] : '';
442
+ const info = this.findComponentInRegistry(fileBase);
443
+
444
+ // <Category>/<Name>/<Name>.js → a registered component (e.g. Pagination
445
+ // importing ../../Service/DataGridEngine/DataGridEngine.js).
446
+ if (info && folder === info.name) {
447
+ if (!seen.has(`comp:${info.name}`)) {
448
+ Print.info(`↳ dependency: ${info.name} (${info.category})`);
449
+ }
450
+ await this.installComponent(info.name, info.category, force, { seen, withDeps: true, isDep: true });
451
+ } else {
452
+ await this.installHelperFile(resolved, seen, force);
453
+ }
454
+ }
455
+ }
456
+
457
+ // Resolves an import specifier to a path relative to the repo Components root,
458
+ // or null if it isn't a fetchable in-repo JS module.
459
+ resolveRepoImportPath(fromRepoRelPath, spec) {
460
+ const dir = path.posix.dirname(fromRepoRelPath);
461
+ let resolved = path.posix.normalize(path.posix.join(dir, spec));
462
+
463
+ // Escapes the Components root (e.g. test fixtures) → not fetchable here.
464
+ if (resolved.startsWith('..') || path.posix.isAbsolute(resolved)) return null;
465
+
466
+ const ext = path.posix.extname(resolved);
467
+ if (!ext) {
468
+ resolved += '.js';
469
+ } else if (ext !== '.js') {
470
+ return null; // only JS modules are followed
471
+ }
472
+ return resolved;
473
+ }
474
+
475
+ // Downloads a single helper module (a non-component .js imported by a
476
+ // component) into its mirrored location, then follows its own dependencies.
477
+ async installHelperFile(repoRelPath, seen, force = false) {
478
+ const seenKey = `file:${repoRelPath}`;
479
+ if (seen.has(seenKey)) return;
480
+ seen.add(seenKey);
481
+
482
+ await this._ensureConfig();
483
+ const folderSuffix = this.config?.production?.enabled === true ? 'dist' : 'src';
484
+ const segments = repoRelPath.split('/');
485
+ const localPath = getPath(import.meta.url, folderSuffix, 'Components', ...segments);
486
+
487
+ if (await fs.pathExists(localPath) && !force) {
488
+ Print.info(`↳ helper module ${repoRelPath} already present — skipping`);
489
+ return;
490
+ }
491
+
492
+ const url = `${DOCS_REPO_BASE_URL}/${repoRelPath}`;
493
+ let content;
494
+ try {
495
+ content = await fetchWithRetry(url, 3, 500, false);
496
+ } catch (error) {
497
+ Print.warning(`Could not download helper module '${repoRelPath}' — ${error.message}`);
498
+ return;
499
+ }
500
+
501
+ await fs.ensureDir(path.dirname(localPath));
502
+ await fs.writeFile(localPath, content, 'utf8');
503
+ Print.registryUpdate(`↳ helper module ${repoRelPath}`);
504
+
505
+ // A helper can import further helpers or build components.
506
+ await this.resolveDependencies(content, repoRelPath, seen, force);
507
+ }
508
+
509
+ async installMultipleComponents(componentNames, category = 'Visual', force = false, withDeps = true) {
379
510
  const results = [];
511
+ // One shared visited-set so a dependency shared by several requested
512
+ // components (e.g. DataGridEngine under both Table and Pagination) installs once.
513
+ const seen = new Set();
380
514
  Print.info(`Getting ${componentNames.length} ${category} components from official repository...`);
381
515
  const total = componentNames.length;
382
516
  let done = 0;
383
517
  const spinner = ora(`Installing 0/${total}`).start();
384
518
  const worker = async (componentName) => {
385
519
  try {
386
- const result = await this.installComponent(componentName, category, force);
520
+ const result = await this.installComponent(componentName, category, force, { seen, withDeps });
387
521
  results.push({ name: componentName, success: result });
388
522
  } catch (error) {
389
523
  Print.componentError(componentName, 'getting', error.message);
@@ -630,10 +764,13 @@ async function getComponents(componentNames = [], options = {}) {
630
764
  // Determine category
631
765
  const category = options.service ? 'Service' : 'Visual';
632
766
 
767
+ // Dependency resolution is on by default; `slice get X --no-deps` opts out.
768
+ const withDeps = options.deps !== false;
769
+
633
770
  if (componentNames.length === 1) {
634
771
  // Single component install
635
772
  const componentInfo = sharedRegistry.findComponentInRegistry(componentNames[0]);
636
-
773
+
637
774
  if (!componentInfo) {
638
775
  Print.error(`Component '${componentNames[0]}' not found in official repository`);
639
776
  Print.commandExample('View available components', 'slice browse');
@@ -644,7 +781,7 @@ async function getComponents(componentNames = [], options = {}) {
644
781
  const actualCategory = options.service ? 'Service' : componentInfo.category;
645
782
 
646
783
  try {
647
- await sharedRegistry.installComponent(componentInfo.name, actualCategory, options.force);
784
+ await sharedRegistry.installComponent(componentInfo.name, actualCategory, options.force, { seen: new Set(), withDeps });
648
785
  return true;
649
786
  } catch (error) {
650
787
  Print.error(`Error installing component: ${error.message}`);
@@ -652,12 +789,12 @@ async function getComponents(componentNames = [], options = {}) {
652
789
  }
653
790
  } else {
654
791
  // Multiple components install
655
- const normalizedComponents = componentNames.map(name =>
792
+ const normalizedComponents = componentNames.map(name =>
656
793
  name.charAt(0).toUpperCase() + name.slice(1)
657
794
  );
658
795
 
659
796
  try {
660
- await sharedRegistry.installMultipleComponents(normalizedComponents, category, options.force);
797
+ await sharedRegistry.installMultipleComponents(normalizedComponents, category, options.force, withDeps);
661
798
  return true;
662
799
  } catch (error) {
663
800
  Print.error(`Error installing components: ${error.message}`);
@@ -0,0 +1,69 @@
1
+ // commands/utils/analyzeSource.js
2
+ //
3
+ // Static dependency extraction for a single component/module source file.
4
+ // Used by the `get` flow to discover what a downloaded component needs so the
5
+ // whole dependency tree is installed, not just its own three files.
6
+ //
7
+ // Two kinds of dependency are reported:
8
+ // - builds: component names referenced via slice.build('Name') → components
9
+ // - imports: relative import/export specifiers (start with '.') → components OR helper modules
10
+ //
11
+ // Only static forms are detected (string-literal build names, static import
12
+ // specifiers). Dynamic `slice.build(variable)` cannot be resolved here.
13
+
14
+ import { parse } from '@babel/parser';
15
+ import traverse from '@babel/traverse';
16
+
17
+ /**
18
+ * @param {string} sourceText
19
+ * @returns {{ builds: Set<string>, imports: string[] }}
20
+ */
21
+ export function analyzeSource(sourceText) {
22
+ const builds = new Set();
23
+ const imports = new Set();
24
+
25
+ const addImport = (node) => {
26
+ const src = node?.source?.value;
27
+ if (typeof src === 'string' && src.startsWith('.')) imports.add(src);
28
+ };
29
+
30
+ try {
31
+ const ast = parse(sourceText, { sourceType: 'module', plugins: ['jsx'] });
32
+
33
+ traverse.default(ast, {
34
+ CallExpression(path) {
35
+ const { callee, arguments: args } = path.node;
36
+
37
+ // slice.build('Name', ...)
38
+ if (
39
+ callee.type === 'MemberExpression' &&
40
+ callee.object?.name === 'slice' &&
41
+ callee.property?.name === 'build' &&
42
+ args[0]?.type === 'StringLiteral'
43
+ ) {
44
+ builds.add(args[0].value);
45
+ return;
46
+ }
47
+
48
+ // dynamic import('./x.js')
49
+ if (
50
+ callee.type === 'Import' &&
51
+ args[0]?.type === 'StringLiteral' &&
52
+ args[0].value.startsWith('.')
53
+ ) {
54
+ imports.add(args[0].value);
55
+ }
56
+ },
57
+
58
+ ImportDeclaration(path) { addImport(path.node); },
59
+ ExportNamedDeclaration(path) { addImport(path.node); },
60
+ ExportAllDeclaration(path) { addImport(path.node); }
61
+ });
62
+ } catch {
63
+ // Unparseable source → discover nothing; the component still installs as-is.
64
+ }
65
+
66
+ return { builds, imports: Array.from(imports) };
67
+ }
68
+
69
+ export default analyzeSource;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicejs-cli",
3
- "version": "3.7.2",
3
+ "version": "3.8.0",
4
4
  "description": "Command client for developing web applications with Slice.js framework",
5
5
  "main": "client.js",
6
6
  "bin": {