solid-optimizer 0.2.0 → 0.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 (53) hide show
  1. package/README.md +294 -14
  2. package/dist/compile-BQuBDA0Q.d.mts +199 -0
  3. package/dist/compile-BQuBDA0Q.d.mts.map +1 -0
  4. package/dist/compile-D3caSUtw.mjs +4244 -0
  5. package/dist/compile-D3caSUtw.mjs.map +1 -0
  6. package/dist/index.d.mts +2 -0
  7. package/dist/index.mjs +2 -0
  8. package/dist/vite.d.mts +53 -0
  9. package/dist/vite.d.mts.map +1 -0
  10. package/dist/vite.mjs +1743 -0
  11. package/dist/vite.mjs.map +1 -0
  12. package/package.json +60 -58
  13. package/src/ast.ts +271 -0
  14. package/src/compile.ts +355 -0
  15. package/src/constants.ts +249 -0
  16. package/src/context.ts +116 -0
  17. package/src/fold.ts +850 -0
  18. package/src/index.ts +5 -107
  19. package/src/inline.ts +2237 -0
  20. package/src/jsx.ts +170 -0
  21. package/src/memo.ts +416 -0
  22. package/src/provider.ts +899 -0
  23. package/src/scope.ts +588 -0
  24. package/src/server.ts +275 -0
  25. package/src/size.ts +309 -0
  26. package/src/value.ts +386 -0
  27. package/src/vite/index.ts +1378 -0
  28. package/src/vite/inject.ts +350 -0
  29. package/src/vite/namespace.ts +66 -0
  30. package/src/vite/refs.ts +99 -0
  31. package/src/vite/report.ts +74 -0
  32. package/src/vite/runtime.ts +370 -0
  33. package/src/vite/usage.ts +405 -0
  34. package/dist/cjs/development/index.cjs +0 -228
  35. package/dist/cjs/development/index.cjs.map +0 -7
  36. package/dist/cjs/production/index.cjs +0 -1
  37. package/dist/esm/development/index.mjs +0 -197
  38. package/dist/esm/development/index.mjs.map +0 -7
  39. package/dist/esm/production/index.mjs +0 -1
  40. package/dist/types/checks.d.ts +0 -9
  41. package/dist/types/checks.d.ts.map +0 -1
  42. package/dist/types/index.d.ts +0 -3
  43. package/dist/types/index.d.ts.map +0 -1
  44. package/dist/types/path-references-import.d.ts +0 -3
  45. package/dist/types/path-references-import.d.ts.map +0 -1
  46. package/dist/types/unwrap-node.d.ts +0 -7
  47. package/dist/types/unwrap-node.d.ts.map +0 -1
  48. package/dist/types/unwrap-path.d.ts +0 -6
  49. package/dist/types/unwrap-path.d.ts.map +0 -1
  50. package/src/checks.ts +0 -42
  51. package/src/path-references-import.ts +0 -82
  52. package/src/unwrap-node.ts +0 -27
  53. package/src/unwrap-path.ts +0 -18
@@ -0,0 +1,1378 @@
1
+ /**
2
+ * `solid-optimizer/vite`: `vite-plugin-solid` with the optimizer built in.
3
+ *
4
+ * It takes the same options as `vite-plugin-solid`, plus `optimizer`, and
5
+ * returns the official plugin with the optimizer wired in. It runs in one of
6
+ * two modes.
7
+ *
8
+ * - Chunk mode keeps JSX through bundling. Each chunk is optimized as a whole
9
+ * and then lowered by Solid's JSX transform, so a component inlines into
10
+ * any other component in the same chunk. It applies to client builds that
11
+ * do not hydrate.
12
+ * - Module mode optimizes each module before the official plugin lowers it.
13
+ * It applies everywhere else. A server build and its client build chunk
14
+ * differently, and hydration needs both to render the same tree, so
15
+ * hydrating builds only optimize within a module.
16
+ */
17
+ import { readFile } from 'node:fs/promises';
18
+ import { createRequire } from 'node:module';
19
+ import path from 'node:path';
20
+ import remapping from '@jridgewell/remapping';
21
+ import type * as Babel from '@babel/core';
22
+ import MagicString from 'magic-string';
23
+ import type { Node, Program } from 'oxc-parser';
24
+ import type { Plugin, ResolvedConfig, Rollup } from 'vite';
25
+ import { createFilter, transformWithOxc } from 'vite';
26
+ import type { Options as SolidPluginOptions } from 'vite-plugin-solid';
27
+ import solidPlugin from 'vite-plugin-solid';
28
+ import type { CompileOptions, CompileResult, ModuleConstants } from '../compile';
29
+ import { compile, readModuleConstants } from '../compile';
30
+ import { collectParents, forEachChild, isIntrinsicTag, parse } from '../ast';
31
+ import { analyzeScopes } from '../scope';
32
+ import { CONTEXT_SAFE_PRIMITIVES } from '../provider';
33
+ import type { ImportedConstants } from '../constants';
34
+ import type { Primitive } from '../value';
35
+ import type { Skip } from '../context';
36
+ import type { OptimizerReport } from './report';
37
+ import { formatReport } from './report';
38
+ import { exposeLocals, readExportedComponent } from './inject';
39
+ import { nameNamespaceTags } from './namespace';
40
+ import { protectRefs, restoreRefs } from './refs';
41
+ import type { UsageIndex } from './usage';
42
+ import { buildUsageIndex } from './usage';
43
+ import {
44
+ MARKER,
45
+ MissingHelperError,
46
+ addMarker,
47
+ linkHelpers,
48
+ readMarkers,
49
+ repairJSXSequences,
50
+ } from './runtime';
51
+
52
+ export interface OptimizerOptions extends Pick<
53
+ CompileOptions,
54
+ 'fold' | 'inline' | 'alwaysInline' | 'contexts' | 'memos' | 'maxPasses'
55
+ > {
56
+ /**
57
+ * Reduce Solid's reactive primitives to what they do on the server, in
58
+ * server builds. See the `server` option of `compile`.
59
+ *
60
+ * @default true
61
+ */
62
+ server?: boolean;
63
+ /**
64
+ * Where the optimizer runs.
65
+ *
66
+ * - `auto` uses chunk mode for client builds that do not hydrate, and module mode otherwise.
67
+ * - `module` optimizes each module on its own.
68
+ *
69
+ * @default 'auto'
70
+ */
71
+ mode?: 'auto' | 'module';
72
+ /**
73
+ * Also optimize while serving, in module mode.
74
+ *
75
+ * @default false
76
+ */
77
+ dev?: boolean;
78
+ /**
79
+ * Report what the optimizer leaves alone in each build, and why: each
80
+ * component call that stays a call, each provider that stays, and each
81
+ * memo that stays. `true` prints the report. A function receives it
82
+ * instead, once per build environment.
83
+ *
84
+ * @default false
85
+ */
86
+ report?: boolean | ((report: OptimizerReport) => void);
87
+ }
88
+
89
+ export type { OptimizerReport } from './report';
90
+
91
+ export interface Options extends Partial<SolidPluginOptions> {
92
+ /** Set to `false` to use `vite-plugin-solid` as it is. */
93
+ optimizer?: OptimizerOptions | false;
94
+ }
95
+
96
+ /** The options `babel-preset-solid` takes. */
97
+ type JSXOptions = NonNullable<SolidPluginOptions['solid']> & {
98
+ generate?: 'dom' | 'ssr' | 'universal';
99
+ hydratable?: boolean;
100
+ };
101
+
102
+ interface Compiler {
103
+ readonly babel: typeof Babel;
104
+ readonly preset: Babel.PluginTarget;
105
+ }
106
+
107
+ const DEFAULT_MODULE_NAME = 'solid-js/web';
108
+
109
+ const DEFAULT_BUILT_INS = [
110
+ 'For',
111
+ 'Show',
112
+ 'Switch',
113
+ 'Match',
114
+ 'Suspense',
115
+ 'SuspenseList',
116
+ 'Portal',
117
+ 'Index',
118
+ 'Dynamic',
119
+ 'ErrorBoundary',
120
+ ];
121
+
122
+ const JSX_MODULE = /\.[mc]?[jt]sx$/i;
123
+
124
+ /**
125
+ * Helpers the JSX transform picks between for the same attribute. Inlining
126
+ * can turn one form into the other: a style object that was a prop becomes a
127
+ * literal, which the transform writes one property at a time. A module that
128
+ * needs one keeps the other too.
129
+ */
130
+ const RELATED_HELPERS: Readonly<Record<string, readonly string[]>> = {
131
+ style: ['setStyleProperty'],
132
+ setStyleProperty: ['style'],
133
+ };
134
+
135
+ function withRelated(helpers: readonly string[]): Set<string> {
136
+ const result = new Set(helpers);
137
+ for (const helper of helpers) {
138
+ for (const related of RELATED_HELPERS[helper] ?? []) {
139
+ result.add(related);
140
+ }
141
+ }
142
+ return result;
143
+ }
144
+
145
+ /**
146
+ * The common kinds of attribute: a class, any other attribute, events, and
147
+ * children. Inlining a component turns a spread onto an element into
148
+ * attributes like these, in a module that may not use their helpers itself.
149
+ * A rarer kind, like `style`, can still need a helper no module imports.
150
+ * The chunk is then lowered without optimizing it.
151
+ */
152
+ const ATTRIBUTE_SAMPLE = `const a = () => 0;
153
+ export const Sample = () => (
154
+ <div class={a()} id={a()} onClick={a()} onScroll={a()}>{a()}</div>
155
+ );`;
156
+
157
+ /** Whether the code spreads anything onto an intrinsic element. */
158
+ function spreadsOntoElement(code: string, filename: string): boolean {
159
+ if (!code.includes('...')) {
160
+ return false;
161
+ }
162
+ let found = false;
163
+ const visit = (node: Node): void => {
164
+ if (found) {
165
+ return;
166
+ }
167
+ if (
168
+ node.type === 'JSXOpeningElement' &&
169
+ node.name.type === 'JSXIdentifier' &&
170
+ isIntrinsicTag(node.name.name) &&
171
+ node.attributes.some((attribute) => attribute.type === 'JSXSpreadAttribute')
172
+ ) {
173
+ found = true;
174
+ return;
175
+ }
176
+ forEachChild(node, visit);
177
+ };
178
+ visit(parse(filename, code));
179
+ return found;
180
+ }
181
+
182
+ function loadCompiler(): Compiler {
183
+ // Use the Babel and preset `vite-plugin-solid` uses, so both lower JSX the same way.
184
+ const require = createRequire(import.meta.url);
185
+ const pluginRequire = createRequire(require.resolve('vite-plugin-solid'));
186
+ const presetRequire = createRequire(pluginRequire.resolve('babel-preset-solid'));
187
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
188
+ const babel = presetRequire('@babel/core') as typeof Babel;
189
+ const preset: unknown = pluginRequire('babel-preset-solid');
190
+ if (typeof preset !== 'function') {
191
+ throw new TypeError('[solid-optimizer] babel-preset-solid did not load');
192
+ }
193
+ return { babel, preset };
194
+ }
195
+
196
+ /**
197
+ * Lowers JSX with `babel-preset-solid`, as `vite-plugin-solid` does.
198
+ */
199
+ function lower(
200
+ compiler: Compiler,
201
+ code: string,
202
+ filename: string,
203
+ options: JSXOptions,
204
+ sourceMaps: boolean,
205
+ ): { code: string; map: string | undefined } {
206
+ const result = compiler.babel.transformSync(code, {
207
+ filename,
208
+ sourceFileName: filename,
209
+ presets: [[compiler.preset, options]],
210
+ ast: false,
211
+ sourceMaps,
212
+ configFile: false,
213
+ babelrc: false,
214
+ parserOpts: {
215
+ plugins: /\.[mc]?tsx$/i.test(filename) ? ['jsx', 'typescript'] : ['jsx'],
216
+ },
217
+ });
218
+ // An empty module, like a chunk a library build left empty, lowers to ''.
219
+ if (typeof result?.code !== 'string') {
220
+ throw new Error(`[solid-optimizer] babel-preset-solid produced no code for ${filename}`);
221
+ }
222
+ return { code: result.code, map: result.map ? JSON.stringify(result.map) : undefined };
223
+ }
224
+
225
+ /**
226
+ * The helpers `babel-preset-solid` imports from `moduleName` to lower `code`.
227
+ * Only the AST is built, since its code would only be read for its imports.
228
+ */
229
+ function helpersOf(
230
+ compiler: Compiler,
231
+ code: string,
232
+ filename: string,
233
+ options: JSXOptions,
234
+ moduleName: string,
235
+ ): string[] {
236
+ const result = compiler.babel.transformSync(code, {
237
+ filename,
238
+ presets: [[compiler.preset, options]],
239
+ ast: true,
240
+ code: false,
241
+ configFile: false,
242
+ babelrc: false,
243
+ parserOpts: {
244
+ plugins: /\.[mc]?tsx$/i.test(filename) ? ['jsx', 'typescript'] : ['jsx'],
245
+ },
246
+ });
247
+ const names: string[] = [];
248
+ for (const statement of result?.ast?.program.body ?? []) {
249
+ if (statement.type !== 'ImportDeclaration' || statement.source.value !== moduleName) {
250
+ continue;
251
+ }
252
+ for (const specifier of statement.specifiers) {
253
+ // Generated imports are named `_$helper`, which the module's own are not.
254
+ if (specifier.type === 'ImportSpecifier' && specifier.local.name.startsWith('_$')) {
255
+ const { imported } = specifier;
256
+ names.push(imported.type === 'StringLiteral' ? imported.value : imported.name);
257
+ }
258
+ }
259
+ }
260
+ return names;
261
+ }
262
+
263
+ function stripQuery(id: string): string {
264
+ return id.replace(/\?.*$/, '');
265
+ }
266
+
267
+ /**
268
+ * Chains the maps of each step into one, or `null` when the build writes no
269
+ * source maps, since chaining the maps of a large chunk takes a while.
270
+ */
271
+ function combineMaps(wanted: boolean, maps: (string | null | undefined)[]): string | null {
272
+ const present = maps.filter((map): map is string => typeof map === 'string');
273
+ if (!wanted || present.length === 0) {
274
+ return null;
275
+ }
276
+ return remapping(present.reverse(), () => null).toString();
277
+ }
278
+
279
+ /**
280
+ * The local name of each value a module imports, keyed by its source and
281
+ * the name it is imported as: an export name, `default`, or `*`.
282
+ */
283
+ function importedNames(program: Program): Map<string, string> {
284
+ const names = new Map<string, string>();
285
+ for (const statement of program.body) {
286
+ if (statement.type !== 'ImportDeclaration' || statement.importKind === 'type') {
287
+ continue;
288
+ }
289
+ for (const specifier of statement.specifiers) {
290
+ let imported = '*';
291
+ if (specifier.type === 'ImportDefaultSpecifier') {
292
+ imported = 'default';
293
+ } else if (specifier.type === 'ImportSpecifier') {
294
+ imported =
295
+ specifier.imported.type === 'Identifier'
296
+ ? specifier.imported.name
297
+ : specifier.imported.value;
298
+ }
299
+ const typeOnly = specifier.type === 'ImportSpecifier' && specifier.importKind === 'type';
300
+ if (!typeOnly) {
301
+ names.set(`${statement.source.value}\0${imported}`, specifier.local.name);
302
+ }
303
+ }
304
+ }
305
+ return names;
306
+ }
307
+
308
+ /**
309
+ * A key for a module in the build environment of `context`. The server and
310
+ * client builds transform the same module into different code.
311
+ */
312
+ function environmentKey(context: { environment?: { name: string } }, id: string): string {
313
+ return `${context.environment?.name ?? ''}\0${id}`;
314
+ }
315
+
316
+ function isClient(context: { environment?: { config: { consumer: string } } }): boolean {
317
+ return context.environment?.config.consumer === 'client';
318
+ }
319
+
320
+ export default function solidOptimizer(options: Options = {}): Plugin[] {
321
+ const { optimizer: optimizerOption, ...solidOptions } = options;
322
+ const main = solidPlugin(solidOptions);
323
+ if (optimizerOption === false) {
324
+ return [main];
325
+ }
326
+ const optimizer = optimizerOption ?? {};
327
+ const moduleName = solidOptions.solid?.moduleName ?? DEFAULT_MODULE_NAME;
328
+ const moduleSources = [...new Set(['solid-js', DEFAULT_MODULE_NAME, moduleName])];
329
+ const builtIns = new Set(solidOptions.solid?.builtIns ?? DEFAULT_BUILT_INS);
330
+ const compileOptions: CompileOptions = {
331
+ fold: optimizer.fold,
332
+ inline: optimizer.inline,
333
+ alwaysInline: optimizer.alwaysInline,
334
+ contexts: optimizer.contexts,
335
+ memos: optimizer.memos,
336
+ maxPasses: optimizer.maxPasses,
337
+ builtIns: [...builtIns],
338
+ moduleSources,
339
+ report: optimizer.report !== undefined && optimizer.report !== false,
340
+ };
341
+
342
+ let config: ResolvedConfig | undefined;
343
+ /**
344
+ * A skip's name with the module it names, like `Card (/app/src/card.tsx)`,
345
+ * relative to the project root, or to `node_modules` for a package.
346
+ */
347
+ const shortName = (name: string): string =>
348
+ name.replace(/\((\/.*)\)$/, (whole, file: string) => {
349
+ const index = file.lastIndexOf('/node_modules/');
350
+ if (index !== -1) {
351
+ return `(${file.slice(index + '/node_modules/'.length)})`;
352
+ }
353
+ return config ? `(${path.relative(config.root, file)})` : whole;
354
+ });
355
+
356
+ /** What the final compile of each chunk or module left alone, by environment. */
357
+ const skips = new Map<string, Skip[]>();
358
+ const addSkips = (context: { environment?: { name: string } }, list?: readonly Skip[]): void => {
359
+ if (!list) {
360
+ return;
361
+ }
362
+ const environment = context.environment?.name ?? 'client';
363
+ const entries = skips.get(environment) ?? [];
364
+ entries.push(...list.map((skip) => ({ ...skip, name: shortName(skip.name) })));
365
+ skips.set(environment, entries);
366
+ };
367
+
368
+ let compiler: Compiler | undefined;
369
+ let filter: ((id: string) => boolean) | undefined;
370
+ const getCompiler = (): Compiler => {
371
+ compiler ??= loadCompiler();
372
+ return compiler;
373
+ };
374
+
375
+ const isBuild = (): boolean => config?.command === 'build';
376
+ /** Whether the output needs source maps: while serving, or when the build writes them. */
377
+ const wantsMaps = (): boolean => !isBuild() || Boolean(config?.build.sourcemap);
378
+
379
+ /**
380
+ * The JSX options the official plugin passes for a posture, so the
381
+ * lowering here matches it. Mirrors the `transform` hook of `vite-plugin-solid`.
382
+ */
383
+ const jsxOptions = (isSsr: boolean): JSXOptions => {
384
+ let posture: JSXOptions = { generate: 'dom', hydratable: false };
385
+ if (solidOptions.ssr) {
386
+ posture = { generate: isSsr ? 'ssr' : 'dom', hydratable: true };
387
+ }
388
+ return { ...posture, ...solidOptions.solid };
389
+ };
390
+
391
+ let sampleHelpers: string[] | undefined;
392
+ /** The helpers the JSX transform uses for attributes in chunk mode. */
393
+ const attributeHelpers = (): string[] => {
394
+ sampleHelpers ??= helpersOf(
395
+ getCompiler(),
396
+ ATTRIBUTE_SAMPLE,
397
+ 'sample.jsx',
398
+ jsxOptions(false),
399
+ moduleName,
400
+ );
401
+ return sampleHelpers;
402
+ };
403
+
404
+ /**
405
+ * Whether client builds keep JSX until chunks are rendered.
406
+ */
407
+ const chunkMode = (): boolean => {
408
+ if (!isBuild() || (optimizer.mode ?? 'auto') !== 'auto') {
409
+ return false;
410
+ }
411
+ // The user's Babel plugins have to see the modules, which chunk mode skips.
412
+ if (solidOptions.babel) {
413
+ return false;
414
+ }
415
+ const client = jsxOptions(false);
416
+ return client.generate === 'dom' && client.hydratable !== true;
417
+ };
418
+
419
+ const isJSXModule = (id: string): boolean => {
420
+ filter ??= createFilter(solidOptions.include, solidOptions.exclude);
421
+ return filter(id) && JSX_MODULE.test(stripQuery(id));
422
+ };
423
+
424
+ /** Modules that keep their JSX, which the bundler must parse as JSX. */
425
+ const preserved = new Set<string>();
426
+
427
+ /** What each module imports and the constants it exports, by module id. */
428
+ const moduleConstants = new Map<string, Promise<ModuleConstants | undefined>>();
429
+
430
+ /**
431
+ * The module an import resolves to, when its constants can be read.
432
+ *
433
+ * A module with JSX is skipped. This plugin's transform may be waiting for
434
+ * it, and it may be waiting for this one, so loading it could deadlock.
435
+ * Dependencies are skipped to keep the build fast.
436
+ */
437
+ async function resolveConstantModule(
438
+ context: Rollup.PluginContext,
439
+ specifier: string,
440
+ importer: string,
441
+ ): Promise<string | undefined> {
442
+ if (moduleSources.includes(specifier)) {
443
+ return undefined;
444
+ }
445
+ const resolved = await context.resolve(specifier, importer);
446
+ if (
447
+ !resolved ||
448
+ resolved.external ||
449
+ resolved.id.includes('/node_modules/') ||
450
+ isJSXModule(resolved.id)
451
+ ) {
452
+ return undefined;
453
+ }
454
+ return resolved.id;
455
+ }
456
+
457
+ /**
458
+ * The constants of the modules `code` imports, keyed by import specifier.
459
+ *
460
+ * Each module is read as the bundler loads it, after every plugin has
461
+ * transformed it, so a plugin that replaces or rewrites a module is seen.
462
+ * A module that imports constants itself resolves them first, and a cycle
463
+ * leaves the modules in it without them.
464
+ */
465
+ async function importedConstants(
466
+ context: Rollup.PluginContext,
467
+ imports: readonly string[],
468
+ importer: string,
469
+ visiting: ReadonlySet<string>,
470
+ ): Promise<ImportedConstants> {
471
+ const entries = await Promise.all(
472
+ imports.map(async (specifier) => {
473
+ const id = await resolveConstantModule(context, specifier, importer);
474
+ if (id === undefined || visiting.has(id)) {
475
+ return undefined;
476
+ }
477
+ const constants = await constantsOf(context, id, visiting);
478
+ if (!constants || Object.keys(constants.exports).length === 0) {
479
+ return undefined;
480
+ }
481
+ return [specifier, constants.exports] as const;
482
+ }),
483
+ );
484
+ return Object.fromEntries(
485
+ entries.filter(
486
+ (entry): entry is readonly [string, Record<string, Primitive>] => entry !== undefined,
487
+ ),
488
+ );
489
+ }
490
+
491
+ async function constantsOf(
492
+ context: Rollup.PluginContext,
493
+ id: string,
494
+ visiting: ReadonlySet<string>,
495
+ ): Promise<ModuleConstants | undefined> {
496
+ let pending = moduleConstants.get(id);
497
+ if (!pending) {
498
+ pending = (async () => {
499
+ const { code } = await context.load({ id });
500
+ if (code === null) {
501
+ return undefined;
502
+ }
503
+ // Loaded code is JavaScript, whatever the module was written in.
504
+ const filename = `${stripQuery(id)}.js`;
505
+ try {
506
+ const own = readModuleConstants(code, { filename });
507
+ if (own.imports.length === 0) {
508
+ return own;
509
+ }
510
+ const imported = await importedConstants(
511
+ context,
512
+ own.imports,
513
+ id,
514
+ new Set([...visiting, id]),
515
+ );
516
+ return readModuleConstants(code, { filename, importedConstants: imported });
517
+ } catch (error) {
518
+ // A module the parser rejects fails its own transform, with a better error.
519
+ if (error instanceof SyntaxError) {
520
+ return undefined;
521
+ }
522
+ throw error;
523
+ }
524
+ })();
525
+ moduleConstants.set(id, pending);
526
+ }
527
+ return pending;
528
+ }
529
+
530
+ /**
531
+ * The compile options for a module, with the constants of its imports.
532
+ */
533
+ async function moduleOptions(
534
+ context: Rollup.PluginContext,
535
+ code: string,
536
+ id: string,
537
+ ): Promise<CompileOptions> {
538
+ const filename = stripQuery(id);
539
+ // The dev server cannot give back the code of a loaded module.
540
+ if (optimizer.fold === false || !isBuild()) {
541
+ return { ...compileOptions, filename, sourceMap: wantsMaps() };
542
+ }
543
+ const { imports } = readModuleConstants(code, { filename });
544
+ return {
545
+ ...compileOptions,
546
+ filename,
547
+ sourceMap: wantsMaps(),
548
+ importedConstants: await importedConstants(context, imports, filename, new Set([filename])),
549
+ };
550
+ }
551
+
552
+ /** The modules each transform waits for, so two never wait for each other. */
553
+ const waiting = new Map<string, Set<string>>();
554
+
555
+ /** Whether the transform of `from` waits, directly or not, for `to`. */
556
+ const waitsFor = (from: string, to: string): boolean => {
557
+ const seen = new Set<string>();
558
+ const stack = [from];
559
+ for (let current = stack.pop(); current !== undefined; current = stack.pop()) {
560
+ if (current === to) {
561
+ return true;
562
+ }
563
+ if (!seen.has(current)) {
564
+ seen.add(current);
565
+ stack.push(...(waiting.get(current) ?? []));
566
+ }
567
+ }
568
+ return false;
569
+ };
570
+
571
+ /**
572
+ * The code of a module with JSX, as the bundler loads it. `undefined`
573
+ * when that module's transform waits for the importer, which would then
574
+ * wait for it in turn.
575
+ */
576
+ async function loadModule(
577
+ context: Rollup.PluginContext,
578
+ importer: string,
579
+ target: string,
580
+ ): Promise<string | undefined> {
581
+ if (waitsFor(target, importer)) {
582
+ return undefined;
583
+ }
584
+ const targets = waiting.get(importer) ?? new Set<string>();
585
+ targets.add(target);
586
+ waiting.set(importer, targets);
587
+ try {
588
+ const info = await context.load({ id: target });
589
+ return info.code ?? undefined;
590
+ } finally {
591
+ targets.delete(target);
592
+ }
593
+ }
594
+
595
+ /**
596
+ * The code of each module with JSX as this plugin's module step returned
597
+ * it, before Solid's JSX transform lowers it. In module mode, an importer
598
+ * copies components from it.
599
+ */
600
+ const recorded = new Map<string, string>();
601
+
602
+ /** The modules with JSX each module imports, read from its file. */
603
+ const jsxImports = new Map<string, Promise<string[]>>();
604
+
605
+ /**
606
+ * The modules with JSX a module imports. They come from the file on disk,
607
+ * so they do not depend on the order modules are transformed in.
608
+ */
609
+ async function jsxImportsOf(context: Rollup.PluginContext, id: string): Promise<string[]> {
610
+ let pending = jsxImports.get(id);
611
+ if (!pending) {
612
+ pending = (async () => {
613
+ let code: string;
614
+ try {
615
+ code = await readFile(stripQuery(id), 'utf8');
616
+ } catch {
617
+ return [];
618
+ }
619
+ let program: Program;
620
+ try {
621
+ program = parse(stripQuery(id), code);
622
+ } catch {
623
+ return [];
624
+ }
625
+ const sources = new Set<string>();
626
+ for (const statement of program.body) {
627
+ if (
628
+ (statement.type === 'ImportDeclaration' && statement.importKind !== 'type') ||
629
+ ((statement.type === 'ExportNamedDeclaration' ||
630
+ statement.type === 'ExportAllDeclaration') &&
631
+ statement.source &&
632
+ statement.exportKind !== 'type')
633
+ ) {
634
+ const value = statement.source?.value;
635
+ if (value !== undefined && !moduleSources.includes(value)) {
636
+ sources.add(value);
637
+ }
638
+ }
639
+ }
640
+ const resolved = await Promise.all(
641
+ [...sources].map(async (source) => context.resolve(source, id)),
642
+ );
643
+ return resolved
644
+ .filter((target) => target && !target.external && isJSXModule(target.id))
645
+ .map((target) => target?.id ?? '');
646
+ })();
647
+ jsxImports.set(id, pending);
648
+ }
649
+ return pending;
650
+ }
651
+
652
+ /** Whether `from` imports `to`, directly or through other modules with JSX. */
653
+ async function reaches(
654
+ context: Rollup.PluginContext,
655
+ from: string,
656
+ to: string,
657
+ ): Promise<boolean> {
658
+ const seen = new Set<string>();
659
+ let frontier = [from];
660
+ while (frontier.length > 0) {
661
+ if (frontier.includes(to)) {
662
+ return true;
663
+ }
664
+ for (const id of frontier) {
665
+ seen.add(id);
666
+ }
667
+ // oxlint-disable-next-line no-await-in-loop
668
+ const next = await Promise.all(frontier.map(async (id) => jsxImportsOf(context, id)));
669
+ frontier = [...new Set(next.flat())].filter((id) => !seen.has(id));
670
+ }
671
+ return false;
672
+ }
673
+
674
+ /**
675
+ * The code of a module with JSX before Solid's JSX transform, with its
676
+ * types stripped. A module that imports the importer back is skipped, so
677
+ * no two transforms wait for each other, and the server and client builds
678
+ * skip the same ones.
679
+ */
680
+ async function loadRecorded(
681
+ context: Rollup.PluginContext,
682
+ importer: string,
683
+ target: string,
684
+ ): Promise<string | undefined> {
685
+ if (await reaches(context, target, importer)) {
686
+ return undefined;
687
+ }
688
+ await context.load({ id: target });
689
+ const code = recorded.get(environmentKey(context, target));
690
+ if (code === undefined) {
691
+ return undefined;
692
+ }
693
+ const stripped = await transformWithOxc(code, stripQuery(target), {
694
+ jsx: 'preserve',
695
+ sourcemap: false,
696
+ });
697
+ return stripped.code;
698
+ }
699
+
700
+ /**
701
+ * The scripts an entry runs: the entry itself, or the module scripts of an
702
+ * HTML entry. `undefined` when an HTML entry has an inline module script,
703
+ * whose imports the usage index cannot read.
704
+ */
705
+ async function scriptEntries(
706
+ context: Rollup.PluginContext,
707
+ id: string,
708
+ ): Promise<string[] | undefined> {
709
+ if (/\.[mc]?[jt]sx?(?:\?|$)/.test(id)) {
710
+ return [id];
711
+ }
712
+ let html: string;
713
+ try {
714
+ html = await readFile(stripQuery(id), 'utf8');
715
+ } catch {
716
+ return undefined;
717
+ }
718
+ const scripts: string[] = [];
719
+ for (const [tag] of html.matchAll(/<script\b[^>]*>/gi)) {
720
+ if (!/\btype\s*=\s*["']?module/i.test(tag)) {
721
+ continue;
722
+ }
723
+ const src = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1];
724
+ if (src === undefined) {
725
+ return undefined;
726
+ }
727
+ // oxlint-disable-next-line no-await-in-loop
728
+ const resolved = await context.resolve(src, id);
729
+ if (!resolved || resolved.external) {
730
+ return undefined;
731
+ }
732
+ scripts.push(resolved.id);
733
+ }
734
+ return scripts;
735
+ }
736
+
737
+ /** How the app uses each export, built once per environment and build. */
738
+ const usageIndexes = new Map<string, Promise<UsageIndex>>();
739
+
740
+ /**
741
+ * How the app uses each export, read from the modules the entries reach.
742
+ */
743
+ async function usageIndex(context: Rollup.PluginContext): Promise<UsageIndex> {
744
+ const key = environmentKey(context, '');
745
+ let pending = usageIndexes.get(key);
746
+ if (!pending) {
747
+ pending = (async () => {
748
+ const entries = await Promise.all(
749
+ [...context.getModuleIds()]
750
+ .filter((id) => context.getModuleInfo(id)?.isEntry === true)
751
+ .map(async (id) => scriptEntries(context, id)),
752
+ );
753
+ // A script the index cannot read could use any export.
754
+ const known = entries.every((scripts) => scripts !== undefined);
755
+ return buildUsageIndex(known ? entries.flat() : [], {
756
+ resolve: async (source, importer) => {
757
+ const resolved = await context.resolve(source, importer);
758
+ return !resolved || resolved.external || resolved.id.includes('/node_modules/')
759
+ ? undefined
760
+ : resolved.id;
761
+ },
762
+ read: async (id) => {
763
+ try {
764
+ return await readFile(stripQuery(id), 'utf8');
765
+ } catch {
766
+ return undefined;
767
+ }
768
+ },
769
+ });
770
+ })();
771
+ usageIndexes.set(key, pending);
772
+ }
773
+ return pending;
774
+ }
775
+
776
+ /**
777
+ * The text that imports a binding under `local`.
778
+ */
779
+ function importText(local: string, imported: string, source: string): string {
780
+ const from = JSON.stringify(source);
781
+ if (imported === '*') {
782
+ return `import * as ${local} from ${from};`;
783
+ }
784
+ if (imported === 'default') {
785
+ return `import ${local} from ${from};`;
786
+ }
787
+ return `import { ${imported} as ${local} } from ${from};`;
788
+ }
789
+
790
+ interface Copy {
791
+ /** The module and export the copy comes from. */
792
+ readonly key: string;
793
+ readonly name: string;
794
+ /** The tags in the importer that call it. */
795
+ readonly tags: Node[];
796
+ readonly text: string;
797
+ }
798
+
799
+ interface CopyState {
800
+ /** Components that cannot be copied, or were left over before. */
801
+ readonly excluded: Set<string>;
802
+ /** The contexts the copies import, by module. */
803
+ readonly contexts: Map<string, Set<string>>;
804
+ /** Imports a binding into the importer, and gives its local name. */
805
+ readonly importAs: (base: string, imported: string, from: string) => string;
806
+ /** The code of a module with JSX to copy from, or `undefined` to skip it. */
807
+ readonly load: (target: string) => Promise<string | undefined>;
808
+ /** Where the copies that are not made are recorded, when the report is on. */
809
+ readonly skips: Skip[] | undefined;
810
+ }
811
+
812
+ /**
813
+ * Reads the component `source` exports as `imported`, and imports what it
814
+ * needs into the importer. `undefined` when it cannot be copied.
815
+ */
816
+ async function copyImported(
817
+ context: Rollup.PluginContext,
818
+ id: string,
819
+ source: string,
820
+ imported: string,
821
+ state: CopyState,
822
+ ): Promise<{ key: string; text: (name: string) => string } | undefined> {
823
+ const skip = (reason: string): void => {
824
+ state.skips?.push({ pass: 'inline', reason, name: `${imported} (${source})` });
825
+ };
826
+ const resolved = await context.resolve(source, id);
827
+ if (!resolved || resolved.external) {
828
+ skip('copy-external');
829
+ return undefined;
830
+ }
831
+ if (resolved.id.includes('/node_modules/')) {
832
+ skip('copy-package');
833
+ return undefined;
834
+ }
835
+ if (resolved.id === id) {
836
+ return undefined;
837
+ }
838
+ if (!isJSXModule(resolved.id)) {
839
+ skip('copy-not-jsx');
840
+ return undefined;
841
+ }
842
+ const key = `${resolved.id}\0${imported}`;
843
+ if (state.excluded.has(key)) {
844
+ return undefined;
845
+ }
846
+ const loaded = await state.load(resolved.id);
847
+ if (loaded === undefined) {
848
+ state.excluded.add(key);
849
+ skip('copy-cycle');
850
+ return undefined;
851
+ }
852
+ const component = readExportedComponent(
853
+ loaded,
854
+ stripQuery(resolved.id),
855
+ imported,
856
+ moduleSources,
857
+ );
858
+ if (!component) {
859
+ state.excluded.add(key);
860
+ skip('copy-shape');
861
+ return undefined;
862
+ }
863
+ // Its copy would still call a component of that module, so the call
864
+ // site gains nothing. Moving its template out of its module makes both
865
+ // compress worse.
866
+ if (component.wrapsLocal) {
867
+ state.excluded.add(key);
868
+ skip('copy-wrapper');
869
+ return undefined;
870
+ }
871
+ // Each import of the module resolves from it, so the copy imports the same module.
872
+ const targets = new Map<string, string>();
873
+ for (const dependency of component.dependencies.values()) {
874
+ if (dependency.kind === 'import' && !moduleSources.includes(dependency.source)) {
875
+ // oxlint-disable-next-line no-await-in-loop
876
+ const target = await context.resolve(dependency.source, resolved.id);
877
+ if (!target) {
878
+ state.excluded.add(key);
879
+ skip('copy-external');
880
+ return undefined;
881
+ }
882
+ targets.set(dependency.source, target.external ? dependency.source : target.id);
883
+ }
884
+ }
885
+ const rename = new Map<string, string>();
886
+ for (const [local, dependency] of component.dependencies) {
887
+ if (dependency.kind === 'import') {
888
+ const from = targets.get(dependency.source) ?? dependency.source;
889
+ rename.set(local, state.importAs(local, dependency.imported, from));
890
+ continue;
891
+ }
892
+ rename.set(local, state.importAs(local, dependency.exported, resolved.id));
893
+ if (dependency.context) {
894
+ const known = state.contexts.get(resolved.id) ?? new Set<string>();
895
+ known.add(dependency.exported);
896
+ state.contexts.set(resolved.id, known);
897
+ }
898
+ }
899
+ return { key, text: (name) => component.copy(name, rename) };
900
+ }
901
+
902
+ /**
903
+ * Copies the components a module imports from other modules with JSX into
904
+ * it, and inlines them there. A copy the inline pass cannot inline at
905
+ * every call is left out, so a component is never in both places. Copies
906
+ * can import components in turn, which a few more rounds take in.
907
+ */
908
+ async function inlineImports(
909
+ context: Rollup.PluginContext,
910
+ source: string,
911
+ id: string,
912
+ compileOptionsOfModule: CompileOptions,
913
+ load: (target: string) => Promise<string | undefined>,
914
+ copySkips?: Skip[],
915
+ ): Promise<{ code: string; maps: string[]; skipped?: Skip[] } | undefined> {
916
+ const filename = stripQuery(id);
917
+ const maps: string[] = [];
918
+ let skipped: Skip[] | undefined;
919
+ const excluded = new Set<string>();
920
+ const usage = await usageIndex(context);
921
+ // The components copied here that leave their module, by module.
922
+ const absorbed = new Map<string, Set<string>>();
923
+ // How many modules use the original of a copy, this one included.
924
+ const usersOf = (copy: Copy): number => {
925
+ const [module = '', exported = ''] = copy.key.split('\0');
926
+ return usage.users(module, exported, id, absorbed);
927
+ };
928
+ // The contexts the copies import, which the provider pass needs to know.
929
+ const contexts = new Map<string, Set<string>>();
930
+ let code = source;
931
+ const copyNames = new Map<string, string>();
932
+ for (let round = 0; round < 4; round += 1) {
933
+ const program = parse(filename, code);
934
+ const scopes = analyzeScopes(program);
935
+ const parents = collectParents(program);
936
+ const names = new Set(scopes.names);
937
+ const fresh = (base: string): string => {
938
+ let name = base;
939
+ for (let index = 1; names.has(name); index += 1) {
940
+ name = `${base}$${String(index)}`;
941
+ }
942
+ names.add(name);
943
+ return name;
944
+ };
945
+
946
+ // The module's own imports, so a copy reuses one instead of adding another.
947
+ // Two imports of one context would be two bindings to the provider pass.
948
+ const existing = importedNames(program);
949
+ // Imports added in this round, shared by every copy.
950
+ const imports: string[] = [];
951
+ const added = new Map<string, string>();
952
+ const importAs = (base: string, imported: string, from: string): string => {
953
+ const key = `${from}\0${imported}`;
954
+ const known = existing.get(key) ?? added.get(key);
955
+ if (known !== undefined) {
956
+ return known;
957
+ }
958
+ const name = fresh(base);
959
+ added.set(key, name);
960
+ imports.push(importText(name, imported, from));
961
+ return name;
962
+ };
963
+
964
+ // Each imported binding used as a JSX tag, and its copy.
965
+ const copies: Copy[] = [];
966
+ for (const statement of program.body) {
967
+ if (
968
+ statement.type !== 'ImportDeclaration' ||
969
+ statement.importKind === 'type' ||
970
+ moduleSources.includes(statement.source.value)
971
+ ) {
972
+ continue;
973
+ }
974
+ for (const specifier of statement.specifiers) {
975
+ const binding = scopes.root.bindings.get(specifier.local.name);
976
+ // Only tags are copied. The import stays for any other use.
977
+ const tags = (binding?.references ?? []).filter((reference) => {
978
+ const parent = parents.get(reference);
979
+ return (
980
+ (parent?.type === 'JSXOpeningElement' || parent?.type === 'JSXClosingElement') &&
981
+ parent.name === reference
982
+ );
983
+ });
984
+ if (
985
+ specifier.type === 'ImportNamespaceSpecifier' ||
986
+ binding?.imported === undefined ||
987
+ tags.length === 0
988
+ ) {
989
+ continue;
990
+ }
991
+ // oxlint-disable-next-line no-await-in-loop
992
+ const copy = await copyImported(context, id, statement.source.value, binding.imported, {
993
+ excluded,
994
+ contexts,
995
+ importAs,
996
+ load,
997
+ skips: copySkips,
998
+ });
999
+ if (copy && copySkips) {
1000
+ // A copy the inline pass leaves behind is recorded under the reason it gave.
1001
+ copyNames.set(copy.key, `${binding.imported} (${statement.source.value})`);
1002
+ }
1003
+ if (copy) {
1004
+ const name = fresh(specifier.local.name);
1005
+ copies.push({ key: copy.key, name, tags, text: copy.text(name) });
1006
+ }
1007
+ }
1008
+ }
1009
+ if (copies.length === 0) {
1010
+ break;
1011
+ }
1012
+
1013
+ // Drop the copies the inline pass leaves behind, and try again without them.
1014
+ let result: CompileResult | undefined;
1015
+ let edit: MagicString | undefined;
1016
+ for (let attempt = 0; attempt < 4 && copies.length > 0; attempt += 1) {
1017
+ edit = new MagicString(code);
1018
+ for (const copy of copies) {
1019
+ for (const tag of copy.tags) {
1020
+ edit.overwrite(tag.start, tag.end, copy.name);
1021
+ }
1022
+ edit.append(`\n${copy.text}\n`);
1023
+ }
1024
+ edit.append(`\n${imports.join('\n')}\n`);
1025
+ result = compile(edit.toString(), {
1026
+ ...compileOptionsOfModule,
1027
+ filename,
1028
+ sourceMap: wantsMaps(),
1029
+ importedContexts: Object.fromEntries(
1030
+ [...contexts].map(([module, exported]) => [module, [...exported]]),
1031
+ ),
1032
+ // The original of a copy stays in its module for its other users.
1033
+ sharedComponents: Object.fromEntries(
1034
+ copies
1035
+ .map((copy): [string, number] => [copy.name, usersOf(copy)])
1036
+ .filter(([, users]) => users !== 1),
1037
+ ),
1038
+ });
1039
+ const left = analyzeScopes(parse(filename, result.code)).root.bindings;
1040
+ const stuck = copies.filter((copy) => left.has(copy.name));
1041
+ if (stuck.length === 0) {
1042
+ break;
1043
+ }
1044
+ for (const copy of stuck) {
1045
+ excluded.add(copy.key);
1046
+ copies.splice(copies.indexOf(copy), 1);
1047
+ const reason = result.skipped?.find((entry) => entry.name === copy.name)?.reason;
1048
+ copySkips?.push({
1049
+ pass: 'inline',
1050
+ reason: `copy-${reason ?? 'left'}`,
1051
+ name: copyNames.get(copy.key) ?? copy.name,
1052
+ });
1053
+ }
1054
+ result = undefined;
1055
+ }
1056
+ if (!result || !edit) {
1057
+ break;
1058
+ }
1059
+ // Their uses of other components move here with them.
1060
+ for (const copy of copies.filter((item) => usersOf(item) === 1)) {
1061
+ const [module = '', exported = ''] = copy.key.split('\0');
1062
+ absorbed.set(module, new Set([...(absorbed.get(module) ?? []), exported]));
1063
+ }
1064
+ if (wantsMaps()) {
1065
+ maps.push(
1066
+ edit.generateMap({ source: filename, hires: true, includeContent: true }).toString(),
1067
+ );
1068
+ }
1069
+ if (result.map) {
1070
+ maps.push(result.map.toString());
1071
+ }
1072
+ code = result.code;
1073
+ ({ skipped } = result);
1074
+ }
1075
+ return code === source ? undefined : { code, maps, skipped };
1076
+ }
1077
+
1078
+ /**
1079
+ * Prepares a client module for chunk mode. It adds the helper marker
1080
+ * instead of lowering JSX. Vite strips the types afterwards.
1081
+ */
1082
+ async function keepJSX(
1083
+ context: Rollup.PluginContext,
1084
+ source: string,
1085
+ id: string,
1086
+ ): Promise<Rollup.TransformResult> {
1087
+ const filename = stripQuery(id);
1088
+ // Fold and inline memos before bundling. A branch that folds away takes
1089
+ // its imports and `lazy()` chunks out of the module graph, which the
1090
+ // chunk step can no longer do. Inlining waits for the chunk, where the
1091
+ // components it can reach are known.
1092
+ const moduleCompileOptions = await moduleOptions(context, source, id);
1093
+ const local = compile(source, { ...moduleCompileOptions, inline: false });
1094
+ let code = local.code;
1095
+ const maps: (string | null | undefined)[] = [local.map?.toString()];
1096
+ // `<Ns.Member>` would keep a namespace object, which lowered code does not.
1097
+ const named = nameNamespaceTags(code, filename);
1098
+ if (named) {
1099
+ code = named.code;
1100
+ maps.push(named.map);
1101
+ }
1102
+
1103
+ // Components imported from other modules inline here, so the bundler
1104
+ // drops them, and what only they used, before it splits the chunks.
1105
+ if (moduleCompileOptions.inline !== false) {
1106
+ const copySkips: Skip[] | undefined = compileOptions.report ? [] : undefined;
1107
+ const imported = await inlineImports(
1108
+ context,
1109
+ code,
1110
+ id,
1111
+ moduleCompileOptions,
1112
+ async (target) => loadModule(context, id, target),
1113
+ copySkips,
1114
+ );
1115
+ // The rest of the report comes from the chunk this module ends up in.
1116
+ addSkips(context, copySkips);
1117
+ if (imported) {
1118
+ code = imported.code;
1119
+ maps.push(...imported.maps);
1120
+ }
1121
+ }
1122
+ // An entry's exports are its public API, so it gets no extra names.
1123
+ const exposed = context.getModuleInfo(id)?.isEntry ? undefined : exposeLocals(code, filename);
1124
+ if (exposed) {
1125
+ code = exposed.code;
1126
+ maps.push(exposed.map);
1127
+ }
1128
+ // The helpers the module's JSX needs, as written and with its own
1129
+ // components inlined. Inlining can turn a spread into attributes, which
1130
+ // need helpers the spread did not.
1131
+ const inlined =
1132
+ moduleCompileOptions.inline === false
1133
+ ? undefined
1134
+ : compile(code, { ...moduleCompileOptions, sourceMap: false });
1135
+ const needed = new Set<string>();
1136
+ for (const version of new Set([code, inlined?.code ?? code])) {
1137
+ for (const helper of helpersOf(
1138
+ getCompiler(),
1139
+ version,
1140
+ filename,
1141
+ jsxOptions(false),
1142
+ moduleName,
1143
+ )) {
1144
+ needed.add(helper);
1145
+ }
1146
+ }
1147
+ // A component inlined into another module of the chunk can turn its
1148
+ // spread into any attribute.
1149
+ if (moduleCompileOptions.inline !== false && spreadsOntoElement(code, filename)) {
1150
+ for (const helper of attributeHelpers()) {
1151
+ needed.add(helper);
1152
+ }
1153
+ }
1154
+ // The bundler has to see that a `ref` writes its variable. See `refs.ts`.
1155
+ const protectedRefs = protectRefs(code, filename);
1156
+ if (protectedRefs) {
1157
+ code = protectedRefs.code;
1158
+ maps.push(protectedRefs.map);
1159
+ }
1160
+ preserved.add(id);
1161
+ if (needed.size === 0) {
1162
+ return code === source ? null : { code, map: combineMaps(wantsMaps(), maps) };
1163
+ }
1164
+ const marked = addMarker(code, filename, {
1165
+ moduleName,
1166
+ helpers: withRelated([...needed]),
1167
+ moduleSources,
1168
+ // The passes also recognize these primitives, which a chunk renames too.
1169
+ builtIns: new Set([...builtIns, 'createContext', ...CONTEXT_SAFE_PRIMITIVES]),
1170
+ });
1171
+ if (!marked) {
1172
+ return code === source ? null : { code, map: combineMaps(wantsMaps(), maps) };
1173
+ }
1174
+ return {
1175
+ code: marked.code,
1176
+ map: combineMaps(wantsMaps(), [...maps, marked.map]),
1177
+ };
1178
+ }
1179
+
1180
+ const originalTransform = main.transform;
1181
+ const originalHandler =
1182
+ typeof originalTransform === 'function' ? originalTransform : originalTransform?.handler;
1183
+ if (originalHandler) {
1184
+ main.transform = async function transform(code, id, transformOptions) {
1185
+ if (chunkMode() && isClient(this) && isJSXModule(id)) {
1186
+ return keepJSX(this, code, id);
1187
+ }
1188
+ return originalHandler.call(this, code, id, transformOptions);
1189
+ };
1190
+ }
1191
+
1192
+ const modulePlugin: Plugin = {
1193
+ name: 'solid-optimizer:module',
1194
+ enforce: 'pre',
1195
+ configResolved(resolved) {
1196
+ config = resolved;
1197
+ },
1198
+ buildStart() {
1199
+ moduleConstants.clear();
1200
+ jsxImports.clear();
1201
+ usageIndexes.clear();
1202
+ skips.delete(this.environment.name);
1203
+ },
1204
+ watchChange() {
1205
+ moduleConstants.clear();
1206
+ jsxImports.clear();
1207
+ usageIndexes.clear();
1208
+ },
1209
+ async transform(source, id) {
1210
+ if (!isBuild() && optimizer.dev !== true) {
1211
+ return null;
1212
+ }
1213
+ if ((chunkMode() && isClient(this)) || !isJSXModule(id)) {
1214
+ return null;
1215
+ }
1216
+ const filename = stripQuery(id);
1217
+ const sourceOptions: CompileOptions = {
1218
+ ...(await moduleOptions(this, source, id)),
1219
+ // The server renders once, so its reactive primitives reduce to plain calls.
1220
+ server: optimizer.server !== false && !isClient(this),
1221
+ };
1222
+ const result = compile(source, sourceOptions);
1223
+ let code = result.code;
1224
+ const maps: (string | null | undefined)[] = [result.map?.toString()];
1225
+ // Components imported from other modules inline here too. The server
1226
+ // and client builds read the same modules, so they inline the same ones.
1227
+ let { skipped } = result;
1228
+ if (isBuild() && sourceOptions.inline !== false) {
1229
+ const copySkips: Skip[] | undefined = compileOptions.report ? [] : undefined;
1230
+ const imported = await inlineImports(
1231
+ this,
1232
+ code,
1233
+ id,
1234
+ sourceOptions,
1235
+ async (target) => loadRecorded(this, id, target),
1236
+ copySkips,
1237
+ );
1238
+ addSkips(this, copySkips);
1239
+ if (imported) {
1240
+ code = imported.code;
1241
+ maps.push(...imported.maps);
1242
+ skipped = imported.skipped ?? skipped;
1243
+ }
1244
+ // Entries get the extra exports too. The server and client builds
1245
+ // have different entries, and both have to copy the same components.
1246
+ const exposed = exposeLocals(code, filename);
1247
+ if (exposed) {
1248
+ code = exposed.code;
1249
+ maps.push(exposed.map);
1250
+ }
1251
+ }
1252
+ addSkips(this, skipped);
1253
+ recorded.set(environmentKey(this, id), code);
1254
+ if (code === source) {
1255
+ return null;
1256
+ }
1257
+ return { code, map: combineMaps(wantsMaps(), maps) };
1258
+ },
1259
+ };
1260
+
1261
+ const chunkPlugin: Plugin = {
1262
+ name: 'solid-optimizer:chunk',
1263
+ enforce: 'post',
1264
+ config(_, env) {
1265
+ if (env.command !== 'build') {
1266
+ return undefined;
1267
+ }
1268
+ // Kept JSX has to reach the bundler as JSX. Modules the official plugin
1269
+ // lowers have no JSX left, so this changes nothing for them.
1270
+ return {
1271
+ oxc: { jsx: 'preserve' },
1272
+ build: { rolldownOptions: { transform: { jsx: 'preserve' } } },
1273
+ };
1274
+ },
1275
+ renderChunk: {
1276
+ order: 'pre',
1277
+ handler(code, chunk) {
1278
+ if (!chunkMode() || !isClient(this) || !code.includes(MARKER)) {
1279
+ return null;
1280
+ }
1281
+ const filename = chunk.fileName;
1282
+ let repaired: { code: string; map: string } | undefined;
1283
+ let runtime: ReturnType<typeof readMarkers>;
1284
+ try {
1285
+ runtime = readMarkers(code, filename);
1286
+ } catch (error) {
1287
+ repaired = error instanceof SyntaxError ? repairJSXSequences(code, filename) : undefined;
1288
+ if (!repaired) {
1289
+ throw error;
1290
+ }
1291
+ runtime = readMarkers(repaired.code, filename);
1292
+ }
1293
+ if (!runtime) {
1294
+ return null;
1295
+ }
1296
+ const restored = restoreRefs(runtime.code, filename);
1297
+ const chunkCode = restored?.code ?? runtime.code;
1298
+ let optimized: CompileResult | undefined = compile(chunkCode, {
1299
+ ...compileOptions,
1300
+ filename,
1301
+ sourceMap: wantsMaps(),
1302
+ constantVars: true,
1303
+ builtInAliases: runtime.builtInAliases,
1304
+ });
1305
+ let lowered = lower(
1306
+ getCompiler(),
1307
+ optimized.code,
1308
+ filename,
1309
+ jsxOptions(false),
1310
+ wantsMaps(),
1311
+ );
1312
+ let linked: { code: string; map: string };
1313
+ try {
1314
+ linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1315
+ addSkips(this, optimized.skipped);
1316
+ } catch (error) {
1317
+ if (!(error instanceof MissingHelperError)) {
1318
+ throw error;
1319
+ }
1320
+ // Each module keeps the helpers its own JSX needs, and a merged
1321
+ // tree can need one none of them did. Without it, the chunk is
1322
+ // lowered as its modules were written. Chunk mode never hydrates,
1323
+ // so the chunks do not have to match anything else.
1324
+ this.warn(`${error.message} ${filename} is not optimized.`);
1325
+ optimized = undefined;
1326
+ addSkips(this, [{ pass: 'inline', reason: 'missing-helper', name: filename }]);
1327
+ lowered = lower(getCompiler(), chunkCode, filename, jsxOptions(false), wantsMaps());
1328
+ linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
1329
+ }
1330
+ return {
1331
+ code: linked.code,
1332
+ map: combineMaps(wantsMaps(), [
1333
+ repaired?.map,
1334
+ runtime.map,
1335
+ restored?.map,
1336
+ optimized?.map?.toString(),
1337
+ lowered.map,
1338
+ linked.map,
1339
+ ]),
1340
+ };
1341
+ },
1342
+ },
1343
+ };
1344
+
1345
+ // Prints the report once every chunk is rendered.
1346
+ chunkPlugin.generateBundle = function generateBundle() {
1347
+ const { report } = optimizer;
1348
+ if (report === undefined || report === false) {
1349
+ return;
1350
+ }
1351
+ const environment = this.environment.name;
1352
+ const result: OptimizerReport = { environment, skips: skips.get(environment) ?? [] };
1353
+ if (typeof report === 'function') {
1354
+ report(result);
1355
+ } else {
1356
+ this.environment.logger.info(formatReport(result));
1357
+ }
1358
+ };
1359
+
1360
+ // Runs after `vite:oxc` strips types, which reports the module as plain
1361
+ // JavaScript, and before the built-in plugins that parse it again.
1362
+ const moduleTypePlugin: Plugin = {
1363
+ name: 'solid-optimizer:module-type',
1364
+ transform(code, id) {
1365
+ if (!preserved.has(id)) {
1366
+ return null;
1367
+ }
1368
+ // `vite:oxc` prints JSX like Rolldown does, without the parentheses a
1369
+ // comma expression needs in a JSX expression container.
1370
+ const repaired = repairJSXSequences(code, stripQuery(id));
1371
+ return repaired
1372
+ ? { code: repaired.code, map: repaired.map, moduleType: 'jsx' }
1373
+ : { code, moduleType: 'jsx' };
1374
+ },
1375
+ };
1376
+
1377
+ return [modulePlugin, main, moduleTypePlugin, chunkPlugin];
1378
+ }