solid-optimizer 0.3.0 → 1.0.0-next.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.
@@ -14,7 +14,7 @@
14
14
  * adds when the module is transformed.
15
15
  */
16
16
  import MagicString from 'magic-string';
17
- import type { Node, Program } from 'oxc-parser';
17
+ import type { Expression, Node, Program } from 'oxc-parser';
18
18
  import { forEachChild, parse, unwrap } from '../ast';
19
19
  import type { Binding, ScopeAnalysis } from '../scope';
20
20
  import { analyzeScopes } from '../scope';
@@ -213,6 +213,55 @@ export interface ExportedComponent {
213
213
  * as `rename` gives it.
214
214
  */
215
215
  readonly copy: (name: string, rename: ReadonlyMap<string, string>) => string;
216
+ /**
217
+ * Whether the component only returns a call of another component of its
218
+ * module, like `(props) => <Icon {...props}><path /></Icon>`.
219
+ */
220
+ readonly wrapsLocal: boolean;
221
+ }
222
+
223
+ /**
224
+ * Whether a function returns JSX whose root calls a component declared at
225
+ * the top of its own module. A context's provider does not count, since the
226
+ * provider pass can remove it from a copy.
227
+ */
228
+ function returnsLocalCall(
229
+ fn: TopLevelFunction['fn'],
230
+ scopes: ScopeAnalysis,
231
+ moduleSources: readonly string[],
232
+ ): boolean {
233
+ if (
234
+ fn.type !== 'FunctionDeclaration' &&
235
+ fn.type !== 'FunctionExpression' &&
236
+ fn.type !== 'ArrowFunctionExpression'
237
+ ) {
238
+ return false;
239
+ }
240
+ const { body } = fn;
241
+ if (!body) {
242
+ return false;
243
+ }
244
+ let root: Expression | null | undefined;
245
+ if (body.type === 'BlockStatement') {
246
+ const last = body.body.at(-1);
247
+ root = last?.type === 'ReturnStatement' ? last.argument : undefined;
248
+ } else {
249
+ root = body;
250
+ }
251
+ if (!root) {
252
+ return false;
253
+ }
254
+ const inner = unwrap(root);
255
+ if (inner.type !== 'JSXElement' || inner.openingElement.name.type !== 'JSXIdentifier') {
256
+ return false;
257
+ }
258
+ const binding = scopes.references.get(inner.openingElement.name);
259
+ return (
260
+ binding !== undefined &&
261
+ binding.scope === scopes.root &&
262
+ binding.kind !== 'import' &&
263
+ !isContext(binding, scopes, moduleSources)
264
+ );
216
265
  }
217
266
 
218
267
  /**
@@ -307,5 +356,5 @@ export function readExportedComponent(
307
356
  }
308
357
  return `const ${name} = ${s.slice(component.fn.start, component.fn.end)};`;
309
358
  };
310
- return { dependencies, copy };
359
+ return { dependencies, copy, wrapsLocal: returnsLocalCall(component.fn, scopes, moduleSources) };
311
360
  }
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Keeps a `ref` that names a variable working through bundling.
3
+ *
4
+ * Solid's JSX transform turns `<input ref={el} />` into code that assigns
5
+ * the element to `el`. In chunk mode the JSX reaches the bundler before that
6
+ * code exists, so the bundler only sees `el` read. A `let el` that nothing
7
+ * else writes to then looks like it is always `undefined`, and the bundler
8
+ * folds its reads, like `el ? el.value : ''`, to the `undefined` branch.
9
+ *
10
+ * Before bundling, `ref={el}` becomes `ref={__SO_REF__(el, (v) => (el = v))}`,
11
+ * which shows the bundler the write. The bundler renames both uses of `el`
12
+ * alike. Before the chunk is lowered, the call becomes `ref={el}` again, so
13
+ * the JSX transform writes the same code it would have.
14
+ */
15
+ import type { CallExpression, JSXAttribute, Node } from 'oxc-parser';
16
+ import MagicString from 'magic-string';
17
+ import { forEachChild, parse } from '../ast';
18
+ import { analyzeScopes } from '../scope';
19
+ import type { EditResult } from './runtime';
20
+
21
+ export const REF_MARKER = '__SO_REF__';
22
+
23
+ function generateMap(s: MagicString, filename: string): string {
24
+ return s.generateMap({ source: filename, hires: true, includeContent: true }).toString();
25
+ }
26
+
27
+ function isRefAttribute(node: Node): node is JSXAttribute {
28
+ return (
29
+ node.type === 'JSXAttribute' && node.name.type === 'JSXIdentifier' && node.name.name === 'ref'
30
+ );
31
+ }
32
+
33
+ /**
34
+ * Wraps each `ref` whose value is a `let` or `var` binding, so the bundler
35
+ * sees it written. `undefined` when there is none.
36
+ */
37
+ export function protectRefs(code: string, filename: string): EditResult | undefined {
38
+ if (!code.includes('ref')) {
39
+ return undefined;
40
+ }
41
+ const program = parse(filename, code);
42
+ const scopes = analyzeScopes(program);
43
+ const s = new MagicString(code);
44
+ const visit = (node: Node): void => {
45
+ if (isRefAttribute(node) && node.value?.type === 'JSXExpressionContainer') {
46
+ const { expression } = node.value;
47
+ const binding =
48
+ expression.type === 'Identifier' ? scopes.references.get(expression) : undefined;
49
+ if (
50
+ expression.type === 'Identifier' &&
51
+ (binding?.kind === 'let' || binding?.kind === 'var')
52
+ ) {
53
+ const { name } = expression;
54
+ s.overwrite(
55
+ expression.start,
56
+ expression.end,
57
+ `${REF_MARKER}(${name}, (__so_ref) => (${name} = __so_ref))`,
58
+ );
59
+ }
60
+ }
61
+ forEachChild(node, visit);
62
+ };
63
+ visit(program);
64
+ return s.hasChanged() ? { code: s.toString(), map: generateMap(s, filename) } : undefined;
65
+ }
66
+
67
+ /**
68
+ * Turns each wrapped `ref` back into its variable. `undefined` when there
69
+ * is none.
70
+ */
71
+ export function restoreRefs(code: string, filename: string): EditResult | undefined {
72
+ if (!code.includes(REF_MARKER)) {
73
+ return undefined;
74
+ }
75
+ const program = parse(filename, code);
76
+ const s = new MagicString(code);
77
+ const visit = (node: Node): void => {
78
+ if (isRefAttribute(node) && node.value?.type === 'JSXExpressionContainer') {
79
+ const { expression } = node.value;
80
+ if (isMarkerCall(expression)) {
81
+ const target = expression.arguments.at(0);
82
+ if (target?.type === 'Identifier') {
83
+ s.overwrite(expression.start, expression.end, target.name);
84
+ }
85
+ }
86
+ }
87
+ forEachChild(node, visit);
88
+ };
89
+ visit(program);
90
+ return s.hasChanged() ? { code: s.toString(), map: generateMap(s, filename) } : undefined;
91
+ }
92
+
93
+ function isMarkerCall(node: Node): node is CallExpression {
94
+ return (
95
+ node.type === 'CallExpression' &&
96
+ node.callee.type === 'Identifier' &&
97
+ node.callee.name === REF_MARKER
98
+ );
99
+ }
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The report of what the optimizer leaves alone in a build, and why.
3
+ *
4
+ * Each pass records a short reason code for every component call, provider,
5
+ * and memo it does not optimize. The plugin collects them from the final
6
+ * compile of each chunk or module, and prints them grouped by reason.
7
+ */
8
+ import type { Skip, SkipPass } from '../context';
9
+
10
+ /** What the optimizer left alone in one build environment. */
11
+ export interface OptimizerReport {
12
+ /** The Vite environment, like `client` or `ssr`. */
13
+ readonly environment: string;
14
+ readonly skips: readonly Skip[];
15
+ }
16
+
17
+ export interface ReasonSummary {
18
+ readonly pass: SkipPass;
19
+ readonly reason: string;
20
+ readonly count: number;
21
+ /** How many times each name was skipped for this reason, most first. */
22
+ readonly names: readonly (readonly [string, number])[];
23
+ }
24
+
25
+ /**
26
+ * Groups skips by pass and reason, most frequent first.
27
+ */
28
+ export function summarizeSkips(skips: readonly Skip[]): ReasonSummary[] {
29
+ const groups = new Map<string, { pass: SkipPass; reason: string; names: Map<string, number> }>();
30
+ for (const skip of skips) {
31
+ const key = `${skip.pass}\0${skip.reason}`;
32
+ const group = groups.get(key) ?? { pass: skip.pass, reason: skip.reason, names: new Map() };
33
+ group.names.set(skip.name, (group.names.get(skip.name) ?? 0) + 1);
34
+ groups.set(key, group);
35
+ }
36
+ return [...groups.values()]
37
+ .map(({ pass, reason, names }) => ({
38
+ pass,
39
+ reason,
40
+ count: [...names.values()].reduce((sum, count) => sum + count, 0),
41
+ names: [...names].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])),
42
+ }))
43
+ .sort(
44
+ (a, b) =>
45
+ b.count - a.count || a.pass.localeCompare(b.pass) || a.reason.localeCompare(b.reason),
46
+ );
47
+ }
48
+
49
+ /** The most names listed for a reason. */
50
+ const NAMES_SHOWN = 6;
51
+
52
+ /**
53
+ * The report as text, one line per reason.
54
+ */
55
+ export function formatReport(report: OptimizerReport): string {
56
+ const lines = [`solid-optimizer: what stays as written in ${report.environment}`];
57
+ const summaries = summarizeSkips(report.skips);
58
+ if (summaries.length === 0) {
59
+ lines.push(' nothing');
60
+ }
61
+ const reasonWidth = Math.max(0, ...summaries.map((summary) => summary.reason.length));
62
+ for (const summary of summaries) {
63
+ const shown = summary.names
64
+ .slice(0, NAMES_SHOWN)
65
+ .map(([name, count]) => (count > 1 ? `${name}×${String(count)}` : name));
66
+ if (summary.names.length > NAMES_SHOWN) {
67
+ shown.push(`${String(summary.names.length - NAMES_SHOWN)} more`);
68
+ }
69
+ lines.push(
70
+ ` ${summary.pass.padEnd(8)} ${summary.reason.padEnd(reasonWidth)} ${String(summary.count).padStart(4)} ${shown.join(', ')}`,
71
+ );
72
+ }
73
+ return lines.join('\n');
74
+ }
@@ -2,7 +2,7 @@
2
2
  * Keeps Solid's runtime helpers reachable while JSX waits in a bundled chunk.
3
3
  *
4
4
  * Solid's JSX transform imports helpers like `template` and `insert` from
5
- * `solid-js/web`. When the transform runs on a chunk, the bundle is already
5
+ * `@solidjs/web`. When the transform runs on a chunk, the bundle is already
6
6
  * built, so a new bare import cannot be resolved or bundled anymore. Instead,
7
7
  * every module imports the helpers it will need before bundling, and passes
8
8
  * them to a marker call. The bundler keeps the call, since it could have side
@@ -91,7 +91,7 @@ export function generatedImports(code: string, filename: string, source: string)
91
91
  }
92
92
 
93
93
  export interface MarkerOptions {
94
- /** The module the helpers come from, usually `solid-js/web`. */
94
+ /** The module the helpers come from, usually `@solidjs/web`. */
95
95
  readonly moduleName: string;
96
96
  /** The helpers to keep. */
97
97
  readonly helpers: ReadonlySet<string>;
@@ -258,7 +258,7 @@ export function repairJSXSequences(code: string, filename: string): EditResult |
258
258
  }
259
259
 
260
260
  export interface ChunkRuntime extends EditResult {
261
- /** The chunk's name for each helper, keyed by the name `solid-js/web` exports. */
261
+ /** The chunk's name for each helper, keyed by the name `@solidjs/web` exports. */
262
262
  readonly helpers: ReadonlyMap<string, string>;
263
263
  /** The built-in each chunk binding refers to, keyed by the chunk's name for it. */
264
264
  readonly builtInAliases: Record<string, string>;
@@ -1 +0,0 @@
1
- {"version":3,"file":"compile-BroGlagZ.d.mts","names":[],"sources":["../src/value.ts","../src/constants.ts","../src/compile.ts"],"mappings":";;;;KAUY;;;;;;;KCSA,oBAAoB,SAAS,eAAe,SAAS,eAAe;;;UCJ/D;;;;;;;EAOf;;;;;;;EAOA;;;;;;EAMA;;;;;;;;;;;;;EAaA;;;;;;;EAOA;;;;;;;EAOA;;;;;;;EAOA;;;;;;;EAOA;;;;;;EAMA,iBAAiB,SAAS;;;;;;;EAO1B;;;;;;EAMA,oBAAoB;;;;;;EAMpB,mBAAmB,SAAS;;;;;;;;EAQ5B,mBAAmB,SAAS;;;;;;;;EAQ5B;;;;;;;;EAQA;;;;;;EAMA;;UAGe;EACf;;EAEA,KAAK;;;;;;;;;;;;;iBAkFS,QAAQ,cAAc,UAAS,iBAAsB;UAuDpD;;;;;EAKf;;;;;;EAMA,SAAS,eAAe;;;;;;;;iBASV,oBACd,cACA,UAAS,KAAK,oDACb"}