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,230 +1,230 @@
1
- // Single entry point for every JavaScript minification the CLI performs.
2
- //
3
- // Terser used to be called from three places with three hand-written option
4
- // objects, and they had drifted:
5
- //
6
- // buildProduction.minifyJavaScript parse ecma 2022, no `module`
7
- // buildProduction.processComponentsFile no ecma at all, no `module`
8
- // BundleGenerator.applyBundleTransforms parse+format ecma 2022, no `module`
9
- //
10
- // The missing `module` flag meant Terser parsed sources in script mode, where
11
- // top-level `await` is a syntax error — every build printed
12
- // `Unexpected token: name (...)` for App/index.js and shipped it unminified.
13
- // Fixing that in one call site would have left the other two behind, which is
14
- // exactly how the drift happened in the first place.
15
- //
16
- // So: the invariants (ECMA level, name preservation, comment stripping, module
17
- // parsing) live here once, each caller picks a *profile* for what it is
18
- // minifying, and nothing outside this module imports terser.
19
- import { minify as terserMinify } from 'terser';
20
-
21
- /** ECMA level used for parsing, compressing and formatting, everywhere. */
22
- export const TERSER_ECMA = 2022;
23
-
24
- /**
25
- * Identifiers Terser must never rename. Slice resolves a lot by name at
26
- * runtime (component classes, lifecycle hooks, framework internals reached
27
- * through `slice.*`), so renaming any of these breaks the app silently.
28
- */
29
- export const RESERVED_NAMES = Object.freeze([
30
- // Core Slice
31
- 'slice', 'Slice', 'SliceJS', 'window', 'document',
32
- // Main classes
33
- 'Controller', 'StylesManager', 'Router', 'Logger', 'Debugger',
34
- // Slice methods
35
- 'getClass', 'isProduction', 'getComponent', 'build', 'setTheme', 'attachTemplate',
36
- // Controller
37
- 'componentCategories', 'templates', 'classes', 'requestedStyles', 'activeComponents',
38
- 'registerComponent', 'registerComponentsRecursively', 'loadTemplateToComponent',
39
- 'fetchText', 'setComponentProps', 'verifyComponentIds', 'destroyComponent',
40
- // StylesManager
41
- 'componentStyles', 'themeManager', 'init', 'appendComponentStyles', 'registerComponentStyles',
42
- // Router
43
- 'routes', 'pathToRouteMap', 'activeRoute', 'navigate', 'matchRoute', 'handleRoute',
44
- 'onRouteChange', 'loadInitialRoute', 'renderRoutesComponentsInPage',
45
- // Component properties
46
- 'sliceId', 'sliceType', 'sliceConfig', 'debuggerProps', 'parentComponent',
47
- 'value', 'customColor', 'icon', 'layout', 'view', 'items', 'columns', 'rows',
48
- 'onClickCallback', 'props',
49
- // Custom Elements
50
- 'customElements', 'define', 'HTMLElement',
51
- // Critical DOM APIs
52
- 'addEventListener', 'removeEventListener', 'querySelector', 'querySelectorAll',
53
- 'appendChild', 'removeChild', 'innerHTML', 'textContent', 'style', 'classList',
54
- // Lifecycle
55
- 'beforeMount', 'afterMount', 'beforeDestroy', 'afterDestroy',
56
- 'mount', 'unmount', 'destroy', 'update', 'start', 'stop',
57
- // Browser APIs
58
- 'fetch', 'setTimeout', 'clearTimeout', 'localStorage', 'history', 'pushState',
59
- // Exports/Imports
60
- 'default', 'export', 'import', 'from', 'await', 'async',
61
- // Component names
62
- 'Button', 'Grid', 'Layout', 'HomePage', 'NotFound', 'Loading', 'TreeView', 'Link',
63
- 'FetchManager'
64
- ]);
65
-
66
- /**
67
- * Options every profile shares. Kept in one place so a bump to the ECMA level
68
- * or a change in name preservation cannot reach one code path and miss another.
69
- * @returns {object}
70
- */
71
- function baseOptions() {
72
- return {
73
- parse: { ecma: TERSER_ECMA },
74
- ecma: TERSER_ECMA,
75
- // Slice looks components up by class name and hooks by function name.
76
- keep_fnames: true,
77
- keep_classnames: true,
78
- format: {
79
- comments: false,
80
- ecma: TERSER_ECMA
81
- }
82
- };
83
- }
84
-
85
- /**
86
- * Profile for an individual source file copied src/ -> dist/.
87
- * @returns {object}
88
- */
89
- export function sourceFileOptions() {
90
- const options = baseOptions();
91
- return {
92
- ...options,
93
- compress: {
94
- drop_console: false,
95
- drop_debugger: true,
96
- pure_funcs: [],
97
- passes: 1,
98
- // Slice components are reached by name at runtime, so Terser cannot see
99
- // every use site — dropping "unused" code or reordering side effects
100
- // would remove things the framework still needs.
101
- unused: false,
102
- side_effects: false,
103
- reduce_vars: false,
104
- collapse_vars: false
105
- },
106
- mangle: {
107
- reserved: [...RESERVED_NAMES],
108
- // Off, matching the bundle profile.
109
- //
110
- // af946f8 turned this off for bundles because Terser renames a property
111
- // access but cannot see inside a string literal, so a library doing
112
- // `obj['_rep']` broke. It only changed BundleGenerator, leaving source
113
- // files mangling `/^_/` — and the two generators write the same dist/.
114
- // The result was one method with two names: `_loadNotes` stayed itself
115
- // inside dist/bundles/*.js and became `ki` in
116
- // dist/Components/**/ConsensoService.js, so a component loaded from the
117
- // individual file could not call one loaded from a bundle.
118
- //
119
- // Measured on Conclave the saving was 3.8% of dist/Components (608KB ->
120
- // 631KB), on files the runtime only reads when a component is in no bundle
121
- // at all. Not worth a whole class of name-mismatch bugs.
122
- properties: false
123
- },
124
- format: {
125
- ...options.format,
126
- beautify: false
127
- }
128
- };
129
- }
130
-
131
- /**
132
- * Profile for the components.js registry. The runtime parses this file's shape,
133
- * so nothing is compressed or renamed — only whitespace and comments go.
134
- * @returns {object}
135
- */
136
- export function componentsRegistryOptions() {
137
- const options = baseOptions();
138
- return {
139
- ...options,
140
- compress: false,
141
- mangle: false,
142
- format: {
143
- ...options.format,
144
- beautify: false,
145
- indent_level: 0
146
- }
147
- };
148
- }
149
-
150
- /**
151
- * Profile for a generated bundle.
152
- * @param {object} [config]
153
- * @param {boolean} [config.minify] run the compress pass
154
- * @param {boolean} [config.obfuscate] run the mangle pass
155
- * @param {boolean} [config.sourcemap] emit a source map
156
- * @param {string} [config.fileName] bundle file name, for the source map
157
- * @returns {object}
158
- */
159
- export function bundleOptions({ minify = false, obfuscate = false, sourcemap = false, fileName = null } = {}) {
160
- const options = baseOptions();
161
- return {
162
- ...options,
163
- compress: minify ? {
164
- drop_console: false,
165
- drop_debugger: true,
166
- passes: 1
167
- } : false,
168
- mangle: obfuscate ? {
169
- // Bundle-wide property mangling breaks vendor libraries whose property
170
- // names also appear in string literals (see the same regression test).
171
- properties: false,
172
- // `module: true` would otherwise turn top-level mangling on and rename
173
- // the factory/template bindings. Pinned off so enabling module parsing
174
- // does not silently change what obfuscated bundles look like.
175
- toplevel: false
176
- } : false,
177
- // Map the minified output back to the readable pre-minified bundle
178
- // (embedded via includeSources so DevTools shows it without a sidecar
179
- // source). The URL comment is appended by the caller.
180
- ...(sourcemap ? { sourceMap: { includeSources: true, filename: fileName } } : {})
181
- };
182
- }
183
-
184
- function unwrap(result) {
185
- if (result.error) {
186
- throw result.error instanceof Error ? result.error : new Error(String(result.error));
187
- }
188
- return result;
189
- }
190
-
191
- /**
192
- * Runs Terser over ES-module JavaScript.
193
- *
194
- * Everything the CLI minifies is an ES module, and module-only syntax
195
- * (top-level `await`, top-level `await import()`) needs `module: true` to parse
196
- * at all. A project can still hold a classic script that only parses in sloppy
197
- * mode (`with`, octal literals), so a failed module parse retries in script
198
- * mode instead of failing the build.
199
- *
200
- * Takes a FACTORY, not an options object, because Terser writes into the object
201
- * it is handed: it sets `parse.module` and parks the parsed AST on
202
- * `parse.toplevel`. Sharing one object between the two attempts leaked
203
- * `module: true` into the fallback (so the fallback silently never applied),
204
- * and sharing it between files would hand Terser the previous file's AST
205
- * instead of the new source. Every attempt gets a freshly built object.
206
- *
207
- * @param {string} code
208
- * @param {() => object} createOptions one of the profile factories above
209
- * @returns {Promise<{code: string, map: string|undefined}>}
210
- * @throws {Error} when neither parse mode succeeds, or Terser reports an error
211
- */
212
- export async function minifyJs(code, createOptions) {
213
- if (typeof createOptions !== 'function') {
214
- throw new TypeError('minifyJs expects an options factory, not an options object (Terser mutates it)');
215
- }
216
-
217
- try {
218
- return unwrap(await terserMinify(code, { ...createOptions(), module: true }));
219
- } catch (moduleParseError) {
220
- try {
221
- return unwrap(await terserMinify(code, createOptions()));
222
- } catch (scriptParseError) {
223
- // Script mode is the last word, so its error is the one reported — but
224
- // keep the module-mode failure reachable, since for an actual ES module
225
- // that is the message that explains the real problem.
226
- scriptParseError.cause = moduleParseError;
227
- throw scriptParseError;
228
- }
229
- }
230
- }
1
+ // Single entry point for every JavaScript minification the CLI performs.
2
+ //
3
+ // Terser used to be called from three places with three hand-written option
4
+ // objects, and they had drifted:
5
+ //
6
+ // buildProduction.minifyJavaScript parse ecma 2022, no `module`
7
+ // buildProduction.processComponentsFile no ecma at all, no `module`
8
+ // BundleGenerator.applyBundleTransforms parse+format ecma 2022, no `module`
9
+ //
10
+ // The missing `module` flag meant Terser parsed sources in script mode, where
11
+ // top-level `await` is a syntax error — every build printed
12
+ // `Unexpected token: name (...)` for App/index.js and shipped it unminified.
13
+ // Fixing that in one call site would have left the other two behind, which is
14
+ // exactly how the drift happened in the first place.
15
+ //
16
+ // So: the invariants (ECMA level, name preservation, comment stripping, module
17
+ // parsing) live here once, each caller picks a *profile* for what it is
18
+ // minifying, and nothing outside this module imports terser.
19
+ import { minify as terserMinify } from 'terser';
20
+
21
+ /** ECMA level used for parsing, compressing and formatting, everywhere. */
22
+ export const TERSER_ECMA = 2022;
23
+
24
+ /**
25
+ * Identifiers Terser must never rename. Slice resolves a lot by name at
26
+ * runtime (component classes, lifecycle hooks, framework internals reached
27
+ * through `slice.*`), so renaming any of these breaks the app silently.
28
+ */
29
+ export const RESERVED_NAMES = Object.freeze([
30
+ // Core Slice
31
+ 'slice', 'Slice', 'SliceJS', 'window', 'document',
32
+ // Main classes
33
+ 'Controller', 'StylesManager', 'Router', 'Logger', 'Debugger',
34
+ // Slice methods
35
+ 'getClass', 'isProduction', 'getComponent', 'build', 'setTheme', 'attachTemplate',
36
+ // Controller
37
+ 'componentCategories', 'templates', 'classes', 'requestedStyles', 'activeComponents',
38
+ 'registerComponent', 'registerComponentsRecursively', 'loadTemplateToComponent',
39
+ 'fetchText', 'setComponentProps', 'verifyComponentIds', 'destroyComponent',
40
+ // StylesManager
41
+ 'componentStyles', 'themeManager', 'init', 'appendComponentStyles', 'registerComponentStyles',
42
+ // Router
43
+ 'routes', 'pathToRouteMap', 'activeRoute', 'navigate', 'matchRoute', 'handleRoute',
44
+ 'onRouteChange', 'loadInitialRoute', 'renderRoutesComponentsInPage',
45
+ // Component properties
46
+ 'sliceId', 'sliceType', 'sliceConfig', 'debuggerProps', 'parentComponent',
47
+ 'value', 'customColor', 'icon', 'layout', 'view', 'items', 'columns', 'rows',
48
+ 'onClickCallback', 'props',
49
+ // Custom Elements
50
+ 'customElements', 'define', 'HTMLElement',
51
+ // Critical DOM APIs
52
+ 'addEventListener', 'removeEventListener', 'querySelector', 'querySelectorAll',
53
+ 'appendChild', 'removeChild', 'innerHTML', 'textContent', 'style', 'classList',
54
+ // Lifecycle
55
+ 'beforeMount', 'afterMount', 'beforeDestroy', 'afterDestroy',
56
+ 'mount', 'unmount', 'destroy', 'update', 'start', 'stop',
57
+ // Browser APIs
58
+ 'fetch', 'setTimeout', 'clearTimeout', 'localStorage', 'history', 'pushState',
59
+ // Exports/Imports
60
+ 'default', 'export', 'import', 'from', 'await', 'async',
61
+ // Component names
62
+ 'Button', 'Grid', 'Layout', 'HomePage', 'NotFound', 'Loading', 'TreeView', 'Link',
63
+ 'FetchManager'
64
+ ]);
65
+
66
+ /**
67
+ * Options every profile shares. Kept in one place so a bump to the ECMA level
68
+ * or a change in name preservation cannot reach one code path and miss another.
69
+ * @returns {object}
70
+ */
71
+ function baseOptions() {
72
+ return {
73
+ parse: { ecma: TERSER_ECMA },
74
+ ecma: TERSER_ECMA,
75
+ // Slice looks components up by class name and hooks by function name.
76
+ keep_fnames: true,
77
+ keep_classnames: true,
78
+ format: {
79
+ comments: false,
80
+ ecma: TERSER_ECMA
81
+ }
82
+ };
83
+ }
84
+
85
+ /**
86
+ * Profile for an individual source file copied src/ -> dist/.
87
+ * @returns {object}
88
+ */
89
+ export function sourceFileOptions() {
90
+ const options = baseOptions();
91
+ return {
92
+ ...options,
93
+ compress: {
94
+ drop_console: false,
95
+ drop_debugger: true,
96
+ pure_funcs: [],
97
+ passes: 1,
98
+ // Slice components are reached by name at runtime, so Terser cannot see
99
+ // every use site — dropping "unused" code or reordering side effects
100
+ // would remove things the framework still needs.
101
+ unused: false,
102
+ side_effects: false,
103
+ reduce_vars: false,
104
+ collapse_vars: false
105
+ },
106
+ mangle: {
107
+ reserved: [...RESERVED_NAMES],
108
+ // Off, matching the bundle profile.
109
+ //
110
+ // af946f8 turned this off for bundles because Terser renames a property
111
+ // access but cannot see inside a string literal, so a library doing
112
+ // `obj['_rep']` broke. It only changed BundleGenerator, leaving source
113
+ // files mangling `/^_/` — and the two generators write the same dist/.
114
+ // The result was one method with two names: `_loadNotes` stayed itself
115
+ // inside dist/bundles/*.js and became `ki` in
116
+ // dist/Components/**/ConsensoService.js, so a component loaded from the
117
+ // individual file could not call one loaded from a bundle.
118
+ //
119
+ // Measured on Conclave the saving was 3.8% of dist/Components (608KB ->
120
+ // 631KB), on files the runtime only reads when a component is in no bundle
121
+ // at all. Not worth a whole class of name-mismatch bugs.
122
+ properties: false
123
+ },
124
+ format: {
125
+ ...options.format,
126
+ beautify: false
127
+ }
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Profile for the components.js registry. The runtime parses this file's shape,
133
+ * so nothing is compressed or renamed — only whitespace and comments go.
134
+ * @returns {object}
135
+ */
136
+ export function componentsRegistryOptions() {
137
+ const options = baseOptions();
138
+ return {
139
+ ...options,
140
+ compress: false,
141
+ mangle: false,
142
+ format: {
143
+ ...options.format,
144
+ beautify: false,
145
+ indent_level: 0
146
+ }
147
+ };
148
+ }
149
+
150
+ /**
151
+ * Profile for a generated bundle.
152
+ * @param {object} [config]
153
+ * @param {boolean} [config.minify] run the compress pass
154
+ * @param {boolean} [config.obfuscate] run the mangle pass
155
+ * @param {boolean} [config.sourcemap] emit a source map
156
+ * @param {string} [config.fileName] bundle file name, for the source map
157
+ * @returns {object}
158
+ */
159
+ export function bundleOptions({ minify = false, obfuscate = false, sourcemap = false, fileName = null } = {}) {
160
+ const options = baseOptions();
161
+ return {
162
+ ...options,
163
+ compress: minify ? {
164
+ drop_console: false,
165
+ drop_debugger: true,
166
+ passes: 1
167
+ } : false,
168
+ mangle: obfuscate ? {
169
+ // Bundle-wide property mangling breaks vendor libraries whose property
170
+ // names also appear in string literals (see the same regression test).
171
+ properties: false,
172
+ // `module: true` would otherwise turn top-level mangling on and rename
173
+ // the factory/template bindings. Pinned off so enabling module parsing
174
+ // does not silently change what obfuscated bundles look like.
175
+ toplevel: false
176
+ } : false,
177
+ // Map the minified output back to the readable pre-minified bundle
178
+ // (embedded via includeSources so DevTools shows it without a sidecar
179
+ // source). The URL comment is appended by the caller.
180
+ ...(sourcemap ? { sourceMap: { includeSources: true, filename: fileName } } : {})
181
+ };
182
+ }
183
+
184
+ function unwrap(result) {
185
+ if (result.error) {
186
+ throw result.error instanceof Error ? result.error : new Error(String(result.error));
187
+ }
188
+ return result;
189
+ }
190
+
191
+ /**
192
+ * Runs Terser over ES-module JavaScript.
193
+ *
194
+ * Everything the CLI minifies is an ES module, and module-only syntax
195
+ * (top-level `await`, top-level `await import()`) needs `module: true` to parse
196
+ * at all. A project can still hold a classic script that only parses in sloppy
197
+ * mode (`with`, octal literals), so a failed module parse retries in script
198
+ * mode instead of failing the build.
199
+ *
200
+ * Takes a FACTORY, not an options object, because Terser writes into the object
201
+ * it is handed: it sets `parse.module` and parks the parsed AST on
202
+ * `parse.toplevel`. Sharing one object between the two attempts leaked
203
+ * `module: true` into the fallback (so the fallback silently never applied),
204
+ * and sharing it between files would hand Terser the previous file's AST
205
+ * instead of the new source. Every attempt gets a freshly built object.
206
+ *
207
+ * @param {string} code
208
+ * @param {() => object} createOptions one of the profile factories above
209
+ * @returns {Promise<{code: string, map: string|undefined}>}
210
+ * @throws {Error} when neither parse mode succeeds, or Terser reports an error
211
+ */
212
+ export async function minifyJs(code, createOptions) {
213
+ if (typeof createOptions !== 'function') {
214
+ throw new TypeError('minifyJs expects an options factory, not an options object (Terser mutates it)');
215
+ }
216
+
217
+ try {
218
+ return unwrap(await terserMinify(code, { ...createOptions(), module: true }));
219
+ } catch (moduleParseError) {
220
+ try {
221
+ return unwrap(await terserMinify(code, createOptions()));
222
+ } catch (scriptParseError) {
223
+ // Script mode is the last word, so its error is the one reported — but
224
+ // keep the module-mode failure reachable, since for an actual ES module
225
+ // that is the message that explains the real problem.
226
+ scriptParseError.cause = moduleParseError;
227
+ throw scriptParseError;
228
+ }
229
+ }
230
+ }
@@ -1,53 +1,78 @@
1
- import fs from 'node:fs';
2
- import path from 'node:path';
3
-
4
- function getParentDirectory(dir) {
5
- const parent = path.dirname(dir);
6
- return parent === dir ? null : parent;
7
- }
8
-
9
- export function isLocalDelegationDisabled(env = process.env) {
10
- return env.SLICE_NO_LOCAL_DELEGATION === '1';
11
- }
12
-
13
- export function findNearestLocalCliEntry(startDirectory, resolveCandidate) {
14
- if (!startDirectory || typeof resolveCandidate !== 'function') {
15
- return null;
16
- }
17
-
18
- let current = path.resolve(startDirectory);
19
- while (current) {
20
- const candidate = resolveCandidate(current);
21
- if (candidate) {
22
- return candidate;
23
- }
24
- current = getParentDirectory(current);
25
- }
26
-
27
- return null;
28
- }
29
-
30
- export function resolveLocalCliCandidate(directory) {
31
- const candidate = path.join(directory, 'node_modules', 'slicejs-cli', 'client.js');
32
-
33
- try {
34
- const stats = fs.statSync(candidate);
35
- return stats.isFile() ? candidate : null;
36
- } catch {
37
- return null;
38
- }
39
- }
40
-
41
- export function shouldDelegateToLocalCli(currentEntryPath, localEntryPath) {
42
- if (!localEntryPath) {
43
- return false;
44
- }
45
-
46
- try {
47
- const currentReal = fs.realpathSync(currentEntryPath);
48
- const localReal = fs.realpathSync(localEntryPath);
49
- return currentReal !== localReal;
50
- } catch {
51
- return path.resolve(currentEntryPath) !== path.resolve(localEntryPath);
52
- }
53
- }
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+
4
+ function getParentDirectory(dir) {
5
+ const parent = path.dirname(dir);
6
+ return parent === dir ? null : parent;
7
+ }
8
+
9
+ export function isLocalDelegationDisabled(env = process.env) {
10
+ return env.SLICE_NO_LOCAL_DELEGATION === '1';
11
+ }
12
+
13
+ /**
14
+ * The first positional token of the invocation (`init`, `build`, …), skipping
15
+ * flags. `null` when the argv carries no command (`--version`, `--help`).
16
+ */
17
+ export function commandNameFromArgv(argv = process.argv.slice(2)) {
18
+ const command = argv.find((arg) => typeof arg === 'string' && !arg.startsWith('-'));
19
+ return command || null;
20
+ }
21
+
22
+ /**
23
+ * Commands that must run on the CLI the user actually invoked.
24
+ *
25
+ * `init` creates a project somewhere else, so resolving "which CLI" by walking
26
+ * up from the current folder is meaningless and harmful: a subdirectory of any
27
+ * existing Slice project would run that project's (possibly old) CLI, and a
28
+ * `pnpm dlx slicejs-cli@latest init` would silently use the local version
29
+ * instead of the one the user asked for. Everything else may delegate: there,
30
+ * matching the project's pinned version is exactly the point.
31
+ */
32
+ const NON_DELEGATING_COMMANDS = new Set(['init']);
33
+
34
+ export function isNonDelegatingCommand(argv = process.argv.slice(2)) {
35
+ return NON_DELEGATING_COMMANDS.has(commandNameFromArgv(argv));
36
+ }
37
+
38
+ export function findNearestLocalCliEntry(startDirectory, resolveCandidate) {
39
+ if (!startDirectory || typeof resolveCandidate !== 'function') {
40
+ return null;
41
+ }
42
+
43
+ let current = path.resolve(startDirectory);
44
+ while (current) {
45
+ const candidate = resolveCandidate(current);
46
+ if (candidate) {
47
+ return candidate;
48
+ }
49
+ current = getParentDirectory(current);
50
+ }
51
+
52
+ return null;
53
+ }
54
+
55
+ export function resolveLocalCliCandidate(directory) {
56
+ const candidate = path.join(directory, 'node_modules', 'slicejs-cli', 'client.js');
57
+
58
+ try {
59
+ const stats = fs.statSync(candidate);
60
+ return stats.isFile() ? candidate : null;
61
+ } catch {
62
+ return null;
63
+ }
64
+ }
65
+
66
+ export function shouldDelegateToLocalCli(currentEntryPath, localEntryPath) {
67
+ if (!localEntryPath) {
68
+ return false;
69
+ }
70
+
71
+ try {
72
+ const currentReal = fs.realpathSync(currentEntryPath);
73
+ const localReal = fs.realpathSync(localEntryPath);
74
+ return currentReal !== localReal;
75
+ } catch {
76
+ return path.resolve(currentEntryPath) !== path.resolve(localEntryPath);
77
+ }
78
+ }