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