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
@@ -0,0 +1,130 @@
1
+ // Shared plumbing for the `slice seo` commands: locating the project's
2
+ // framework, reading the manifest, and writing a file without ever clobbering
3
+ // one silently.
4
+
5
+ import fs from 'node:fs';
6
+ import fsp from 'node:fs/promises';
7
+ import path from 'node:path';
8
+ import { pathToFileURL } from 'node:url';
9
+ import { getProjectRoot } from '../utils/PathHelper.js';
10
+
11
+ export const MANIFEST_FILE = 'seo.json';
12
+ export const SITEMAP_FILE = path.join('src', 'public', 'sitemap.xml');
13
+ export const ROBOTS_FILE = path.join('src', 'public', 'robots.txt');
14
+
15
+ export const resolveRoot = (moduleUrl) => getProjectRoot(moduleUrl);
16
+
17
+ /**
18
+ * The validator and the builders live in the framework, so the rules cannot
19
+ * drift between `slice seo check`, `slice doctor` and the server. Resolve it
20
+ * from the project first: that is the version the app actually runs.
21
+ */
22
+ export async function loadFrameworkSeo(projectRoot) {
23
+ const seoPath = path.join(projectRoot, 'node_modules', 'slicejs-web-framework', 'api', 'framework', 'seo.js');
24
+ if (fs.existsSync(seoPath)) {
25
+ return import(pathToFileURL(seoPath).href);
26
+ }
27
+ try {
28
+ return await import('slicejs-web-framework/api/framework/seo.js');
29
+ } catch (error) {
30
+ throw new Error(
31
+ `Cannot load the framework SEO module from ${projectRoot} ` +
32
+ `(${error.message}). Update slicejs-web-framework to a version that ships api/framework/seo.js.`,
33
+ { cause: error }
34
+ );
35
+ }
36
+ }
37
+
38
+ /**
39
+ * Find the manifest. Apps that hand-write it keep it at the project root; a
40
+ * generated pipeline writes it inside the deployed public/ folder, which is
41
+ * where the framework server looks too.
42
+ */
43
+ export function loadManifest(projectRoot) {
44
+ const candidates = [
45
+ path.join(projectRoot, MANIFEST_FILE),
46
+ path.join(projectRoot, 'src', 'public', MANIFEST_FILE),
47
+ path.join(projectRoot, 'dist', 'public', MANIFEST_FILE)
48
+ ];
49
+ const file = candidates.find((candidate) => fs.existsSync(candidate));
50
+ if (!file) return { file: candidates[0], manifest: null };
51
+ return { file, manifest: JSON.parse(fs.readFileSync(file, 'utf8')) };
52
+ }
53
+
54
+ /** Prompt only when there is a human: CI must fail, never hang. */
55
+ export async function promptYesNo(question, { defaultValue = false } = {}) {
56
+ const { createInterface } = await import('node:readline/promises');
57
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
58
+ try {
59
+ const suffix = defaultValue ? '[Y/n]' : '[y/N]';
60
+ const answer = (await rl.question(`${question} ${suffix} `)).trim().toLowerCase();
61
+ if (!answer) return defaultValue;
62
+ return answer === 'y' || answer === 'yes';
63
+ } finally {
64
+ rl.close();
65
+ }
66
+ }
67
+
68
+ const isInteractive = () => Boolean(process.stdin.isTTY && process.stdout.isTTY);
69
+
70
+ /**
71
+ * Write `content` to `file` unless that would clobber a different file without
72
+ * permission.
73
+ *
74
+ * Statuses: `created`, `unchanged` (nothing written, no mtime churn),
75
+ * `updated`, `skipped` (the user said no), `would-change` (dry run),
76
+ * `needs-confirmation` (no TTY and no --yes).
77
+ *
78
+ * @returns {Promise<{ status: string, file: string }>}
79
+ */
80
+ export async function writeFileConfirmed(file, content, options = {}) {
81
+ const { yes = false, dryRun = false, confirm = null } = options;
82
+
83
+ const exists = fs.existsSync(file);
84
+ const current = exists ? fs.readFileSync(file, 'utf8') : null;
85
+ if (current === content) return { status: 'unchanged', file };
86
+ if (!exists) {
87
+ if (!dryRun) await writeAtomic(file, content);
88
+ return { status: dryRun ? 'would-change' : 'created', file };
89
+ }
90
+
91
+ if (dryRun) return { status: 'would-change', file };
92
+ if (!yes) {
93
+ const allowed = confirm
94
+ ? await confirm(file)
95
+ : isInteractive()
96
+ ? await promptYesNo(`${file} already exists and would change. Overwrite it?`, { defaultValue: false })
97
+ : false;
98
+ if (!allowed) {
99
+ return { status: isInteractive() || confirm ? 'skipped' : 'needs-confirmation', file };
100
+ }
101
+ }
102
+
103
+ await writeAtomic(file, content);
104
+ return { status: 'updated', file };
105
+ }
106
+
107
+ async function writeAtomic(file, content) {
108
+ await fsp.mkdir(path.dirname(file), { recursive: true });
109
+ const tmp = `${file}.${process.pid}.tmp`;
110
+ await fsp.writeFile(tmp, content);
111
+ await fsp.rename(tmp, file);
112
+ }
113
+
114
+ /**
115
+ * `robots.txt` from the manifest. Returns null when the manifest does not ask
116
+ * for one, so a hand-written file is never touched.
117
+ */
118
+ export function buildRobotsTxt(manifest, origin) {
119
+ const config = manifest?.robotsTxt;
120
+ if (!config || config === false) return null;
121
+
122
+ const lines = ['User-agent: *'];
123
+ const allow = Array.isArray(config.allow) ? config.allow : [];
124
+ const disallow = Array.isArray(config.disallow) ? config.disallow : [];
125
+ if (!allow.length && !disallow.length) lines.push('Allow: /');
126
+ for (const entry of allow) lines.push(`Allow: ${entry}`);
127
+ for (const entry of disallow) lines.push(`Disallow: ${entry}`);
128
+ if (config.sitemap !== false) lines.push(`Sitemap: ${origin}/sitemap.xml`);
129
+ return `${lines.join('\n')}\n`;
130
+ }
@@ -0,0 +1,151 @@
1
+ // slice setup lint — add linting to a project that already exists.
2
+ //
3
+ // `slice init` does not decide this for you: ESLint is a choice (some projects
4
+ // use another linter, some none), and init only runs once. This command is
5
+ // idempotent, never overwrites an eslint config you wrote, and works on any
6
+ // Slice project.
7
+
8
+ import fs from 'fs-extra';
9
+ import path from 'node:path';
10
+ import { execSync } from 'node:child_process';
11
+ import Print from '../Print.js';
12
+ import { installCommand, resolvePackageManager } from '../utils/PackageManager.js';
13
+ import { runGenerateTypes } from '../types/types.js';
14
+
15
+ export const ESLINT_CONFIG_FILE = 'eslint.config.js';
16
+
17
+ /** The config written when the project has none. */
18
+ export const eslintConfigContent = `import slice from 'slicejs-cli/eslint-config.js';
19
+
20
+ export default [...slice];
21
+ `;
22
+
23
+ const LINT_SCRIPTS = {
24
+ lint: 'slice lint',
25
+ 'lint:fix': 'slice lint --fix'
26
+ };
27
+
28
+ const TYPE_SCRIPTS = {
29
+ // Same command init writes, so a project set up later has the script too.
30
+ 'slice:types': 'node ./node_modules/slicejs-cli/client.js types generate',
31
+ typecheck: 'slice typecheck'
32
+ };
33
+
34
+ const hasLocalPackage = (projectRoot, name) => fs.pathExistsSync(
35
+ path.join(projectRoot, 'node_modules', name, 'package.json')
36
+ );
37
+
38
+ /**
39
+ * Inspects, installs and writes. `runInstall` is injectable so the tests do not
40
+ * touch the network.
41
+ */
42
+ export async function setupLint({ projectRoot, dryRun = false, withTypes = false, runInstall = null }) {
43
+ const packagePath = path.join(projectRoot, 'package.json');
44
+ if (!(await fs.pathExists(packagePath))) {
45
+ return {
46
+ ok: false,
47
+ error: 'No package.json here. Run this from the root of a Slice project.',
48
+ actions: []
49
+ };
50
+ }
51
+
52
+ const pkg = await fs.readJson(packagePath);
53
+ const packageManager = resolvePackageManager(projectRoot).name;
54
+ const actions = [];
55
+
56
+ // 1. The tools the config and the command need, as devDependencies.
57
+ const required = withTypes ? ['eslint', 'slicejs-cli', 'typescript'] : ['eslint', 'slicejs-cli'];
58
+ const missing = required.filter((name) => !hasLocalPackage(projectRoot, name));
59
+ if (missing.length > 0) {
60
+ const command = installCommand(packageManager, missing.join(' '), { dev: true });
61
+ actions.push({ kind: 'install', detail: command });
62
+ if (!dryRun) {
63
+ if (runInstall) await runInstall(command);
64
+ else execSync(command, { cwd: projectRoot, stdio: 'inherit' });
65
+ }
66
+ }
67
+
68
+ // 2. The config, only when there is none. A project may have its own, and it
69
+ // may use another linter entirely: never overwrite it.
70
+ const configPath = path.join(projectRoot, ESLINT_CONFIG_FILE);
71
+ const hasConfig = await fs.pathExists(configPath);
72
+ if (!hasConfig) {
73
+ actions.push({ kind: 'write', detail: ESLINT_CONFIG_FILE });
74
+ if (!dryRun) await fs.writeFile(configPath, eslintConfigContent, 'utf8');
75
+ } else {
76
+ actions.push({ kind: 'keep', detail: `${ESLINT_CONFIG_FILE} already exists` });
77
+ }
78
+
79
+ // 3. Scripts, without clobbering what the project already wires.
80
+ const scripts = { ...(pkg.scripts || {}) };
81
+ const scriptChanges = [];
82
+ const wanted = withTypes ? { ...LINT_SCRIPTS, ...TYPE_SCRIPTS } : LINT_SCRIPTS;
83
+ for (const [name, command] of Object.entries(wanted)) {
84
+ if (scripts[name] === undefined) {
85
+ scripts[name] = command;
86
+ scriptChanges.push({ name, command });
87
+ } else if (scripts[name] !== command) {
88
+ actions.push({ kind: 'keep', detail: `script "${name}" already set to "${scripts[name]}"` });
89
+ }
90
+ }
91
+
92
+ if (scriptChanges.length > 0) {
93
+ actions.push({ kind: 'scripts', detail: scriptChanges.map((change) => `${change.name}: ${change.command}`).join(', ') });
94
+ if (!dryRun) {
95
+ await fs.writeJson(packagePath, { ...pkg, scripts }, { spaces: 2 });
96
+ }
97
+ }
98
+
99
+ // With TypeScript installed, generate the declarations and the jsconfig so
100
+ // `slice typecheck` works immediately. Only when the project has components.
101
+ if (withTypes && !dryRun && await fs.pathExists(path.join(projectRoot, 'src', 'Components', 'components.js'))) {
102
+ try {
103
+ await runGenerateTypes({
104
+ projectRoot,
105
+ outputPath: path.join(projectRoot, 'src', 'slice-build.generated.d.ts')
106
+ });
107
+ actions.push({ kind: 'types', detail: 'src/slice-build.generated.d.ts + jsconfig.json' });
108
+ } catch (error) {
109
+ actions.push({ kind: 'types-failed', detail: error.message });
110
+ }
111
+ }
112
+
113
+ return { ok: true, actions, dryRun };
114
+ }
115
+
116
+ export default async function setupLintCommand(options = {}, projectRoot) {
117
+ const dryRun = Boolean(options.dryRun);
118
+
119
+ let result;
120
+ try {
121
+ result = await setupLint({ projectRoot, dryRun, withTypes: Boolean(options.withTypes) });
122
+ } catch (error) {
123
+ Print.error('slice setup lint:', error.message);
124
+ process.exitCode = 1;
125
+ return false;
126
+ }
127
+
128
+ if (!result.ok) {
129
+ Print.error(result.error);
130
+ process.exitCode = 1;
131
+ return false;
132
+ }
133
+
134
+ for (const action of result.actions) {
135
+ if (action.kind === 'install') Print.info(`Install devDependencies: ${action.detail}`);
136
+ else if (action.kind === 'write') Print.success(`Created ${action.detail}`);
137
+ else if (action.kind === 'scripts') Print.success(`Added scripts: ${action.detail}`);
138
+ else if (action.kind === 'types') Print.success(`Generated declarations: ${action.detail}`);
139
+ else if (action.kind === 'types-failed') Print.warning(`Could not generate the declarations: ${action.detail}`);
140
+ else Print.info(action.detail);
141
+ }
142
+
143
+ if (dryRun) {
144
+ Print.info('Dry run: nothing was written.');
145
+ return true;
146
+ }
147
+
148
+ Print.newLine();
149
+ Print.success('Linting is set up. Run "slice lint" (or "npm run lint").');
150
+ return true;
151
+ }