slicejs-cli 4.3.0 → 4.4.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 (49) hide show
  1. package/LICENSE +21 -21
  2. package/README.md +260 -257
  3. package/client.js +927 -823
  4. package/commands/Print.js +163 -163
  5. package/commands/Validations.js +92 -92
  6. package/commands/build/build.js +97 -107
  7. package/commands/buildProduction/buildProduction.js +613 -613
  8. package/commands/bundle/bundle.js +251 -239
  9. package/commands/createComponent/VisualComponentTemplate.js +55 -55
  10. package/commands/createComponent/createComponent.js +128 -128
  11. package/commands/deleteComponent/deleteComponent.js +81 -81
  12. package/commands/docs/docs.js +365 -365
  13. package/commands/doctor/doctor.js +677 -563
  14. package/commands/getComponent/getComponent.js +842 -842
  15. package/commands/init/init.js +526 -475
  16. package/commands/lint/lint.js +75 -0
  17. package/commands/lint/types.js +85 -0
  18. package/commands/listComponents/listComponents.js +172 -172
  19. package/commands/seo/check.js +91 -0
  20. package/commands/seo/images.js +586 -0
  21. package/commands/seo/sitemap.js +106 -0
  22. package/commands/seo/support.js +130 -0
  23. package/commands/setup/lint.js +151 -0
  24. package/commands/skill/skill.js +236 -236
  25. package/commands/startServer/startServer.js +240 -240
  26. package/commands/startServer/watchServer.js +66 -66
  27. package/commands/typecheck/typecheck.js +83 -0
  28. package/commands/types/types.js +1378 -1097
  29. package/commands/utils/JsMinifier.js +230 -230
  30. package/commands/utils/LocalCliDelegation.js +78 -53
  31. package/commands/utils/PackageManager.js +148 -148
  32. package/commands/utils/PathHelper.js +87 -75
  33. package/commands/utils/ProjectValidation.js +274 -0
  34. package/commands/utils/SourceDiagnostics.js +201 -201
  35. package/commands/utils/VersionChecker.js +169 -169
  36. package/commands/utils/analyzeSource.js +77 -77
  37. package/commands/utils/bundling/BundleGenerator.js +3748 -3776
  38. package/commands/utils/bundling/DependencyAnalyzer.js +976 -976
  39. package/commands/utils/bundling/ExternalModuleBundler.js +298 -298
  40. package/commands/utils/componentAudit.js +74 -0
  41. package/commands/utils/compressAssets.js +103 -103
  42. package/commands/utils/cssScope.js +83 -0
  43. package/commands/utils/loadConfig.js +31 -31
  44. package/commands/utils/semver.js +66 -0
  45. package/commands/utils/sliceConfigSchema.js +72 -0
  46. package/commands/utils/sliceScripts.js +48 -48
  47. package/commands/utils/updateManager.js +471 -471
  48. package/eslint-config.js +128 -0
  49. package/package.json +19 -13
@@ -1,563 +1,677 @@
1
- import fs from 'fs-extra';
2
- import path from 'path';
3
- import { createServer } from 'net';
4
- import chalk from 'chalk';
5
- import Table from 'cli-table3';
6
- import Print from '../Print.js';
7
- import { getProjectRoot, getSrcPath, getApiPath, getConfigPath, getPath, getComponentsJsPath } from '../utils/PathHelper.js';
8
- import { resolvePackageManager, installCommand } from '../utils/PackageManager.js';
9
- import updateManager from '../utils/updateManager.js';
10
- import { parseComponentsRegistry, validateComponentProps } from '../types/types.js';
11
- import { parse as parseModule } from '@babel/parser';
12
- import traverse from '@babel/traverse';
13
- import ExternalModuleBundler from '../utils/bundling/ExternalModuleBundler.js';
14
-
15
- /**
16
- * Checks the Node.js version
17
- */
18
- async function checkNodeVersion() {
19
- const currentVersion = process.version;
20
- const majorVersion = parseInt(currentVersion.slice(1).split('.')[0]);
21
- const required = 20;
22
-
23
- if (majorVersion >= required) {
24
- return {
25
- pass: true,
26
- message: `Node.js version: ${currentVersion} (required: >= v${required})`
27
- };
28
- } else {
29
- return {
30
- pass: false,
31
- message: `Node.js version: ${currentVersion} (required: >= v${required})`,
32
- suggestion: `Update Node.js to v${required} or higher`
33
- };
34
- }
35
- }
36
-
37
- /**
38
- * Checks the directory structure
39
- */
40
- async function checkDirectoryStructure() {
41
- const srcPath = getSrcPath(import.meta.url);
42
- const apiPath = getApiPath(import.meta.url);
43
-
44
- const srcExists = await fs.pathExists(srcPath);
45
- const apiExists = await fs.pathExists(apiPath);
46
-
47
- if (srcExists && apiExists) {
48
- return {
49
- pass: true,
50
- message: 'Project structure (src/ and api/) exists'
51
- };
52
- } else {
53
- const missing = [];
54
- if (!srcExists) missing.push('src/');
55
- if (!apiExists) missing.push('api/');
56
-
57
- return {
58
- pass: false,
59
- message: `Missing directories: ${missing.join(', ')}`,
60
- suggestion: 'Run "slice init" to initialize your project'
61
- };
62
- }
63
- }
64
-
65
- /**
66
- * Checks sliceConfig.json
67
- */
68
- async function checkConfig() {
69
- const configPath = getConfigPath(import.meta.url);
70
-
71
- if (!await fs.pathExists(configPath)) {
72
- return {
73
- pass: false,
74
- message: 'sliceConfig.json not found',
75
- suggestion: 'Run "slice init" to create configuration'
76
- };
77
- }
78
-
79
- try {
80
- const config = await fs.readJson(configPath);
81
-
82
- if (!config.paths || !config.paths.components) {
83
- return {
84
- pass: false,
85
- message: 'sliceConfig.json is invalid (missing paths.components)',
86
- suggestion: 'Check your configuration file'
87
- };
88
- }
89
-
90
- return {
91
- pass: true,
92
- message: 'sliceConfig.json is valid'
93
- };
94
- } catch (error) {
95
- return {
96
- pass: false,
97
- message: `sliceConfig.json is invalid JSON: ${error.message}`,
98
- suggestion: 'Fix JSON syntax errors in sliceConfig.json'
99
- };
100
- }
101
- }
102
-
103
- /**
104
- * Checks port availability
105
- */
106
- async function checkPort() {
107
- const configPath = getConfigPath(import.meta.url);
108
- let port = 3000;
109
-
110
- try {
111
- if (await fs.pathExists(configPath)) {
112
- const config = await fs.readJson(configPath);
113
- port = config.server?.port || 3000;
114
- }
115
- } catch { /* config missing or unreadable — use default port */ }
116
-
117
- return new Promise((resolve) => {
118
- const server = createServer();
119
-
120
- server.once('error', (err) => {
121
- if (err.code === 'EADDRINUSE') {
122
- resolve({
123
- warn: true,
124
- message: `Port ${port} is already in use`,
125
- suggestion: `Stop the process using port ${port} or use: slice dev -p <other-port>`
126
- });
127
- } else {
128
- resolve({
129
- pass: true,
130
- message: `Port ${port} is available`
131
- });
132
- }
133
- });
134
-
135
- server.once('listening', () => {
136
- server.close();
137
- resolve({
138
- pass: true,
139
- message: `Port ${port} is available`
140
- });
141
- });
142
-
143
- server.listen(port);
144
- });
145
- }
146
-
147
- /**
148
- * Checks the package manager setup: mixed lockfiles, packageManager field
149
- * consistency, and a project-local CLI install (required for local delegation).
150
- * Exported for tests.
151
- */
152
- export async function checkPackageManagerSetup(projectRoot = getProjectRoot(import.meta.url)) {
153
- const issues = [];
154
- const suggestions = [];
155
-
156
- const LOCKFILE_PM = {
157
- 'package-lock.json': 'npm',
158
- 'pnpm-lock.yaml': 'pnpm'
159
- };
160
- const lockfiles = [];
161
- for (const lockfile of Object.keys(LOCKFILE_PM)) {
162
- if (await fs.pathExists(path.join(projectRoot, lockfile))) {
163
- lockfiles.push(lockfile);
164
- }
165
- }
166
-
167
- let pkg = null;
168
- const pkgPath = path.join(projectRoot, 'package.json');
169
- if (await fs.pathExists(pkgPath)) {
170
- try { pkg = await fs.readJson(pkgPath); } catch { /* reported by Dependencies check */ }
171
- }
172
- const pmField = typeof pkg?.packageManager === 'string' ? pkg.packageManager.split('@')[0] : null;
173
- const pm = resolvePackageManager(projectRoot).name;
174
-
175
- if (lockfiles.length > 1) {
176
- issues.push(`Mixed lockfiles found: ${lockfiles.join(', ')}`);
177
- const keep = pmField || pm;
178
- const keepLockfile = Object.entries(LOCKFILE_PM).find(([, name]) => name === keep)?.[0];
179
- suggestions.push(`Keep only ${keepLockfile ?? 'the lockfile of your package manager'} and delete the rest`);
180
- }
181
-
182
- if (pkg && !pmField) {
183
- issues.push('No "packageManager" field in package.json');
184
- suggestions.push(`Pin it (e.g. "packageManager": "${pm}@<version>") so every tool resolves the same package manager`);
185
- } else if (pmField && lockfiles.length === 1 && LOCKFILE_PM[lockfiles[0]] !== pmField) {
186
- issues.push(`packageManager is "${pmField}" but the lockfile is ${lockfiles[0]}`);
187
- suggestions.push(`Reinstall with ${pmField} (or update the packageManager field) so they agree`);
188
- }
189
-
190
- const localCliPath = path.join(projectRoot, 'node_modules', 'slicejs-cli', 'package.json');
191
- if (pkg && !(await fs.pathExists(localCliPath))) {
192
- issues.push('slicejs-cli is not installed locally');
193
- suggestions.push(`Run "${installCommand(pm, 'slicejs-cli', { dev: true })}" so the launcher delegates to a version pinned per project`);
194
- }
195
-
196
- if (issues.length === 0) {
197
- return {
198
- pass: true,
199
- message: `Package manager setup is consistent (${pmField || pm})`
200
- };
201
- }
202
- return {
203
- warn: true,
204
- message: issues.join(' | '),
205
- suggestion: suggestions.join(' | ')
206
- };
207
- }
208
-
209
- /**
210
- * Checks dependencies in package.json
211
- */
212
- async function checkDependencies() {
213
- const projectRoot = getProjectRoot(import.meta.url);
214
- const packagePath = getPath(import.meta.url, 'package.json');
215
-
216
- if (!await fs.pathExists(packagePath)) {
217
- return {
218
- warn: true,
219
- message: 'package.json not found',
220
- suggestion: 'Run "npm init" to create package.json'
221
- };
222
- }
223
-
224
- try {
225
- const pkg = await fs.readJson(packagePath);
226
- const hasFrameworkDep = pkg.dependencies?.['slicejs-web-framework'] || pkg.devDependencies?.['slicejs-web-framework'];
227
- const frameworkNodePath = getPath(import.meta.url, 'node_modules', 'slicejs-web-framework', 'package.json');
228
- const hasFrameworkNode = await fs.pathExists(frameworkNodePath);
229
- const hasFramework = !!(hasFrameworkDep || hasFrameworkNode);
230
-
231
- if (hasFramework) {
232
- return {
233
- pass: true,
234
- message: 'Required framework dependency is installed'
235
- };
236
- } else {
237
- const missing = ['slicejs-web-framework'];
238
-
239
- return {
240
- warn: true,
241
- message: `Missing dependencies: ${missing.join(', ')}`,
242
- suggestion: missing.includes('slicejs-web-framework')
243
- ? `Run "${installCommand(resolvePackageManager(getProjectRoot(import.meta.url)).name, 'slicejs-web-framework@latest')}" in your project`
244
- : `Run "${installCommand(resolvePackageManager(getProjectRoot(import.meta.url)).name, 'slicejs-cli@latest', { dev: true })}" in your project`,
245
- missing
246
- };
247
- }
248
- } catch (error) {
249
- return {
250
- pass: false,
251
- message: `package.json is invalid: ${error.message}`,
252
- suggestion: 'Fix JSON syntax errors in package.json'
253
- };
254
- }
255
- }
256
-
257
- /**
258
- * Checks component integrity
259
- */
260
- async function checkComponents() {
261
- const configPath = getConfigPath(import.meta.url);
262
- const projectRoot = getProjectRoot(import.meta.url);
263
-
264
- if (!await fs.pathExists(configPath)) {
265
- return {
266
- warn: true,
267
- message: 'Cannot check components (no config)',
268
- suggestion: 'Run "slice init" first'
269
- };
270
- }
271
-
272
- try {
273
- const config = await fs.readJson(configPath);
274
- const componentPaths = config.paths?.components || {};
275
-
276
- let totalComponents = 0;
277
- let componentIssues = 0;
278
-
279
- for (const [category, { path: compPath }] of Object.entries(componentPaths)) {
280
- const fullPath = getSrcPath(import.meta.url, compPath);
281
-
282
- if (await fs.pathExists(fullPath)) {
283
- const items = await fs.readdir(fullPath);
284
-
285
- for (const item of items) {
286
- const itemPath = path.join(fullPath, item);
287
- const stat = await fs.stat(itemPath);
288
-
289
- if (stat.isDirectory()) {
290
- totalComponents++;
291
-
292
- // Check JS files
293
- const jsFile = path.join(itemPath, `${item}.js`);
294
- if (!await fs.pathExists(jsFile)) {
295
- componentIssues++;
296
- }
297
- }
298
- }
299
- }
300
- }
301
-
302
- if (componentIssues === 0) {
303
- return {
304
- pass: true,
305
- message: `${totalComponents} components checked, all OK`
306
- };
307
- } else {
308
- return {
309
- warn: true,
310
- message: `${componentIssues} component(s) have missing files`,
311
- suggestion: 'Check your component directories'
312
- };
313
- }
314
- } catch (error) {
315
- return {
316
- warn: true,
317
- message: `Cannot check components: ${error.message}`,
318
- suggestion: 'Verify your project structure'
319
- };
320
- }
321
- }
322
-
323
- /**
324
- * Lints component static props for common issues.
325
- * Uses the same Babel parsing as slice types generate.
326
- */
327
- async function checkComponentProps() {
328
- const registryPath = getComponentsJsPath(import.meta.url);
329
- if (!await fs.pathExists(registryPath)) {
330
- return { pass: true, message: 'No components to check' };
331
- }
332
-
333
- try {
334
- // Same validation `slice build` runs, so doctor and build agree exactly.
335
- const { errors, warnings, checkedCount } = await validateComponentProps({
336
- projectRoot: getProjectRoot(import.meta.url)
337
- });
338
-
339
- const issues = [
340
- ...errors.map((e) => ({ ...e, severity: 'error' })),
341
- ...warnings.map((w) => ({ ...w, severity: 'warning' }))
342
- ];
343
-
344
- if (issues.length === 0) {
345
- return { pass: true, message: `${checkedCount} components checked, props look good` };
346
- }
347
-
348
- const componentCount = new Set(issues.map((i) => i.component)).size;
349
- const errorNote = errors.length > 0 ? ` (${errors.length} would block "slice build")` : '';
350
- return {
351
- warn: true,
352
- message: `${issues.length} prop issue(s) across ${componentCount} component(s)${errorNote}`,
353
- suggestion: issues
354
- .map((i) => ` [${i.severity}] ${i.component}.${i.prop}: ${i.message}`)
355
- .join('\n'),
356
- issues
357
- };
358
- } catch (error) {
359
- return { warn: true, message: `Cannot check props: ${error.message}` };
360
- }
361
- }
362
-
363
- /** Package root of a bare specifier: 'lodash/fp' -> 'lodash', '@s/p/x' -> '@s/p'. */
364
- function packageRootOf(spec) {
365
- const parts = spec.split('/');
366
- return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
367
- }
368
-
369
- /** Collects bare (node_modules) import specifiers from a module's source. */
370
- function extractBareImports(source) {
371
- const found = new Set();
372
- const add = (spec) => {
373
- if (typeof spec === 'string' && ExternalModuleBundler.isBareSpecifier(spec)) found.add(spec);
374
- };
375
- try {
376
- const ast = parseModule(source, { sourceType: 'module', plugins: ['jsx'] });
377
- traverse.default(ast, {
378
- ImportDeclaration(p) { add(p.node.source?.value); },
379
- ExportNamedDeclaration(p) { if (p.node.source) add(p.node.source.value); },
380
- ExportAllDeclaration(p) { add(p.node.source?.value); },
381
- CallExpression(p) {
382
- if (p.node.callee?.type === 'Import' && p.node.arguments?.[0]?.type === 'StringLiteral') {
383
- add(p.node.arguments[0].value);
384
- }
385
- }
386
- });
387
- } catch { /* unparseable → skip */ }
388
- return found;
389
- }
390
-
391
- /**
392
- * Verifies that every node_modules package imported by a component is actually
393
- * installed. Bare imports are resolved from node_modules at build/dev time, so a
394
- * missing package would fail there — this surfaces it early.
395
- */
396
- async function checkExternalDependencies() {
397
- const registryPath = getComponentsJsPath(import.meta.url);
398
- const configPath = getConfigPath(import.meta.url);
399
- const projectRoot = getProjectRoot(import.meta.url);
400
-
401
- if (!await fs.pathExists(registryPath)) {
402
- return { pass: true, message: 'No components to check' };
403
- }
404
-
405
- try {
406
- const content = await fs.readFile(registryPath, 'utf-8');
407
- const entries = Object.entries(parseComponentsRegistry(content, registryPath));
408
-
409
- const categoryPathCache = new Map();
410
- if (await fs.pathExists(configPath)) {
411
- try {
412
- const config = await fs.readJson(configPath);
413
- for (const [cat, catMeta] of Object.entries(config.paths?.components || {})) {
414
- categoryPathCache.set(cat, catMeta.path?.replace(/^[/\\]+/, '') || '');
415
- }
416
- } catch { /* config issues reported elsewhere */ }
417
- }
418
-
419
- const usedBy = new Map(); // packageRoot -> Set(component names)
420
- for (const [compName, meta] of entries) {
421
- const category = typeof meta === 'string' ? meta : (meta.category || '');
422
- const relPath = categoryPathCache.get(category);
423
- if (!relPath) continue;
424
- const jsPath = getSrcPath(import.meta.url, relPath, compName, `${compName}.js`);
425
- if (!await fs.pathExists(jsPath)) continue;
426
-
427
- const source = await fs.readFile(jsPath, 'utf-8');
428
- for (const spec of extractBareImports(source)) {
429
- const root = packageRootOf(spec);
430
- if (!usedBy.has(root)) usedBy.set(root, new Set());
431
- usedBy.get(root).add(compName);
432
- }
433
- }
434
-
435
- if (usedBy.size === 0) {
436
- return { pass: true, message: 'No external (node_modules) imports' };
437
- }
438
-
439
- const missing = [];
440
- for (const root of usedBy.keys()) {
441
- const pkgJson = path.join(projectRoot, 'node_modules', root, 'package.json');
442
- if (!await fs.pathExists(pkgJson)) missing.push(root);
443
- }
444
-
445
- if (missing.length === 0) {
446
- return { pass: true, message: `${usedBy.size} external package(s) imported, all installed` };
447
- }
448
-
449
- return {
450
- warn: true,
451
- message: `${missing.length} imported package(s) not in node_modules: ${missing.sort().join(', ')}`,
452
- details: missing.sort().map((m) => `Install "${m}" — used by: ${Array.from(usedBy.get(m)).sort().join(', ')}`)
453
- };
454
- } catch (error) {
455
- return { warn: true, message: `Cannot check external dependencies: ${error.message}` };
456
- }
457
- }
458
-
459
- /**
460
- * Main diagnostic command
461
- */
462
- export {
463
- checkNodeVersion,
464
- checkDirectoryStructure,
465
- checkConfig,
466
- checkPort,
467
- checkDependencies,
468
- checkComponents,
469
- checkComponentProps,
470
- checkExternalDependencies
471
- };
472
-
473
- export default async function runDiagnostics() {
474
- Print.newLine();
475
- Print.title('🔍 Running Slice.js Diagnostics...');
476
- Print.newLine();
477
-
478
- const checks = [
479
- { name: 'Node.js Version', fn: checkNodeVersion },
480
- { name: 'Project Structure', fn: checkDirectoryStructure },
481
- { name: 'Configuration', fn: checkConfig },
482
- { name: 'Port Availability', fn: checkPort },
483
- { name: 'Package Manager', fn: checkPackageManagerSetup },
484
- { name: 'Dependencies', fn: checkDependencies },
485
- { name: 'Components', fn: checkComponents },
486
- { name: 'Component Props', fn: checkComponentProps },
487
- { name: 'External Dependencies', fn: checkExternalDependencies }
488
- ];
489
-
490
- const results = [];
491
-
492
- for (const check of checks) {
493
- const result = await check.fn();
494
- results.push({ ...result, name: check.name });
495
- }
496
-
497
- // Crear tabla de resultados
498
- const table = new Table({
499
- head: [chalk.cyan.bold('Check'), chalk.cyan.bold('Status'), chalk.cyan.bold('Details')],
500
- colWidths: [25, 10, 55],
501
- style: {
502
- head: [],
503
- border: ['gray']
504
- },
505
- wordWrap: true
506
- });
507
-
508
- results.forEach(result => {
509
- let status;
510
- if (result.pass) {
511
- status = chalk.green('✅ PASS');
512
- } else if (result.warn) {
513
- status = chalk.yellow('⚠️ WARN');
514
- } else {
515
- status = chalk.red('❌ FAIL');
516
- }
517
-
518
- const details = result.suggestion
519
- ? `${result.message}\n${chalk.gray('→ ' + result.suggestion)}`
520
- : result.message;
521
-
522
- table.push([result.name, status, details]);
523
- });
524
-
525
- console.log(table.toString());
526
-
527
- // Resumen
528
- const issues = results.filter(r => !r.pass && !r.warn).length;
529
- const warnings = results.filter(r => r.warn).length;
530
- const passed = results.filter(r => r.pass).length;
531
-
532
- Print.newLine();
533
- Print.separator();
534
-
535
- const depsResult = results.find(r => r.name === 'Dependencies');
536
- if (depsResult && depsResult.warn && Array.isArray(depsResult.missing) && depsResult.missing.length > 0) {
537
- const projectRoot = getProjectRoot(import.meta.url);
538
- const pm = resolvePackageManager(projectRoot).name;
539
- for (const pkg of depsResult.missing) {
540
- Print.info(`Missing: ${pkg}. Install with: ${installCommand(pm, `${pkg}@latest`)}`);
541
- }
542
- }
543
-
544
- if (issues === 0 && warnings === 0) {
545
- Print.success('All checks passed! 🎉');
546
- Print.info('Your Slice.js project is correctly configured');
547
- } else {
548
- console.log(chalk.bold('📊 Summary:'));
549
- console.log(chalk.green(` ✅ Passed: ${passed}`));
550
- if (warnings > 0) console.log(chalk.yellow(` ⚠️ Warnings: ${warnings}`));
551
- if (issues > 0) console.log(chalk.red(` ❌ Issues: ${issues}`));
552
-
553
- Print.newLine();
554
-
555
- if (issues > 0) {
556
- Print.warning('Fix the issues above to ensure proper functionality');
557
- } else {
558
- Print.info('Warnings are non-critical but should be addressed');
559
- }
560
- }
561
-
562
- Print.separator();
563
- }
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import { createServer } from 'net';
4
+ import chalk from 'chalk';
5
+ import Table from 'cli-table3';
6
+ import Print from '../Print.js';
7
+ import { getProjectRoot, getSrcPath, getApiPath, getConfigPath, getPath, getComponentsJsPath } from '../utils/PathHelper.js';
8
+ import { resolvePackageManager, installCommand } from '../utils/PackageManager.js';
9
+ import updateManager from '../utils/updateManager.js';
10
+ import { parseComponentsRegistry } from '../types/types.js';
11
+ import { validateConfigRules, validateProject, validateServerEntry, classifyValidation, describeIssue } from '../utils/ProjectValidation.js';
12
+ import { loadConfigSchema, validateAgainstSchema } from '../utils/sliceConfigSchema.js';
13
+ import { rangeMismatch } from '../utils/semver.js';
14
+ import { parse as parseModule } from '@babel/parser';
15
+ import traverse from '@babel/traverse';
16
+ import ExternalModuleBundler from '../utils/bundling/ExternalModuleBundler.js';
17
+ import { loadFrameworkSeo, loadManifest } from '../seo/support.js';
18
+ import { loadRoutes } from '../seo/check.js';
19
+
20
+ /**
21
+ * SEO: is it configured, and is it safe to deploy?
22
+ *
23
+ * Warns rather than fails for an unconfigured project (SEO is opt-in), and
24
+ * fails only for input the user has to fix. The rules are the framework's
25
+ * validator, the same one `slice seo check` uses, so the two cannot disagree.
26
+ */
27
+ async function checkSeoConfiguration() {
28
+ const projectRoot = getProjectRoot(import.meta.url);
29
+
30
+ if (!fs.existsSync(path.join(projectRoot, 'api', 'index.js'))) {
31
+ return { pass: true, message: 'Not a server app (no api/index.js)' };
32
+ }
33
+
34
+ let loaded;
35
+ try {
36
+ loaded = loadManifest(projectRoot);
37
+ } catch (error) {
38
+ return {
39
+ message: `seo.json is not valid JSON: ${error.message}`,
40
+ suggestion: 'Fix the file: the server fails at startup on the same error'
41
+ };
42
+ }
43
+
44
+ const { manifest } = loaded;
45
+ if (!manifest) {
46
+ return {
47
+ warn: true,
48
+ message: 'Not configured: every route shares one <head> and unknown paths answer 200',
49
+ suggestion: 'Add seo.json and pass it to createSliceServer({ seo: { manifest: "seo.json" } })'
50
+ };
51
+ }
52
+
53
+ let framework;
54
+ try {
55
+ framework = await loadFrameworkSeo(projectRoot);
56
+ } catch (error) {
57
+ return { warn: true, message: `seo.json exists, but the installed framework has no SEO module: ${error.message}` };
58
+ }
59
+
60
+ const routes = await loadRoutes(projectRoot).catch(() => []);
61
+ const { errors, warnings } = framework.validateSeoManifest(manifest, {
62
+ routes,
63
+ publicDir: path.join(projectRoot, 'src', 'public')
64
+ });
65
+
66
+ // The sitemap is a committed artifact, so a stale one is a deploy problem.
67
+ if (manifest.sitemap !== false) {
68
+ const sitemapFile = path.join(projectRoot, 'src', 'public', 'sitemap.xml');
69
+ const origin = framework.normalizeOrigin(manifest.origin);
70
+ if (!fs.existsSync(sitemapFile)) {
71
+ warnings.push('sitemap.xml is missing: run `slice seo sitemap`');
72
+ } else if (origin && fs.readFileSync(sitemapFile, 'utf8') !== framework.buildSitemap({ manifest, origin })) {
73
+ warnings.push('sitemap.xml is out of date: run `slice seo sitemap`');
74
+ }
75
+ }
76
+
77
+ const routeCount = Object.keys(manifest.routes || {}).length;
78
+
79
+ if (errors.length) {
80
+ return {
81
+ message: `${errors.length} problem(s) in seo.json: ${errors[0]}`,
82
+ suggestion: errors.length > 1 ? `${errors[1]} (run \`slice seo check\` for the full list)` : 'Run `slice seo check`'
83
+ };
84
+ }
85
+
86
+ if (warnings.length) {
87
+ return {
88
+ warn: true,
89
+ message: `origin ${manifest.origin}, ${routeCount} routes — ${warnings.length} warning(s): ${warnings[0]}`,
90
+ suggestion: warnings.length > 1 ? `${warnings[1]} (run \`slice seo check\` for the full list)` : undefined
91
+ };
92
+ }
93
+
94
+ return {
95
+ pass: true,
96
+ message: `origin ${manifest.origin}, ${routeCount} routes, sitemap ${manifest.sitemap === false ? 'off' : 'ok'}`
97
+ };
98
+ }
99
+
100
+ /**
101
+ * Checks the Node.js version
102
+ */
103
+ async function checkNodeVersion() {
104
+ const currentVersion = process.version;
105
+ const majorVersion = parseInt(currentVersion.slice(1).split('.')[0]);
106
+ const required = 20;
107
+
108
+ if (majorVersion >= required) {
109
+ return {
110
+ pass: true,
111
+ message: `Node.js version: ${currentVersion} (required: >= v${required})`
112
+ };
113
+ } else {
114
+ return {
115
+ pass: false,
116
+ message: `Node.js version: ${currentVersion} (required: >= v${required})`,
117
+ suggestion: `Update Node.js to v${required} or higher`
118
+ };
119
+ }
120
+ }
121
+
122
+ /**
123
+ * Checks the directory structure
124
+ */
125
+ async function checkDirectoryStructure() {
126
+ const srcPath = getSrcPath(import.meta.url);
127
+ const apiPath = getApiPath(import.meta.url);
128
+
129
+ const srcExists = await fs.pathExists(srcPath);
130
+ const apiExists = await fs.pathExists(apiPath);
131
+
132
+ if (srcExists && apiExists) {
133
+ return {
134
+ pass: true,
135
+ message: 'Project structure (src/ and api/) exists'
136
+ };
137
+ } else {
138
+ const missing = [];
139
+ if (!srcExists) missing.push('src/');
140
+ if (!apiExists) missing.push('api/');
141
+
142
+ return {
143
+ pass: false,
144
+ message: `Missing directories: ${missing.join(', ')}`,
145
+ suggestion: 'Run "slice init" to initialize your project'
146
+ };
147
+ }
148
+ }
149
+
150
+ /**
151
+ * Checks sliceConfig.json
152
+ */
153
+ async function checkConfig() {
154
+ const configPath = getConfigPath(import.meta.url);
155
+
156
+ if (!await fs.pathExists(configPath)) {
157
+ return {
158
+ pass: false,
159
+ message: 'sliceConfig.json not found',
160
+ suggestion: 'Run "slice init" to create configuration'
161
+ };
162
+ }
163
+
164
+ try {
165
+ const config = await fs.readJson(configPath);
166
+
167
+ if (!config.paths || !config.paths.components) {
168
+ return {
169
+ pass: false,
170
+ message: 'sliceConfig.json is invalid (missing paths.components)',
171
+ suggestion: 'Check your configuration file'
172
+ };
173
+ }
174
+
175
+ // The framework publishes a JSON Schema for this file and nothing read
176
+ // it. Type errors are silent killers: `"port": "3001"` makes listen()
177
+ // open a pipe, `"enabled": "false"` is truthy.
178
+ const schema = await loadConfigSchema(getProjectRoot(import.meta.url));
179
+ if (schema) {
180
+ const schemaIssues = validateAgainstSchema(config, schema);
181
+ if (schemaIssues.length > 0) {
182
+ return {
183
+ pass: false,
184
+ message: `sliceConfig.json does not match the published schema: ${schemaIssues[0].path} ${schemaIssues[0].message}`,
185
+ suggestion: schemaIssues
186
+ .slice(0, 5)
187
+ .map((issue) => `${issue.path} ${issue.message}`)
188
+ .join('\n') + (schemaIssues.length > 5 ? `\n… ${schemaIssues.length - 5} more` : '')
189
+ };
190
+ }
191
+ }
192
+
193
+ // Same rules `slice build` applies before bundling. A config that passes
194
+ // here but blocks the build is worse than no check at all.
195
+ const ruleProblems = validateConfigRules(config);
196
+ if (ruleProblems.length > 0) {
197
+ return {
198
+ pass: false,
199
+ message: `sliceConfig.json would build a broken bundle: ${ruleProblems[0].path}`,
200
+ suggestion: ruleProblems.map((problem) => `${problem.path} ${problem.message}`).join('\n')
201
+ };
202
+ }
203
+
204
+ return {
205
+ pass: true,
206
+ message: 'sliceConfig.json is valid'
207
+ };
208
+ } catch (error) {
209
+ return {
210
+ pass: false,
211
+ message: `sliceConfig.json is invalid JSON: ${error.message}`,
212
+ suggestion: 'Fix JSON syntax errors in sliceConfig.json'
213
+ };
214
+ }
215
+ }
216
+
217
+ /**
218
+ * Checks port availability
219
+ */
220
+ async function checkPort() {
221
+ const configPath = getConfigPath(import.meta.url);
222
+ let port = 3000;
223
+
224
+ try {
225
+ if (await fs.pathExists(configPath)) {
226
+ const config = await fs.readJson(configPath);
227
+ port = config.server?.port || 3000;
228
+ }
229
+ } catch { /* config missing or unreadable — use default port */ }
230
+
231
+ return new Promise((resolve) => {
232
+ const server = createServer();
233
+
234
+ server.once('error', (err) => {
235
+ if (err.code === 'EADDRINUSE') {
236
+ resolve({
237
+ warn: true,
238
+ message: `Port ${port} is already in use`,
239
+ suggestion: `Stop the process using port ${port} or use: slice dev -p <other-port>`
240
+ });
241
+ } else {
242
+ resolve({
243
+ pass: true,
244
+ message: `Port ${port} is available`
245
+ });
246
+ }
247
+ });
248
+
249
+ server.once('listening', () => {
250
+ server.close();
251
+ resolve({
252
+ pass: true,
253
+ message: `Port ${port} is available`
254
+ });
255
+ });
256
+
257
+ server.listen(port);
258
+ });
259
+ }
260
+
261
+ /**
262
+ * Checks the package manager setup: mixed lockfiles, packageManager field
263
+ * consistency, and a project-local CLI install (required for local delegation).
264
+ * Exported for tests.
265
+ */
266
+ export async function checkPackageManagerSetup(projectRoot = getProjectRoot(import.meta.url)) {
267
+ const issues = [];
268
+ const suggestions = [];
269
+
270
+ const LOCKFILE_PM = {
271
+ 'package-lock.json': 'npm',
272
+ 'pnpm-lock.yaml': 'pnpm'
273
+ };
274
+ const lockfiles = [];
275
+ for (const lockfile of Object.keys(LOCKFILE_PM)) {
276
+ if (await fs.pathExists(path.join(projectRoot, lockfile))) {
277
+ lockfiles.push(lockfile);
278
+ }
279
+ }
280
+
281
+ let pkg = null;
282
+ const pkgPath = path.join(projectRoot, 'package.json');
283
+ if (await fs.pathExists(pkgPath)) {
284
+ try { pkg = await fs.readJson(pkgPath); } catch { /* reported by Dependencies check */ }
285
+ }
286
+ const pmField = typeof pkg?.packageManager === 'string' ? pkg.packageManager.split('@')[0] : null;
287
+ const pm = resolvePackageManager(projectRoot).name;
288
+
289
+ if (lockfiles.length > 1) {
290
+ issues.push(`Mixed lockfiles found: ${lockfiles.join(', ')}`);
291
+ const keep = pmField || pm;
292
+ const keepLockfile = Object.entries(LOCKFILE_PM).find(([, name]) => name === keep)?.[0];
293
+ suggestions.push(`Keep only ${keepLockfile ?? 'the lockfile of your package manager'} and delete the rest`);
294
+ }
295
+
296
+ if (pkg && !pmField) {
297
+ issues.push('No "packageManager" field in package.json');
298
+ suggestions.push(`Pin it (e.g. "packageManager": "${pm}@<version>") so every tool resolves the same package manager`);
299
+ } else if (pmField && lockfiles.length === 1 && LOCKFILE_PM[lockfiles[0]] !== pmField) {
300
+ issues.push(`packageManager is "${pmField}" but the lockfile is ${lockfiles[0]}`);
301
+ suggestions.push(`Reinstall with ${pmField} (or update the packageManager field) so they agree`);
302
+ }
303
+
304
+ const localCliPath = path.join(projectRoot, 'node_modules', 'slicejs-cli', 'package.json');
305
+ if (pkg && !(await fs.pathExists(localCliPath))) {
306
+ issues.push('slicejs-cli is not installed locally');
307
+ suggestions.push(`Run "${installCommand(pm, 'slicejs-cli', { dev: true })}" so the launcher delegates to a version pinned per project`);
308
+ }
309
+
310
+ if (issues.length === 0) {
311
+ return {
312
+ pass: true,
313
+ message: `Package manager setup is consistent (${pmField || pm})`
314
+ };
315
+ }
316
+ return {
317
+ warn: true,
318
+ message: issues.join(' | '),
319
+ suggestion: suggestions.join(' | ')
320
+ };
321
+ }
322
+
323
+ /**
324
+ * Checks dependencies in package.json
325
+ */
326
+ async function checkDependencies() {
327
+ const projectRoot = getProjectRoot(import.meta.url);
328
+ const packagePath = getPath(import.meta.url, 'package.json');
329
+
330
+ if (!await fs.pathExists(packagePath)) {
331
+ return {
332
+ warn: true,
333
+ message: 'package.json not found',
334
+ suggestion: 'Run "npm init" to create package.json'
335
+ };
336
+ }
337
+
338
+ try {
339
+ const pkg = await fs.readJson(packagePath);
340
+ const hasFrameworkDep = pkg.dependencies?.['slicejs-web-framework'] || pkg.devDependencies?.['slicejs-web-framework'];
341
+ const frameworkNodePath = getPath(import.meta.url, 'node_modules', 'slicejs-web-framework', 'package.json');
342
+ const hasFrameworkNode = await fs.pathExists(frameworkNodePath);
343
+ const hasFramework = !!(hasFrameworkDep || hasFrameworkNode);
344
+
345
+ if (hasFramework) {
346
+ // A declared range that does not accept the installed version is a
347
+ // reproducibility bug: the next clean install gets a different
348
+ // runtime. The CLI's own requirement matters more — a published CLI
349
+ // declaring ^3.5.0 while the app runs 4.x shipped a broken install.
350
+ const mismatches = [];
351
+ const installed = await fs.readJson(frameworkNodePath).catch(() => null);
352
+
353
+ if (installed?.version) {
354
+ const appRange = pkg.dependencies?.['slicejs-web-framework'] || pkg.devDependencies?.['slicejs-web-framework'];
355
+ const appMismatch = appRange ? rangeMismatch(appRange, installed.version) : null;
356
+ if (appMismatch) {
357
+ mismatches.push(`package.json declares ${appMismatch}, but ${installed.version} is installed`);
358
+ }
359
+
360
+ const cliPkgPath = getPath(import.meta.url, 'node_modules', 'slicejs-cli', 'package.json');
361
+ const cliPkg = await fs.pathExists(cliPkgPath) ? await fs.readJson(cliPkgPath).catch(() => null) : null;
362
+ const cliRange = cliPkg?.dependencies?.['slicejs-web-framework'];
363
+ const cliMismatch = cliRange ? rangeMismatch(cliRange, installed.version) : null;
364
+ if (cliMismatch) {
365
+ mismatches.push(`slicejs-cli@${cliPkg.version} requires slicejs-web-framework@${cliRange}, but ${installed.version} is installed`);
366
+ }
367
+ }
368
+
369
+ if (mismatches.length > 0) {
370
+ return {
371
+ warn: true,
372
+ message: `Version mismatch: ${mismatches[0]}`,
373
+ suggestion: mismatches.length > 1
374
+ ? mismatches.slice(1).join('\n')
375
+ : 'Align the declared range with the installed version, or reinstall from the lockfile.'
376
+ };
377
+ }
378
+
379
+ return {
380
+ pass: true,
381
+ message: 'Required framework dependency is installed'
382
+ };
383
+ } else {
384
+ const missing = ['slicejs-web-framework'];
385
+
386
+ return {
387
+ warn: true,
388
+ message: `Missing dependencies: ${missing.join(', ')}`,
389
+ suggestion: missing.includes('slicejs-web-framework')
390
+ ? `Run "${installCommand(resolvePackageManager(getProjectRoot(import.meta.url)).name, 'slicejs-web-framework@latest')}" in your project`
391
+ : `Run "${installCommand(resolvePackageManager(getProjectRoot(import.meta.url)).name, 'slicejs-cli@latest', { dev: true })}" in your project`,
392
+ missing
393
+ };
394
+ }
395
+ } catch (error) {
396
+ return {
397
+ pass: false,
398
+ message: `package.json is invalid: ${error.message}`,
399
+ suggestion: 'Fix JSON syntax errors in package.json'
400
+ };
401
+ }
402
+ }
403
+
404
+ /**
405
+ * Components and routes: one verdict for everything the build validates statically.
406
+ *
407
+ * The same pass `slice build` runs, classified by the same helper. It used to be
408
+ * two rows that disagreed with each other and with the build: "Components"
409
+ * scanned folders, "Component Props" read only prop definitions and dropped the
410
+ * source errors the build blocks on, and routes were never checked at all.
411
+ */
412
+ async function checkComponents() {
413
+ const registryPath = getComponentsJsPath(import.meta.url);
414
+
415
+ if (!await fs.pathExists(registryPath)) {
416
+ return { pass: true, message: 'No components registered (components.js not found)' };
417
+ }
418
+
419
+ try {
420
+ const validation = await validateProject({ projectRoot: getProjectRoot(import.meta.url) });
421
+ const { blocking, advisory } = classifyValidation(validation);
422
+ const summary = `${validation.registeredCount} components, ${validation.routeCount} routes`;
423
+
424
+ if (blocking.length > 0) {
425
+ const componentCount = new Set(blocking.map((issue) => issue.component)).size;
426
+ return {
427
+ message: `${blocking.length} issue(s) in ${componentCount} file(s) block "slice build"`,
428
+ suggestion: blocking
429
+ .slice(0, 5)
430
+ .map(describeIssue)
431
+ .join('\n') + (blocking.length > 5 ? `\n… ${blocking.length - 5} more (run "slice build" for the full list)` : ''),
432
+ issues: blocking
433
+ };
434
+ }
435
+
436
+ if (advisory.length > 0) {
437
+ return {
438
+ warn: true,
439
+ message: `${summary}, ${advisory.length} warning(s) — none block the build`,
440
+ suggestion: advisory
441
+ .slice(0, 3)
442
+ .map(describeIssue)
443
+ .join('\n') + (advisory.length > 3 ? `\n… ${advisory.length - 3} more` : ''),
444
+ issues: advisory
445
+ };
446
+ }
447
+
448
+ return {
449
+ pass: true,
450
+ message: `${summary}, ${validation.checkedCount} with static props: all valid`
451
+ };
452
+ } catch (error) {
453
+ return { warn: true, message: `Cannot check components: ${error.message}` };
454
+ }
455
+ }
456
+
457
+ /**
458
+ * The deployment entrypoint. `slice build` bundles `src/` and never runs `api/`,
459
+ * so a syntax error there reached production as a 500.
460
+ */
461
+ async function checkServerEntry() {
462
+ const { serverErrors, hasServer } = await validateServerEntry({ projectRoot: getProjectRoot(import.meta.url) });
463
+
464
+ if (!hasServer) return { pass: true, message: 'No api/index.js (static app)' };
465
+ if (serverErrors.length === 0) return { pass: true, message: 'api/index.js parses' };
466
+
467
+ return {
468
+ message: `api/index.js does not parse: ${serverErrors[0].message.split('\n')[0]}`,
469
+ suggestion: 'Fix the syntax error: the deploy fails on the same file.'
470
+ };
471
+ }
472
+
473
+ /** Package root of a bare specifier: 'lodash/fp' -> 'lodash', '@s/p/x' -> '@s/p'. */
474
+ function packageRootOf(spec) {
475
+ const parts = spec.split('/');
476
+ return spec.startsWith('@') ? parts.slice(0, 2).join('/') : parts[0];
477
+ }
478
+
479
+ /** Collects bare (node_modules) import specifiers from a module's source. */
480
+ function extractBareImports(source) {
481
+ const found = new Set();
482
+ const add = (spec) => {
483
+ if (typeof spec === 'string' && ExternalModuleBundler.isBareSpecifier(spec)) found.add(spec);
484
+ };
485
+ try {
486
+ const ast = parseModule(source, { sourceType: 'module', plugins: ['jsx'] });
487
+ traverse.default(ast, {
488
+ ImportDeclaration(p) { add(p.node.source?.value); },
489
+ ExportNamedDeclaration(p) { if (p.node.source) add(p.node.source.value); },
490
+ ExportAllDeclaration(p) { add(p.node.source?.value); },
491
+ CallExpression(p) {
492
+ if (p.node.callee?.type === 'Import' && p.node.arguments?.[0]?.type === 'StringLiteral') {
493
+ add(p.node.arguments[0].value);
494
+ }
495
+ }
496
+ });
497
+ } catch { /* unparseable → skip */ }
498
+ return found;
499
+ }
500
+
501
+ /**
502
+ * Verifies that every node_modules package imported by a component is actually
503
+ * installed. Bare imports are resolved from node_modules at build/dev time, so a
504
+ * missing package would fail there — this surfaces it early.
505
+ */
506
+ async function checkExternalDependencies() {
507
+ const registryPath = getComponentsJsPath(import.meta.url);
508
+ const configPath = getConfigPath(import.meta.url);
509
+ const projectRoot = getProjectRoot(import.meta.url);
510
+
511
+ if (!await fs.pathExists(registryPath)) {
512
+ return { pass: true, message: 'No components to check' };
513
+ }
514
+
515
+ try {
516
+ const content = await fs.readFile(registryPath, 'utf-8');
517
+ const entries = Object.entries(parseComponentsRegistry(content, registryPath));
518
+
519
+ const categoryPathCache = new Map();
520
+ if (await fs.pathExists(configPath)) {
521
+ try {
522
+ const config = await fs.readJson(configPath);
523
+ for (const [cat, catMeta] of Object.entries(config.paths?.components || {})) {
524
+ categoryPathCache.set(cat, catMeta.path?.replace(/^[/\\]+/, '') || '');
525
+ }
526
+ } catch { /* config issues reported elsewhere */ }
527
+ }
528
+
529
+ const usedBy = new Map(); // packageRoot -> Set(component names)
530
+ for (const [compName, meta] of entries) {
531
+ const category = typeof meta === 'string' ? meta : (meta.category || '');
532
+ const relPath = categoryPathCache.get(category);
533
+ if (!relPath) continue;
534
+ const jsPath = getSrcPath(import.meta.url, relPath, compName, `${compName}.js`);
535
+ if (!await fs.pathExists(jsPath)) continue;
536
+
537
+ const source = await fs.readFile(jsPath, 'utf-8');
538
+ for (const spec of extractBareImports(source)) {
539
+ const root = packageRootOf(spec);
540
+ if (!usedBy.has(root)) usedBy.set(root, new Set());
541
+ usedBy.get(root).add(compName);
542
+ }
543
+ }
544
+
545
+ if (usedBy.size === 0) {
546
+ return { pass: true, message: 'No external (node_modules) imports' };
547
+ }
548
+
549
+ const missing = [];
550
+ for (const root of usedBy.keys()) {
551
+ const pkgJson = path.join(projectRoot, 'node_modules', root, 'package.json');
552
+ if (!await fs.pathExists(pkgJson)) missing.push(root);
553
+ }
554
+
555
+ if (missing.length === 0) {
556
+ return { pass: true, message: `${usedBy.size} external package(s) imported, all installed` };
557
+ }
558
+
559
+ return {
560
+ warn: true,
561
+ message: `${missing.length} imported package(s) not in node_modules: ${missing.sort().join(', ')}`,
562
+ details: missing.sort().map((m) => `Install "${m}" — used by: ${Array.from(usedBy.get(m)).sort().join(', ')}`)
563
+ };
564
+ } catch (error) {
565
+ return { warn: true, message: `Cannot check external dependencies: ${error.message}` };
566
+ }
567
+ }
568
+
569
+ /**
570
+ * Main diagnostic command
571
+ */
572
+ export {
573
+ checkNodeVersion,
574
+ checkDirectoryStructure,
575
+ checkConfig,
576
+ checkSeoConfiguration,
577
+ checkPort,
578
+ checkDependencies,
579
+ checkComponents,
580
+ checkServerEntry,
581
+ checkExternalDependencies
582
+ };
583
+
584
+ export default async function runDiagnostics() {
585
+ Print.newLine();
586
+ Print.title('🔍 Running Slice.js Diagnostics...');
587
+ Print.newLine();
588
+
589
+ const checks = [
590
+ { name: 'Node.js Version', fn: checkNodeVersion },
591
+ { name: 'Project Structure', fn: checkDirectoryStructure },
592
+ { name: 'Configuration', fn: checkConfig },
593
+ { name: 'SEO', fn: checkSeoConfiguration },
594
+ { name: 'Port Availability', fn: checkPort },
595
+ { name: 'Package Manager', fn: checkPackageManagerSetup },
596
+ { name: 'Dependencies', fn: checkDependencies },
597
+ { name: 'Components & Routes', fn: checkComponents },
598
+ { name: 'Server entry', fn: checkServerEntry },
599
+ { name: 'External Dependencies', fn: checkExternalDependencies }
600
+ ];
601
+
602
+ const results = [];
603
+
604
+ for (const check of checks) {
605
+ const result = await check.fn();
606
+ results.push({ ...result, name: check.name });
607
+ }
608
+
609
+ // Crear tabla de resultados
610
+ const table = new Table({
611
+ head: [chalk.cyan.bold('Check'), chalk.cyan.bold('Status'), chalk.cyan.bold('Details')],
612
+ colWidths: [25, 10, 55],
613
+ style: {
614
+ head: [],
615
+ border: ['gray']
616
+ },
617
+ wordWrap: true
618
+ });
619
+
620
+ results.forEach(result => {
621
+ let status;
622
+ if (result.pass) {
623
+ status = chalk.green('✅ PASS');
624
+ } else if (result.warn) {
625
+ status = chalk.yellow('⚠️ WARN');
626
+ } else {
627
+ status = chalk.red('❌ FAIL');
628
+ }
629
+
630
+ const details = result.suggestion
631
+ ? `${result.message}\n${chalk.gray('→ ' + result.suggestion)}`
632
+ : result.message;
633
+
634
+ table.push([result.name, status, details]);
635
+ });
636
+
637
+ console.log(table.toString());
638
+
639
+ // Resumen
640
+ const issues = results.filter(r => !r.pass && !r.warn).length;
641
+ const warnings = results.filter(r => r.warn).length;
642
+ const passed = results.filter(r => r.pass).length;
643
+
644
+ Print.newLine();
645
+ Print.separator();
646
+
647
+ const depsResult = results.find(r => r.name === 'Dependencies');
648
+ if (depsResult && depsResult.warn && Array.isArray(depsResult.missing) && depsResult.missing.length > 0) {
649
+ const projectRoot = getProjectRoot(import.meta.url);
650
+ const pm = resolvePackageManager(projectRoot).name;
651
+ for (const pkg of depsResult.missing) {
652
+ Print.info(`Missing: ${pkg}. Install with: ${installCommand(pm, `${pkg}@latest`)}`);
653
+ }
654
+ }
655
+
656
+ if (issues === 0 && warnings === 0) {
657
+ Print.success('All checks passed! 🎉');
658
+ Print.info('Your Slice.js project is correctly configured');
659
+ } else {
660
+ console.log(chalk.bold('📊 Summary:'));
661
+ console.log(chalk.green(` ✅ Passed: ${passed}`));
662
+ if (warnings > 0) console.log(chalk.yellow(` ⚠️ Warnings: ${warnings}`));
663
+ if (issues > 0) console.log(chalk.red(` ❌ Issues: ${issues}`));
664
+
665
+ Print.newLine();
666
+
667
+ if (issues > 0) {
668
+ Print.warning('Fix the issues above: they block "slice build" and would ship a broken project');
669
+ // A diagnostic command that always exits 0 cannot gate a pipeline.
670
+ process.exitCode = 1;
671
+ } else {
672
+ Print.info('Warnings are non-critical but should be addressed');
673
+ }
674
+ }
675
+
676
+ Print.separator();
677
+ }