slicejs-cli 4.1.1 → 4.2.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.
@@ -0,0 +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
+ }
@@ -0,0 +1,201 @@
1
+ // Shared reporting for "this source file does not parse".
2
+ //
3
+ // Two places hit it — buildProduction minifying a file src/ -> dist/, and
4
+ // BundleGenerator preparing a component for a bundle — and each used to report
5
+ // it in its own way: Terser's `Unexpected token punc «(», expected punc «,»`
6
+ // with no location, or a position inside the *generated* bundle. Neither told
7
+ // the developer which line of their own file to look at.
8
+ import fs from 'fs-extra';
9
+ import path from 'path';
10
+ import { parse } from '@babel/parser';
11
+
12
+ /** Extensions a relative specifier is resolved against. */
13
+ export const RESOLVABLE_MODULE_EXTENSIONS = ['.js', '.json', '.mjs'];
14
+
15
+ /**
16
+ * Renders a few lines of source around a position, with a caret under it.
17
+ * Deliberately hand-rolled: @babel/code-frame is not a dependency, and this is
18
+ * all it needs to do.
19
+ *
20
+ * @param {string} code
21
+ * @param {number} line 1-based
22
+ * @param {number} column 0-based
23
+ * @returns {string}
24
+ */
25
+ export function formatSourceFrame(code, line, column) {
26
+ const lines = String(code).split('\n');
27
+ const first = Math.max(1, line - 2);
28
+ const last = Math.min(lines.length, line + 2);
29
+ const gutter = String(last).length;
30
+ const out = [];
31
+
32
+ for (let current = first; current <= last; current += 1) {
33
+ const marker = current === line ? '>' : ' ';
34
+ out.push(` ${marker} ${String(current).padStart(gutter)} | ${lines[current - 1]}`);
35
+ if (current === line) {
36
+ out.push(` ${' '.repeat(gutter)} | ${' '.repeat(Math.max(0, column))}^`);
37
+ }
38
+ }
39
+ return out.join('\n');
40
+ }
41
+
42
+ /**
43
+ * Parses `code`, returning a readable diagnostic when it fails.
44
+ *
45
+ * @param {string} code
46
+ * @param {string} filePath shown in the message
47
+ * @returns {{ok: true} | {ok: false, message: string, line: number|null, column: number|null}}
48
+ */
49
+ export function describeSyntaxError(code, filePath) {
50
+ try {
51
+ parse(code, { sourceType: 'module', plugins: ['jsx'] });
52
+ return { ok: true };
53
+ } catch (error) {
54
+ const line = error.loc?.line ?? null;
55
+ const column = error.loc?.column ?? 0;
56
+ const where = line ? `${filePath}:${line}:${column + 1}` : filePath;
57
+ // Babel appends its own "(line:col)"; drop it, the location is already
58
+ // stated above in a form editors can jump to.
59
+ const detail = String(error.message).replace(/\s*\(\d+:\d+\)\s*$/, '');
60
+ const frame = line ? `\n\n${formatSourceFrame(code, line, column)}\n` : '';
61
+
62
+ return {
63
+ ok: false,
64
+ line,
65
+ column,
66
+ message: `${where}: ${detail}.${frame}`
67
+ };
68
+ }
69
+ }
70
+
71
+ /**
72
+ * Resolves a relative specifier the way the bundler does.
73
+ * @param {string} specifier
74
+ * @param {string} fromDir
75
+ * @returns {string|null} absolute path, or null when nothing matches
76
+ */
77
+ export function resolveRelativeSpecifier(specifier, fromDir) {
78
+ const resolved = path.resolve(fromDir, specifier);
79
+ if (!path.extname(resolved)) {
80
+ for (const extension of RESOLVABLE_MODULE_EXTENSIONS) {
81
+ if (fs.existsSync(resolved + extension)) return resolved + extension;
82
+ }
83
+ }
84
+ return fs.existsSync(resolved) ? resolved : null;
85
+ }
86
+
87
+ /**
88
+ * Relative imports that name a JavaScript module and resolve to nothing.
89
+ *
90
+ * Only module-like specifiers are reported — extensionless, or one of
91
+ * RESOLVABLE_MODULE_EXTENSIONS. A relative asset import has its own delivery
92
+ * story and is not the bundler's business.
93
+ *
94
+ * @param {string} code
95
+ * @param {string} fromDir directory the specifiers resolve against
96
+ * @returns {string[]} unresolved specifiers, in source order
97
+ */
98
+ export function findUnresolvedRelativeImports(code, fromDir) {
99
+ let ast;
100
+ try {
101
+ ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
102
+ } catch {
103
+ return []; // unparseable: describeSyntaxError reports that instead
104
+ }
105
+
106
+ const unresolved = [];
107
+ for (const node of ast.program.body) {
108
+ const isImportLike = node.type === 'ImportDeclaration'
109
+ || node.type === 'ExportNamedDeclaration'
110
+ || node.type === 'ExportAllDeclaration';
111
+ const specifier = isImportLike ? node.source?.value : null;
112
+ if (typeof specifier !== 'string') continue;
113
+ if (!specifier.startsWith('./') && !specifier.startsWith('../')) continue;
114
+
115
+ const ext = path.extname(specifier);
116
+ const moduleLike = ext === '' || RESOLVABLE_MODULE_EXTENSIONS.includes(ext);
117
+ if (!moduleLike) continue;
118
+
119
+ if (!resolveRelativeSpecifier(specifier, fromDir)) unresolved.push(specifier);
120
+ }
121
+ return unresolved;
122
+ }
123
+
124
+ /**
125
+ * True when the module has a default export.
126
+ *
127
+ * Slice loads a component with `const { default: myClass } = await import(...)`
128
+ * (Slice.getClass), so a component without one can never be built.
129
+ *
130
+ * @param {string} code
131
+ * @returns {boolean|null} null when the source does not parse
132
+ */
133
+ export function hasDefaultExport(code) {
134
+ try {
135
+ const ast = parse(code, { sourceType: 'module', plugins: ['jsx'] });
136
+ return ast.program.body.some((node) => node.type === 'ExportDefaultDeclaration');
137
+ } catch {
138
+ return null;
139
+ }
140
+ }
141
+
142
+ /**
143
+ * `slice.build('Name')` calls whose component is not in the registry.
144
+ *
145
+ * `slice.build` resolves a component by its registered name, so a typo returns
146
+ * null and the component simply never renders — the framework logs
147
+ * "Component X not found in components.js file" and carries on. Catching it at
148
+ * build time is the closest thing to a "module not found".
149
+ *
150
+ * Deliberately narrow:
151
+ * - only a `slice.build(...)` receiver (not an arbitrary `.build()` method),
152
+ * - only a string-literal first argument (a computed name cannot be checked),
153
+ * - `getComponent` is NOT checked: it takes a sliceId, which is arbitrary
154
+ * (`slice.getComponent('appTopbar')`), not a component name.
155
+ *
156
+ * @param {string} code
157
+ * @param {Set<string>} registeredNames
158
+ * @returns {string[]} unknown component names, deduped, in source order
159
+ */
160
+ export function findUnknownComponentBuilds(code, registeredNames) {
161
+ let ast;
162
+ try {
163
+ ast = parse(code, { sourceType: 'module', plugins: ['jsx', 'classProperties'] });
164
+ } catch {
165
+ return [];
166
+ }
167
+
168
+ const unknown = [];
169
+ const seen = new Set();
170
+
171
+ const isSliceBuildCallee = (callee) => {
172
+ if (!callee || callee.type !== 'MemberExpression') return false;
173
+ if (callee.property?.name !== 'build') return false;
174
+ const object = callee.object;
175
+ if (object?.type === 'Identifier') return object.name === 'slice';
176
+ // window.slice.build(...)
177
+ return object?.type === 'MemberExpression' && object.property?.name === 'slice';
178
+ };
179
+
180
+ const walk = (node) => {
181
+ if (!node || typeof node !== 'object') return;
182
+ if (Array.isArray(node)) {
183
+ for (const child of node) walk(child);
184
+ return;
185
+ }
186
+ if (node.type === 'CallExpression' && isSliceBuildCallee(node.callee)) {
187
+ const first = node.arguments?.[0];
188
+ if (first?.type === 'StringLiteral' && !registeredNames.has(first.value) && !seen.has(first.value)) {
189
+ seen.add(first.value);
190
+ unknown.push(first.value);
191
+ }
192
+ }
193
+ for (const key of Object.keys(node)) {
194
+ if (key === 'loc' || key === 'start' || key === 'end') continue;
195
+ walk(node[key]);
196
+ }
197
+ };
198
+
199
+ walk(ast.program.body);
200
+ return unknown;
201
+ }