solid-optimizer 1.0.0 → 1.1.1

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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "solid-optimizer",
3
- "version": "1.0.0",
3
+ "version": "1.1.1",
4
4
  "description": "Experimental compile-time optimizer for SolidJS",
5
5
  "keywords": [
6
6
  "compiler",
package/src/compile.ts CHANGED
@@ -15,6 +15,7 @@ import { lowerConditionals } from './conditional';
15
15
  import type { ScopeAnalysis } from './scope';
16
16
  import { analyzeScopes } from './scope';
17
17
  import { terminateStatements } from './terminate';
18
+ import { tidyJSX } from './tidy';
18
19
  import { Editor } from './text';
19
20
  import type { Primitive } from './value';
20
21
 
@@ -136,6 +137,15 @@ export interface CompileOptions {
136
137
  * @default 10
137
138
  */
138
139
  maxPasses?: number;
140
+ /**
141
+ * Tidy the JSX the passes write: drop empty braces, write strings in
142
+ * braces as plain JSX, and unwrap fragments that hold one element. It only
143
+ * changes how the output reads: Solid's JSX transform lowers it to the same
144
+ * code. It runs only on a module the passes changed.
145
+ *
146
+ * @default true
147
+ */
148
+ tidy?: boolean;
139
149
  /**
140
150
  * Generate a source map.
141
151
  *
@@ -364,6 +374,19 @@ export function compile(code: string, options: CompileOptions = {}): CompileResu
364
374
  maps.push(result.map);
365
375
  }
366
376
  }
377
+ // The passes leave empty braces, strings in braces and one-element
378
+ // fragments behind. Tidying them changes nothing Solid's JSX transform
379
+ // makes, but the output reads like code a person wrote.
380
+ const tidied =
381
+ (options.tidy ?? true)
382
+ ? runPass(parsedCurrent(), filename, resolved, sourceMap, tidyJSX, undefined)
383
+ : undefined;
384
+ if (tidied) {
385
+ current = tidied.code;
386
+ if (tidied.map !== undefined) {
387
+ maps.push(tidied.map);
388
+ }
389
+ }
367
390
  }
368
391
 
369
392
  const report = skipped ? { skipped } : {};
package/src/inline.ts CHANGED
@@ -210,6 +210,8 @@ interface PreparedSite {
210
210
  readonly host: { fn: Node; host: Host } | undefined;
211
211
  readonly statements: Content[];
212
212
  readonly root: Text;
213
+ /** What replaces the call, when it is not `root`: a fragment root's children. */
214
+ readonly spliced?: Text;
213
215
  }
214
216
 
215
217
  function isWithin(node: Node, container: Node): boolean {
@@ -1641,11 +1643,33 @@ class Inliner {
1641
1643
  const text = copy.slice(first.start, last.end);
1642
1644
  statements.push(text.code.endsWith(';') ? text : joinText`${text};`);
1643
1645
  }
1646
+ // Solid's JSX transform only takes a fragment at the top of an expression, so a fragment
1647
+ // root that lands among an element's children gives them its own children instead.
1648
+ const { root } = component;
1649
+ const parent = this.context.parents.get(element);
1650
+ const spliceChildren =
1651
+ root.type === 'JSXFragment' &&
1652
+ (parent?.type === 'JSXElement' || parent?.type === 'JSXFragment');
1653
+ // Edge text that JSX keeps would join the text around the call, and JSX collapses the
1654
+ // joined run differently: `a<Label />b` with `<>\n hello\n</>` would render `a hello b`.
1655
+ // JSX keeps text with a non-space character, and space-only text with no line break.
1656
+ if (spliceChildren) {
1657
+ const edges = [root.children.at(0), root.children.at(-1)];
1658
+ const kept = (value: string): boolean =>
1659
+ /\S/.test(value) || (value !== '' && !value.includes('\n'));
1660
+ if (edges.some((child) => child?.type === 'JSXText' && kept(child.value))) {
1661
+ this.reason = 'fragment-text';
1662
+ return undefined;
1663
+ }
1664
+ }
1644
1665
  return {
1645
1666
  element,
1646
1667
  host,
1647
1668
  statements,
1648
- root: copy.slice(component.root.start, component.root.end),
1669
+ root: copy.slice(root.start, root.end),
1670
+ spliced: spliceChildren
1671
+ ? copy.slice(root.openingFragment.end, root.closingFragment.start)
1672
+ : undefined,
1649
1673
  };
1650
1674
  }
1651
1675
 
@@ -1661,7 +1685,7 @@ class Inliner {
1661
1685
  * Writes a prepared copy over its call site.
1662
1686
  */
1663
1687
  private commit(site: PreparedSite): void {
1664
- this.context.s.overwrite(site.element.start, site.element.end, site.root);
1688
+ this.context.s.overwrite(site.element.start, site.element.end, site.spliced ?? site.root);
1665
1689
  if (site.host) {
1666
1690
  this.addToHost(site.host, site.statements);
1667
1691
  }
@@ -2638,8 +2662,14 @@ class Inliner {
2638
2662
  // from its new body. A copy made now would miss what was inlined into it.
2639
2663
  const changedBodies = new Set<Component>(this.findTransparentProviders(components, sites));
2640
2664
  const worthwhile = this.worthwhileComponents(sites, changedBodies, otherUses);
2665
+ // The hosts that copies made in this pass moved statements into. They are written at the
2666
+ // end of the pass, so an outer call holding one copies it in the next pass instead: a
2667
+ // copy made now would miss the statements, and writing them later would edit text the
2668
+ // outer copy has already replaced.
2669
+ const pendingHosts: Node[] = [];
2641
2670
  for (const site of inBodyOrder(sites)) {
2642
- const postponed = changedBodies.has(site.component);
2671
+ const holdsPendingHost = pendingHosts.some((host) => isWithin(host, site.element));
2672
+ const postponed = changedBodies.has(site.component) || holdsPendingHost;
2643
2673
  // Each copy is made now, so it takes in the call sites inside it that
2644
2674
  // were inlined before it.
2645
2675
  const copy =
@@ -2650,6 +2680,9 @@ class Inliner {
2650
2680
  if (copy) {
2651
2681
  this.commit(copy);
2652
2682
  this.changed = true;
2683
+ if (copy.host) {
2684
+ pendingHosts.push(copy.host.fn);
2685
+ }
2653
2686
  const elements = inlined.get(site.component) ?? [];
2654
2687
  elements.push(site.element);
2655
2688
  inlined.set(site.component, elements);
@@ -2736,7 +2769,8 @@ class Inliner {
2736
2769
  ): { reason: string; name: string } | undefined {
2737
2770
  const tag = element.openingElement.name;
2738
2771
  if (tag.type === 'JSXMemberExpression') {
2739
- return { reason: 'member-tag', name: getText(this.context, tag).code };
2772
+ // The pass has edited the code by now, so the name comes from the original.
2773
+ return { reason: 'member-tag', name: this.context.code.slice(tag.start, tag.end) };
2740
2774
  }
2741
2775
  if (tag.type !== 'JSXIdentifier' || !isCapitalized(tag.name)) {
2742
2776
  return undefined;
package/src/tidy.ts ADDED
@@ -0,0 +1,390 @@
1
+ /**
2
+ * Tidies the JSX the other passes wrote, without changing what it renders.
3
+ *
4
+ * - An empty `{}` child goes. The passes write one to keep two texts apart,
5
+ * so it only goes when the texts on both sides read the same without it.
6
+ * - A string in braces becomes plain JSX: `class={'card'}` becomes
7
+ * `class="card"`, and a `{'Hello'}` child becomes the text `Hello`.
8
+ * - A fragment that holds one element, with only line breaks around it,
9
+ * becomes that element.
10
+ *
11
+ * Each edit follows a model of how Solid's JSX transform reads JSX: its
12
+ * whitespace rule, which strings it writes as they are, and where a fragment
13
+ * around one element lowers the same as the element. Anything outside the
14
+ * model, such as unusual whitespace, stays as it is. The tests lower the
15
+ * tidied and untidied output and expect the same code.
16
+ */
17
+ import type {
18
+ JSXAttribute,
19
+ JSXElement,
20
+ JSXExpressionContainer,
21
+ JSXFragment,
22
+ Node,
23
+ } from 'oxc-parser';
24
+ import { forEachChild } from './ast';
25
+ import type { PassContext } from './context';
26
+
27
+ type Child = JSXElement['children'][number];
28
+
29
+ /**
30
+ * The text Solid's JSX transform makes of a raw text child: when the text
31
+ * has a line break, each line after the first loses its leading spaces, lines
32
+ * of only spaces drop out and the rest join with a space; then every run of
33
+ * spaces becomes one space. This differs from React's rule, which keeps runs
34
+ * of spaces on one line.
35
+ */
36
+ export function cleanText(raw: string): string {
37
+ let text = raw.replaceAll('\r', '');
38
+ if (text.includes('\n')) {
39
+ const kept: string[] = [];
40
+ for (const [index, line] of text.split('\n').entries()) {
41
+ const trimmed = index === 0 ? line : line.replace(/^[ \t]+/, '');
42
+ if (/[^ \t]/.test(trimmed)) {
43
+ kept.push(trimmed);
44
+ }
45
+ }
46
+ text = kept.join(' ');
47
+ }
48
+ return text.replaceAll(/[ \t\n]+/g, ' ');
49
+ }
50
+
51
+ /**
52
+ * Whether a text holds whitespace or format characters other than space,
53
+ * tab and line breaks, such as U+0085 or a byte order mark. Solid's JSX
54
+ * transform and JavaScript disagree on some of them, so such text stays as it is.
55
+ */
56
+ function hasUnusualSpace(text: string): boolean {
57
+ return /(?![ \t\n\r])[\s\p{White_Space}\p{Cf}]/u.test(text);
58
+ }
59
+
60
+ /**
61
+ * The string a container holds when it is a plain string written without
62
+ * escapes, such as `{'a'}` or `{`a`}`. The characters between the quotes are
63
+ * then the string itself, so tidying keeps them, and their source map
64
+ * positions, and only drops what is around them.
65
+ */
66
+ function readString(container: JSXExpressionContainer, code: string): string | undefined {
67
+ const { expression } = container;
68
+ let value: string | undefined;
69
+ if (expression.type === 'Literal' && typeof expression.value === 'string') {
70
+ value = expression.value;
71
+ } else if (
72
+ expression.type === 'TemplateLiteral' &&
73
+ expression.expressions.length === 0 &&
74
+ expression.quasis.length === 1
75
+ ) {
76
+ value = expression.quasis[0].value.cooked ?? undefined;
77
+ }
78
+ if (value === undefined || code.slice(expression.start + 1, expression.end - 1) !== value) {
79
+ return undefined;
80
+ }
81
+ // Braces that hold a comment beside the string keep it.
82
+ const around =
83
+ code.slice(container.start + 1, expression.start) +
84
+ code.slice(expression.end, container.end - 1);
85
+ if (around.trim() !== '') {
86
+ return undefined;
87
+ }
88
+ return value;
89
+ }
90
+
91
+ /**
92
+ * Replaces the braces and quotes around a string with `before` and `after`,
93
+ * keeping the string's own characters where they are.
94
+ */
95
+ function unwrapString(
96
+ container: JSXExpressionContainer,
97
+ before: string,
98
+ after: string,
99
+ context: PassContext,
100
+ ): void {
101
+ const { expression } = container;
102
+ const { code, s } = context;
103
+ // Removing keeps the mapping of the string's characters, and of quotes
104
+ // that stay. Only a quote that changes is written.
105
+ s.remove(container.start, expression.start);
106
+ s.remove(expression.end, container.end);
107
+ const open = code[expression.start];
108
+ const close = code[expression.end - 1];
109
+ if (before === open) {
110
+ // The quote stays.
111
+ } else if (before === '') {
112
+ s.remove(expression.start, expression.start + 1);
113
+ } else {
114
+ s.overwrite(expression.start, expression.start + 1, s.written(before, expression.start));
115
+ }
116
+ if (after === close) {
117
+ // The quote stays.
118
+ } else if (after === '') {
119
+ s.remove(expression.end - 1, expression.end);
120
+ } else {
121
+ s.overwrite(expression.end - 1, expression.end, s.written(after, expression.end - 1));
122
+ }
123
+ }
124
+
125
+ /** Whether a container holds nothing, not even a comment. */
126
+ function isEmpty(container: JSXExpressionContainer, code: string): boolean {
127
+ return (
128
+ container.expression.type === 'JSXEmptyExpression' &&
129
+ code.slice(container.start + 1, container.end - 1).trim() === ''
130
+ );
131
+ }
132
+
133
+ /**
134
+ * A child as it renders: raw text, which JSX cleans together with the raw
135
+ * text next to it; a literal string, which renders as it is and keeps the
136
+ * texts on its sides apart; or something else, such as an element.
137
+ */
138
+ type Part = { raw: string } | { literal: string } | { other: number };
139
+
140
+ /**
141
+ * The pieces a list of children renders: each text that is not empty, and a
142
+ * mark for each child that is not text.
143
+ */
144
+ function renderPieces(parts: readonly (Part | undefined)[]): string[] {
145
+ const pieces: string[] = [];
146
+ let raw: string | undefined;
147
+ const flush = (): void => {
148
+ if (raw !== undefined) {
149
+ const text = cleanText(raw);
150
+ if (text !== '') {
151
+ pieces.push(text);
152
+ }
153
+ raw = undefined;
154
+ }
155
+ };
156
+ for (const part of parts) {
157
+ if (!part) {
158
+ continue;
159
+ }
160
+ if ('raw' in part) {
161
+ raw = (raw ?? '') + part.raw;
162
+ } else if ('literal' in part) {
163
+ flush();
164
+ if (part.literal !== '') {
165
+ pieces.push(part.literal);
166
+ }
167
+ } else {
168
+ flush();
169
+ pieces.push(`\0${String(part.other)}`);
170
+ }
171
+ }
172
+ flush();
173
+ return pieces;
174
+ }
175
+
176
+ /**
177
+ * What a list of children renders. In an element, Solid's JSX transform
178
+ * writes the texts next to each other into the template as one text, so
179
+ * only the joined text counts. Anywhere else, such as a fragment, each text
180
+ * stays its own string, so the pieces must stay apart too.
181
+ */
182
+ function render(parts: readonly (Part | undefined)[], inElement: boolean): string {
183
+ const pieces = renderPieces(parts);
184
+ if (!inElement) {
185
+ return JSON.stringify(pieces);
186
+ }
187
+ let joined = '';
188
+ for (const piece of pieces) {
189
+ joined += piece.startsWith('\0') ? `${piece}\0` : piece;
190
+ }
191
+ return joined;
192
+ }
193
+
194
+ /** Whether an element is an HTML or SVG element, which Solid lowers into a template. */
195
+ function isIntrinsic(element: JSXElement): boolean {
196
+ const { name } = element.openingElement;
197
+ if (name.type === 'JSXNamespacedName') {
198
+ return true;
199
+ }
200
+ return name.type === 'JSXIdentifier' && /^[a-z]/.test(name.name);
201
+ }
202
+
203
+ /** A string that can be written as JSX text: no syntax, no entities, no line breaks. */
204
+ function isPlainText(value: string): boolean {
205
+ return (
206
+ value !== '' &&
207
+ !/[{}<>&\r\n\t]/.test(value) &&
208
+ !hasUnusualSpace(value) &&
209
+ value.trim() === value
210
+ );
211
+ }
212
+
213
+ /** A string that can be written as a JSX attribute in double quotes. */
214
+ function isPlainAttribute(value: string): boolean {
215
+ return !/["&\r\n]/.test(value) && !hasUnusualSpace(value);
216
+ }
217
+
218
+ /**
219
+ * Attributes whose string Solid's JSX transform treats differently once it
220
+ * is written as a plain value: it moves a static `style` last, and `ref`,
221
+ * `classList`, event handlers (`on` in any case) and namespaced attributes do
222
+ * not take a string.
223
+ */
224
+ function isTidyAttribute(attribute: JSXAttribute): boolean {
225
+ const { name } = attribute;
226
+ return (
227
+ name.type === 'JSXIdentifier' &&
228
+ name.name !== 'style' &&
229
+ name.name !== 'ref' &&
230
+ name.name !== 'classList' &&
231
+ !name.name.startsWith('on')
232
+ );
233
+ }
234
+
235
+ /**
236
+ * Whether an element can get children from an attribute: a `children`
237
+ * attribute or a spread. Its own children then decide whether those show, so
238
+ * even an empty `{}` among them counts, and they stay as they are.
239
+ */
240
+ function hasChildrenAttribute(element: JSXElement): boolean {
241
+ for (const attribute of element.openingElement.attributes) {
242
+ if (
243
+ attribute.type === 'JSXSpreadAttribute' ||
244
+ (attribute.name.type === 'JSXIdentifier' && attribute.name.name === 'children')
245
+ ) {
246
+ return true;
247
+ }
248
+ }
249
+ return false;
250
+ }
251
+
252
+ /**
253
+ * Removes empty braces and writes plain strings as text, one at a time. Each
254
+ * edit is kept only when the children still render the same with every edit
255
+ * kept so far.
256
+ */
257
+ function tidyChildren(
258
+ children: readonly Child[],
259
+ inElement: boolean,
260
+ context: PassContext,
261
+ ): boolean {
262
+ const { code, s } = context;
263
+ for (const child of children) {
264
+ if (child.type === 'JSXText' && hasUnusualSpace(code.slice(child.start, child.end))) {
265
+ return false;
266
+ }
267
+ }
268
+ const parts: (Part | undefined)[] = [];
269
+ for (const [index, child] of children.entries()) {
270
+ if (child.type === 'JSXText') {
271
+ parts.push({ raw: code.slice(child.start, child.end) });
272
+ } else if (child.type === 'JSXExpressionContainer' && isEmpty(child, code)) {
273
+ parts.push({ literal: '' });
274
+ } else if (child.type === 'JSXExpressionContainer' && readString(child, code) !== undefined) {
275
+ parts.push({ literal: readString(child, code) ?? '' });
276
+ } else {
277
+ parts.push({ other: index });
278
+ }
279
+ }
280
+ const expected = render(parts, inElement);
281
+ let changed = false;
282
+ for (const [index, child] of children.entries()) {
283
+ if (child.type !== 'JSXExpressionContainer') {
284
+ continue;
285
+ }
286
+ const empty = isEmpty(child, code);
287
+ const value = empty ? undefined : readString(child, code);
288
+ if (!empty && (value === undefined || !isPlainText(value))) {
289
+ continue;
290
+ }
291
+ // Without the braces, the texts on both sides meet, and a string joins them as text.
292
+ const before = parts[index];
293
+ parts[index] = empty ? undefined : { raw: value ?? '' };
294
+ if (render(parts, inElement) === expected) {
295
+ if (empty) {
296
+ s.remove(child.start, child.end);
297
+ } else {
298
+ unwrapString(child, '', '', context);
299
+ }
300
+ changed = true;
301
+ } else {
302
+ parts[index] = before;
303
+ }
304
+ }
305
+ return changed;
306
+ }
307
+
308
+ /** The one element a fragment holds, when everything else in it is line breaks or empty braces. */
309
+ function findOnlyElement(fragment: JSXFragment, code: string): JSXElement | undefined {
310
+ let only: JSXElement | undefined;
311
+ for (const child of fragment.children) {
312
+ if (child.type === 'JSXElement') {
313
+ if (only) {
314
+ return undefined;
315
+ }
316
+ only = child;
317
+ } else if (child.type === 'JSXText') {
318
+ // Spaces without a line break are text: `<> <b /></>` renders a space.
319
+ if (!/^[ \t\r\n]*$/.test(child.value) || cleanText(child.value) !== '') {
320
+ return undefined;
321
+ }
322
+ } else if (!(child.type === 'JSXExpressionContainer' && isEmpty(child, code))) {
323
+ return undefined;
324
+ }
325
+ }
326
+ return only;
327
+ }
328
+
329
+ function tidyAttribute(attribute: JSXAttribute, context: PassContext): boolean {
330
+ const { value } = attribute;
331
+ if (value?.type !== 'JSXExpressionContainer' || !isTidyAttribute(attribute)) {
332
+ return false;
333
+ }
334
+ const text = readString(value, context.code);
335
+ if (text === undefined || !isPlainAttribute(text)) {
336
+ return false;
337
+ }
338
+ unwrapString(value, '"', '"', context);
339
+ return true;
340
+ }
341
+
342
+ /**
343
+ * Whether a fragment is a branch of `? :`, or the right side of `&&`, `||`
344
+ * or `??`, where the lowering of `<Show>` and `<Switch>` leaves them. There a
345
+ * fragment around one element lowers the same as the element. Elsewhere,
346
+ * such as a function's return, Solid's JSX transform writes different code.
347
+ */
348
+ function isBranch(fragment: JSXFragment, context: PassContext): boolean {
349
+ let node: Node = fragment;
350
+ let parent = context.parents.get(node);
351
+ while (parent?.type === 'ParenthesizedExpression') {
352
+ node = parent;
353
+ parent = context.parents.get(node);
354
+ }
355
+ if (parent?.type === 'ConditionalExpression') {
356
+ return parent.consequent === node || parent.alternate === node;
357
+ }
358
+ return parent?.type === 'LogicalExpression' && parent.right === node;
359
+ }
360
+
361
+ export function tidyJSX(context: PassContext): boolean {
362
+ let changed = false;
363
+ const visit = (node: Node): void => {
364
+ if (node.type === 'JSXFragment' && isBranch(node, context)) {
365
+ const only = findOnlyElement(node, context.code);
366
+ if (only) {
367
+ // Everything around the element is line breaks or empty braces, so it all goes.
368
+ context.s.remove(node.start, only.start);
369
+ context.s.remove(only.end, node.end);
370
+ changed = true;
371
+ visit(only);
372
+ return;
373
+ }
374
+ }
375
+ const childrenFixed = node.type === 'JSXElement' && hasChildrenAttribute(node);
376
+ if ((node.type === 'JSXElement' || node.type === 'JSXFragment') && !childrenFixed) {
377
+ const inElement = node.type === 'JSXElement' && isIntrinsic(node);
378
+ if (tidyChildren(node.children, inElement, context)) {
379
+ changed = true;
380
+ }
381
+ }
382
+ if (node.type === 'JSXAttribute' && tidyAttribute(node, context)) {
383
+ changed = true;
384
+ return;
385
+ }
386
+ forEachChild(node, visit);
387
+ };
388
+ visit(context.program);
389
+ return changed;
390
+ }
package/src/vite/index.ts CHANGED
@@ -14,7 +14,7 @@
14
14
  * differently, and hydration needs both to render the same tree, so
15
15
  * hydrating builds only optimize within a module.
16
16
  */
17
- import { readFile } from 'node:fs/promises';
17
+ import { access, readFile } from 'node:fs/promises';
18
18
  import { createRequire } from 'node:module';
19
19
  import path from 'node:path';
20
20
  import { gzipSync } from 'node:zlib';
@@ -25,7 +25,7 @@ import type { Options as SolidPluginOptions } from '@solidjs/vite-plugin';
25
25
  import solidPlugin from '@solidjs/vite-plugin';
26
26
  import type { Node, Program } from 'oxc-parser';
27
27
  import type { Plugin, ResolvedConfig, Rollup } from 'vite';
28
- import { createFilter, minifySync, transformWithOxc } from 'vite';
28
+ import { createFilter, createIdResolver, minifySync, transformWithOxc } from 'vite';
29
29
  import type { CompileOptions, CompileResult, ModuleConstants } from '../compile';
30
30
  import { compile, readModuleConstants } from '../compile';
31
31
  import { collectParents, forEachChild, isIntrinsicTag, parse } from '../ast';
@@ -53,6 +53,8 @@ import {
53
53
  repairJSXSequences,
54
54
  } from './runtime';
55
55
 
56
+ type IdResolver = ReturnType<typeof createIdResolver>;
57
+
56
58
  export interface OptimizerOptions extends Pick<
57
59
  CompileOptions,
58
60
  'fold' | 'inline' | 'alwaysInline' | 'contexts' | 'memos' | 'conditionals' | 'maxPasses'
@@ -397,6 +399,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
397
399
  };
398
400
 
399
401
  let config: ResolvedConfig | undefined;
402
+ let idResolver: IdResolver | undefined;
400
403
  /** The `define` entries and `import.meta.env` values every environment shares. */
401
404
  let globals: Record<string, Primitive> = {};
402
405
  let compiler: Compiler | undefined;
@@ -511,6 +514,21 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
511
514
  readonly partial: boolean;
512
515
  }
513
516
 
517
+ /**
518
+ * Whether `id` names a file in the project that does not exist. An alias can resolve a
519
+ * Babel macro module, which a later plugin compiles away, to such a path. Loading it fails
520
+ * the build even when the error is caught, and it has nothing to read, so it is left to the
521
+ * bundler. A virtual module has an id that is not a project path, and is still loaded.
522
+ */
523
+ async function isMissingProjectFile(id: string): Promise<boolean> {
524
+ const file = stripQuery(id);
525
+ const root = config?.root ?? process.cwd();
526
+ const relative = path.relative(root, file);
527
+ const inProject =
528
+ path.isAbsolute(file) && !relative.startsWith('..') && !path.isAbsolute(relative);
529
+ return inProject && !(await fileExists(file));
530
+ }
531
+
514
532
  /**
515
533
  * The module an import resolves to, when its constants can be read, and
516
534
  * whether it has JSX. Dependencies are skipped to keep the build fast.
@@ -527,6 +545,9 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
527
545
  if (!resolved || resolved.external || resolved.id.includes('/node_modules/')) {
528
546
  return undefined;
529
547
  }
548
+ if (await isMissingProjectFile(resolved.id)) {
549
+ return undefined;
550
+ }
530
551
  return { id: resolved.id, jsx: isJSXModule(resolved.id) };
531
552
  }
532
553
 
@@ -782,7 +803,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
782
803
  try {
783
804
  return await readFile(stripQuery(id), 'utf8');
784
805
  } catch {
785
- if (isJSXModule(id)) {
806
+ if (isJSXModule(id) || (await isMissingProjectFile(id))) {
786
807
  return undefined;
787
808
  }
788
809
  }
@@ -829,7 +850,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
829
850
  const resolving = [];
830
851
  for (const source of runtimeImportSources(program)) {
831
852
  if (!moduleSources.includes(source) && !source.startsWith('node:')) {
832
- resolving.push(context.resolve(source, id));
853
+ resolving.push(resolveForWalk(context, source, id));
833
854
  }
834
855
  }
835
856
  const resolved = await Promise.all(resolving);
@@ -846,6 +867,34 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
846
867
  return pending;
847
868
  }
848
869
 
870
+ /**
871
+ * Resolves an import of a file on disk, for the walks that read imports from files. The
872
+ * import may never reach the bundler: a framework plugin can compile it away first, like
873
+ * the server-only imports of a module whose server functions become client stubs. Other
874
+ * plugins' `resolveId` hooks can act on every resolution they see, and TanStack Start's
875
+ * import protection reports one of those imports as a violation. So aliases and files are
876
+ * resolved without plugin hooks. Anything that is not a file path, like a virtual module or
877
+ * a runtime built-in, goes through the plugins.
878
+ */
879
+ async function resolveForWalk(
880
+ context: Rollup.PluginContext,
881
+ source: string,
882
+ importer: string,
883
+ ): Promise<{ id: string; external: boolean | 'absolute' | 'relative' } | null> {
884
+ const environment = (context as { environment?: Parameters<IdResolver>[0] }).environment;
885
+ if (config && environment) {
886
+ idResolver ??= createIdResolver(config);
887
+ const id = await idResolver(environment, source, importer);
888
+ // It returns a runtime built-in, like `cloudflare:workers`, as its own id. Only a file
889
+ // path is a module to read. Anything else gets the plugins' answer, which marks a
890
+ // built-in external.
891
+ if (id !== undefined && path.isAbsolute(stripQuery(id))) {
892
+ return { id, external: false };
893
+ }
894
+ }
895
+ return context.resolve(source, importer);
896
+ }
897
+
849
898
  /** Whether `from` imports `to`, directly or through other modules. */
850
899
  async function reaches(
851
900
  context: Rollup.PluginContext,
@@ -991,7 +1040,7 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
991
1040
  }
992
1041
  return buildUsageIndex(known ? scriptIds : [], {
993
1042
  resolve: async (source, importer) => {
994
- const resolved = await context.resolve(source, importer);
1043
+ const resolved = await resolveForWalk(context, source, importer);
995
1044
  return !resolved || resolved.external || resolved.id.includes('/node_modules/')
996
1045
  ? undefined
997
1046
  : resolved.id;
@@ -1542,6 +1591,8 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1542
1591
  configResolved(resolved) {
1543
1592
  config = resolved;
1544
1593
  globals = sharedGlobals(resolved);
1594
+ // The resolver captures the config, so a new config needs a new one.
1595
+ idResolver = undefined;
1545
1596
  },
1546
1597
  buildStart() {
1547
1598
  moduleConstants.clear();
@@ -1747,3 +1798,12 @@ export default function solidOptimizer(options: Options = {}): Plugin[] {
1747
1798
 
1748
1799
  return [modulePlugin, ...plugins, moduleTypePlugin, chunkPlugin];
1749
1800
  }
1801
+
1802
+ async function fileExists(file: string): Promise<boolean> {
1803
+ try {
1804
+ await access(file);
1805
+ return true;
1806
+ } catch {
1807
+ return false;
1808
+ }
1809
+ }