slicejs-web-framework 3.4.3 → 3.4.4

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 (107) hide show
  1. package/.opencode/opencode.json +14 -14
  2. package/Slice/Components/Structural/ContextManager/ContextManager.js +422 -422
  3. package/Slice/Components/Structural/ContextManager/ContextManagerDebugger.js +468 -468
  4. package/Slice/Components/Structural/Controller/Controller.js +1271 -1198
  5. package/Slice/Components/Structural/Debugger/Debugger.js +1503 -1503
  6. package/Slice/Components/Structural/EventManager/EventManager.js +366 -366
  7. package/Slice/Components/Structural/Logger/Logger.js +225 -225
  8. package/Slice/Components/Structural/Router/Router.js +775 -775
  9. package/Slice/Components/Structural/StylesManager/StylesManager.js +82 -82
  10. package/Slice/Components/Structural/StylesManager/ThemeManager/ThemeManager.js +106 -106
  11. package/Slice/Slice.js +650 -627
  12. package/Slice/tests/build-singleton.test.js +244 -244
  13. package/Slice/tests/bundle-v2-runtime-contract.test.js +738 -738
  14. package/Slice/tests/context-patch-use.test.js +95 -95
  15. package/Slice/tests/fixtures/real-runtime-loader.mjs +21 -21
  16. package/Slice/tests/public-env-typed-accessors.test.js +66 -66
  17. package/api/index.js +281 -281
  18. package/api/utils/publicEnvResolver.js +123 -123
  19. package/package.json +44 -44
  20. package/slicejs-cli/.github/workflows/ci.yml +43 -0
  21. package/slicejs-cli/LICENSE +21 -0
  22. package/slicejs-cli/assets/Slice.js-logo.png +0 -0
  23. package/slicejs-cli/client.js +740 -0
  24. package/slicejs-cli/commands/Print.js +164 -0
  25. package/slicejs-cli/commands/Validations.js +92 -0
  26. package/slicejs-cli/commands/build/build.js +40 -0
  27. package/slicejs-cli/commands/buildProduction/buildProduction.js +577 -0
  28. package/slicejs-cli/commands/bundle/bundle.js +236 -0
  29. package/slicejs-cli/commands/createComponent/VisualComponentTemplate.js +55 -0
  30. package/slicejs-cli/commands/createComponent/createComponent.js +128 -0
  31. package/slicejs-cli/commands/deleteComponent/deleteComponent.js +81 -0
  32. package/slicejs-cli/commands/doctor/doctor.js +516 -0
  33. package/slicejs-cli/commands/getComponent/getComponent.js +695 -0
  34. package/slicejs-cli/commands/init/init.js +473 -0
  35. package/slicejs-cli/commands/listComponents/listComponents.js +172 -0
  36. package/slicejs-cli/commands/startServer/startServer.js +240 -0
  37. package/slicejs-cli/commands/startServer/watchServer.js +66 -0
  38. package/slicejs-cli/commands/types/types.js +583 -0
  39. package/slicejs-cli/commands/utils/LocalCliDelegation.js +53 -0
  40. package/slicejs-cli/commands/utils/PackageManager.js +148 -0
  41. package/slicejs-cli/commands/utils/PathHelper.js +75 -0
  42. package/slicejs-cli/commands/utils/VersionChecker.js +169 -0
  43. package/slicejs-cli/commands/utils/bundling/BundleGenerator.js +2525 -0
  44. package/slicejs-cli/commands/utils/bundling/DependencyAnalyzer.js +933 -0
  45. package/slicejs-cli/commands/utils/loadConfig.js +31 -0
  46. package/slicejs-cli/commands/utils/sliceScripts.js +48 -0
  47. package/slicejs-cli/commands/utils/updateManager.js +471 -0
  48. package/slicejs-cli/package.json +71 -0
  49. package/slicejs-cli/playwright.config.js +51 -0
  50. package/slicejs-cli/pnpm-lock.yaml +1629 -0
  51. package/slicejs-cli/tests/build-command-integration.test.js +87 -0
  52. package/slicejs-cli/tests/build-mangling-e2e.test.js +290 -0
  53. package/slicejs-cli/tests/build-production-e2e.test.js +140 -0
  54. package/slicejs-cli/tests/builder-edge-cases.test.js +322 -0
  55. package/slicejs-cli/tests/bundle-generate-e2e.test.js +115 -0
  56. package/slicejs-cli/tests/bundle-generator.test.js +691 -0
  57. package/slicejs-cli/tests/bundle-v2-register-output.test.js +470 -0
  58. package/slicejs-cli/tests/bundling-dependency-edges.test.js +127 -0
  59. package/slicejs-cli/tests/bundling-imports-unit.test.js +267 -0
  60. package/slicejs-cli/tests/client-launcher-contract.test.js +211 -0
  61. package/slicejs-cli/tests/commands-component-crud.test.js +128 -0
  62. package/slicejs-cli/tests/commands-doctor.test.js +152 -0
  63. package/slicejs-cli/tests/commands-version-checker.test.js +37 -0
  64. package/slicejs-cli/tests/component-registry-parse.test.js +34 -0
  65. package/slicejs-cli/tests/dependency-analyzer.test.js +24 -0
  66. package/slicejs-cli/tests/e2e/bundles.spec.js +91 -0
  67. package/slicejs-cli/tests/e2e/dependency-scenarios.spec.js +56 -0
  68. package/slicejs-cli/tests/e2e/fixtures/components/Service/FetchManager/FetchManager.js +136 -0
  69. package/slicejs-cli/tests/e2e/fixtures/components/Service/IndexedDbManager/IndexedDbManager.js +149 -0
  70. package/slicejs-cli/tests/e2e/fixtures/components/Service/LocalStorageManager/LocalStorageManager.js +45 -0
  71. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Button/Button.css +106 -0
  72. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Button/Button.html +5 -0
  73. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Button/Button.js +158 -0
  74. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Link/Link.js +33 -0
  75. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Loading/Loading.css +56 -0
  76. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Loading/Loading.html +83 -0
  77. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Loading/Loading.js +164 -0
  78. package/slicejs-cli/tests/e2e/fixtures/components/Visual/MultiRoute/MultiRoute.js +167 -0
  79. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Navbar/Navbar.css +116 -0
  80. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Navbar/Navbar.html +44 -0
  81. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Navbar/Navbar.js +180 -0
  82. package/slicejs-cli/tests/e2e/fixtures/components/Visual/NotFound/NotFound.js +20 -0
  83. package/slicejs-cli/tests/e2e/fixtures/components/Visual/Route/Route.js +181 -0
  84. package/slicejs-cli/tests/e2e/fixtures/components/registry.json +12 -0
  85. package/slicejs-cli/tests/e2e/fixtures/vendor-components.mjs +65 -0
  86. package/slicejs-cli/tests/e2e/navigation.spec.js +44 -0
  87. package/slicejs-cli/tests/e2e/render.spec.js +34 -0
  88. package/slicejs-cli/tests/e2e/serve.mjs +264 -0
  89. package/slicejs-cli/tests/e2e/shared-deps.spec.js +61 -0
  90. package/slicejs-cli/tests/e2e/unminified.spec.js +33 -0
  91. package/slicejs-cli/tests/e2e-serve.test.js +148 -0
  92. package/slicejs-cli/tests/fixtures/components.js +8 -0
  93. package/slicejs-cli/tests/fixtures/sliceConfig.json +74 -0
  94. package/slicejs-cli/tests/getcomponent.test.js +435 -0
  95. package/slicejs-cli/tests/helpers/setup.js +102 -0
  96. package/slicejs-cli/tests/init-command-contract.test.js +101 -0
  97. package/slicejs-cli/tests/init-e2e.test.js +82 -0
  98. package/slicejs-cli/tests/init-project-isolation.test.js +98 -0
  99. package/slicejs-cli/tests/local-cli-delegation.test.js +81 -0
  100. package/slicejs-cli/tests/package-manager.test.js +127 -0
  101. package/slicejs-cli/tests/path-helper.test.js +206 -0
  102. package/slicejs-cli/tests/perf-budget.test.js +84 -0
  103. package/slicejs-cli/tests/postinstall-command.test.js +103 -0
  104. package/slicejs-cli/tests/property-mangling-regression.test.js +182 -0
  105. package/slicejs-cli/tests/types-breakage.test.js +491 -0
  106. package/slicejs-cli/tests/types-generator-errors.test.js +361 -0
  107. package/slicejs-cli/tests/types-generator.test.js +348 -0
@@ -0,0 +1,740 @@
1
+ #!/usr/bin/env node
2
+ import { program } from "commander";
3
+ import inquirer from "inquirer";
4
+ import initializeProject from "./commands/init/init.js";
5
+ import createComponent from "./commands/createComponent/createComponent.js";
6
+ import listComponents from "./commands/listComponents/listComponents.js";
7
+ import deleteComponent from "./commands/deleteComponent/deleteComponent.js";
8
+ import getComponent, { listComponents as listRemoteComponents, syncComponents } from "./commands/getComponent/getComponent.js";
9
+ import startServer from "./commands/startServer/startServer.js";
10
+ import runDiagnostics from "./commands/doctor/doctor.js";
11
+ import versionChecker from "./commands/utils/VersionChecker.js";
12
+ import updateManager from "./commands/utils/updateManager.js";
13
+ import fs from "fs";
14
+ import path from "path";
15
+ import { fileURLToPath } from "url";
16
+ import { getProjectRoot, getSrcPath, getPath } from "./commands/utils/PathHelper.js";
17
+ import { loadConfigSync as sharedLoadConfigSync } from "./commands/utils/loadConfig.js";
18
+ import { spawnSync } from "node:child_process";
19
+ import validations from "./commands/Validations.js";
20
+ import Print from "./commands/Print.js";
21
+ import build from './commands/build/build.js';
22
+ import { runGenerateTypes } from './commands/types/types.js';
23
+ import { cleanBundles, bundleInfo } from './commands/bundle/bundle.js';
24
+ import {
25
+ isLocalDelegationDisabled,
26
+ findNearestLocalCliEntry,
27
+ resolveLocalCliCandidate,
28
+ shouldDelegateToLocalCli
29
+ } from './commands/utils/LocalCliDelegation.js';
30
+ import {
31
+ detectPackageManager,
32
+ getAvailablePackageManagers,
33
+ isPackageManagerAvailable,
34
+ resolvePackageManager,
35
+ runScriptCommand,
36
+ SUPPORTED_PACKAGE_MANAGERS
37
+ } from './commands/utils/PackageManager.js';
38
+ import { SLICE_SCRIPTS, verifySliceScriptsInPackageJson } from './commands/utils/sliceScripts.js';
39
+
40
+ const __dirname = path.dirname(fileURLToPath(import.meta.url));
41
+
42
+ const getCategories = () => {
43
+ const config = sharedLoadConfigSync(import.meta.url);
44
+ return config && config.paths?.components ? Object.keys(config.paths.components) : [];
45
+ };
46
+
47
+ // Helper to validate port number
48
+ function parsePort(value) {
49
+ if (!value) return undefined;
50
+ const port = parseInt(value, 10);
51
+ if (isNaN(port) || port < 1 || port > 65535) {
52
+ Print.error(`Invalid port: "${value}". Must be a number between 1 and 65535.`);
53
+ process.exit(1);
54
+ }
55
+ return port;
56
+ }
57
+
58
+ async function withNodeEnv(env, fn) {
59
+ const prevEnv = process.env.NODE_ENV;
60
+ process.env.NODE_ENV = env;
61
+ listComponents();
62
+ try {
63
+ return await fn();
64
+ } finally {
65
+ process.env.NODE_ENV = prevEnv;
66
+ }
67
+ }
68
+
69
+ // Function to run version check for all commands
70
+ async function runWithVersionCheck(commandFunction, ...args) {
71
+ try {
72
+ const globalOpts = program.opts();
73
+ const skipVersionCheck = globalOpts.noVersionCheck === false;
74
+
75
+ if (!skipVersionCheck) {
76
+ updateManager.notifyAvailableUpdates().catch(() => {});
77
+ }
78
+
79
+ const result = await commandFunction(...args);
80
+
81
+ if (!skipVersionCheck) {
82
+ setTimeout(() => {
83
+ versionChecker.checkForUpdates(false);
84
+ }, 100);
85
+ }
86
+
87
+ return result;
88
+ } catch (error) {
89
+ Print.error(`Command execution: ${error.message}`);
90
+ console.error(error.stack);
91
+ return false;
92
+ }
93
+ }
94
+
95
+ function maybeDelegateToLocalCli() {
96
+ if (isLocalDelegationDisabled(process.env)) {
97
+ return;
98
+ }
99
+
100
+ const currentEntryPath = fileURLToPath(import.meta.url);
101
+ const localEntryPath = findNearestLocalCliEntry(process.cwd(), resolveLocalCliCandidate);
102
+
103
+ if (!shouldDelegateToLocalCli(currentEntryPath, localEntryPath)) {
104
+ return;
105
+ }
106
+
107
+ const child = spawnSync(
108
+ process.execPath,
109
+ [localEntryPath, ...process.argv.slice(2)],
110
+ {
111
+ stdio: 'inherit',
112
+ cwd: process.cwd(),
113
+ env: { ...process.env, SLICE_NO_LOCAL_DELEGATION: '1' }
114
+ }
115
+ );
116
+
117
+ process.exit(child.status ?? 1);
118
+ }
119
+
120
+ maybeDelegateToLocalCli();
121
+
122
+ const sliceClient = program;
123
+
124
+ try {
125
+ const pkgPath = path.join(__dirname, "./package.json");
126
+ const pkgRaw = fs.readFileSync(pkgPath, "utf-8");
127
+ const pkg = JSON.parse(pkgRaw);
128
+ sliceClient.version(pkg.version).description("CLI for managing Slice.js framework components");
129
+ } catch {
130
+ sliceClient.version("0.0.0").description("CLI for managing Slice.js framework components");
131
+ }
132
+
133
+ // INIT COMMAND
134
+ sliceClient
135
+ .command("init")
136
+ .description("Initialize a new Slice.js project")
137
+ .argument("[name]", "Project name (defaults to my-slice-app)")
138
+ .option("-y, --yes", "Skip prompts")
139
+ .option("--pm <packageManager>", "Package manager to use (pnpm or npm). Auto-detected when omitted")
140
+ .action(async (name, options) => {
141
+ let projectName = name ? name.trim().toLowerCase().replace(/\s+/g, '-').replace(/[^a-z0-9-]/g, '').replace(/-+/g, '-').replace(/^-|-$/g, '') : 'my-slice-app';
142
+ if (!options.yes) {
143
+ const answers = await inquirer.prompt([
144
+ {
145
+ type: 'input',
146
+ name: 'projectName',
147
+ message: 'What is the name of your project?',
148
+ default: projectName,
149
+ filter: (input) => input.trim()
150
+ .toLowerCase()
151
+ .replace(/\s+/g, '-')
152
+ .replace(/[^a-z0-9-]/g, '')
153
+ .replace(/-+/g, '-')
154
+ .replace(/^-|-$/g, ''),
155
+ validate: (input) => {
156
+ if (!input || !input.trim()) return 'Project name cannot be empty';
157
+ if (input.includes('/') || input.includes('\\')) return 'Use a simple name, not a path';
158
+ return true;
159
+ }
160
+ }
161
+ ]);
162
+ projectName = answers.projectName;
163
+ }
164
+
165
+ // Resolve the package manager: --pm flag → detection → interactive prompt.
166
+ // Detection here has no project root yet (the folder is new), so it relies on
167
+ // npm_config_user_agent (npx / pnpm dlx / PM scripts) or a single available binary.
168
+ let packageManager = options.pm;
169
+ if (packageManager && !SUPPORTED_PACKAGE_MANAGERS.includes(packageManager)) {
170
+ Print.error(`Unsupported package manager "${packageManager}". Use one of: ${SUPPORTED_PACKAGE_MANAGERS.join(', ')}`);
171
+ return;
172
+ }
173
+ if (packageManager && !isPackageManagerAvailable(packageManager)) {
174
+ Print.error(`Package manager "${packageManager}" is not available on this system`);
175
+ return;
176
+ }
177
+ if (!packageManager) {
178
+ const detected = detectPackageManager(null);
179
+ if (detected) {
180
+ packageManager = detected.name;
181
+ } else if (!options.yes) {
182
+ const available = getAvailablePackageManagers();
183
+ if (available.length === 0) {
184
+ Print.error('No package manager found (pnpm or npm). Install one and retry.');
185
+ return;
186
+ }
187
+ const { pm } = await inquirer.prompt([
188
+ {
189
+ type: 'list',
190
+ name: 'pm',
191
+ message: 'Which package manager do you want to use?',
192
+ choices: available,
193
+ default: available.includes('pnpm') ? 'pnpm' : available[0]
194
+ }
195
+ ]);
196
+ packageManager = pm;
197
+ } else {
198
+ const available = getAvailablePackageManagers();
199
+ packageManager = available.includes('pnpm') ? 'pnpm' : available[0];
200
+ if (!packageManager) {
201
+ Print.error('No package manager found (pnpm or npm). Install one and retry.');
202
+ return;
203
+ }
204
+ }
205
+ }
206
+
207
+ const projectDir = path.resolve(projectName);
208
+
209
+ if (fs.existsSync(projectDir)) {
210
+ const contents = fs.readdirSync(projectDir);
211
+ if (contents.length > 0) {
212
+ if (options.yes) {
213
+ Print.error(`Directory "${projectName}" already exists and is not empty. Aborting.`);
214
+ return;
215
+ }
216
+ const { overwrite } = await inquirer.prompt([
217
+ {
218
+ type: 'confirm',
219
+ name: 'overwrite',
220
+ message: `Directory "${projectName}" already exists and is not empty. Continue?`,
221
+ default: false
222
+ }
223
+ ]);
224
+ if (!overwrite) {
225
+ Print.info('Initialization cancelled.');
226
+ return;
227
+ }
228
+ }
229
+ } else {
230
+ fs.mkdirSync(projectDir, { recursive: true });
231
+ }
232
+
233
+ process.chdir(projectDir);
234
+ process.env.INIT_CWD = projectDir;
235
+
236
+ await runWithVersionCheck(async () => {
237
+ await initializeProject({ packageManager });
238
+ });
239
+ });
240
+
241
+ // VERSION COMMAND
242
+ sliceClient
243
+ .command("version")
244
+ .alias("v")
245
+ .description("Show version information and check for updates")
246
+ .action(async () => {
247
+ await versionChecker.showVersionInfo();
248
+ });
249
+
250
+ // BUILD COMMAND
251
+ const buildCommand = sliceClient.command("build")
252
+ .description("Build Slice.js project for production")
253
+ .action(async (options) => {
254
+ await withNodeEnv('production', () => runWithVersionCheck(async () => {
255
+ await build(options);
256
+ }));
257
+ });
258
+
259
+ buildCommand
260
+ .command("clean")
261
+ .description("Remove all generated bundles")
262
+ .action(async () => {
263
+ await cleanBundles();
264
+ });
265
+
266
+ buildCommand
267
+ .command("info")
268
+ .description("Show information about generated bundles")
269
+ .action(async () => {
270
+ await bundleInfo();
271
+ });
272
+
273
+ buildCommand
274
+ .option("-a, --analyze", "Analyze project dependencies without bundling")
275
+ .option("-v, --verbose", "Show detailed output")
276
+ .option("--no-minify", "Disable minification (enabled by default)")
277
+ .option("--no-obfuscate", "Disable obfuscation (enabled by default, no prop mangling)")
278
+ .option("--preview", "Start preview server after build")
279
+ .option("--serve", "Start preview server without building")
280
+ .option("--skip-clean", "Skip cleaning dist before build");
281
+
282
+ // DEV COMMAND (DEVELOPMENT)
283
+ sliceClient
284
+ .command("dev")
285
+ .description("Start development server with hot reload enabled by default")
286
+ .option("-p, --port <port>", "Port for development server")
287
+ .option("--no-hmr", "Disable hot module reload (enabled by default)")
288
+ .action(async (options) => {
289
+ await withNodeEnv('development', () => runWithVersionCheck(async () => {
290
+ await startServer({
291
+ mode: 'development',
292
+ port: parsePort(options.port),
293
+ watch: options.hmr
294
+ });
295
+ }));
296
+ });
297
+
298
+ // START COMMAND - PRODUCTION MODE
299
+ sliceClient
300
+ .command("start")
301
+ .description("Serve production files from dist/ (requires prior slice build)")
302
+ .option("-p, --port <port>", "Port for server")
303
+ .action(async (options) => {
304
+ await withNodeEnv('production', () => runWithVersionCheck(async () => {
305
+ await startServer({
306
+ mode: 'production',
307
+ port: parsePort(options.port)
308
+ });
309
+ }));
310
+ });
311
+
312
+ // COMPONENT COMMAND GROUP - For local component management
313
+ const componentCommand = sliceClient.command("component").alias("comp").description("Manage local project components");
314
+
315
+ // CREATE LOCAL COMPONENT
316
+ componentCommand
317
+ .command("create [name]")
318
+ .alias("new")
319
+ .description("Create a new component in your local project")
320
+ .option("-c, --category <category>", "Component category (e.g. Visual, Service, AppComponents). Skips the prompt when provided.")
321
+ .action(async (name, options) => {
322
+ await runWithVersionCheck(async () => {
323
+ const categories = getCategories();
324
+ if (categories.length === 0) {
325
+ Print.error("No categories found in your project configuration");
326
+ Print.info("Run 'slice init' to initialize your project first");
327
+ Print.commandExample("Initialize project", "slice init");
328
+ return;
329
+ }
330
+
331
+ let componentName = name;
332
+ let category = options.category;
333
+
334
+ // Prompt only for the values not supplied on the command line. Passing both
335
+ // a name and --category runs fully non-interactively (handy for scripts/agents).
336
+ const prompts = [];
337
+ if (!componentName) {
338
+ prompts.push({
339
+ type: "input",
340
+ name: "componentName",
341
+ message: "Enter the component name:",
342
+ validate: (input) => {
343
+ if (!input) return "Component name cannot be empty";
344
+ if (!/^[a-zA-Z][a-zA-Z0-9]*$/.test(input)) {
345
+ return "Component name must start with a letter and contain only alphanumeric characters";
346
+ }
347
+ return true;
348
+ },
349
+ });
350
+ }
351
+ if (!category) {
352
+ prompts.push({
353
+ type: "list",
354
+ name: "category",
355
+ message: "Select the component category:",
356
+ choices: categories,
357
+ });
358
+ }
359
+
360
+ if (prompts.length > 0) {
361
+ const answers = await inquirer.prompt(prompts);
362
+ componentName = componentName ?? answers.componentName;
363
+ category = category ?? answers.category;
364
+ }
365
+
366
+ // createComponent validates the name and the category (and reports a clear
367
+ // error listing valid categories if --category is wrong).
368
+ const result = createComponent(componentName, category);
369
+ if (result) {
370
+ Print.success(`Component '${componentName}' created successfully in category '${category}'`);
371
+ Print.info("Listing updated components:");
372
+ listComponents();
373
+ }
374
+ });
375
+ });
376
+
377
+ // LIST LOCAL COMPONENTS
378
+ componentCommand
379
+ .command("list")
380
+ .alias("ls")
381
+ .description("List all components in your local project")
382
+ .action(async () => {
383
+ await runWithVersionCheck(() => {
384
+ listComponents();
385
+ return Promise.resolve();
386
+ });
387
+ });
388
+
389
+ // DELETE LOCAL COMPONENT
390
+ componentCommand
391
+ .command("delete [name]")
392
+ .alias("remove")
393
+ .description("Delete a component from your local project")
394
+ .option("-c, --category <category>", "Component category. Skips the category prompt when provided.")
395
+ .option("-y, --yes", "Skip the confirmation prompt (for non-interactive use)")
396
+ .action(async (name, options) => {
397
+ await runWithVersionCheck(async () => {
398
+ const categories = getCategories();
399
+ if (categories.length === 0) {
400
+ Print.error("No categories available. Check your configuration");
401
+ Print.info("Run 'slice init' to initialize your project");
402
+ return;
403
+ }
404
+
405
+ try {
406
+ let category = options.category;
407
+ let componentName = name;
408
+
409
+ // Resolve category (prompt only if not provided)
410
+ if (!category) {
411
+ const categoryAnswer = await inquirer.prompt([
412
+ {
413
+ type: "list",
414
+ name: "category",
415
+ message: "Select the component category:",
416
+ choices: categories,
417
+ }
418
+ ]);
419
+ category = categoryAnswer.category;
420
+ }
421
+
422
+ const config = sharedLoadConfigSync(import.meta.url);
423
+ if (!config) {
424
+ Print.error("Could not load configuration");
425
+ return;
426
+ }
427
+
428
+ if (!config.paths.components[category]) {
429
+ Print.error(`Invalid category: '${category}'`);
430
+ Print.info(`Available categories: ${categories.join(", ")}`);
431
+ return;
432
+ }
433
+
434
+ const categoryPath = config.paths.components[category].path;
435
+ const fullPath = getSrcPath(import.meta.url, categoryPath);
436
+
437
+ if (!fs.existsSync(fullPath)) {
438
+ Print.error(`Category path does not exist: ${categoryPath}`);
439
+ return;
440
+ }
441
+
442
+ // Resolve component name (prompt with a list only if not provided)
443
+ if (!componentName) {
444
+ const components = fs.readdirSync(fullPath).filter(item => {
445
+ const itemPath = path.join(fullPath, item);
446
+ return fs.statSync(itemPath).isDirectory();
447
+ });
448
+
449
+ if (components.length === 0) {
450
+ Print.info(`No components found in category '${category}'`);
451
+ return;
452
+ }
453
+
454
+ const componentAnswer = await inquirer.prompt([
455
+ {
456
+ type: "list",
457
+ name: "componentName",
458
+ message: "Select the component to delete:",
459
+ choices: components,
460
+ }
461
+ ]);
462
+ componentName = componentAnswer.componentName;
463
+ }
464
+
465
+ // Confirm unless --yes was passed (passing name + --category + --yes is fully non-interactive)
466
+ if (!options.yes) {
467
+ const { confirm } = await inquirer.prompt([
468
+ {
469
+ type: "confirm",
470
+ name: "confirm",
471
+ message: `Are you sure you want to delete '${componentName}' from '${category}'?`,
472
+ default: false,
473
+ }
474
+ ]);
475
+ if (!confirm) {
476
+ Print.info("Delete operation cancelled");
477
+ return;
478
+ }
479
+ }
480
+
481
+ // deleteComponent validates the name/category and that the component exists.
482
+ if (deleteComponent(componentName, category)) {
483
+ Print.success(`Component ${componentName} deleted successfully`);
484
+ Print.info("Listing updated components:");
485
+ listComponents();
486
+ }
487
+ } catch (error) {
488
+ Print.error(`Deleting component: ${error.message}`);
489
+ }
490
+ });
491
+ });
492
+
493
+ // REGISTRY COMMAND GROUP - For component registry operations
494
+ const registryCommand = sliceClient.command("registry").alias("reg").description("Manage components from official Slice.js repository");
495
+
496
+ // TYPES COMMAND GROUP - TypeScript declarations from static props
497
+ const typesCommand = sliceClient.command("types").description("Generate TypeScript declarations from component static props");
498
+
499
+ typesCommand
500
+ .command("generate")
501
+ .description("Generate src/slice-build.generated.d.ts for slice.build autocomplete")
502
+ .option("-o, --output <path>", "Custom output path", "src/slice-build.generated.d.ts")
503
+ .action(async (options) => {
504
+ await runWithVersionCheck(async () => {
505
+ const projectRoot = getProjectRoot(import.meta.url);
506
+ const outputPath = path.isAbsolute(options.output)
507
+ ? options.output
508
+ : path.join(projectRoot, options.output);
509
+
510
+ await runGenerateTypes({
511
+ projectRoot,
512
+ outputPath
513
+ });
514
+ });
515
+ });
516
+
517
+ // GET COMPONENTS FROM REGISTRY
518
+ registryCommand
519
+ .command("get [components...]")
520
+ .description("Download and install components from official repository")
521
+ .option("-f, --force", "Force overwrite existing components")
522
+ .option("-s, --service", "Install Service components instead of Visual")
523
+ .action(async (components, options) => {
524
+ await runWithVersionCheck(async () => {
525
+ await getComponent(components, {
526
+ force: options.force,
527
+ service: options.service
528
+ });
529
+ });
530
+ });
531
+
532
+ // LIST REGISTRY COMPONENTS
533
+ registryCommand
534
+ .command("list")
535
+ .alias("ls")
536
+ .description("List all available components in the official repository")
537
+ .action(async () => {
538
+ await runWithVersionCheck(async () => {
539
+ await listRemoteComponents();
540
+ });
541
+ });
542
+
543
+ // SYNC COMPONENTS FROM REGISTRY
544
+ registryCommand
545
+ .command("sync")
546
+ .description("Update all local components to latest versions from repository")
547
+ .option("-f, --force", "Force update without confirmation")
548
+ .action(async (options) => {
549
+ await runWithVersionCheck(async () => {
550
+ await syncComponents({
551
+ force: options.force
552
+ });
553
+ });
554
+ });
555
+
556
+ // SHORTCUTS - Top-level convenient commands
557
+ sliceClient
558
+ .command("get [components...]")
559
+ .description("Quick install components from registry")
560
+ .option("-f, --force", "Force overwrite existing components")
561
+ .option("-s, --service", "Install Service components instead of Visual")
562
+ .action(async (components, options) => {
563
+ await runWithVersionCheck(async () => {
564
+ if (!components || components.length === 0) {
565
+ Print.info("Use 'slice registry list' to see available components");
566
+ Print.commandExample("Get multiple components", "slice get Button Card Input");
567
+ Print.commandExample("Get service component", "slice get FetchManager --service");
568
+ Print.commandExample("Browse components", "slice browse");
569
+ return;
570
+ }
571
+
572
+ await getComponent(components, {
573
+ force: options.force,
574
+ service: options.service
575
+ });
576
+ });
577
+ });
578
+
579
+ sliceClient
580
+ .command("browse")
581
+ .description("Quick browse available components")
582
+ .action(async () => {
583
+ await runWithVersionCheck(async () => {
584
+ await listRemoteComponents();
585
+ });
586
+ });
587
+
588
+ sliceClient
589
+ .command("sync")
590
+ .description("Quick sync local components to latest versions")
591
+ .option("-f, --force", "Force update without confirmation")
592
+ .action(async (options) => {
593
+ await runWithVersionCheck(async () => {
594
+ await syncComponents({
595
+ force: options.force
596
+ });
597
+ });
598
+ });
599
+
600
+ // LIST COMMAND - Quick shortcut for listing local components
601
+ sliceClient
602
+ .command("list")
603
+ .description("Quick list all local components (alias for component list)")
604
+ .action(async () => {
605
+ await runWithVersionCheck(() => {
606
+ listComponents();
607
+ return Promise.resolve();
608
+ });
609
+ });
610
+
611
+ // DOCTOR COMMAND - Diagnose project issues
612
+ sliceClient
613
+ .command("doctor")
614
+ .alias("diagnose")
615
+ .description("Run diagnostics to check project health")
616
+ .action(async () => {
617
+ await runWithVersionCheck(async () => {
618
+ await runDiagnostics();
619
+ });
620
+ });
621
+
622
+ // POSTINSTALL COMMAND - Configure npm scripts in existing project
623
+ sliceClient
624
+ .command("postinstall")
625
+ .description("Configure npm scripts in package.json (useful when adding slicejs-cli to an existing project)")
626
+ .action(() => {
627
+ const pnpmHome = process.env.PNPM_HOME;
628
+ const cliEntryPath = fileURLToPath(import.meta.url);
629
+ const isGlobal = process.env.npm_config_global === 'true'
630
+ || (pnpmHome && cliEntryPath.startsWith(pnpmHome));
631
+ if (isGlobal) {
632
+ console.log('⚠️ Global installation of slicejs-cli detected.');
633
+ console.log(' We strongly recommend using a local installation to avoid version mismatches.');
634
+ console.log(` Uninstall global: ${pnpmHome ? 'pnpm remove -g slicejs-cli' : 'npm uninstall -g slicejs-cli'}`);
635
+ return;
636
+ }
637
+
638
+ const projectRoot = getProjectRoot(import.meta.url);
639
+ const pkgPath = path.join(projectRoot, 'package.json');
640
+ const packageManager = resolvePackageManager(projectRoot).name;
641
+
642
+ const sliceScripts = SLICE_SCRIPTS;
643
+
644
+ try {
645
+ let pkg = {};
646
+ if (fs.existsSync(pkgPath)) {
647
+ pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8'));
648
+ } else {
649
+ pkg = {
650
+ name: path.basename(projectRoot),
651
+ version: '1.0.0',
652
+ description: 'Slice.js project',
653
+ scripts: {}
654
+ };
655
+ }
656
+
657
+ pkg.scripts = pkg.scripts || {};
658
+ let addedCount = 0;
659
+ for (const [script, command] of Object.entries(sliceScripts)) {
660
+ if (!pkg.scripts[script]) {
661
+ pkg.scripts[script] = command;
662
+ addedCount++;
663
+ }
664
+ }
665
+
666
+ fs.writeFileSync(pkgPath, JSON.stringify(pkg, null, 2), 'utf-8');
667
+ console.log(`✅ slicejs-cli installed successfully. Added ${addedCount} package scripts to package.json.`);
668
+ console.log(` Run: ${runScriptCommand(packageManager, 'slice:dev')}`);
669
+ } catch (err) {
670
+ console.log('✅ slicejs-cli installed successfully.');
671
+ console.log(' Could not auto-configure scripts:', err.message);
672
+ console.log(` Configure scripts manually and run: ${runScriptCommand(packageManager, 'slice:dev')}`);
673
+ }
674
+ });
675
+
676
+ // Enhanced help
677
+ sliceClient
678
+ .option("--no-version-check", "Skip version check for this command")
679
+ .configureHelp({
680
+ sortSubcommands: true,
681
+ subcommandTerm: (cmd) => cmd.name() + ' ' + cmd.usage()
682
+ });
683
+
684
+
685
+ // Custom help - SIMPLIFIED for development only
686
+ sliceClient.addHelpText('after', `
687
+ Common Usage Examples:
688
+ slice init - Initialize new Slice.js project
689
+ slice dev - Start development server
690
+ slice build - Build production output (bundles + dist)
691
+ slice start - Start production server
692
+ slice get Button Card Input - Install Visual components from registry
693
+ slice get FetchManager -s - Install Service component from registry
694
+ slice browse - Browse all available components
695
+ slice sync - Update local components to latest versions
696
+ slice component create - Create new local component
697
+ slice list - List all local components
698
+ slice doctor - Run project diagnostics
699
+ slice types generate - Generate TypeScript typings for slice.build
700
+ slice postinstall - Configure npm scripts in package.json
701
+
702
+ Command Categories:
703
+ • init, dev, start - Project lifecycle (development only)
704
+ • get, browse, sync, list - Quick shortcuts
705
+ • component <cmd> - Local component management
706
+ • registry <cmd> - Official repository operations
707
+ • types generate - Type declarations from static props
708
+ • version, doctor, setup - Maintenance commands
709
+
710
+ Development Workflow:
711
+ • slice init - Initialize project
712
+ • slice dev - Start development server (serves from /src)
713
+ • slice build - Build production output to /dist (includes bundles)
714
+ • slice start - Serve production build from /dist
715
+
716
+ More info: https://slice-js-docs.vercel.app/
717
+ `);
718
+
719
+ // Default action with better messaging
720
+ if (!process.argv.slice(2).length) {
721
+ Print.newLine();
722
+ Print.info("Start with: slice init");
723
+ Print.commandExample("Development", "slice dev");
724
+ Print.commandExample("View available components", "slice browse");
725
+ Print.info("Use 'slice --help' for full help");
726
+ }
727
+
728
+ // Error handling for unknown commands
729
+ program.on('command:*', () => {
730
+ Print.error('Invalid command. See available commands above');
731
+ Print.info("Use 'slice --help' for help");
732
+ process.exit(1);
733
+ });
734
+
735
+ // HELP Command
736
+ const helpCommand = sliceClient.command("help").description("Display help information for Slice.js CLI").action(() => {
737
+ sliceClient.outputHelp();
738
+ });
739
+
740
+ program.parse();