slicejs-cli 3.8.1 → 4.0.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.
@@ -209,8 +209,13 @@ export default class DependencyAnalyzer {
209
209
  // Read JavaScript file
210
210
  const content = await fs.readFile(jsFile, 'utf-8');
211
211
 
212
- // Calculate size
213
- component.size = await this.calculateComponentSize(component.path);
212
+ // Calculate size. `size` is the whole component folder (used for stats);
213
+ // `codeSize` is only the code that actually goes into a bundle (js/html/css),
214
+ // which is what bundle budgeting must use — a large non-code asset in the
215
+ // folder (image, demo dataset) must not inflate a bundle's budgeted size.
216
+ const sizes = await this.calculateComponentSize(component.path);
217
+ component.size = sizes.total;
218
+ component.codeSize = sizes.code;
214
219
 
215
220
  // Parse and extract dependencies
216
221
  component.dependencies = await this.extractDependencies(content, jsFile);
@@ -345,6 +350,10 @@ export default class DependencyAnalyzer {
345
350
  */
346
351
  async extractDependencies(code, componentFilePath = null) {
347
352
  const dependencies = new Set();
353
+ // `path` is shadowed by the Babel NodePath param inside visitors, so derive
354
+ // the label here where `path` is still the node module.
355
+ const componentLabel = componentFilePath ? path.basename(componentFilePath) : '';
356
+ const warnedDynamicBuilds = new Set();
348
357
 
349
358
  const resolveRoutesArray = (node, scope) => {
350
359
  if (!node) return null;
@@ -699,14 +708,34 @@ export default class DependencyAnalyzer {
699
708
  addMultiRouteDependencies(routesArrayNode);
700
709
  }
701
710
  }
702
- // Regular slice.build() calls
711
+ // Regular slice.build() calls. Resolve the component name statically:
712
+ // a string literal, a template with no expressions, or an identifier /
713
+ // member that resolves to one of those (imported const, config object).
703
714
  else if (
704
715
  callee.type === 'MemberExpression' &&
705
716
  callee.object.name === 'slice' &&
706
- callee.property.name === 'build' &&
707
- args[0]?.type === 'StringLiteral'
717
+ callee.property.name === 'build'
708
718
  ) {
709
- dependencies.add(args[0].value);
719
+ const resolvedName = args[0] ? resolveStringValue(args[0], path.scope) : null;
720
+ if (resolvedName) {
721
+ dependencies.add(resolvedName);
722
+ } else if (args[0]) {
723
+ // The component name is computed at runtime, so it cannot be linked
724
+ // into the route/critical bundle graph. The component still loads
725
+ // individually at runtime — warn so it's not a silent optimization
726
+ // gap. Deduped per source expression within this component.
727
+ const snippet = typeof args[0].start === 'number'
728
+ ? code.slice(args[0].start, args[0].end)
729
+ : '<expr>';
730
+ const line = args[0].loc?.start?.line;
731
+ const key = `${snippet}@${line ?? '?'}`;
732
+ if (!warnedDynamicBuilds.has(key)) {
733
+ warnedDynamicBuilds.add(key);
734
+ const where = componentLabel ? ` in ${componentLabel}` : '';
735
+ const at = line ? `:${line}` : '';
736
+ console.warn(`⚠️ Dynamic slice.build(${snippet})${where}${at} — the component name is computed at runtime, so it can't be linked into a bundle. It will still load individually at runtime (no bundle optimization). Use a string literal or a resolvable constant to bundle it.`);
737
+ }
738
+ }
710
739
  }
711
740
  },
712
741
 
@@ -860,6 +889,7 @@ export default class DependencyAnalyzer {
860
889
  */
861
890
  async calculateComponentSize(componentPath) {
862
891
  let totalSize = 0;
892
+ let codeSize = 0;
863
893
  const files = await fs.readdir(componentPath);
864
894
 
865
895
  for (const file of files) {
@@ -868,10 +898,15 @@ export default class DependencyAnalyzer {
868
898
 
869
899
  if (stat.isFile()) {
870
900
  totalSize += stat.size;
901
+ // Only .js/.html/.css are inlined into a bundle; everything else in the
902
+ // folder is a sidecar asset that never contributes to the bundle size.
903
+ if (/\.(js|html|css)$/i.test(file)) {
904
+ codeSize += stat.size;
905
+ }
871
906
  }
872
907
  }
873
908
 
874
- return totalSize;
909
+ return { total: totalSize, code: codeSize };
875
910
  }
876
911
 
877
912
  /**
@@ -0,0 +1,298 @@
1
+ // commands/utils/bundling/ExternalModuleBundler.js
2
+ //
3
+ // Internal wrapper around esbuild used to resolve and bundle bare package
4
+ // imports (e.g. `import dayjs from 'dayjs'`) from the project's node_modules
5
+ // into a single, self-contained module string that the Slice bundle runtime
6
+ // can evaluate.
7
+ //
8
+ // Design notes:
9
+ // - esbuild does the hard parts we deliberately do NOT reimplement by hand:
10
+ // Node resolution (package.json exports/main/module, index fallback,
11
+ // nested node_modules), CommonJS <-> ESM interop, transitive third-party
12
+ // graph, and tree-shaking.
13
+ // - Output format is CJS. esbuild wraps the virtual entry's exports onto a
14
+ // `module.exports` object; we evaluate that inside an IIFE that provides
15
+ // `module`/`exports`, and return the resulting namespace-like object. This
16
+ // avoids running esbuild's already-bundled output back through the Babel
17
+ // export-rewriting used for hand-written relative helper modules.
18
+ // - The returned object mirrors an ES module namespace: named exports as own
19
+ // keys plus a `default` key (when requested), which is exactly what the
20
+ // existing `buildDependencyBindings` runtime contract expects.
21
+ //
22
+ // This module is the ONLY place allowed to import esbuild. All other code must
23
+ // go through this wrapper (team rule: external libraries stay behind an
24
+ // internal abstraction).
25
+
26
+ import { build } from 'esbuild';
27
+
28
+ const URL_SCHEME_RE = /^[a-zA-Z][a-zA-Z0-9+.-]*:/;
29
+
30
+ // Non-JS assets a package may import. They are inlined as base64 data URLs so
31
+ // the emitted dependency module stays self-contained (no sidecar files). WASM
32
+ // as a data URL works with the common `fetch(url) -> WebAssembly.instantiate`
33
+ // pattern; url() references inside bundled CSS are inlined the same way.
34
+ export const ASSET_LOADERS = {
35
+ '.wasm': 'dataurl',
36
+ '.png': 'dataurl',
37
+ '.jpg': 'dataurl',
38
+ '.jpeg': 'dataurl',
39
+ '.gif': 'dataurl',
40
+ '.svg': 'dataurl',
41
+ '.webp': 'dataurl',
42
+ '.avif': 'dataurl',
43
+ '.woff': 'dataurl',
44
+ '.woff2': 'dataurl',
45
+ '.ttf': 'dataurl',
46
+ '.eot': 'dataurl',
47
+ // Text assets some packages import as strings (GLSL shaders, templates).
48
+ // Loaded verbatim so `import src from './x.glsl'` yields the file contents.
49
+ '.txt': 'text',
50
+ '.glsl': 'text',
51
+ '.vert': 'text',
52
+ '.frag': 'text',
53
+ '.vs': 'text',
54
+ '.fs': 'text'
55
+ };
56
+
57
+ /**
58
+ * Minimal browser shims for the Node globals that browser-targeted packages
59
+ * still touch at runtime: `process` (env/platform/nextTick) and `global`. This
60
+ * is NOT a Node polyfill — there is no Buffer, stream, or fs. It only prevents
61
+ * a ReferenceError when a package reads e.g. `process.platform` or `global`
62
+ * dynamically; static `process.env.NODE_ENV` is still folded at bundle time by
63
+ * the esbuild `define`. The snippet is idempotent and guarded (it never
64
+ * clobbers a real `process`), so prepending it to every bundled package as an
65
+ * esbuild banner is safe.
66
+ * @param {string} nodeEnv value exposed as process.env.NODE_ENV at runtime.
67
+ * @returns {string}
68
+ */
69
+ export function nodeGlobalsBanner(nodeEnv) {
70
+ return [
71
+ '(function(){',
72
+ ' if (typeof globalThis === "undefined") return;',
73
+ ' if (typeof globalThis.global === "undefined") globalThis.global = globalThis;',
74
+ ' if (typeof globalThis.process === "undefined") {',
75
+ ` globalThis.process = { env: { NODE_ENV: ${JSON.stringify(nodeEnv)} }, argv: [], platform: "browser", browser: true, version: "", versions: {}, cwd: function(){ return "/"; }, nextTick: function(cb){ Promise.resolve().then(cb); } };`,
76
+ ' } else if (typeof globalThis.process.env === "undefined") {',
77
+ ` globalThis.process.env = { NODE_ENV: ${JSON.stringify(nodeEnv)} };`,
78
+ ' }',
79
+ '})();'
80
+ ].join('\n');
81
+ }
82
+
83
+ /** Stable short key for a CSS payload (djb2), used to de-duplicate injection. */
84
+ export function cssInjectionKey(css) {
85
+ let h = 5381;
86
+ for (let i = 0; i < css.length; i += 1) {
87
+ h = ((h << 5) + h + css.charCodeAt(i)) >>> 0;
88
+ }
89
+ return `ext-${h.toString(36)}`;
90
+ }
91
+
92
+ /**
93
+ * Runtime snippet that injects a package's bundled CSS as a <style> element.
94
+ * esbuild resolves @import and url() while bundling, so the passed CSS is
95
+ * already flattened and self-contained. Injection is idempotent: the same CSS
96
+ * (e.g. a package present in two route bundles) is only injected once.
97
+ * @param {string} css
98
+ * @returns {string}
99
+ */
100
+ export function buildCssInjectionSnippet(css) {
101
+ const key = cssInjectionKey(css);
102
+ return [
103
+ '(function(){',
104
+ ' if (typeof document === "undefined") return;',
105
+ ` var __k = ${JSON.stringify(key)};`,
106
+ " if (document.querySelector('style[data-slice-external=\"' + __k + '\"]')) return;",
107
+ ' var __sliceStyle = document.createElement("style");',
108
+ ' __sliceStyle.setAttribute("data-slice-external", __k);',
109
+ ` __sliceStyle.textContent = ${JSON.stringify(css)};`,
110
+ ' document.head.appendChild(__sliceStyle);',
111
+ '})();'
112
+ ].join('\n');
113
+ }
114
+
115
+ /**
116
+ * Splits esbuild's outputFiles into the JS entry text plus an optional injected
117
+ * CSS side-effect snippet. Shared by the build and dev bundlers.
118
+ * @param {Array<{ path: string, text: string }>} outputFiles
119
+ * @returns {string}
120
+ */
121
+ export function combineEsbuildOutputs(outputFiles = []) {
122
+ const jsOut = outputFiles.find((f) => /\.(js|mjs|cjs)$/.test(f.path)) || outputFiles[0];
123
+ const cssOut = outputFiles.find((f) => f.path.endsWith('.css'));
124
+ let code = jsOut?.text || '';
125
+ if (cssOut?.text && cssOut.text.trim()) {
126
+ code += `\n${buildCssInjectionSnippet(cssOut.text)}`;
127
+ }
128
+ return code;
129
+ }
130
+
131
+ export default class ExternalModuleBundler {
132
+ /**
133
+ * @param {object} options
134
+ * @param {string} options.resolveDir Directory esbuild resolves node_modules from (project root).
135
+ * @param {string} [options.target] esbuild target (default 'es2020').
136
+ * @param {boolean} [options.minify] Minify the bundled dependency output.
137
+ */
138
+ constructor({ resolveDir, target = 'es2020', minify = false } = {}) {
139
+ if (!resolveDir) {
140
+ throw new Error('ExternalModuleBundler requires a resolveDir');
141
+ }
142
+ this.resolveDir = resolveDir;
143
+ this.target = target;
144
+ this.minify = minify;
145
+ // Cache keyed by `${specifier}::${needsDefault}` so a package used by many
146
+ // components is only bundled once per build.
147
+ this.cache = new Map();
148
+ }
149
+
150
+ /**
151
+ * Returns true for bare package specifiers: not relative ('./', '../'), not
152
+ * absolute ('/…' — those are served from src/public/), not a URL/data/blob
153
+ * scheme, not a Node subpath import ('#…'). Scoped packages ('@scope/pkg')
154
+ * and deep subpaths ('lodash/fp') are bare.
155
+ * @param {string} spec
156
+ * @returns {boolean}
157
+ */
158
+ static isBareSpecifier(spec) {
159
+ if (typeof spec !== 'string' || spec.length === 0) return false;
160
+ if (spec.startsWith('.')) return false;
161
+ if (spec.startsWith('/')) return false;
162
+ if (spec.startsWith('#')) return false;
163
+ if (URL_SCHEME_RE.test(spec)) return false;
164
+ return true;
165
+ }
166
+
167
+ /**
168
+ * Bundles a bare package into a self-contained module expression.
169
+ *
170
+ * @param {string} specifier e.g. 'dayjs', '@scope/pkg', 'lodash/fp'
171
+ * @param {object} [usage]
172
+ * @param {boolean} [usage.needsDefault] Whether any consumer default-imports it.
173
+ * @returns {Promise<{ name: string, expression: string, warnings: string[] }>}
174
+ * @throws when esbuild cannot resolve or bundle the package.
175
+ */
176
+ async bundle(specifier, usage = {}) {
177
+ const needsDefault = usage.needsDefault !== false; // default true unless explicitly false
178
+ const cacheKey = `${specifier}::${needsDefault}`;
179
+ if (this.cache.has(cacheKey)) {
180
+ return this.cache.get(cacheKey);
181
+ }
182
+
183
+ let result;
184
+ try {
185
+ result = await this.runEsbuild(this.buildVirtualEntry(specifier, needsDefault));
186
+ } catch (error) {
187
+ // A package with no default export makes the explicit default re-export
188
+ // fail; retry with a namespace-only entry so named-only ESM packages still
189
+ // resolve (esp. for dynamic imports, which request the default blindly).
190
+ if (needsDefault && /default/i.test(this.formatEsbuildError(error))) {
191
+ try {
192
+ result = await this.runEsbuild(this.buildVirtualEntry(specifier, false));
193
+ } catch (retryError) {
194
+ throw new Error(`Could not bundle external dependency "${specifier}": ${this.formatEsbuildError(retryError)}`);
195
+ }
196
+ } else {
197
+ throw new Error(`Could not bundle external dependency "${specifier}": ${this.formatEsbuildError(error)}`);
198
+ }
199
+ }
200
+
201
+ // JS entry plus an optional injected-CSS side effect (kept self-contained).
202
+ const code = combineEsbuildOutputs(result.outputFiles);
203
+ const warnings = (result.warnings || []).map((w) => w.text);
204
+ const out = {
205
+ name: specifier,
206
+ expression: this.wrapAsModuleExpression(code),
207
+ warnings
208
+ };
209
+ this.cache.set(cacheKey, out);
210
+ return out;
211
+ }
212
+
213
+ runEsbuild(entry) {
214
+ return build({
215
+ stdin: {
216
+ contents: entry,
217
+ resolveDir: this.resolveDir,
218
+ sourcefile: 'slice-external-entry.js',
219
+ loader: 'js'
220
+ },
221
+ bundle: true,
222
+ format: 'cjs',
223
+ platform: 'browser',
224
+ target: this.target,
225
+ minify: this.minify,
226
+ write: false,
227
+ metafile: false,
228
+ legalComments: 'none',
229
+ logLevel: 'silent',
230
+ // Standard browser-build substitutions (as Vite/webpack do): let packages
231
+ // that gate on NODE_ENV or reference `global` work without a polyfill.
232
+ // esbuild respects local shadowing, so this only rewrites free references.
233
+ define: {
234
+ 'process.env.NODE_ENV': JSON.stringify('production'),
235
+ global: 'globalThis'
236
+ },
237
+ // Runtime shim for the Node globals `define` cannot fold statically (a
238
+ // dynamic `process.platform` / `process.env[key]` / free `global`). Runs
239
+ // once, guarded, before the package body — see nodeGlobalsBanner.
240
+ banner: { js: nodeGlobalsBanner('production') },
241
+ // A virtual outdir is required for esbuild to emit a CSS output file
242
+ // (in outputFiles) when a package imports CSS; nothing is written to
243
+ // disk because write:false.
244
+ outdir: 'slice-external-out',
245
+ // Inline non-JS assets (WASM, images, fonts) as data URLs, and let
246
+ // esbuild bundle any CSS the package imports (resolving @import/url()).
247
+ loader: ASSET_LOADERS,
248
+ // Keep import.meta from crashing browser CJS output for packages that
249
+ // reference it; esbuild replaces it with an empty object shim.
250
+ supported: { 'import-meta': false }
251
+ });
252
+ }
253
+
254
+ /**
255
+ * Virtual entry re-exporting the target package. `export *` covers named +
256
+ * namespace usage; the explicit default re-export is added only when a
257
+ * consumer actually default-imports the package, so ESM packages without a
258
+ * default export don't fail to build when nobody asked for their default.
259
+ */
260
+ buildVirtualEntry(specifier, needsDefault) {
261
+ const spec = JSON.stringify(specifier);
262
+ const lines = [`export * from ${spec};`];
263
+ if (needsDefault) {
264
+ lines.push(`export { default } from ${spec};`);
265
+ }
266
+ return lines.join('\n');
267
+ }
268
+
269
+ /**
270
+ * Wraps esbuild's CJS output in an IIFE that provides the CommonJS scaffolding
271
+ * and returns the populated `module.exports`. The result is an expression that
272
+ * can be assigned directly: `SLICE_BUNDLE_DEPENDENCIES["pkg"] = <expression>;`
273
+ */
274
+ wrapAsModuleExpression(cjsCode) {
275
+ const indented = String(cjsCode)
276
+ .split('\n')
277
+ .map((line) => (line ? ` ${line}` : line))
278
+ .join('\n');
279
+ return [
280
+ '(() => {',
281
+ ' const module = { exports: {} };',
282
+ ' let exports = module.exports;',
283
+ ' const require = (id) => {',
284
+ ' throw new Error(`[Slice.js] Unexpected runtime require("${id}") in a bundled dependency`);',
285
+ ' };',
286
+ indented,
287
+ ' return module.exports;',
288
+ '})()'
289
+ ].join('\n');
290
+ }
291
+
292
+ formatEsbuildError(error) {
293
+ if (error && Array.isArray(error.errors) && error.errors.length > 0) {
294
+ return error.errors.map((e) => e.text).join('; ');
295
+ }
296
+ return error?.message || String(error);
297
+ }
298
+ }
@@ -0,0 +1,103 @@
1
+ // commands/utils/compressAssets.js
2
+ //
3
+ // Precompresses text assets in a built `dist/` tree to `.gz` (gzip) and `.br`
4
+ // (brotli) siblings, so a static server can serve the already-compressed file
5
+ // directly (with Content-Encoding) instead of compressing on every request.
6
+ // Brotli is run at maximum quality — that only makes sense offline, which is
7
+ // exactly what a build step is.
8
+ //
9
+ // Uses Node's built-in `zlib` only — no external dependency (team rule: no new
10
+ // deps without confirmation, and none is needed here).
11
+
12
+ import fs from 'fs-extra';
13
+ import path from 'path';
14
+ import zlib from 'node:zlib';
15
+
16
+ // Text-ish assets that compress well and are safe to serve pre-encoded. Binary
17
+ // assets already compressed (png/jpg/woff2/…) are intentionally excluded.
18
+ export const COMPRESSIBLE_EXTENSIONS = new Set([
19
+ '.js', '.mjs', '.cjs', '.css', '.html', '.htm',
20
+ '.json', '.svg', '.xml', '.txt', '.map', '.webmanifest'
21
+ ]);
22
+
23
+ // Files below this size don't benefit — the encoding overhead and the extra
24
+ // request negotiation aren't worth it, so the server should serve the original.
25
+ const DEFAULT_MIN_SIZE = 1024;
26
+
27
+ export function isCompressibleFile(filePath) {
28
+ const ext = path.extname(filePath).toLowerCase();
29
+ return COMPRESSIBLE_EXTENSIONS.has(ext);
30
+ }
31
+
32
+ /** Deterministic max-level gzip of a buffer. */
33
+ export function gzipBuffer(buffer) {
34
+ return zlib.gzipSync(buffer, { level: zlib.constants.Z_BEST_COMPRESSION });
35
+ }
36
+
37
+ /** Deterministic max-quality brotli of a buffer (size hint aids the encoder). */
38
+ export function brotliBuffer(buffer) {
39
+ return zlib.brotliCompressSync(buffer, {
40
+ params: {
41
+ [zlib.constants.BROTLI_PARAM_QUALITY]: zlib.constants.BROTLI_MAX_QUALITY,
42
+ [zlib.constants.BROTLI_PARAM_SIZE_HINT]: buffer.length
43
+ }
44
+ });
45
+ }
46
+
47
+ async function* walkFiles(dir) {
48
+ const entries = await fs.readdir(dir, { withFileTypes: true });
49
+ for (const entry of entries) {
50
+ const full = path.join(dir, entry.name);
51
+ if (entry.isDirectory()) {
52
+ yield* walkFiles(full);
53
+ } else if (entry.isFile()) {
54
+ yield full;
55
+ }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * Walks `dir` and writes a `.gz` and `.br` next to every compressible file over
61
+ * `minSize`. Already-compressed siblings (`.gz`/`.br`) are skipped so re-runs
62
+ * don't recurse. Best-effort per file: a failure on one file is logged and
63
+ * skipped, not fatal.
64
+ * @param {string} dir directory to precompress (e.g. the dist root)
65
+ * @param {object} [options]
66
+ * @param {number} [options.minSize] minimum original size to compress (bytes)
67
+ * @returns {Promise<{ files: number, originalBytes: number, gzipBytes: number, brotliBytes: number }>}
68
+ */
69
+ export async function precompressDirectory(dir, options = {}) {
70
+ const minSize = typeof options.minSize === 'number' ? options.minSize : DEFAULT_MIN_SIZE;
71
+ const stats = { files: 0, originalBytes: 0, gzipBytes: 0, brotliBytes: 0 };
72
+
73
+ if (!await fs.pathExists(dir)) {
74
+ return stats;
75
+ }
76
+
77
+ for await (const filePath of walkFiles(dir)) {
78
+ const ext = path.extname(filePath).toLowerCase();
79
+ if (ext === '.gz' || ext === '.br') continue; // never recompress an artifact
80
+ if (!COMPRESSIBLE_EXTENSIONS.has(ext)) continue;
81
+
82
+ try {
83
+ const buffer = await fs.readFile(filePath);
84
+ if (buffer.length < minSize) continue;
85
+
86
+ const gz = gzipBuffer(buffer);
87
+ const br = brotliBuffer(buffer);
88
+ await fs.writeFile(`${filePath}.gz`, gz);
89
+ await fs.writeFile(`${filePath}.br`, br);
90
+
91
+ stats.files += 1;
92
+ stats.originalBytes += buffer.length;
93
+ stats.gzipBytes += gz.length;
94
+ stats.brotliBytes += br.length;
95
+ } catch (error) {
96
+ console.warn(`Warning: could not precompress ${filePath}: ${error.message}`);
97
+ }
98
+ }
99
+
100
+ return stats;
101
+ }
102
+
103
+ export default precompressDirectory;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "slicejs-cli",
3
- "version": "3.8.1",
3
+ "version": "4.0.0",
4
4
  "description": "Command client for developing web applications with Slice.js framework",
5
5
  "main": "client.js",
6
6
  "bin": {
@@ -58,6 +58,7 @@
58
58
  "clean-css": "^5.3.3",
59
59
  "cli-table3": "^0.6.5",
60
60
  "commander": "^12.0.0",
61
+ "esbuild": "^0.28.1",
61
62
  "fs-extra": "^11.2.0",
62
63
  "html-minifier-terser": "^7.2.0",
63
64
  "inquirer": "^12.4.2",