slicejs-cli 4.2.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 -780
  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 -0
  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,475 +1,526 @@
1
- import fs from 'fs-extra';
2
- import path from 'path';
3
- import { fileURLToPath } from 'url';
4
- import ora from 'ora';
5
- import Print from '../Print.js';
6
- import { getProjectRoot, getApiPath, getSrcPath, getPath } from '../utils/PathHelper.js';
7
- import { execSync } from 'child_process';
8
- import {
9
- resolvePackageManager,
10
- getPackageManagerVersion,
11
- installCommand
12
- } from '../utils/PackageManager.js';
13
- import { SLICE_SCRIPTS } from '../utils/sliceScripts.js';
14
-
15
- // Import ComponentRegistry class from getComponent
16
- import { ComponentRegistry } from '../getComponent/getComponent.js';
17
-
18
- // Fetch the latest published version straight from the npm registry. This is
19
- // informational only (we never pin installs to it): it avoids depending on
20
- // `npm view` (absent on pnpm-only machines) and plays nice with pnpm's
21
- // minimumReleaseAge quarantine, which may legitimately resolve an older version.
22
- async function fetchLatestVersion(packageName) {
23
- try {
24
- const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`, {
25
- headers: { 'Accept': 'application/json' }
26
- });
27
- if (!response.ok) return null;
28
- const data = await response.json();
29
- return data.version || null;
30
- } catch {
31
- return null;
32
- }
33
- }
34
-
35
- function getRunningCliVersion() {
36
- try {
37
- const cliRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
38
- const cliPkg = fs.readJsonSync(path.join(cliRoot, 'package.json'));
39
- return typeof cliPkg.version === 'string' ? cliPkg.version : null;
40
- } catch {
41
- return null;
42
- }
43
- }
44
-
45
- async function ensurePnpmAllowBuilds(projectRoot) {
46
- const workspacePath = path.join(projectRoot, 'pnpm-workspace.yaml');
47
- const allowBuildLine = ' slicejs-cli: true';
48
-
49
- if (!(await fs.pathExists(workspacePath))) {
50
- await fs.writeFile(workspacePath, `allowBuilds:\n${allowBuildLine}\n`, 'utf8');
51
- return;
52
- }
53
-
54
- const raw = await fs.readFile(workspacePath, 'utf8');
55
- const lines = raw.split(/\r?\n/);
56
- const allowIdx = lines.findIndex((line) => /^allowBuilds:\s*$/.test(line));
57
-
58
- if (allowIdx === -1) {
59
- const suffix = raw.endsWith('\n') ? '' : '\n';
60
- await fs.writeFile(workspacePath, `${raw}${suffix}allowBuilds:\n${allowBuildLine}\n`, 'utf8');
61
- return;
62
- }
63
-
64
- let blockEnd = lines.length;
65
- for (let i = allowIdx + 1; i < lines.length; i++) {
66
- const line = lines[i];
67
- if (!line.trim()) continue;
68
- if (!/^\s/.test(line)) {
69
- blockEnd = i;
70
- break;
71
- }
72
- }
73
-
74
- let found = false;
75
- for (let i = allowIdx + 1; i < blockEnd; i++) {
76
- if (/^\s+slicejs-cli\s*:/.test(lines[i])) {
77
- lines[i] = allowBuildLine;
78
- found = true;
79
- break;
80
- }
81
- }
82
-
83
- if (!found) {
84
- lines.splice(blockEnd, 0, allowBuildLine);
85
- }
86
-
87
- await fs.writeFile(workspacePath, `${lines.join('\n').replace(/\n*$/, '\n')}`, 'utf8');
88
- }
89
-
90
- // Create the project manifest BEFORE any install runs. Without a package.json in
91
- // the project folder, npm/pnpm walk up the directory tree looking for the nearest
92
- // manifest and anchor node_modules (and the dependency entry) OUTSIDE the project.
93
- // Exported for tests (init-project-isolation.test.js).
94
- export async function ensureProjectManifest(projectRoot, packageManager) {
95
- const pkgPath = path.join(projectRoot, 'package.json');
96
- if (await fs.pathExists(pkgPath)) return pkgPath;
97
-
98
- const pkg = {
99
- name: path.basename(projectRoot),
100
- version: '1.0.0',
101
- description: 'Slice.js project',
102
- main: 'api/index.js',
103
- type: 'module',
104
- engines: { node: '>=20.0.0' },
105
- scripts: {}
106
- };
107
-
108
- // Persist the chosen package manager (corepack convention) so every later
109
- // command — slice update, slice doctor — detects it deterministically.
110
- const pmVersion = getPackageManagerVersion(packageManager);
111
- if (pmVersion) {
112
- pkg.packageManager = `${packageManager}@${pmVersion}`;
113
- }
114
-
115
- await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), 'utf8');
116
- return pkgPath;
117
- }
118
-
119
- // Visual components used by the App Shell + MultiRoute starter project.
120
- // We install only these on init; newcomers add more on demand with `slice get <Name>`.
121
- const STARTER_VISUAL_COMPONENTS = [
122
- 'Button',
123
- 'Link',
124
- 'Loading',
125
- 'MultiRoute',
126
- 'Navbar',
127
- 'NotFound',
128
- 'Route'
129
- ];
130
-
131
- // Service components are now also pulled from the registry on init (instead of
132
- // being vendored in the framework package), so Visual and Service share a single
133
- // source of truth. Newcomers add more on demand with `slice get <Name>`.
134
- const STARTER_SERVICE_COMPONENTS = [
135
- 'FetchManager',
136
- 'IndexedDbManager',
137
- 'LocalStorageManager'
138
- ];
139
-
140
- export default async function initializeProject(options = {}) {
141
- try {
142
- const projectRoot = getProjectRoot(import.meta.url);
143
- const destinationApi = getApiPath(import.meta.url);
144
- const destinationSrc = getSrcPath(import.meta.url);
145
-
146
- // Resolve the package manager chosen in `slice init` (or detect it when
147
- // initializeProject is invoked directly, e.g. inside an existing folder).
148
- const packageManager = options.packageManager
149
- || resolvePackageManager(projectRoot).name;
150
-
151
- if (packageManager === 'pnpm') {
152
- await ensurePnpmAllowBuilds(projectRoot);
153
- }
154
-
155
- // 0. CREATE PROJECT MANIFEST FIRST — must exist before any install so the
156
- // package manager anchors node_modules inside the project folder.
157
- await ensureProjectManifest(projectRoot, packageManager);
158
-
159
- const fwSpinner = ora('Ensuring latest Slice framework...').start();
160
- let latestVersion = null;
161
- let installedVersion = null;
162
- let sliceBaseDir;
163
- try {
164
- latestVersion = await fetchLatestVersion('slicejs-web-framework');
165
- const frameworkPackage = latestVersion
166
- ? `slicejs-web-framework@${latestVersion}`
167
- : 'slicejs-web-framework';
168
- const installedPkgPath = getPath(import.meta.url, 'node_modules', 'slicejs-web-framework', 'package.json');
169
- let installed = null;
170
- if (await fs.pathExists(installedPkgPath)) {
171
- const pkg = await fs.readJson(installedPkgPath);
172
- installed = pkg.version;
173
- }
174
- if (!installed || (latestVersion && installed !== latestVersion)) {
175
- execSync(installCommand(packageManager, frameworkPackage), { cwd: projectRoot, stdio: 'inherit' });
176
- }
177
- if (await fs.pathExists(installedPkgPath)) {
178
- const pkg = await fs.readJson(installedPkgPath);
179
- installedVersion = pkg.version;
180
- }
181
- sliceBaseDir = getPath(import.meta.url, 'node_modules', 'slicejs-web-framework');
182
- fwSpinner.succeed(`slicejs-web-framework@${installedVersion || 'unknown'} ready`);
183
- if (latestVersion && installedVersion && installedVersion !== latestVersion) {
184
- Print.info(`Latest published is ${latestVersion}; your package manager resolved ${installedVersion} (release-age policy or cached registry).`);
185
- }
186
- } catch (err) {
187
- // Fallback uses __dirname-style path because it looks for a local development copy,
188
- // not a project-relative path — the install failed, so we fall back to monorepo sibling.
189
- const fallback = path.join(path.dirname(fileURLToPath(import.meta.url)), '../../../slicejs-web-framework');
190
- if (await fs.pathExists(fallback)) {
191
- sliceBaseDir = fallback;
192
- fwSpinner.warn('Using local slicejs-web-framework fallback');
193
- } else {
194
- fwSpinner.fail('Failed to ensure latest slicejs-web-framework');
195
- Print.error(err.message);
196
- console.error(err.stack);
197
- return;
198
- }
199
- }
200
-
201
- // 0b. INSTALL THE CLI LOCALLY (devDependency) so the generated scripts
202
- // (`npm run dev` → `slice dev`) resolve via local delegation to a version
203
- // pinned per project, as the docs recommend.
204
- const cliSpinner = ora('Installing slicejs-cli as devDependency...').start();
205
- try {
206
- const cliPkgPath = getPath(import.meta.url, 'node_modules', 'slicejs-cli', 'package.json');
207
- const currentCliVersion = getRunningCliVersion();
208
- const cliPackage = currentCliVersion
209
- ? `slicejs-cli@${currentCliVersion}`
210
- : 'slicejs-cli';
211
-
212
- let installedCliVersion = null;
213
- if (await fs.pathExists(cliPkgPath)) {
214
- const pkg = await fs.readJson(cliPkgPath);
215
- installedCliVersion = pkg.version;
216
- }
217
-
218
- if (!installedCliVersion || (currentCliVersion && installedCliVersion !== currentCliVersion)) {
219
- execSync(installCommand(packageManager, cliPackage, { dev: true }), { cwd: projectRoot, stdio: 'inherit' });
220
- }
221
- cliSpinner.succeed('slicejs-cli installed locally');
222
- } catch (err) {
223
- cliSpinner.warn('Could not install slicejs-cli locally — scripts will use the global CLI');
224
- Print.info(`You can add it later with: ${installCommand(packageManager, `slicejs-cli@${getRunningCliVersion() || 'latest'}`, { dev: true })}`);
225
- }
226
-
227
- // These derive from sliceBaseDir (which comes from npm install or fallback),
228
- // so they're already dynamic — no PathHelper needed.
229
- const apiDir = path.join(sliceBaseDir, 'api');
230
- const srcDir = path.join(sliceBaseDir, 'src');
231
-
232
- try {
233
- if (fs.existsSync(path.join(destinationApi, 'index.js'))) throw new Error(`api/index.js already exists: ${path.join(destinationApi, 'index.js')}`);
234
- if (fs.existsSync(destinationSrc)) throw new Error(`The "src" directory already exists: ${destinationSrc}`);
235
- } catch (error) {
236
- Print.error('Validating destination directories:', error.message);
237
- console.error(error.stack);
238
- return;
239
- }
240
-
241
- // 1. COPY ONLY api/index.js — el resto se importa desde el paquete
242
- const apiSpinner = ora('Creating api/index.js...').start();
243
- try {
244
- const srcIndex = path.join(apiDir, 'index.js');
245
- if (!fs.existsSync(srcIndex)) throw new Error(`api/index.js not found: ${srcIndex}`);
246
- await fs.ensureDir(destinationApi);
247
- await fs.copy(srcIndex, path.join(destinationApi, 'index.js'));
248
- apiSpinner.succeed('api/index.js created successfully');
249
- } catch (error) {
250
- apiSpinner.fail('Error creating api/index.js');
251
- Print.error(error.message);
252
- console.error(error.stack);
253
- return;
254
- }
255
-
256
- // 2. CREATE BASIC SRC STRUCTURE (without copying Visual components)
257
- const srcSpinner = ora('Creating src structure...').start();
258
- try {
259
- if (!fs.existsSync(srcDir)) throw new Error(`src folder not found: ${srcDir}`);
260
-
261
- // Copy only base src files, excluding Components/Visual
262
- await fs.ensureDir(destinationSrc);
263
-
264
- // Copy src files and folders except Components/Visual
265
- const srcItems = await fs.readdir(srcDir);
266
-
267
- for (const item of srcItems) {
268
- const srcItemPath = path.join(srcDir, item);
269
- const destItemPath = path.join(destinationSrc, item);
270
- const stat = await fs.stat(srcItemPath);
271
-
272
- if (stat.isDirectory()) {
273
- if (item === 'Components') {
274
- // Create Components structure but without copying Visual or Service
275
- await fs.ensureDir(destItemPath);
276
-
277
- const componentItems = await fs.readdir(srcItemPath);
278
- for (const componentItem of componentItems) {
279
- const componentItemPath = path.join(srcItemPath, componentItem);
280
- const destComponentItemPath = path.join(destItemPath, componentItem);
281
-
282
- if (componentItem !== 'Visual' && componentItem !== 'Service') {
283
- // Copy AppComponents and other template types from the framework
284
- await fs.copy(componentItemPath, destComponentItemPath, { recursive: true });
285
- } else {
286
- // Visual and Service are installed from the registry below
287
- await fs.ensureDir(destComponentItemPath);
288
- }
289
- }
290
- } else {
291
- // Copy other folders normally
292
- await fs.copy(srcItemPath, destItemPath, { recursive: true });
293
- }
294
- } else {
295
- // Copy files normally
296
- await fs.copy(srcItemPath, destItemPath);
297
- }
298
- }
299
-
300
- srcSpinner.succeed('Source structure created successfully');
301
- } catch (error) {
302
- srcSpinner.fail('Error creating source structure');
303
- Print.error(error.message);
304
- console.error(error.stack);
305
- return;
306
- }
307
-
308
- // 3. DOWNLOAD ALL VISUAL COMPONENTS FROM OFFICIAL REPOSITORY
309
- let visualResults = [];
310
- const componentsSpinner = ora('Loading component registry...').start();
311
- try {
312
- const registry = new ComponentRegistry();
313
- await registry.loadRegistry();
314
-
315
- // Install only the Visual components the starter project uses.
316
- const allVisualComponents = STARTER_VISUAL_COMPONENTS;
317
-
318
- if (allVisualComponents.length > 0) {
319
- componentsSpinner.text = `Installing ${allVisualComponents.length} starter Visual components...`;
320
-
321
- visualResults = await registry.installMultipleComponents(
322
- allVisualComponents,
323
- 'Visual',
324
- true // force = true for initial installation
325
- );
326
-
327
- const successful = visualResults.filter(r => r.success).length;
328
- const failed = visualResults.filter(r => !r.success).length;
329
-
330
- if (successful > 0 && failed === 0) {
331
- componentsSpinner.succeed(`All ${successful} Visual components installed successfully`);
332
- } else if (successful > 0) {
333
- componentsSpinner.warn(`${successful} components installed, ${failed} failed`);
334
- } else {
335
- componentsSpinner.fail('Failed to install Visual components');
336
- }
337
- } else {
338
- componentsSpinner.warn('No Visual components found in registry');
339
- Print.info(`You can add components later using "${packageManager} run get -- <component-name>"`);
340
- }
341
-
342
- } catch (error) {
343
- componentsSpinner.fail('Could not download Visual components from official repository');
344
- Print.error(`Repository error: ${error.message}`);
345
- Print.info('Project initialized without Visual components');
346
- Print.info(`You can add them later using "${packageManager} run get -- <component-name>"`);
347
- }
348
-
349
- // 3b. DOWNLOAD STARTER SERVICE COMPONENTS FROM OFFICIAL REPOSITORY
350
- let serviceResults = [];
351
- const serviceSpinner = ora('Installing starter Service components...').start();
352
- try {
353
- const registry = new ComponentRegistry();
354
- await registry.loadRegistry();
355
-
356
- if (STARTER_SERVICE_COMPONENTS.length > 0) {
357
- serviceSpinner.text = `Installing ${STARTER_SERVICE_COMPONENTS.length} starter Service components...`;
358
-
359
- serviceResults = await registry.installMultipleComponents(
360
- STARTER_SERVICE_COMPONENTS,
361
- 'Service',
362
- true // force = true for initial installation
363
- );
364
-
365
- const successful = serviceResults.filter(r => r.success).length;
366
- const failed = serviceResults.filter(r => !r.success).length;
367
-
368
- if (successful > 0 && failed === 0) {
369
- serviceSpinner.succeed(`All ${successful} Service components installed successfully`);
370
- } else if (successful > 0) {
371
- serviceSpinner.warn(`${successful} Service components installed, ${failed} failed`);
372
- } else {
373
- serviceSpinner.fail('Failed to install Service components');
374
- }
375
- } else {
376
- serviceSpinner.succeed('No starter Service components to install');
377
- }
378
- } catch (error) {
379
- serviceSpinner.fail('Could not download Service components from official repository');
380
- Print.error(`Repository error: ${error.message}`);
381
- Print.info(`You can add them later using "${packageManager} run get -- <component-name>"`);
382
- }
383
-
384
- // 4. CONFIGURE SCRIPTS IN PROJECT package.json
385
- const pkgSpinner = ora('Configuring npm scripts...').start();
386
- try {
387
- const projectRoot = getProjectRoot(import.meta.url);
388
- const pkgPath = getPath(import.meta.url, 'package.json');
389
-
390
- let pkg;
391
- if (await fs.pathExists(pkgPath)) {
392
- pkg = await fs.readJson(pkgPath);
393
- } else {
394
- pkg = {
395
- name: path.basename(projectRoot),
396
- version: '1.0.0',
397
- description: 'Slice.js project',
398
- main: 'api/index.js',
399
- scripts: {}
400
- };
401
- }
402
-
403
- pkg.scripts = pkg.scripts || {};
404
- pkg.dependencies = pkg.dependencies || {};
405
-
406
- // Main scripts (local CLI path, no global launcher dependency)
407
- pkg.scripts['dev'] = SLICE_SCRIPTS['slice:dev'];
408
- pkg.scripts['build'] = SLICE_SCRIPTS['slice:build'];
409
- pkg.scripts['start'] = SLICE_SCRIPTS['slice:start'];
410
-
411
- // Component management
412
- pkg.scripts['component:create'] = SLICE_SCRIPTS['slice:create'];
413
- pkg.scripts['component:list'] = SLICE_SCRIPTS['slice:list'];
414
- pkg.scripts['component:delete'] = SLICE_SCRIPTS['slice:delete'];
415
-
416
- // Registry shortcuts
417
- pkg.scripts['get'] = SLICE_SCRIPTS['slice:get'];
418
- pkg.scripts['browse'] = SLICE_SCRIPTS['slice:browse'];
419
- pkg.scripts['sync'] = SLICE_SCRIPTS['slice:sync'];
420
-
421
- // slice:* namespaced set — shared with `slice postinstall`
422
- // (commands/utils/sliceScripts.js) so the three never drift apart.
423
- Object.assign(pkg.scripts, SLICE_SCRIPTS);
424
- pkg.scripts['run'] = SLICE_SCRIPTS['slice:dev'];
425
-
426
- // Module configuration
427
- pkg.type = 'module';
428
- pkg.engines = pkg.engines || { node: '>=20.0.0' };
429
-
430
- // Ensure framework dependency is present (the install above normally
431
- // already wrote it; this is a fallback for the monorepo-sibling path).
432
- if (!pkg.dependencies['slicejs-web-framework']) {
433
- pkg.dependencies['slicejs-web-framework'] = installedVersion ? `^${installedVersion}` : 'latest';
434
- }
435
-
436
- await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), 'utf8');
437
- pkgSpinner.succeed('Package scripts configured successfully');
438
-
439
- Print.title('New recommended commands:');
440
- console.log(` ${packageManager} run dev - Start development server`);
441
- console.log(` ${packageManager} run get - Install components`);
442
- console.log(` ${packageManager} run browse - Browse components`);
443
- } catch (error) {
444
- pkgSpinner.fail('Failed to configure npm scripts');
445
- Print.error(error.message);
446
- console.error(error.stack);
447
- }
448
-
449
- const projectName = path.basename(process.cwd());
450
-
451
- const failedCount = [...visualResults, ...serviceResults].filter(r => !r.success).length;
452
- if (failedCount > 0) {
453
- Print.warning(`${failedCount} component(s) failed to install — run "${packageManager} run get -- <name>" to retry`);
454
- }
455
-
456
- Print.success(`Project initialized successfully in "${projectName}/"`);
457
- Print.newLine();
458
- Print.title('Next steps:');
459
- console.log(` cd ${projectName}`);
460
- console.log(` ${packageManager} run dev - Start development server`);
461
- console.log(` ${packageManager} run browse - View available components`);
462
- console.log(` ${packageManager} run get -- Button - Install specific components`);
463
- console.log(` ${packageManager} run sync - Update all components to latest versions`);
464
-
465
- } catch (error) {
466
- Print.error('Unexpected error initializing project:', error.message);
467
- console.error(error.stack);
468
- }
469
- }
470
-
471
- // NOTE: `slice init` installs only STARTER_VISUAL_COMPONENTS and
472
- // STARTER_SERVICE_COMPONENTS (see top of file); both Visual and Service are pulled
473
- // from the registry rather than vendored in the framework package.
474
- // To install every registry component instead, iterate
475
- // `Object.keys(registry.getAvailableComponents('Visual'))` (and likewise 'Service').
1
+ import fs from 'fs-extra';
2
+ import path from 'path';
3
+ import { fileURLToPath } from 'url';
4
+ import ora from 'ora';
5
+ import Print from '../Print.js';
6
+ import { getProjectRoot, getApiPath, getSrcPath, getPath } from '../utils/PathHelper.js';
7
+ import { execSync } from 'child_process';
8
+ import {
9
+ resolvePackageManager,
10
+ getPackageManagerVersion,
11
+ installCommand
12
+ } from '../utils/PackageManager.js';
13
+ import { SLICE_SCRIPTS } from '../utils/sliceScripts.js';
14
+
15
+ // Import ComponentRegistry class from getComponent
16
+ import { ComponentRegistry } from '../getComponent/getComponent.js';
17
+
18
+ // Fetch the latest published version straight from the npm registry. This is
19
+ // informational only (we never pin installs to it): it avoids depending on
20
+ // `npm view` (absent on pnpm-only machines) and plays nice with pnpm's
21
+ // minimumReleaseAge quarantine, which may legitimately resolve an older version.
22
+ async function fetchLatestVersion(packageName) {
23
+ try {
24
+ const response = await fetch(`https://registry.npmjs.org/${packageName}/latest`, {
25
+ headers: { 'Accept': 'application/json' }
26
+ });
27
+ if (!response.ok) return null;
28
+ const data = await response.json();
29
+ return data.version || null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ function getRunningCliVersion() {
36
+ try {
37
+ const cliRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '../..');
38
+ const cliPkg = fs.readJsonSync(path.join(cliRoot, 'package.json'));
39
+ return typeof cliPkg.version === 'string' ? cliPkg.version : null;
40
+ } catch {
41
+ return null;
42
+ }
43
+ }
44
+
45
+ // Packages whose install scripts a new project needs. `slicejs-cli` has a
46
+ // postinstall; `esbuild` (a framework dependency) verifies its platform binary.
47
+ // Missing either one makes the *next* `pnpm add` fail with
48
+ // ERR_PNPM_IGNORED_BUILDS, which is how it was found.
49
+ const REQUIRED_BUILDS = ['esbuild', 'slicejs-cli'];
50
+
51
+ export async function ensurePnpmAllowBuilds(projectRoot) {
52
+ const workspacePath = path.join(projectRoot, 'pnpm-workspace.yaml');
53
+ const exists = await fs.pathExists(workspacePath);
54
+ const raw = exists ? await fs.readFile(workspacePath, 'utf8') : '';
55
+ const lines = raw ? raw.split(/\r?\n/) : [];
56
+
57
+ let result = lines;
58
+ for (const packageName of REQUIRED_BUILDS) {
59
+ result = ensureAllowBuildEntry(result, packageName);
60
+ }
61
+
62
+ const content = `${result.join('\n').replace(/\n+$/, '')}\n`;
63
+ await fs.writeFile(workspacePath, content, 'utf8');
64
+ }
65
+
66
+ /** Adds `<name>: true` to the `allowBuilds:` block, creating the block if needed. */
67
+ function ensureAllowBuildEntry(lines, packageName) {
68
+ const entry = ` ${packageName}: true`;
69
+ const allowIdx = lines.findIndex((line) => /^allowBuilds:\s*$/.test(line));
70
+
71
+ if (allowIdx === -1) {
72
+ const base = [...lines];
73
+ while (base.length && !base[base.length - 1].trim()) base.pop();
74
+ return [...base, 'allowBuilds:', entry];
75
+ }
76
+
77
+ let blockEnd = lines.length;
78
+ for (let i = allowIdx + 1; i < lines.length; i++) {
79
+ const line = lines[i];
80
+ if (!line.trim()) continue;
81
+ if (!/^\s/.test(line)) {
82
+ blockEnd = i;
83
+ break;
84
+ }
85
+ }
86
+
87
+ const pattern = new RegExp(`^\\s+${packageName}\\s*:`);
88
+ const existing = lines.findIndex((line, index) => index > allowIdx && index < blockEnd && pattern.test(line));
89
+
90
+ if (existing !== -1) {
91
+ const next = [...lines];
92
+ next[existing] = entry;
93
+ return next;
94
+ }
95
+
96
+ const next = [...lines];
97
+ next.splice(blockEnd, 0, entry);
98
+ return next;
99
+ }
100
+
101
+ const GITIGNORE_TEMPLATE = `# Dependencies
102
+ node_modules/
103
+
104
+ # Production build output (slice build)
105
+ dist/
106
+
107
+ # Local environment overrides
108
+ .env
109
+ .env.*
110
+ !.env.example
111
+ `;
112
+
113
+ /**
114
+ * Writes a .gitignore for a new project. An existing file is never touched:
115
+ * `slice init` can run inside a folder that already has history, and silently
116
+ * replacing its ignore rules would be worse than leaving them alone.
117
+ * Exported for tests (init-gitignore.test.js).
118
+ */
119
+ export async function ensureGitignore(projectRoot) {
120
+ const gitignorePath = path.join(projectRoot, '.gitignore');
121
+ if (await fs.pathExists(gitignorePath)) return null;
122
+
123
+ await fs.writeFile(gitignorePath, GITIGNORE_TEMPLATE, 'utf8');
124
+ return gitignorePath;
125
+ }
126
+
127
+ // Create the project manifest BEFORE any install runs. Without a package.json in
128
+ // the project folder, npm/pnpm walk up the directory tree looking for the nearest
129
+ // manifest and anchor node_modules (and the dependency entry) OUTSIDE the project.
130
+ // Exported for tests (init-project-isolation.test.js).
131
+ export async function ensureProjectManifest(projectRoot, packageManager) {
132
+ const pkgPath = path.join(projectRoot, 'package.json');
133
+ if (await fs.pathExists(pkgPath)) return pkgPath;
134
+
135
+ const pkg = {
136
+ name: path.basename(projectRoot),
137
+ version: '1.0.0',
138
+ description: 'Slice.js project',
139
+ main: 'api/index.js',
140
+ type: 'module',
141
+ engines: { node: '>=20.0.0' },
142
+ scripts: {}
143
+ };
144
+
145
+ // Persist the chosen package manager (corepack convention) so every later
146
+ // command — slice update, slice doctor — detects it deterministically.
147
+ const pmVersion = getPackageManagerVersion(packageManager);
148
+ if (pmVersion) {
149
+ pkg.packageManager = `${packageManager}@${pmVersion}`;
150
+ }
151
+
152
+ await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), 'utf8');
153
+ return pkgPath;
154
+ }
155
+
156
+ // Visual components used by the App Shell + MultiRoute starter project.
157
+ // We install only these on init; newcomers add more on demand with `slice get <Name>`.
158
+ const STARTER_VISUAL_COMPONENTS = [
159
+ 'Button',
160
+ 'Link',
161
+ 'Loading',
162
+ 'MultiRoute',
163
+ 'Navbar',
164
+ 'NotFound',
165
+ 'Route'
166
+ ];
167
+
168
+ // Service components are now also pulled from the registry on init (instead of
169
+ // being vendored in the framework package), so Visual and Service share a single
170
+ // source of truth. Newcomers add more on demand with `slice get <Name>`.
171
+ const STARTER_SERVICE_COMPONENTS = [
172
+ 'FetchManager',
173
+ 'IndexedDbManager',
174
+ 'LocalStorageManager'
175
+ ];
176
+
177
+ export default async function initializeProject(options = {}) {
178
+ try {
179
+ const projectRoot = getProjectRoot(import.meta.url);
180
+ const destinationApi = getApiPath(import.meta.url);
181
+ const destinationSrc = getSrcPath(import.meta.url);
182
+
183
+ // Resolve the package manager chosen in `slice init` (or detect it when
184
+ // initializeProject is invoked directly, e.g. inside an existing folder).
185
+ const packageManager = options.packageManager
186
+ || resolvePackageManager(projectRoot).name;
187
+
188
+ if (packageManager === 'pnpm') {
189
+ await ensurePnpmAllowBuilds(projectRoot);
190
+ }
191
+
192
+ // 0. CREATE PROJECT MANIFEST FIRST — must exist before any install so the
193
+ // package manager anchors node_modules inside the project folder.
194
+ await ensureProjectManifest(projectRoot, packageManager);
195
+ await ensureGitignore(projectRoot);
196
+
197
+ const fwSpinner = ora('Ensuring latest Slice framework...').start();
198
+ let latestVersion = null;
199
+ let installedVersion = null;
200
+ let sliceBaseDir;
201
+ try {
202
+ latestVersion = await fetchLatestVersion('slicejs-web-framework');
203
+ const frameworkPackage = latestVersion
204
+ ? `slicejs-web-framework@${latestVersion}`
205
+ : 'slicejs-web-framework';
206
+ const installedPkgPath = getPath(import.meta.url, 'node_modules', 'slicejs-web-framework', 'package.json');
207
+ let installed = null;
208
+ if (await fs.pathExists(installedPkgPath)) {
209
+ const pkg = await fs.readJson(installedPkgPath);
210
+ installed = pkg.version;
211
+ }
212
+ if (!installed || (latestVersion && installed !== latestVersion)) {
213
+ execSync(installCommand(packageManager, frameworkPackage), { cwd: projectRoot, stdio: 'inherit' });
214
+ }
215
+ // Verify the project itself, not whatever node_modules the CLI happens
216
+ // to live in: a package manager can finish successfully without adding
217
+ // the dependency here (workspace protocols, a global .npmrc, an offline
218
+ // store), and the scaffold below would then read the wrong tree.
219
+ if (!(await fs.pathExists(installedPkgPath))) {
220
+ throw new Error(`${frameworkPackage} is not in ${path.join(projectRoot, 'node_modules')} after installing`);
221
+ }
222
+ if (await fs.pathExists(installedPkgPath)) {
223
+ const pkg = await fs.readJson(installedPkgPath);
224
+ installedVersion = pkg.version;
225
+ }
226
+ sliceBaseDir = getPath(import.meta.url, 'node_modules', 'slicejs-web-framework');
227
+ fwSpinner.succeed(`slicejs-web-framework@${installedVersion || 'unknown'} ready`);
228
+ if (latestVersion && installedVersion && installedVersion !== latestVersion) {
229
+ Print.info(`Latest published is ${latestVersion}; your package manager resolved ${installedVersion} (release-age policy or cached registry).`);
230
+ }
231
+ } catch (err) {
232
+ // The only valid fallback is a framework already inside THIS project
233
+ // (a retry, or a dependency linked before init ran). A copy sitting
234
+ // next to a globally installed CLI is a different runtime: scaffolding
235
+ // from it would ship a version the project does not depend on and the
236
+ // lockfile cannot reproduce. That is how a global install used to win
237
+ // over the package manager.
238
+ const projectFramework = getPath(import.meta.url, 'node_modules', 'slicejs-web-framework');
239
+ if (await fs.pathExists(projectFramework)) {
240
+ sliceBaseDir = projectFramework;
241
+ fwSpinner.warn('Install did not run; using the slicejs-web-framework already in this project');
242
+ } else {
243
+ fwSpinner.fail('Failed to install slicejs-web-framework');
244
+ Print.error('slice init:', err.message);
245
+ const retry = installCommand(packageManager, latestVersion ? `slicejs-web-framework@${latestVersion}` : 'slicejs-web-framework');
246
+ Print.info(`Retry with: ${retry}`);
247
+ return;
248
+ }
249
+ }
250
+
251
+ // 0b. INSTALL THE CLI LOCALLY (devDependency) so the generated scripts
252
+ // (`npm run dev` → `slice dev`) resolve via local delegation to a version
253
+ // pinned per project, as the docs recommend.
254
+ const cliSpinner = ora('Installing slicejs-cli as devDependency...').start();
255
+ try {
256
+ const cliPkgPath = getPath(import.meta.url, 'node_modules', 'slicejs-cli', 'package.json');
257
+ const currentCliVersion = getRunningCliVersion();
258
+ const cliPackage = currentCliVersion
259
+ ? `slicejs-cli@${currentCliVersion}`
260
+ : 'slicejs-cli';
261
+
262
+ let installedCliVersion = null;
263
+ if (await fs.pathExists(cliPkgPath)) {
264
+ const pkg = await fs.readJson(cliPkgPath);
265
+ installedCliVersion = pkg.version;
266
+ }
267
+
268
+ if (!installedCliVersion || (currentCliVersion && installedCliVersion !== currentCliVersion)) {
269
+ execSync(installCommand(packageManager, cliPackage, { dev: true }), { cwd: projectRoot, stdio: 'inherit' });
270
+ }
271
+ cliSpinner.succeed('slicejs-cli installed locally');
272
+ } catch (err) {
273
+ cliSpinner.warn('Could not install slicejs-cli locally — scripts will use the global CLI');
274
+ Print.info(`You can add it later with: ${installCommand(packageManager, `slicejs-cli@${getRunningCliVersion() || 'latest'}`, { dev: true })}`);
275
+ }
276
+
277
+ // These derive from sliceBaseDir (which comes from npm install or fallback),
278
+ // so they're already dynamic — no PathHelper needed.
279
+ const apiDir = path.join(sliceBaseDir, 'api');
280
+ const srcDir = path.join(sliceBaseDir, 'src');
281
+
282
+ try {
283
+ if (fs.existsSync(path.join(destinationApi, 'index.js'))) throw new Error(`api/index.js already exists: ${path.join(destinationApi, 'index.js')}`);
284
+ if (fs.existsSync(destinationSrc)) throw new Error(`The "src" directory already exists: ${destinationSrc}`);
285
+ } catch (error) {
286
+ Print.error('Validating destination directories:', error.message);
287
+ console.error(error.stack);
288
+ return;
289
+ }
290
+
291
+ // 1. COPY ONLY api/index.js — el resto se importa desde el paquete
292
+ const apiSpinner = ora('Creating api/index.js...').start();
293
+ try {
294
+ const srcIndex = path.join(apiDir, 'index.js');
295
+ if (!fs.existsSync(srcIndex)) throw new Error(`api/index.js not found: ${srcIndex}`);
296
+ await fs.ensureDir(destinationApi);
297
+ await fs.copy(srcIndex, path.join(destinationApi, 'index.js'));
298
+ apiSpinner.succeed('api/index.js created successfully');
299
+ } catch (error) {
300
+ apiSpinner.fail('Error creating api/index.js');
301
+ Print.error(error.message);
302
+ console.error(error.stack);
303
+ return;
304
+ }
305
+
306
+ // 2. CREATE BASIC SRC STRUCTURE (without copying Visual components)
307
+ const srcSpinner = ora('Creating src structure...').start();
308
+ try {
309
+ if (!fs.existsSync(srcDir)) throw new Error(`src folder not found: ${srcDir}`);
310
+
311
+ // Copy only base src files, excluding Components/Visual
312
+ await fs.ensureDir(destinationSrc);
313
+
314
+ // Copy src files and folders except Components/Visual
315
+ const srcItems = await fs.readdir(srcDir);
316
+
317
+ for (const item of srcItems) {
318
+ const srcItemPath = path.join(srcDir, item);
319
+ const destItemPath = path.join(destinationSrc, item);
320
+ const stat = await fs.stat(srcItemPath);
321
+
322
+ if (stat.isDirectory()) {
323
+ if (item === 'Components') {
324
+ // Create Components structure but without copying Visual or Service
325
+ await fs.ensureDir(destItemPath);
326
+
327
+ const componentItems = await fs.readdir(srcItemPath);
328
+ for (const componentItem of componentItems) {
329
+ const componentItemPath = path.join(srcItemPath, componentItem);
330
+ const destComponentItemPath = path.join(destItemPath, componentItem);
331
+
332
+ if (componentItem !== 'Visual' && componentItem !== 'Service') {
333
+ // Copy AppComponents and other template types from the framework
334
+ await fs.copy(componentItemPath, destComponentItemPath, { recursive: true });
335
+ } else {
336
+ // Visual and Service are installed from the registry below
337
+ await fs.ensureDir(destComponentItemPath);
338
+ }
339
+ }
340
+ } else {
341
+ // Copy other folders normally
342
+ await fs.copy(srcItemPath, destItemPath, { recursive: true });
343
+ }
344
+ } else {
345
+ // Copy files normally
346
+ await fs.copy(srcItemPath, destItemPath);
347
+ }
348
+ }
349
+
350
+ srcSpinner.succeed('Source structure created successfully');
351
+ } catch (error) {
352
+ srcSpinner.fail('Error creating source structure');
353
+ Print.error(error.message);
354
+ console.error(error.stack);
355
+ return;
356
+ }
357
+
358
+ // 3. DOWNLOAD ALL VISUAL COMPONENTS FROM OFFICIAL REPOSITORY
359
+ let visualResults = [];
360
+ const componentsSpinner = ora('Loading component registry...').start();
361
+ try {
362
+ const registry = new ComponentRegistry();
363
+ await registry.loadRegistry();
364
+
365
+ // Install only the Visual components the starter project uses.
366
+ const allVisualComponents = STARTER_VISUAL_COMPONENTS;
367
+
368
+ if (allVisualComponents.length > 0) {
369
+ componentsSpinner.text = `Installing ${allVisualComponents.length} starter Visual components...`;
370
+
371
+ visualResults = await registry.installMultipleComponents(
372
+ allVisualComponents,
373
+ 'Visual',
374
+ true // force = true for initial installation
375
+ );
376
+
377
+ const successful = visualResults.filter(r => r.success).length;
378
+ const failed = visualResults.filter(r => !r.success).length;
379
+
380
+ if (successful > 0 && failed === 0) {
381
+ componentsSpinner.succeed(`All ${successful} Visual components installed successfully`);
382
+ } else if (successful > 0) {
383
+ componentsSpinner.warn(`${successful} components installed, ${failed} failed`);
384
+ } else {
385
+ componentsSpinner.fail('Failed to install Visual components');
386
+ }
387
+ } else {
388
+ componentsSpinner.warn('No Visual components found in registry');
389
+ Print.info(`You can add components later using "${packageManager} run get -- <component-name>"`);
390
+ }
391
+
392
+ } catch (error) {
393
+ componentsSpinner.fail('Could not download Visual components from official repository');
394
+ Print.error(`Repository error: ${error.message}`);
395
+ Print.info('Project initialized without Visual components');
396
+ Print.info(`You can add them later using "${packageManager} run get -- <component-name>"`);
397
+ }
398
+
399
+ // 3b. DOWNLOAD STARTER SERVICE COMPONENTS FROM OFFICIAL REPOSITORY
400
+ let serviceResults = [];
401
+ const serviceSpinner = ora('Installing starter Service components...').start();
402
+ try {
403
+ const registry = new ComponentRegistry();
404
+ await registry.loadRegistry();
405
+
406
+ if (STARTER_SERVICE_COMPONENTS.length > 0) {
407
+ serviceSpinner.text = `Installing ${STARTER_SERVICE_COMPONENTS.length} starter Service components...`;
408
+
409
+ serviceResults = await registry.installMultipleComponents(
410
+ STARTER_SERVICE_COMPONENTS,
411
+ 'Service',
412
+ true // force = true for initial installation
413
+ );
414
+
415
+ const successful = serviceResults.filter(r => r.success).length;
416
+ const failed = serviceResults.filter(r => !r.success).length;
417
+
418
+ if (successful > 0 && failed === 0) {
419
+ serviceSpinner.succeed(`All ${successful} Service components installed successfully`);
420
+ } else if (successful > 0) {
421
+ serviceSpinner.warn(`${successful} Service components installed, ${failed} failed`);
422
+ } else {
423
+ serviceSpinner.fail('Failed to install Service components');
424
+ }
425
+ } else {
426
+ serviceSpinner.succeed('No starter Service components to install');
427
+ }
428
+ } catch (error) {
429
+ serviceSpinner.fail('Could not download Service components from official repository');
430
+ Print.error(`Repository error: ${error.message}`);
431
+ Print.info(`You can add them later using "${packageManager} run get -- <component-name>"`);
432
+ }
433
+
434
+ // 4. CONFIGURE SCRIPTS IN PROJECT package.json
435
+ const pkgSpinner = ora('Configuring npm scripts...').start();
436
+ try {
437
+ const projectRoot = getProjectRoot(import.meta.url);
438
+ const pkgPath = getPath(import.meta.url, 'package.json');
439
+
440
+ let pkg;
441
+ if (await fs.pathExists(pkgPath)) {
442
+ pkg = await fs.readJson(pkgPath);
443
+ } else {
444
+ pkg = {
445
+ name: path.basename(projectRoot),
446
+ version: '1.0.0',
447
+ description: 'Slice.js project',
448
+ main: 'api/index.js',
449
+ scripts: {}
450
+ };
451
+ }
452
+
453
+ pkg.scripts = pkg.scripts || {};
454
+ pkg.dependencies = pkg.dependencies || {};
455
+
456
+ // Main scripts (local CLI path, no global launcher dependency)
457
+ pkg.scripts['dev'] = SLICE_SCRIPTS['slice:dev'];
458
+ pkg.scripts['build'] = SLICE_SCRIPTS['slice:build'];
459
+ pkg.scripts['start'] = SLICE_SCRIPTS['slice:start'];
460
+
461
+ // Component management
462
+ pkg.scripts['component:create'] = SLICE_SCRIPTS['slice:create'];
463
+ pkg.scripts['component:list'] = SLICE_SCRIPTS['slice:list'];
464
+ pkg.scripts['component:delete'] = SLICE_SCRIPTS['slice:delete'];
465
+
466
+ // Registry shortcuts
467
+ pkg.scripts['get'] = SLICE_SCRIPTS['slice:get'];
468
+ pkg.scripts['browse'] = SLICE_SCRIPTS['slice:browse'];
469
+ pkg.scripts['sync'] = SLICE_SCRIPTS['slice:sync'];
470
+
471
+ // slice:* namespaced set — shared with `slice postinstall`
472
+ // (commands/utils/sliceScripts.js) so the three never drift apart.
473
+ Object.assign(pkg.scripts, SLICE_SCRIPTS);
474
+ pkg.scripts['run'] = SLICE_SCRIPTS['slice:dev'];
475
+
476
+ // Module configuration
477
+ pkg.type = 'module';
478
+ pkg.engines = pkg.engines || { node: '>=20.0.0' };
479
+
480
+ // Ensure framework dependency is present (the install above normally
481
+ // already wrote it; this is a fallback for the monorepo-sibling path).
482
+ if (!pkg.dependencies['slicejs-web-framework']) {
483
+ pkg.dependencies['slicejs-web-framework'] = installedVersion ? `^${installedVersion}` : 'latest';
484
+ }
485
+
486
+ await fs.writeFile(pkgPath, JSON.stringify(pkg, null, 2), 'utf8');
487
+ pkgSpinner.succeed('Package scripts configured successfully');
488
+
489
+ Print.title('New recommended commands:');
490
+ console.log(` ${packageManager} run dev - Start development server`);
491
+ console.log(` ${packageManager} run get - Install components`);
492
+ console.log(` ${packageManager} run browse - Browse components`);
493
+ } catch (error) {
494
+ pkgSpinner.fail('Failed to configure npm scripts');
495
+ Print.error(error.message);
496
+ console.error(error.stack);
497
+ }
498
+
499
+ const projectName = path.basename(process.cwd());
500
+
501
+ const failedCount = [...visualResults, ...serviceResults].filter(r => !r.success).length;
502
+ if (failedCount > 0) {
503
+ Print.warning(`${failedCount} component(s) failed to install — run "${packageManager} run get -- <name>" to retry`);
504
+ }
505
+
506
+ Print.success(`Project initialized successfully in "${projectName}/"`);
507
+ Print.newLine();
508
+ Print.title('Next steps:');
509
+ console.log(` cd ${projectName}`);
510
+ console.log(` ${packageManager} run dev - Start development server`);
511
+ console.log(` ${packageManager} run browse - View available components`);
512
+ console.log(` ${packageManager} run get -- Button - Install specific components`);
513
+ console.log(` ${packageManager} run sync - Update all components to latest versions`);
514
+ console.log(` slice setup lint --with-types - ESLint, type checking and the generated types`);
515
+
516
+ } catch (error) {
517
+ Print.error('Unexpected error initializing project:', error.message);
518
+ console.error(error.stack);
519
+ }
520
+ }
521
+
522
+ // NOTE: `slice init` installs only STARTER_VISUAL_COMPONENTS and
523
+ // STARTER_SERVICE_COMPONENTS (see top of file); both Visual and Service are pulled
524
+ // from the registry rather than vendored in the framework package.
525
+ // To install every registry component instead, iterate
526
+ // `Object.keys(registry.getAvailableComponents('Visual'))` (and likewise 'Service').