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.
- package/README.md +294 -14
- package/dist/compile-BQuBDA0Q.d.mts +199 -0
- package/dist/compile-BQuBDA0Q.d.mts.map +1 -0
- package/dist/compile-D3caSUtw.mjs +4244 -0
- package/dist/compile-D3caSUtw.mjs.map +1 -0
- package/dist/index.d.mts +2 -0
- package/dist/index.mjs +2 -0
- package/dist/vite.d.mts +53 -0
- package/dist/vite.d.mts.map +1 -0
- package/dist/vite.mjs +1743 -0
- package/dist/vite.mjs.map +1 -0
- package/package.json +60 -58
- package/src/ast.ts +271 -0
- package/src/compile.ts +355 -0
- package/src/constants.ts +249 -0
- package/src/context.ts +116 -0
- package/src/fold.ts +850 -0
- package/src/index.ts +5 -107
- package/src/inline.ts +2237 -0
- package/src/jsx.ts +170 -0
- package/src/memo.ts +416 -0
- package/src/provider.ts +899 -0
- package/src/scope.ts +588 -0
- package/src/server.ts +275 -0
- package/src/size.ts +309 -0
- package/src/value.ts +386 -0
- package/src/vite/index.ts +1378 -0
- package/src/vite/inject.ts +350 -0
- package/src/vite/namespace.ts +66 -0
- package/src/vite/refs.ts +99 -0
- package/src/vite/report.ts +74 -0
- package/src/vite/runtime.ts +370 -0
- package/src/vite/usage.ts +405 -0
- package/dist/cjs/development/index.cjs +0 -228
- package/dist/cjs/development/index.cjs.map +0 -7
- package/dist/cjs/production/index.cjs +0 -1
- package/dist/esm/development/index.mjs +0 -197
- package/dist/esm/development/index.mjs.map +0 -7
- package/dist/esm/production/index.mjs +0 -1
- package/dist/types/checks.d.ts +0 -9
- package/dist/types/checks.d.ts.map +0 -1
- package/dist/types/index.d.ts +0 -3
- package/dist/types/index.d.ts.map +0 -1
- package/dist/types/path-references-import.d.ts +0 -3
- package/dist/types/path-references-import.d.ts.map +0 -1
- package/dist/types/unwrap-node.d.ts +0 -7
- package/dist/types/unwrap-node.d.ts.map +0 -1
- package/dist/types/unwrap-path.d.ts +0 -6
- package/dist/types/unwrap-path.d.ts.map +0 -1
- package/src/checks.ts +0 -42
- package/src/path-references-import.ts +0 -82
- package/src/unwrap-node.ts +0 -27
- package/src/unwrap-path.ts +0 -18
package/dist/vite.mjs
ADDED
|
@@ -0,0 +1,1743 @@
|
|
|
1
|
+
import { a as lookup, c as forEachChild, d as unwrap, i as analyzeScopes, l as isIntrinsicTag, n as readModuleConstants, o as scopeAt, r as CONTEXT_SAFE_PRIMITIVES, s as collectParents, t as compile, u as parse } from "./compile-D3caSUtw.mjs";
|
|
2
|
+
import { createRequire } from "node:module";
|
|
3
|
+
import remapping from "@jridgewell/remapping";
|
|
4
|
+
import MagicString from "magic-string";
|
|
5
|
+
import { parseSync } from "oxc-parser";
|
|
6
|
+
import { readFile } from "node:fs/promises";
|
|
7
|
+
import path from "node:path";
|
|
8
|
+
import { createFilter, transformWithOxc } from "vite";
|
|
9
|
+
import solidPlugin from "vite-plugin-solid";
|
|
10
|
+
//#region src/vite/report.ts
|
|
11
|
+
/**
|
|
12
|
+
* Groups skips by pass and reason, most frequent first.
|
|
13
|
+
*/
|
|
14
|
+
function summarizeSkips(skips) {
|
|
15
|
+
const groups = /* @__PURE__ */ new Map();
|
|
16
|
+
for (const skip of skips) {
|
|
17
|
+
const key = `${skip.pass}\0${skip.reason}`;
|
|
18
|
+
const group = groups.get(key) ?? {
|
|
19
|
+
pass: skip.pass,
|
|
20
|
+
reason: skip.reason,
|
|
21
|
+
names: /* @__PURE__ */ new Map()
|
|
22
|
+
};
|
|
23
|
+
group.names.set(skip.name, (group.names.get(skip.name) ?? 0) + 1);
|
|
24
|
+
groups.set(key, group);
|
|
25
|
+
}
|
|
26
|
+
return [...groups.values()].map(({ pass, reason, names }) => ({
|
|
27
|
+
pass,
|
|
28
|
+
reason,
|
|
29
|
+
count: [...names.values()].reduce((sum, count) => sum + count, 0),
|
|
30
|
+
names: [...names].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0]))
|
|
31
|
+
})).sort((a, b) => b.count - a.count || a.pass.localeCompare(b.pass) || a.reason.localeCompare(b.reason));
|
|
32
|
+
}
|
|
33
|
+
/** The most names listed for a reason. */
|
|
34
|
+
const NAMES_SHOWN = 6;
|
|
35
|
+
/**
|
|
36
|
+
* The report as text, one line per reason.
|
|
37
|
+
*/
|
|
38
|
+
function formatReport(report) {
|
|
39
|
+
const lines = [`solid-optimizer: what stays as written in ${report.environment}`];
|
|
40
|
+
const summaries = summarizeSkips(report.skips);
|
|
41
|
+
if (summaries.length === 0) lines.push(" nothing");
|
|
42
|
+
const reasonWidth = Math.max(0, ...summaries.map((summary) => summary.reason.length));
|
|
43
|
+
for (const summary of summaries) {
|
|
44
|
+
const shown = summary.names.slice(0, NAMES_SHOWN).map(([name, count]) => count > 1 ? `${name}×${String(count)}` : name);
|
|
45
|
+
if (summary.names.length > NAMES_SHOWN) shown.push(`${String(summary.names.length - NAMES_SHOWN)} more`);
|
|
46
|
+
lines.push(` ${summary.pass.padEnd(8)} ${summary.reason.padEnd(reasonWidth)} ${String(summary.count).padStart(4)} ${shown.join(", ")}`);
|
|
47
|
+
}
|
|
48
|
+
return lines.join("\n");
|
|
49
|
+
}
|
|
50
|
+
//#endregion
|
|
51
|
+
//#region src/vite/runtime.ts
|
|
52
|
+
/**
|
|
53
|
+
* Keeps Solid's runtime helpers reachable while JSX waits in a bundled chunk.
|
|
54
|
+
*
|
|
55
|
+
* Solid's JSX transform imports helpers like `template` and `insert` from
|
|
56
|
+
* `solid-js/web`. When the transform runs on a chunk, the bundle is already
|
|
57
|
+
* built, so a new bare import cannot be resolved or bundled anymore. Instead,
|
|
58
|
+
* every module imports the helpers it will need before bundling, and passes
|
|
59
|
+
* them to a marker call. The bundler keeps the call, since it could have side
|
|
60
|
+
* effects, and renames the helpers to whatever they are called in the chunk.
|
|
61
|
+
* The chunk step reads the marker, removes it, and points the lowered code at
|
|
62
|
+
* those names.
|
|
63
|
+
*
|
|
64
|
+
* The marker also records which bindings are Solid's built-in components, so
|
|
65
|
+
* the fold pass still recognizes `Show` after the bundler renamed it.
|
|
66
|
+
*/
|
|
67
|
+
const MARKER = "__SOLID_OPTIMIZER_KEEP__";
|
|
68
|
+
/**
|
|
69
|
+
* The lowered chunk needs a helper that no module in the chunk kept.
|
|
70
|
+
*/
|
|
71
|
+
var MissingHelperError = class extends Error {
|
|
72
|
+
constructor(..._args) {
|
|
73
|
+
super(..._args);
|
|
74
|
+
this.name = "MissingHelperError";
|
|
75
|
+
}
|
|
76
|
+
};
|
|
77
|
+
const HELPER_PREFIX = "helper:";
|
|
78
|
+
const BUILT_IN_PREFIX = "builtin:";
|
|
79
|
+
function generateMap$2(s, filename) {
|
|
80
|
+
return s.generateMap({
|
|
81
|
+
source: filename,
|
|
82
|
+
hires: true,
|
|
83
|
+
includeContent: true
|
|
84
|
+
}).toString();
|
|
85
|
+
}
|
|
86
|
+
function freshName(scopes, base) {
|
|
87
|
+
let name = base;
|
|
88
|
+
let index = 1;
|
|
89
|
+
while (scopes.names.has(name)) {
|
|
90
|
+
name = `${base}$${String(index)}`;
|
|
91
|
+
index += 1;
|
|
92
|
+
}
|
|
93
|
+
scopes.names.add(name);
|
|
94
|
+
return name;
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* Whether an import specifier was added by Solid's JSX transform, which
|
|
98
|
+
* names every helper it imports `_$name`.
|
|
99
|
+
*/
|
|
100
|
+
function isGeneratedSpecifier(specifier) {
|
|
101
|
+
return specifier.type === "ImportSpecifier" && specifier.local.name.startsWith("_$");
|
|
102
|
+
}
|
|
103
|
+
function exportedName(specifier) {
|
|
104
|
+
return specifier.imported.type === "Literal" ? specifier.imported.value : specifier.imported.name;
|
|
105
|
+
}
|
|
106
|
+
/**
|
|
107
|
+
* The functions declared at the top level of a module, with the statement
|
|
108
|
+
* that declares each: `function A() {}`, `const A = () => ...`, and their
|
|
109
|
+
* `export` forms.
|
|
110
|
+
*/
|
|
111
|
+
function topLevelFunctions(program) {
|
|
112
|
+
const found = [];
|
|
113
|
+
for (const statement of program.body) {
|
|
114
|
+
const declaration = statement.type === "ExportNamedDeclaration" || statement.type === "ExportDefaultDeclaration" ? statement.declaration : statement;
|
|
115
|
+
if (!declaration) continue;
|
|
116
|
+
if (declaration.type === "FunctionDeclaration") found.push({
|
|
117
|
+
statement,
|
|
118
|
+
fn: declaration
|
|
119
|
+
});
|
|
120
|
+
else if (declaration.type === "VariableDeclaration" && declaration.declarations.length === 1) {
|
|
121
|
+
const init = declaration.declarations.at(0)?.init;
|
|
122
|
+
const fn = init ? unwrap(init) : void 0;
|
|
123
|
+
if (fn?.type === "ArrowFunctionExpression" || fn?.type === "FunctionExpression") found.push({
|
|
124
|
+
statement,
|
|
125
|
+
fn
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
return found;
|
|
130
|
+
}
|
|
131
|
+
function containsJSX(node) {
|
|
132
|
+
let found = false;
|
|
133
|
+
const visit = (current) => {
|
|
134
|
+
if (found) return;
|
|
135
|
+
if (current.type === "JSXElement" || current.type === "JSXFragment") {
|
|
136
|
+
found = true;
|
|
137
|
+
return;
|
|
138
|
+
}
|
|
139
|
+
forEachChild(current, visit);
|
|
140
|
+
};
|
|
141
|
+
visit(node);
|
|
142
|
+
return found;
|
|
143
|
+
}
|
|
144
|
+
/**
|
|
145
|
+
* Adds the helper imports and the marker calls to a module.
|
|
146
|
+
*
|
|
147
|
+
* Each top-level function with JSX gets its own marker, so a component the
|
|
148
|
+
* bundler drops takes its helpers with it. JSX anywhere else gets a marker
|
|
149
|
+
* at the top level. Returns `undefined` when the module needs no helper.
|
|
150
|
+
*/
|
|
151
|
+
function addMarker(code, filename, options) {
|
|
152
|
+
if (options.helpers.size === 0) return;
|
|
153
|
+
const program = parse(filename, code);
|
|
154
|
+
const scopes = analyzeScopes(program);
|
|
155
|
+
const entries = [];
|
|
156
|
+
const specifiers = [];
|
|
157
|
+
for (const helper of options.helpers) {
|
|
158
|
+
const local = freshName(scopes, `__so$${helper}`);
|
|
159
|
+
specifiers.push(`${helper} as ${local}`);
|
|
160
|
+
entries.push(`${JSON.stringify(HELPER_PREFIX + helper)}: ${local}`);
|
|
161
|
+
}
|
|
162
|
+
for (const statement of program.body) {
|
|
163
|
+
if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || !options.moduleSources.includes(statement.source.value)) continue;
|
|
164
|
+
for (const specifier of statement.specifiers) {
|
|
165
|
+
if (specifier.type !== "ImportSpecifier" || specifier.importKind === "type") continue;
|
|
166
|
+
const imported = exportedName(specifier);
|
|
167
|
+
const used = (scopes.root.bindings.get(specifier.local.name)?.references.length ?? 0) > 0;
|
|
168
|
+
if (options.builtIns.has(imported) && used) entries.push(`${JSON.stringify(BUILT_IN_PREFIX + imported)}: ${specifier.local.name}`);
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const call = `${MARKER}({ ${entries.join(", ")} })`;
|
|
172
|
+
const s = new MagicString(code);
|
|
173
|
+
const functions = topLevelFunctions(program).filter(({ fn }) => containsJSX(fn));
|
|
174
|
+
for (const { fn } of functions) {
|
|
175
|
+
if (fn.type !== "FunctionDeclaration" && fn.type !== "FunctionExpression" && fn.type !== "ArrowFunctionExpression") continue;
|
|
176
|
+
const { body } = fn;
|
|
177
|
+
if (!body) continue;
|
|
178
|
+
if (body.type === "BlockStatement") s.appendLeft(body.start + 1, `${call};`);
|
|
179
|
+
else {
|
|
180
|
+
s.prependRight(body.start, `{ ${call}; return `);
|
|
181
|
+
s.appendLeft(body.end, "; }");
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
const outside = program.body.some((statement) => !functions.some((entry) => entry.statement === statement) && containsJSX(statement));
|
|
185
|
+
s.append(`\nimport { ${specifiers.join(", ")} } from ${JSON.stringify(options.moduleName)};\n` + (outside ? `${call};\n` : ""));
|
|
186
|
+
return {
|
|
187
|
+
code: s.toString(),
|
|
188
|
+
map: generateMap$2(s, filename)
|
|
189
|
+
};
|
|
190
|
+
}
|
|
191
|
+
/**
|
|
192
|
+
* Puts back the parentheses around a comma expression that is the whole of a
|
|
193
|
+
* JSX expression container. Rolldown drops them when it prints a chunk that
|
|
194
|
+
* kept its JSX, and JSX does not allow the result. Returns `undefined` when
|
|
195
|
+
* the chunk has none.
|
|
196
|
+
*/
|
|
197
|
+
function repairJSXSequences(code, filename) {
|
|
198
|
+
const { program } = parseSync(filename, code, {
|
|
199
|
+
lang: "jsx",
|
|
200
|
+
sourceType: "module",
|
|
201
|
+
preserveParens: true
|
|
202
|
+
});
|
|
203
|
+
const sequences = [];
|
|
204
|
+
const visit = (node) => {
|
|
205
|
+
if (node.type === "JSXExpressionContainer" && node.expression.type === "SequenceExpression") sequences.push(node.expression);
|
|
206
|
+
forEachChild(node, visit);
|
|
207
|
+
};
|
|
208
|
+
visit(program);
|
|
209
|
+
if (sequences.length === 0) return;
|
|
210
|
+
const s = new MagicString(code);
|
|
211
|
+
for (const sequence of sequences) {
|
|
212
|
+
s.appendLeft(sequence.start, "(");
|
|
213
|
+
s.prependRight(sequence.end, ")");
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
code: s.toString(),
|
|
217
|
+
map: generateMap$2(s, filename)
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
function propertyKey(node) {
|
|
221
|
+
if (node.type === "Literal" && typeof node.value === "string") return node.value;
|
|
222
|
+
if (node.type === "Identifier") return node.name;
|
|
223
|
+
}
|
|
224
|
+
/**
|
|
225
|
+
* Reads and removes the marker calls of a chunk.
|
|
226
|
+
* Returns `undefined` when the chunk has none.
|
|
227
|
+
*/
|
|
228
|
+
function readMarkers(code, filename) {
|
|
229
|
+
if (!code.includes("__SOLID_OPTIMIZER_KEEP__")) return;
|
|
230
|
+
const program = parse(filename, code);
|
|
231
|
+
const s = new MagicString(code);
|
|
232
|
+
const helpers = /* @__PURE__ */ new Map();
|
|
233
|
+
const builtInAliases = {};
|
|
234
|
+
const markers = [];
|
|
235
|
+
const visit = (node) => {
|
|
236
|
+
if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "__SOLID_OPTIMIZER_KEEP__") {
|
|
237
|
+
markers.push(node);
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
forEachChild(node, visit);
|
|
241
|
+
};
|
|
242
|
+
visit(program);
|
|
243
|
+
for (const statement of markers) {
|
|
244
|
+
s.remove(statement.start, statement.end);
|
|
245
|
+
if (statement.expression.type !== "CallExpression") continue;
|
|
246
|
+
const argument = statement.expression.arguments.at(0);
|
|
247
|
+
if (argument?.type !== "ObjectExpression") continue;
|
|
248
|
+
for (const property of argument.properties) {
|
|
249
|
+
if (property.type !== "Property" || property.value.type !== "Identifier") continue;
|
|
250
|
+
const key = propertyKey(property.key);
|
|
251
|
+
if (key?.startsWith(HELPER_PREFIX)) helpers.set(key.slice(7), property.value.name);
|
|
252
|
+
else if (key?.startsWith(BUILT_IN_PREFIX)) builtInAliases[property.value.name] = key.slice(8);
|
|
253
|
+
}
|
|
254
|
+
}
|
|
255
|
+
if (markers.length === 0) return;
|
|
256
|
+
return {
|
|
257
|
+
code: s.toString(),
|
|
258
|
+
map: generateMap$2(s, filename),
|
|
259
|
+
helpers,
|
|
260
|
+
builtInAliases
|
|
261
|
+
};
|
|
262
|
+
}
|
|
263
|
+
/**
|
|
264
|
+
* Replaces the helper imports that Solid's JSX transform added to a chunk
|
|
265
|
+
* with the chunk's own names for those helpers.
|
|
266
|
+
*/
|
|
267
|
+
function linkHelpers(code, filename, moduleName, helpers) {
|
|
268
|
+
const program = parse(filename, code);
|
|
269
|
+
const scopes = analyzeScopes(program);
|
|
270
|
+
const parents = collectParents(program);
|
|
271
|
+
const s = new MagicString(code);
|
|
272
|
+
for (const statement of program.body) {
|
|
273
|
+
if (statement.type !== "ImportDeclaration" || statement.source.value !== moduleName || !statement.specifiers.every(isGeneratedSpecifier)) continue;
|
|
274
|
+
for (const specifier of statement.specifiers) {
|
|
275
|
+
if (specifier.type !== "ImportSpecifier") continue;
|
|
276
|
+
const imported = exportedName(specifier);
|
|
277
|
+
const target = helpers.get(imported);
|
|
278
|
+
if (target === void 0) throw new MissingHelperError(`[solid-optimizer] ${filename} needs "${imported}" from "${moduleName}", but no module in the chunk imports it.`);
|
|
279
|
+
const binding = scopes.root.bindings.get(specifier.local.name);
|
|
280
|
+
const targetBinding = scopes.root.bindings.get(target);
|
|
281
|
+
if (!targetBinding) throw new Error(`[solid-optimizer] ${filename} has no top-level "${target}" for "${imported}".`);
|
|
282
|
+
for (const reference of binding?.references ?? []) {
|
|
283
|
+
if (lookup(scopeAt(scopes, parents, reference), target) !== targetBinding) throw new Error(`[solid-optimizer] ${filename} shadows "${target}" where the JSX transform uses "${imported}".`);
|
|
284
|
+
s.overwrite(reference.start, reference.end, target);
|
|
285
|
+
}
|
|
286
|
+
}
|
|
287
|
+
s.remove(statement.start, statement.end);
|
|
288
|
+
}
|
|
289
|
+
return {
|
|
290
|
+
code: s.toString(),
|
|
291
|
+
map: generateMap$2(s, filename)
|
|
292
|
+
};
|
|
293
|
+
}
|
|
294
|
+
//#endregion
|
|
295
|
+
//#region src/vite/inject.ts
|
|
296
|
+
/**
|
|
297
|
+
* Copies components from other modules into a module before bundling, so
|
|
298
|
+
* the inline pass can inline them there.
|
|
299
|
+
*
|
|
300
|
+
* In chunk mode, the chunk step inlines any component in the same chunk.
|
|
301
|
+
* It runs after the bundler has split the chunks, so a shared chunk still
|
|
302
|
+
* exports what an inlined component needed, like the runtime's `spread`.
|
|
303
|
+
* Inlining an imported component while its importer is transformed lets
|
|
304
|
+
* the bundler drop the component, and what only it used, before splitting.
|
|
305
|
+
*
|
|
306
|
+
* A copy refers to the bindings of its own module. Imports are imported
|
|
307
|
+
* again by the module they resolve to. A binding the module declares but
|
|
308
|
+
* does not export is exported under an extra name, which `exposeLocals`
|
|
309
|
+
* adds when the module is transformed.
|
|
310
|
+
*/
|
|
311
|
+
/**
|
|
312
|
+
* Whether a binding is `const X = createContext(...)`, with `createContext`
|
|
313
|
+
* imported from Solid.
|
|
314
|
+
*/
|
|
315
|
+
function isContext(binding, scopes, moduleSources) {
|
|
316
|
+
const { declaration } = binding;
|
|
317
|
+
if (binding.kind !== "const" || binding.mutated || declaration.type !== "VariableDeclarator" || !declaration.init) return false;
|
|
318
|
+
const init = unwrap(declaration.init);
|
|
319
|
+
if (init.type !== "CallExpression" || init.callee.type !== "Identifier") return false;
|
|
320
|
+
const callee = scopes.references.get(init.callee);
|
|
321
|
+
return callee?.kind === "import" && callee.imported === "createContext" && callee.source !== void 0 && moduleSources.includes(callee.source);
|
|
322
|
+
}
|
|
323
|
+
/** The prefix of the name a module exports a local binding under. */
|
|
324
|
+
const LOCAL_EXPORT = "__so_local$";
|
|
325
|
+
function generateMap$1(s, filename) {
|
|
326
|
+
return s.generateMap({
|
|
327
|
+
source: filename,
|
|
328
|
+
hires: true,
|
|
329
|
+
includeContent: true
|
|
330
|
+
}).toString();
|
|
331
|
+
}
|
|
332
|
+
function isCapitalized(name) {
|
|
333
|
+
return /^[A-Z]/.test(name);
|
|
334
|
+
}
|
|
335
|
+
/**
|
|
336
|
+
* The function a top-level binding holds: `function A() {}`, or
|
|
337
|
+
* `const A = () => ...`.
|
|
338
|
+
*/
|
|
339
|
+
function functionOf(binding) {
|
|
340
|
+
const { declaration } = binding;
|
|
341
|
+
if (declaration.type === "FunctionDeclaration") return {
|
|
342
|
+
binding,
|
|
343
|
+
fn: declaration,
|
|
344
|
+
kind: "declaration"
|
|
345
|
+
};
|
|
346
|
+
if (declaration.type === "VariableDeclarator" && binding.kind === "const" && declaration.id === binding.identifier && declaration.init) {
|
|
347
|
+
const init = unwrap(declaration.init);
|
|
348
|
+
if (init.type === "ArrowFunctionExpression" || init.type === "FunctionExpression") return {
|
|
349
|
+
binding,
|
|
350
|
+
fn: init,
|
|
351
|
+
kind: "expression"
|
|
352
|
+
};
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
/**
|
|
356
|
+
* The names a module exports, each with the top-level binding it exports.
|
|
357
|
+
*/
|
|
358
|
+
function exportsOf(program, scopes) {
|
|
359
|
+
const exports = /* @__PURE__ */ new Map();
|
|
360
|
+
const { bindings } = scopes.root;
|
|
361
|
+
for (const statement of program.body) if (statement.type === "ExportNamedDeclaration" && !statement.source) {
|
|
362
|
+
const { declaration } = statement;
|
|
363
|
+
if (declaration?.type === "FunctionDeclaration" && declaration.id) {
|
|
364
|
+
const binding = bindings.get(declaration.id.name);
|
|
365
|
+
if (binding) exports.set(declaration.id.name, binding);
|
|
366
|
+
} else if (declaration?.type === "VariableDeclaration") {
|
|
367
|
+
const declared = declaration.declarations.map((declarator) => declarator.id.type === "Identifier" ? bindings.get(declarator.id.name) : void 0);
|
|
368
|
+
for (const binding of declared.filter((item) => item !== void 0)) exports.set(binding.name, binding);
|
|
369
|
+
}
|
|
370
|
+
for (const specifier of statement.specifiers) {
|
|
371
|
+
const local = specifier.local.type === "Identifier" ? specifier.local.name : void 0;
|
|
372
|
+
const exported = specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value;
|
|
373
|
+
const binding = local === void 0 ? void 0 : bindings.get(local);
|
|
374
|
+
if (binding) exports.set(exported, binding);
|
|
375
|
+
}
|
|
376
|
+
} else if (statement.type === "ExportDefaultDeclaration") {
|
|
377
|
+
const { declaration } = statement;
|
|
378
|
+
if (declaration.type === "FunctionDeclaration" && declaration.id) {
|
|
379
|
+
const binding = bindings.get(declaration.id.name);
|
|
380
|
+
if (binding) exports.set("default", binding);
|
|
381
|
+
} else if (declaration.type === "Identifier") {
|
|
382
|
+
const binding = bindings.get(declaration.name);
|
|
383
|
+
if (binding) exports.set("default", binding);
|
|
384
|
+
}
|
|
385
|
+
}
|
|
386
|
+
return exports;
|
|
387
|
+
}
|
|
388
|
+
/**
|
|
389
|
+
* The top-level bindings a function refers to, other than itself.
|
|
390
|
+
*/
|
|
391
|
+
function outerBindings(fn, self, scopes) {
|
|
392
|
+
const outer = /* @__PURE__ */ new Map();
|
|
393
|
+
for (const [reference, binding] of scopes.references) if (binding && binding !== self && binding.scope === scopes.root && reference.start >= fn.start && reference.end <= fn.end) outer.set(reference, binding);
|
|
394
|
+
return outer;
|
|
395
|
+
}
|
|
396
|
+
/**
|
|
397
|
+
* Exports the top-level bindings that the module's exported components
|
|
398
|
+
* refer to but the module does not export, under an extra name. A copy of
|
|
399
|
+
* such a component in another module imports them from here.
|
|
400
|
+
*/
|
|
401
|
+
function exposeLocals(code, filename) {
|
|
402
|
+
const program = parse(filename, code);
|
|
403
|
+
const scopes = analyzeScopes(program);
|
|
404
|
+
const exports = exportsOf(program, scopes);
|
|
405
|
+
const exported = new Set(exports.values());
|
|
406
|
+
const needed = /* @__PURE__ */ new Set();
|
|
407
|
+
for (const [name, binding] of exports) {
|
|
408
|
+
const component = isCapitalized(binding.name) || name === "default" ? functionOf(binding) : void 0;
|
|
409
|
+
if (!component) continue;
|
|
410
|
+
for (const outer of outerBindings(component.fn, binding, scopes).values()) if (outer.kind !== "import" && !exported.has(outer)) needed.add(outer);
|
|
411
|
+
}
|
|
412
|
+
if (needed.size === 0) return;
|
|
413
|
+
const s = new MagicString(code);
|
|
414
|
+
const specifiers = [...needed].map((binding) => `${binding.name} as ${LOCAL_EXPORT}${binding.name}`);
|
|
415
|
+
s.append(`\nexport { ${specifiers.join(", ")} };\n`);
|
|
416
|
+
return {
|
|
417
|
+
code: s.toString(),
|
|
418
|
+
map: generateMap$1(s, filename)
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
/**
|
|
422
|
+
* Whether a function returns JSX whose root calls a component declared at
|
|
423
|
+
* the top of its own module.
|
|
424
|
+
*/
|
|
425
|
+
function returnsLocalCall(fn, scopes) {
|
|
426
|
+
if (fn.type !== "FunctionDeclaration" && fn.type !== "FunctionExpression" && fn.type !== "ArrowFunctionExpression") return false;
|
|
427
|
+
const { body } = fn;
|
|
428
|
+
if (!body) return false;
|
|
429
|
+
let root;
|
|
430
|
+
if (body.type === "BlockStatement") {
|
|
431
|
+
const last = body.body.at(-1);
|
|
432
|
+
root = last?.type === "ReturnStatement" ? last.argument : void 0;
|
|
433
|
+
} else root = body;
|
|
434
|
+
if (!root) return false;
|
|
435
|
+
const inner = unwrap(root);
|
|
436
|
+
if (inner.type !== "JSXElement" || inner.openingElement.name.type !== "JSXIdentifier") return false;
|
|
437
|
+
const binding = scopes.references.get(inner.openingElement.name);
|
|
438
|
+
return binding !== void 0 && binding.scope === scopes.root && binding.kind !== "import";
|
|
439
|
+
}
|
|
440
|
+
/**
|
|
441
|
+
* Reads the component a module exports under `exportName`, from the module
|
|
442
|
+
* as the bundler loaded it. `undefined` when that export is not a function
|
|
443
|
+
* component, or it refers to a top-level binding the module cannot export.
|
|
444
|
+
*/
|
|
445
|
+
function readExportedComponent(code, filename, exportName, moduleSources) {
|
|
446
|
+
const program = parse(filename, code);
|
|
447
|
+
const scopes = analyzeScopes(program);
|
|
448
|
+
const exports = exportsOf(program, scopes);
|
|
449
|
+
const binding = exports.get(exportName);
|
|
450
|
+
const component = binding ? functionOf(binding) : void 0;
|
|
451
|
+
if (!binding || !component) return;
|
|
452
|
+
const exportNames = /* @__PURE__ */ new Map();
|
|
453
|
+
for (const [name, exported] of exports) if (!exportNames.has(exported)) exportNames.set(exported, name);
|
|
454
|
+
const outer = outerBindings(component.fn, binding, scopes);
|
|
455
|
+
const dependencies = /* @__PURE__ */ new Map();
|
|
456
|
+
for (const dependency of outer.values()) {
|
|
457
|
+
if (dependencies.has(dependency.name)) continue;
|
|
458
|
+
if (dependency.kind === "import") {
|
|
459
|
+
if (dependency.source === void 0 || dependency.imported === void 0) return;
|
|
460
|
+
dependencies.set(dependency.name, {
|
|
461
|
+
kind: "import",
|
|
462
|
+
source: dependency.source,
|
|
463
|
+
imported: dependency.imported
|
|
464
|
+
});
|
|
465
|
+
continue;
|
|
466
|
+
}
|
|
467
|
+
const name = exportNames.get(dependency);
|
|
468
|
+
if (name === void 0) return;
|
|
469
|
+
dependencies.set(dependency.name, {
|
|
470
|
+
kind: "export",
|
|
471
|
+
exported: name,
|
|
472
|
+
context: isContext(dependency, scopes, moduleSources)
|
|
473
|
+
});
|
|
474
|
+
}
|
|
475
|
+
const markers = [];
|
|
476
|
+
const findMarkers = (node) => {
|
|
477
|
+
if (node.type === "ExpressionStatement" && node.expression.type === "CallExpression" && node.expression.callee.type === "Identifier" && node.expression.callee.name === "__SOLID_OPTIMIZER_KEEP__") {
|
|
478
|
+
markers.push(node);
|
|
479
|
+
return;
|
|
480
|
+
}
|
|
481
|
+
forEachChild(node, findMarkers);
|
|
482
|
+
};
|
|
483
|
+
findMarkers(component.fn);
|
|
484
|
+
const copy = (name, rename) => {
|
|
485
|
+
const s = new MagicString(code);
|
|
486
|
+
for (const [reference, dependency] of outer) {
|
|
487
|
+
const renamed = rename.get(dependency.name);
|
|
488
|
+
if (renamed !== void 0 && renamed !== dependency.name) s.overwrite(reference.start, reference.end, renamed);
|
|
489
|
+
}
|
|
490
|
+
for (const marker of markers) s.remove(marker.start, marker.end);
|
|
491
|
+
if (component.kind === "declaration" && component.fn.type === "FunctionDeclaration" && component.fn.id) {
|
|
492
|
+
s.overwrite(component.fn.id.start, component.fn.id.end, name);
|
|
493
|
+
return s.slice(component.fn.start, component.fn.end);
|
|
494
|
+
}
|
|
495
|
+
return `const ${name} = ${s.slice(component.fn.start, component.fn.end)};`;
|
|
496
|
+
};
|
|
497
|
+
return {
|
|
498
|
+
dependencies,
|
|
499
|
+
copy,
|
|
500
|
+
wrapsLocal: returnsLocalCall(component.fn, scopes)
|
|
501
|
+
};
|
|
502
|
+
}
|
|
503
|
+
//#endregion
|
|
504
|
+
//#region src/vite/namespace.ts
|
|
505
|
+
/**
|
|
506
|
+
* Rewrites JSX tags that read a member of a namespace import, like
|
|
507
|
+
* `<Button.Root>` with `import * as Button from '...'`, to a named import.
|
|
508
|
+
*
|
|
509
|
+
* A bundler resolves `Button.Root` in code to the export it reads, and
|
|
510
|
+
* drops the namespace. In a JSX tag name it does not, so a module that
|
|
511
|
+
* keeps its JSX through bundling would make the bundle build a namespace
|
|
512
|
+
* object with every export of the module.
|
|
513
|
+
*/
|
|
514
|
+
function nameNamespaceTags(code, filename) {
|
|
515
|
+
const program = parse(filename, code);
|
|
516
|
+
const scopes = analyzeScopes(program);
|
|
517
|
+
const parents = collectParents(program);
|
|
518
|
+
const s = new MagicString(code);
|
|
519
|
+
const names = new Set(scopes.names);
|
|
520
|
+
const imports = [];
|
|
521
|
+
for (const binding of scopes.root.bindings.values()) {
|
|
522
|
+
const statement = parents.get(binding.declaration);
|
|
523
|
+
if (binding.kind !== "import" || binding.imported !== "*" || binding.source === void 0 || statement?.type !== "ImportDeclaration" || statement.importKind === "type") continue;
|
|
524
|
+
const locals = /* @__PURE__ */ new Map();
|
|
525
|
+
for (const reference of binding.references) {
|
|
526
|
+
const member = parents.get(reference);
|
|
527
|
+
if (reference.type !== "JSXIdentifier" || member?.type !== "JSXMemberExpression" || member.object !== reference) continue;
|
|
528
|
+
const { name } = member.property;
|
|
529
|
+
let local = locals.get(name);
|
|
530
|
+
if (local === void 0) {
|
|
531
|
+
local = `${binding.name}$${name}`;
|
|
532
|
+
for (let index = 1; names.has(local); index += 1) local = `${binding.name}$${name}$${String(index)}`;
|
|
533
|
+
names.add(local);
|
|
534
|
+
locals.set(name, local);
|
|
535
|
+
imports.push(`import { ${name} as ${local} } from ${JSON.stringify(binding.source)};`);
|
|
536
|
+
}
|
|
537
|
+
s.overwrite(member.start, member.end, local);
|
|
538
|
+
}
|
|
539
|
+
}
|
|
540
|
+
if (imports.length === 0) return;
|
|
541
|
+
s.prepend(`${imports.join("\n")}\n`);
|
|
542
|
+
return {
|
|
543
|
+
code: s.toString(),
|
|
544
|
+
map: s.generateMap({
|
|
545
|
+
source: filename,
|
|
546
|
+
hires: true,
|
|
547
|
+
includeContent: true
|
|
548
|
+
}).toString()
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
//#endregion
|
|
552
|
+
//#region src/vite/refs.ts
|
|
553
|
+
const REF_MARKER = "__SO_REF__";
|
|
554
|
+
function generateMap(s, filename) {
|
|
555
|
+
return s.generateMap({
|
|
556
|
+
source: filename,
|
|
557
|
+
hires: true,
|
|
558
|
+
includeContent: true
|
|
559
|
+
}).toString();
|
|
560
|
+
}
|
|
561
|
+
function isRefAttribute(node) {
|
|
562
|
+
return node.type === "JSXAttribute" && node.name.type === "JSXIdentifier" && node.name.name === "ref";
|
|
563
|
+
}
|
|
564
|
+
/**
|
|
565
|
+
* Wraps each `ref` whose value is a `let` or `var` binding, so the bundler
|
|
566
|
+
* sees it written. `undefined` when there is none.
|
|
567
|
+
*/
|
|
568
|
+
function protectRefs(code, filename) {
|
|
569
|
+
if (!code.includes("ref")) return;
|
|
570
|
+
const program = parse(filename, code);
|
|
571
|
+
const scopes = analyzeScopes(program);
|
|
572
|
+
const s = new MagicString(code);
|
|
573
|
+
const visit = (node) => {
|
|
574
|
+
if (isRefAttribute(node) && node.value?.type === "JSXExpressionContainer") {
|
|
575
|
+
const { expression } = node.value;
|
|
576
|
+
const binding = expression.type === "Identifier" ? scopes.references.get(expression) : void 0;
|
|
577
|
+
if (expression.type === "Identifier" && (binding?.kind === "let" || binding?.kind === "var")) {
|
|
578
|
+
const { name } = expression;
|
|
579
|
+
s.overwrite(expression.start, expression.end, `${REF_MARKER}(${name}, (__so_ref) => (${name} = __so_ref))`);
|
|
580
|
+
}
|
|
581
|
+
}
|
|
582
|
+
forEachChild(node, visit);
|
|
583
|
+
};
|
|
584
|
+
visit(program);
|
|
585
|
+
return s.hasChanged() ? {
|
|
586
|
+
code: s.toString(),
|
|
587
|
+
map: generateMap(s, filename)
|
|
588
|
+
} : void 0;
|
|
589
|
+
}
|
|
590
|
+
/**
|
|
591
|
+
* Turns each wrapped `ref` back into its variable. `undefined` when there
|
|
592
|
+
* is none.
|
|
593
|
+
*/
|
|
594
|
+
function restoreRefs(code, filename) {
|
|
595
|
+
if (!code.includes("__SO_REF__")) return;
|
|
596
|
+
const program = parse(filename, code);
|
|
597
|
+
const s = new MagicString(code);
|
|
598
|
+
const visit = (node) => {
|
|
599
|
+
if (isRefAttribute(node) && node.value?.type === "JSXExpressionContainer") {
|
|
600
|
+
const { expression } = node.value;
|
|
601
|
+
if (isMarkerCall(expression)) {
|
|
602
|
+
const target = expression.arguments.at(0);
|
|
603
|
+
if (target?.type === "Identifier") s.overwrite(expression.start, expression.end, target.name);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
forEachChild(node, visit);
|
|
607
|
+
};
|
|
608
|
+
visit(program);
|
|
609
|
+
return s.hasChanged() ? {
|
|
610
|
+
code: s.toString(),
|
|
611
|
+
map: generateMap(s, filename)
|
|
612
|
+
} : void 0;
|
|
613
|
+
}
|
|
614
|
+
function isMarkerCall(node) {
|
|
615
|
+
return node.type === "CallExpression" && node.callee.type === "Identifier" && node.callee.name === "__SO_REF__";
|
|
616
|
+
}
|
|
617
|
+
//#endregion
|
|
618
|
+
//#region src/vite/usage.ts
|
|
619
|
+
/** The name a use counts under when it is not inside an exported declaration. */
|
|
620
|
+
const UNEXPORTED = "";
|
|
621
|
+
const SCRIPT = /\.[mc]?[jt]sx?$/;
|
|
622
|
+
var Usage = class {
|
|
623
|
+
constructor() {
|
|
624
|
+
this.exports = /* @__PURE__ */ new Map();
|
|
625
|
+
this.opaque = /* @__PURE__ */ new Set();
|
|
626
|
+
this.imports = /* @__PURE__ */ new Map();
|
|
627
|
+
}
|
|
628
|
+
/** Whether `from` imports `to`, directly or through other modules. */
|
|
629
|
+
reaches(from, to) {
|
|
630
|
+
const seen = /* @__PURE__ */ new Set();
|
|
631
|
+
const stack = [from];
|
|
632
|
+
for (let id = stack.pop(); id !== void 0; id = stack.pop()) {
|
|
633
|
+
if (id === to) return true;
|
|
634
|
+
if (!seen.has(id)) {
|
|
635
|
+
seen.add(id);
|
|
636
|
+
stack.push(...this.imports.get(id) ?? []);
|
|
637
|
+
}
|
|
638
|
+
}
|
|
639
|
+
return false;
|
|
640
|
+
}
|
|
641
|
+
entry(module, name) {
|
|
642
|
+
const key = `${module}\0${name}`;
|
|
643
|
+
let usage = this.exports.get(key);
|
|
644
|
+
if (!usage) {
|
|
645
|
+
usage = {
|
|
646
|
+
importers: /* @__PURE__ */ new Map(),
|
|
647
|
+
other: false
|
|
648
|
+
};
|
|
649
|
+
this.exports.set(key, usage);
|
|
650
|
+
}
|
|
651
|
+
return usage;
|
|
652
|
+
}
|
|
653
|
+
tag(module, name, importer, containers) {
|
|
654
|
+
const { importers } = this.entry(module, name);
|
|
655
|
+
const known = importers.get(importer) ?? /* @__PURE__ */ new Set();
|
|
656
|
+
for (const container of containers) known.add(container);
|
|
657
|
+
importers.set(importer, known);
|
|
658
|
+
}
|
|
659
|
+
other(module, name) {
|
|
660
|
+
this.entry(module, name).other = true;
|
|
661
|
+
}
|
|
662
|
+
all(module) {
|
|
663
|
+
this.opaque.add(module);
|
|
664
|
+
}
|
|
665
|
+
users(module, exportName, user, absorbed) {
|
|
666
|
+
if (this.opaque.has(module)) return 0;
|
|
667
|
+
const usage = this.exports.get(`${module}\0${exportName}`);
|
|
668
|
+
if (!usage || usage.other || usage.importers.size === 0) return 0;
|
|
669
|
+
const users = /* @__PURE__ */ new Set([user]);
|
|
670
|
+
for (const [importer, containers] of usage.importers) {
|
|
671
|
+
const moved = absorbed.get(importer);
|
|
672
|
+
users.add([...containers].every((name) => moved?.has(name) === true) ? user : importer);
|
|
673
|
+
}
|
|
674
|
+
return [...users].some((id) => this.reaches(module, id)) ? 0 : users.size;
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
function isTagName(reference, parents) {
|
|
678
|
+
const parent = parents.get(reference);
|
|
679
|
+
return parent?.type === "JSXOpeningElement" && parent.name === reference;
|
|
680
|
+
}
|
|
681
|
+
function isClosingTagName(reference, parents) {
|
|
682
|
+
const parent = parents.get(reference);
|
|
683
|
+
return parent?.type === "JSXClosingElement" && parent.name === reference;
|
|
684
|
+
}
|
|
685
|
+
/** The names a declaration exported with `export` declares. */
|
|
686
|
+
function declaredNames(declaration) {
|
|
687
|
+
if (declaration?.type === "FunctionDeclaration" && declaration.id) return [declaration.id.name];
|
|
688
|
+
if (declaration?.type === "VariableDeclaration") return declaration.declarations.flatMap((declarator) => declarator.id.type === "Identifier" ? [declarator.id.name] : []);
|
|
689
|
+
return [];
|
|
690
|
+
}
|
|
691
|
+
/** The top-level bindings a module exports, each with its export names. */
|
|
692
|
+
function exportedBindings(program, scopes) {
|
|
693
|
+
const exported = /* @__PURE__ */ new Map();
|
|
694
|
+
const add = (local, name) => {
|
|
695
|
+
const binding = scopes.root.bindings.get(local);
|
|
696
|
+
if (binding) exported.set(binding, [...exported.get(binding) ?? [], name]);
|
|
697
|
+
};
|
|
698
|
+
for (const statement of program.body) if (statement.type === "ExportNamedDeclaration" && !statement.source) {
|
|
699
|
+
for (const name of declaredNames(statement.declaration)) add(name, name);
|
|
700
|
+
for (const specifier of statement.specifiers) if (specifier.local.type === "Identifier") add(specifier.local.name, specifier.exported.type === "Identifier" ? specifier.exported.name : specifier.exported.value);
|
|
701
|
+
} else if (statement.type === "ExportDefaultDeclaration") {
|
|
702
|
+
const { declaration } = statement;
|
|
703
|
+
if (declaration.type === "FunctionDeclaration" && declaration.id) add(declaration.id.name, "default");
|
|
704
|
+
else if (declaration.type === "Identifier") add(declaration.name, "default");
|
|
705
|
+
}
|
|
706
|
+
return exported;
|
|
707
|
+
}
|
|
708
|
+
/**
|
|
709
|
+
* Records how a module uses what it imports, and the uses of its own
|
|
710
|
+
* exports inside it.
|
|
711
|
+
*/
|
|
712
|
+
function recordModule(usage, id, program, targets) {
|
|
713
|
+
const scopes = analyzeScopes(program);
|
|
714
|
+
const parents = collectParents(program);
|
|
715
|
+
const exported = exportedBindings(program, scopes);
|
|
716
|
+
const containersOf = (reference) => {
|
|
717
|
+
let node = reference;
|
|
718
|
+
let parent = parents.get(node);
|
|
719
|
+
while (parent && parent.type !== "Program") {
|
|
720
|
+
node = parent;
|
|
721
|
+
parent = parents.get(node);
|
|
722
|
+
}
|
|
723
|
+
const declaration = (node.type === "ExportNamedDeclaration" || node.type === "ExportDefaultDeclaration") && node.declaration ? node.declaration : node;
|
|
724
|
+
const bindings = [];
|
|
725
|
+
if (declaration.type === "FunctionDeclaration" && declaration.id) bindings.push(scopes.root.bindings.get(declaration.id.name));
|
|
726
|
+
else if (declaration.type === "VariableDeclaration") {
|
|
727
|
+
for (const declarator of declaration.declarations) if (declarator.id.type === "Identifier" && reference.start >= declarator.start && reference.end <= declarator.end) bindings.push(scopes.root.bindings.get(declarator.id.name));
|
|
728
|
+
}
|
|
729
|
+
const names = bindings.flatMap((binding) => binding ? exported.get(binding) ?? [] : []);
|
|
730
|
+
return names.length > 0 ? names : [UNEXPORTED];
|
|
731
|
+
};
|
|
732
|
+
const record = (binding, target) => {
|
|
733
|
+
const imported = binding.imported ?? "*";
|
|
734
|
+
for (const reference of binding.references) {
|
|
735
|
+
if (isClosingTagName(reference, parents)) continue;
|
|
736
|
+
if (imported !== "*") {
|
|
737
|
+
if (isTagName(reference, parents)) usage.tag(target, imported, id, containersOf(reference));
|
|
738
|
+
else usage.other(target, imported);
|
|
739
|
+
continue;
|
|
740
|
+
}
|
|
741
|
+
const member = parents.get(reference);
|
|
742
|
+
if (member?.type === "JSXMemberExpression" && member.object === reference) {
|
|
743
|
+
if (isTagName(member, parents)) usage.tag(target, member.property.name, id, containersOf(reference));
|
|
744
|
+
else usage.other(target, member.property.name);
|
|
745
|
+
} else if (member?.type === "MemberExpression" && member.object === reference && !member.computed && member.property.type === "Identifier") usage.other(target, member.property.name);
|
|
746
|
+
else usage.all(target);
|
|
747
|
+
}
|
|
748
|
+
};
|
|
749
|
+
for (const binding of scopes.root.bindings.values()) if (binding.kind === "import" && binding.source !== void 0) {
|
|
750
|
+
const target = targets.get(binding.source);
|
|
751
|
+
if (target !== void 0) record(binding, target);
|
|
752
|
+
}
|
|
753
|
+
for (const statement of program.body) if (statement.type === "ExportAllDeclaration") {
|
|
754
|
+
const target = targets.get(statement.source.value);
|
|
755
|
+
if (target !== void 0) usage.all(target);
|
|
756
|
+
} else if (statement.type === "ExportNamedDeclaration" && statement.source) {
|
|
757
|
+
const target = targets.get(statement.source.value);
|
|
758
|
+
for (const specifier of statement.specifiers) {
|
|
759
|
+
const name = specifier.local.type === "Identifier" ? specifier.local.name : specifier.local.value;
|
|
760
|
+
if (target !== void 0) usage.other(target, name);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
for (const [binding, names] of exported) if (binding.references.some((reference) => {
|
|
764
|
+
const parent = parents.get(reference);
|
|
765
|
+
return parent?.type !== "ExportSpecifier" && parent?.type !== "ExportDefaultDeclaration" && !isClosingTagName(reference, parents);
|
|
766
|
+
})) for (const name of names) usage.other(id, name);
|
|
767
|
+
}
|
|
768
|
+
/** The import specifiers a module loads, statically or with `import()`. */
|
|
769
|
+
function specifiersOf(program) {
|
|
770
|
+
const statics = /* @__PURE__ */ new Set();
|
|
771
|
+
const dynamics = /* @__PURE__ */ new Set();
|
|
772
|
+
for (const statement of program.body) if (statement.type === "ImportDeclaration" && statement.importKind !== "type" || (statement.type === "ExportNamedDeclaration" || statement.type === "ExportAllDeclaration") && statement.source && statement.exportKind !== "type") {
|
|
773
|
+
const value = statement.source?.value;
|
|
774
|
+
if (value !== void 0) statics.add(value);
|
|
775
|
+
}
|
|
776
|
+
const visit = (node) => {
|
|
777
|
+
if (node.type === "ImportExpression" && node.source.type === "Literal" && typeof node.source.value === "string") dynamics.add(node.source.value);
|
|
778
|
+
forEachChild(node, visit);
|
|
779
|
+
};
|
|
780
|
+
visit(program);
|
|
781
|
+
return {
|
|
782
|
+
static: statics,
|
|
783
|
+
dynamic: dynamics
|
|
784
|
+
};
|
|
785
|
+
}
|
|
786
|
+
/**
|
|
787
|
+
* Reads every module reachable from `entries` and records how each export
|
|
788
|
+
* is used.
|
|
789
|
+
*/
|
|
790
|
+
async function buildUsageIndex(entries, host) {
|
|
791
|
+
const usage = new Usage();
|
|
792
|
+
for (const entry of entries) usage.all(entry);
|
|
793
|
+
const seen = /* @__PURE__ */ new Set();
|
|
794
|
+
let frontier = entries.filter((id) => SCRIPT.test(id.replace(/\?.*$/, "")));
|
|
795
|
+
while (frontier.length > 0) {
|
|
796
|
+
for (const id of frontier) seen.add(id);
|
|
797
|
+
const next = await Promise.all(frontier.map(async (id) => {
|
|
798
|
+
const code = await host.read(id);
|
|
799
|
+
let program;
|
|
800
|
+
try {
|
|
801
|
+
program = parse(id.replace(/\?.*$/, ""), code ?? "");
|
|
802
|
+
} catch {
|
|
803
|
+
return [];
|
|
804
|
+
}
|
|
805
|
+
const { static: statics, dynamic } = specifiersOf(program);
|
|
806
|
+
const targets = /* @__PURE__ */ new Map();
|
|
807
|
+
await Promise.all([...statics, ...dynamic].map(async (source) => {
|
|
808
|
+
const target = await host.resolve(source, id);
|
|
809
|
+
if (target !== void 0) targets.set(source, target);
|
|
810
|
+
}));
|
|
811
|
+
for (const source of dynamic) {
|
|
812
|
+
const target = targets.get(source);
|
|
813
|
+
if (target !== void 0) usage.all(target);
|
|
814
|
+
}
|
|
815
|
+
recordModule(usage, id, program, targets);
|
|
816
|
+
usage.imports.set(id, [...targets.values()]);
|
|
817
|
+
return [...targets.values()];
|
|
818
|
+
}));
|
|
819
|
+
frontier = [...new Set(next.flat())].filter((id) => !seen.has(id) && SCRIPT.test(id.replace(/\?.*$/, "")));
|
|
820
|
+
}
|
|
821
|
+
return usage;
|
|
822
|
+
}
|
|
823
|
+
//#endregion
|
|
824
|
+
//#region src/vite/index.ts
|
|
825
|
+
/**
|
|
826
|
+
* `solid-optimizer/vite`: `vite-plugin-solid` with the optimizer built in.
|
|
827
|
+
*
|
|
828
|
+
* It takes the same options as `vite-plugin-solid`, plus `optimizer`, and
|
|
829
|
+
* returns the official plugin with the optimizer wired in. It runs in one of
|
|
830
|
+
* two modes.
|
|
831
|
+
*
|
|
832
|
+
* - Chunk mode keeps JSX through bundling. Each chunk is optimized as a whole
|
|
833
|
+
* and then lowered by Solid's JSX transform, so a component inlines into
|
|
834
|
+
* any other component in the same chunk. It applies to client builds that
|
|
835
|
+
* do not hydrate.
|
|
836
|
+
* - Module mode optimizes each module before the official plugin lowers it.
|
|
837
|
+
* It applies everywhere else. A server build and its client build chunk
|
|
838
|
+
* differently, and hydration needs both to render the same tree, so
|
|
839
|
+
* hydrating builds only optimize within a module.
|
|
840
|
+
*/
|
|
841
|
+
const DEFAULT_MODULE_NAME = "solid-js/web";
|
|
842
|
+
const DEFAULT_BUILT_INS = [
|
|
843
|
+
"For",
|
|
844
|
+
"Show",
|
|
845
|
+
"Switch",
|
|
846
|
+
"Match",
|
|
847
|
+
"Suspense",
|
|
848
|
+
"SuspenseList",
|
|
849
|
+
"Portal",
|
|
850
|
+
"Index",
|
|
851
|
+
"Dynamic",
|
|
852
|
+
"ErrorBoundary"
|
|
853
|
+
];
|
|
854
|
+
const JSX_MODULE = /\.[mc]?[jt]sx$/i;
|
|
855
|
+
/**
|
|
856
|
+
* Helpers the JSX transform picks between for the same attribute. Inlining
|
|
857
|
+
* can turn one form into the other: a style object that was a prop becomes a
|
|
858
|
+
* literal, which the transform writes one property at a time. A module that
|
|
859
|
+
* needs one keeps the other too.
|
|
860
|
+
*/
|
|
861
|
+
const RELATED_HELPERS = {
|
|
862
|
+
style: ["setStyleProperty"],
|
|
863
|
+
setStyleProperty: ["style"]
|
|
864
|
+
};
|
|
865
|
+
function withRelated(helpers) {
|
|
866
|
+
const result = new Set(helpers);
|
|
867
|
+
for (const helper of helpers) for (const related of RELATED_HELPERS[helper] ?? []) result.add(related);
|
|
868
|
+
return result;
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* The common kinds of attribute: a class, any other attribute, events, and
|
|
872
|
+
* children. Inlining a component turns a spread onto an element into
|
|
873
|
+
* attributes like these, in a module that may not use their helpers itself.
|
|
874
|
+
* A rarer kind, like `style`, can still need a helper no module imports.
|
|
875
|
+
* The chunk is then lowered without optimizing it.
|
|
876
|
+
*/
|
|
877
|
+
const ATTRIBUTE_SAMPLE = `const a = () => 0;
|
|
878
|
+
export const Sample = () => (
|
|
879
|
+
<div class={a()} id={a()} onClick={a()} onScroll={a()}>{a()}</div>
|
|
880
|
+
);`;
|
|
881
|
+
/** Whether the code spreads anything onto an intrinsic element. */
|
|
882
|
+
function spreadsOntoElement(code, filename) {
|
|
883
|
+
if (!code.includes("...")) return false;
|
|
884
|
+
let found = false;
|
|
885
|
+
const visit = (node) => {
|
|
886
|
+
if (found) return;
|
|
887
|
+
if (node.type === "JSXOpeningElement" && node.name.type === "JSXIdentifier" && isIntrinsicTag(node.name.name) && node.attributes.some((attribute) => attribute.type === "JSXSpreadAttribute")) {
|
|
888
|
+
found = true;
|
|
889
|
+
return;
|
|
890
|
+
}
|
|
891
|
+
forEachChild(node, visit);
|
|
892
|
+
};
|
|
893
|
+
visit(parse(filename, code));
|
|
894
|
+
return found;
|
|
895
|
+
}
|
|
896
|
+
function loadCompiler() {
|
|
897
|
+
const require = createRequire(import.meta.url);
|
|
898
|
+
const pluginRequire = createRequire(require.resolve("vite-plugin-solid"));
|
|
899
|
+
const babel = createRequire(pluginRequire.resolve("babel-preset-solid"))("@babel/core");
|
|
900
|
+
const preset = pluginRequire("babel-preset-solid");
|
|
901
|
+
if (typeof preset !== "function") throw new TypeError("[solid-optimizer] babel-preset-solid did not load");
|
|
902
|
+
return {
|
|
903
|
+
babel,
|
|
904
|
+
preset
|
|
905
|
+
};
|
|
906
|
+
}
|
|
907
|
+
/**
|
|
908
|
+
* Lowers JSX with `babel-preset-solid`, as `vite-plugin-solid` does.
|
|
909
|
+
*/
|
|
910
|
+
function lower(compiler, code, filename, options, sourceMaps) {
|
|
911
|
+
const result = compiler.babel.transformSync(code, {
|
|
912
|
+
filename,
|
|
913
|
+
sourceFileName: filename,
|
|
914
|
+
presets: [[compiler.preset, options]],
|
|
915
|
+
ast: false,
|
|
916
|
+
sourceMaps,
|
|
917
|
+
configFile: false,
|
|
918
|
+
babelrc: false,
|
|
919
|
+
parserOpts: { plugins: /\.[mc]?tsx$/i.test(filename) ? ["jsx", "typescript"] : ["jsx"] }
|
|
920
|
+
});
|
|
921
|
+
if (typeof result?.code !== "string") throw new Error(`[solid-optimizer] babel-preset-solid produced no code for ${filename}`);
|
|
922
|
+
return {
|
|
923
|
+
code: result.code,
|
|
924
|
+
map: result.map ? JSON.stringify(result.map) : void 0
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
/**
|
|
928
|
+
* The helpers `babel-preset-solid` imports from `moduleName` to lower `code`.
|
|
929
|
+
* Only the AST is built, since its code would only be read for its imports.
|
|
930
|
+
*/
|
|
931
|
+
function helpersOf(compiler, code, filename, options, moduleName) {
|
|
932
|
+
const result = compiler.babel.transformSync(code, {
|
|
933
|
+
filename,
|
|
934
|
+
presets: [[compiler.preset, options]],
|
|
935
|
+
ast: true,
|
|
936
|
+
code: false,
|
|
937
|
+
configFile: false,
|
|
938
|
+
babelrc: false,
|
|
939
|
+
parserOpts: { plugins: /\.[mc]?tsx$/i.test(filename) ? ["jsx", "typescript"] : ["jsx"] }
|
|
940
|
+
});
|
|
941
|
+
const names = [];
|
|
942
|
+
for (const statement of result?.ast?.program.body ?? []) {
|
|
943
|
+
if (statement.type !== "ImportDeclaration" || statement.source.value !== moduleName) continue;
|
|
944
|
+
for (const specifier of statement.specifiers) if (specifier.type === "ImportSpecifier" && specifier.local.name.startsWith("_$")) {
|
|
945
|
+
const { imported } = specifier;
|
|
946
|
+
names.push(imported.type === "StringLiteral" ? imported.value : imported.name);
|
|
947
|
+
}
|
|
948
|
+
}
|
|
949
|
+
return names;
|
|
950
|
+
}
|
|
951
|
+
function stripQuery(id) {
|
|
952
|
+
return id.replace(/\?.*$/, "");
|
|
953
|
+
}
|
|
954
|
+
/**
|
|
955
|
+
* Chains the maps of each step into one, or `null` when the build writes no
|
|
956
|
+
* source maps, since chaining the maps of a large chunk takes a while.
|
|
957
|
+
*/
|
|
958
|
+
function combineMaps(wanted, maps) {
|
|
959
|
+
const present = maps.filter((map) => typeof map === "string");
|
|
960
|
+
if (!wanted || present.length === 0) return null;
|
|
961
|
+
return remapping(present.reverse(), () => null).toString();
|
|
962
|
+
}
|
|
963
|
+
/**
|
|
964
|
+
* The local name of each value a module imports, keyed by its source and
|
|
965
|
+
* the name it is imported as: an export name, `default`, or `*`.
|
|
966
|
+
*/
|
|
967
|
+
function importedNames(program) {
|
|
968
|
+
const names = /* @__PURE__ */ new Map();
|
|
969
|
+
for (const statement of program.body) {
|
|
970
|
+
if (statement.type !== "ImportDeclaration" || statement.importKind === "type") continue;
|
|
971
|
+
for (const specifier of statement.specifiers) {
|
|
972
|
+
let imported = "*";
|
|
973
|
+
if (specifier.type === "ImportDefaultSpecifier") imported = "default";
|
|
974
|
+
else if (specifier.type === "ImportSpecifier") imported = specifier.imported.type === "Identifier" ? specifier.imported.name : specifier.imported.value;
|
|
975
|
+
if (!(specifier.type === "ImportSpecifier" && specifier.importKind === "type")) names.set(`${statement.source.value}\0${imported}`, specifier.local.name);
|
|
976
|
+
}
|
|
977
|
+
}
|
|
978
|
+
return names;
|
|
979
|
+
}
|
|
980
|
+
/**
|
|
981
|
+
* A key for a module in the build environment of `context`. The server and
|
|
982
|
+
* client builds transform the same module into different code.
|
|
983
|
+
*/
|
|
984
|
+
function environmentKey(context, id) {
|
|
985
|
+
return `${context.environment?.name ?? ""}\0${id}`;
|
|
986
|
+
}
|
|
987
|
+
function isClient(context) {
|
|
988
|
+
return context.environment?.config.consumer === "client";
|
|
989
|
+
}
|
|
990
|
+
function solidOptimizer(options = {}) {
|
|
991
|
+
const { optimizer: optimizerOption, ...solidOptions } = options;
|
|
992
|
+
const main = solidPlugin(solidOptions);
|
|
993
|
+
if (optimizerOption === false) return [main];
|
|
994
|
+
const optimizer = optimizerOption ?? {};
|
|
995
|
+
const moduleName = solidOptions.solid?.moduleName ?? DEFAULT_MODULE_NAME;
|
|
996
|
+
const moduleSources = [.../* @__PURE__ */ new Set([
|
|
997
|
+
"solid-js",
|
|
998
|
+
DEFAULT_MODULE_NAME,
|
|
999
|
+
moduleName
|
|
1000
|
+
])];
|
|
1001
|
+
const builtIns = new Set(solidOptions.solid?.builtIns ?? DEFAULT_BUILT_INS);
|
|
1002
|
+
const compileOptions = {
|
|
1003
|
+
fold: optimizer.fold,
|
|
1004
|
+
inline: optimizer.inline,
|
|
1005
|
+
alwaysInline: optimizer.alwaysInline,
|
|
1006
|
+
contexts: optimizer.contexts,
|
|
1007
|
+
memos: optimizer.memos,
|
|
1008
|
+
maxPasses: optimizer.maxPasses,
|
|
1009
|
+
builtIns: [...builtIns],
|
|
1010
|
+
moduleSources,
|
|
1011
|
+
report: optimizer.report !== void 0 && optimizer.report !== false
|
|
1012
|
+
};
|
|
1013
|
+
let config;
|
|
1014
|
+
/**
|
|
1015
|
+
* A skip's name with the module it names, like `Card (/app/src/card.tsx)`,
|
|
1016
|
+
* relative to the project root, or to `node_modules` for a package.
|
|
1017
|
+
*/
|
|
1018
|
+
const shortName = (name) => name.replace(/\((\/.*)\)$/, (whole, file) => {
|
|
1019
|
+
const index = file.lastIndexOf("/node_modules/");
|
|
1020
|
+
if (index !== -1) return `(${file.slice(index + 14)})`;
|
|
1021
|
+
return config ? `(${path.relative(config.root, file)})` : whole;
|
|
1022
|
+
});
|
|
1023
|
+
/** What the final compile of each chunk or module left alone, by environment. */
|
|
1024
|
+
const skips = /* @__PURE__ */ new Map();
|
|
1025
|
+
const addSkips = (context, list) => {
|
|
1026
|
+
if (!list) return;
|
|
1027
|
+
const environment = context.environment?.name ?? "client";
|
|
1028
|
+
const entries = skips.get(environment) ?? [];
|
|
1029
|
+
entries.push(...list.map((skip) => ({
|
|
1030
|
+
...skip,
|
|
1031
|
+
name: shortName(skip.name)
|
|
1032
|
+
})));
|
|
1033
|
+
skips.set(environment, entries);
|
|
1034
|
+
};
|
|
1035
|
+
let compiler;
|
|
1036
|
+
let filter;
|
|
1037
|
+
const getCompiler = () => {
|
|
1038
|
+
compiler ??= loadCompiler();
|
|
1039
|
+
return compiler;
|
|
1040
|
+
};
|
|
1041
|
+
const isBuild = () => config?.command === "build";
|
|
1042
|
+
/** Whether the output needs source maps: while serving, or when the build writes them. */
|
|
1043
|
+
const wantsMaps = () => !isBuild() || Boolean(config?.build.sourcemap);
|
|
1044
|
+
/**
|
|
1045
|
+
* The JSX options the official plugin passes for a posture, so the
|
|
1046
|
+
* lowering here matches it. Mirrors the `transform` hook of `vite-plugin-solid`.
|
|
1047
|
+
*/
|
|
1048
|
+
const jsxOptions = (isSsr) => {
|
|
1049
|
+
let posture = {
|
|
1050
|
+
generate: "dom",
|
|
1051
|
+
hydratable: false
|
|
1052
|
+
};
|
|
1053
|
+
if (solidOptions.ssr) posture = {
|
|
1054
|
+
generate: isSsr ? "ssr" : "dom",
|
|
1055
|
+
hydratable: true
|
|
1056
|
+
};
|
|
1057
|
+
return {
|
|
1058
|
+
...posture,
|
|
1059
|
+
...solidOptions.solid
|
|
1060
|
+
};
|
|
1061
|
+
};
|
|
1062
|
+
let sampleHelpers;
|
|
1063
|
+
/** The helpers the JSX transform uses for attributes in chunk mode. */
|
|
1064
|
+
const attributeHelpers = () => {
|
|
1065
|
+
sampleHelpers ??= helpersOf(getCompiler(), ATTRIBUTE_SAMPLE, "sample.jsx", jsxOptions(false), moduleName);
|
|
1066
|
+
return sampleHelpers;
|
|
1067
|
+
};
|
|
1068
|
+
/**
|
|
1069
|
+
* Whether client builds keep JSX until chunks are rendered.
|
|
1070
|
+
*/
|
|
1071
|
+
const chunkMode = () => {
|
|
1072
|
+
if (!isBuild() || (optimizer.mode ?? "auto") !== "auto") return false;
|
|
1073
|
+
if (solidOptions.babel) return false;
|
|
1074
|
+
const client = jsxOptions(false);
|
|
1075
|
+
return client.generate === "dom" && client.hydratable !== true;
|
|
1076
|
+
};
|
|
1077
|
+
const isJSXModule = (id) => {
|
|
1078
|
+
filter ??= createFilter(solidOptions.include, solidOptions.exclude);
|
|
1079
|
+
return filter(id) && JSX_MODULE.test(stripQuery(id));
|
|
1080
|
+
};
|
|
1081
|
+
/** Modules that keep their JSX, which the bundler must parse as JSX. */
|
|
1082
|
+
const preserved = /* @__PURE__ */ new Set();
|
|
1083
|
+
/** What each module imports and the constants it exports, by module id. */
|
|
1084
|
+
const moduleConstants = /* @__PURE__ */ new Map();
|
|
1085
|
+
/**
|
|
1086
|
+
* The module an import resolves to, when its constants can be read.
|
|
1087
|
+
*
|
|
1088
|
+
* A module with JSX is skipped. This plugin's transform may be waiting for
|
|
1089
|
+
* it, and it may be waiting for this one, so loading it could deadlock.
|
|
1090
|
+
* Dependencies are skipped to keep the build fast.
|
|
1091
|
+
*/
|
|
1092
|
+
async function resolveConstantModule(context, specifier, importer) {
|
|
1093
|
+
if (moduleSources.includes(specifier)) return;
|
|
1094
|
+
const resolved = await context.resolve(specifier, importer);
|
|
1095
|
+
if (!resolved || resolved.external || resolved.id.includes("/node_modules/") || isJSXModule(resolved.id)) return;
|
|
1096
|
+
return resolved.id;
|
|
1097
|
+
}
|
|
1098
|
+
/**
|
|
1099
|
+
* The constants of the modules `code` imports, keyed by import specifier.
|
|
1100
|
+
*
|
|
1101
|
+
* Each module is read as the bundler loads it, after every plugin has
|
|
1102
|
+
* transformed it, so a plugin that replaces or rewrites a module is seen.
|
|
1103
|
+
* A module that imports constants itself resolves them first, and a cycle
|
|
1104
|
+
* leaves the modules in it without them.
|
|
1105
|
+
*/
|
|
1106
|
+
async function importedConstants(context, imports, importer, visiting) {
|
|
1107
|
+
const entries = await Promise.all(imports.map(async (specifier) => {
|
|
1108
|
+
const id = await resolveConstantModule(context, specifier, importer);
|
|
1109
|
+
if (id === void 0 || visiting.has(id)) return;
|
|
1110
|
+
const constants = await constantsOf(context, id, visiting);
|
|
1111
|
+
if (!constants || Object.keys(constants.exports).length === 0) return;
|
|
1112
|
+
return [specifier, constants.exports];
|
|
1113
|
+
}));
|
|
1114
|
+
return Object.fromEntries(entries.filter((entry) => entry !== void 0));
|
|
1115
|
+
}
|
|
1116
|
+
async function constantsOf(context, id, visiting) {
|
|
1117
|
+
let pending = moduleConstants.get(id);
|
|
1118
|
+
if (!pending) {
|
|
1119
|
+
pending = (async () => {
|
|
1120
|
+
const { code } = await context.load({ id });
|
|
1121
|
+
if (code === null) return;
|
|
1122
|
+
const filename = `${stripQuery(id)}.js`;
|
|
1123
|
+
try {
|
|
1124
|
+
const own = readModuleConstants(code, { filename });
|
|
1125
|
+
if (own.imports.length === 0) return own;
|
|
1126
|
+
const imported = await importedConstants(context, own.imports, id, /* @__PURE__ */ new Set([...visiting, id]));
|
|
1127
|
+
return readModuleConstants(code, {
|
|
1128
|
+
filename,
|
|
1129
|
+
importedConstants: imported
|
|
1130
|
+
});
|
|
1131
|
+
} catch (error) {
|
|
1132
|
+
if (error instanceof SyntaxError) return;
|
|
1133
|
+
throw error;
|
|
1134
|
+
}
|
|
1135
|
+
})();
|
|
1136
|
+
moduleConstants.set(id, pending);
|
|
1137
|
+
}
|
|
1138
|
+
return pending;
|
|
1139
|
+
}
|
|
1140
|
+
/**
|
|
1141
|
+
* The compile options for a module, with the constants of its imports.
|
|
1142
|
+
*/
|
|
1143
|
+
async function moduleOptions(context, code, id) {
|
|
1144
|
+
const filename = stripQuery(id);
|
|
1145
|
+
if (optimizer.fold === false || !isBuild()) return {
|
|
1146
|
+
...compileOptions,
|
|
1147
|
+
filename,
|
|
1148
|
+
sourceMap: wantsMaps()
|
|
1149
|
+
};
|
|
1150
|
+
const { imports } = readModuleConstants(code, { filename });
|
|
1151
|
+
return {
|
|
1152
|
+
...compileOptions,
|
|
1153
|
+
filename,
|
|
1154
|
+
sourceMap: wantsMaps(),
|
|
1155
|
+
importedConstants: await importedConstants(context, imports, filename, /* @__PURE__ */ new Set([filename]))
|
|
1156
|
+
};
|
|
1157
|
+
}
|
|
1158
|
+
/** The modules each transform waits for, so two never wait for each other. */
|
|
1159
|
+
const waiting = /* @__PURE__ */ new Map();
|
|
1160
|
+
/** Whether the transform of `from` waits, directly or not, for `to`. */
|
|
1161
|
+
const waitsFor = (from, to) => {
|
|
1162
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1163
|
+
const stack = [from];
|
|
1164
|
+
for (let current = stack.pop(); current !== void 0; current = stack.pop()) {
|
|
1165
|
+
if (current === to) return true;
|
|
1166
|
+
if (!seen.has(current)) {
|
|
1167
|
+
seen.add(current);
|
|
1168
|
+
stack.push(...waiting.get(current) ?? []);
|
|
1169
|
+
}
|
|
1170
|
+
}
|
|
1171
|
+
return false;
|
|
1172
|
+
};
|
|
1173
|
+
/**
|
|
1174
|
+
* The code of a module with JSX, as the bundler loads it. `undefined`
|
|
1175
|
+
* when that module's transform waits for the importer, which would then
|
|
1176
|
+
* wait for it in turn.
|
|
1177
|
+
*/
|
|
1178
|
+
async function loadModule(context, importer, target) {
|
|
1179
|
+
if (waitsFor(target, importer)) return;
|
|
1180
|
+
const targets = waiting.get(importer) ?? /* @__PURE__ */ new Set();
|
|
1181
|
+
targets.add(target);
|
|
1182
|
+
waiting.set(importer, targets);
|
|
1183
|
+
try {
|
|
1184
|
+
return (await context.load({ id: target })).code ?? void 0;
|
|
1185
|
+
} finally {
|
|
1186
|
+
targets.delete(target);
|
|
1187
|
+
}
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* The code of each module with JSX as this plugin's module step returned
|
|
1191
|
+
* it, before Solid's JSX transform lowers it. In module mode, an importer
|
|
1192
|
+
* copies components from it.
|
|
1193
|
+
*/
|
|
1194
|
+
const recorded = /* @__PURE__ */ new Map();
|
|
1195
|
+
/** The modules with JSX each module imports, read from its file. */
|
|
1196
|
+
const jsxImports = /* @__PURE__ */ new Map();
|
|
1197
|
+
/**
|
|
1198
|
+
* The modules with JSX a module imports. They come from the file on disk,
|
|
1199
|
+
* so they do not depend on the order modules are transformed in.
|
|
1200
|
+
*/
|
|
1201
|
+
async function jsxImportsOf(context, id) {
|
|
1202
|
+
let pending = jsxImports.get(id);
|
|
1203
|
+
if (!pending) {
|
|
1204
|
+
pending = (async () => {
|
|
1205
|
+
let code;
|
|
1206
|
+
try {
|
|
1207
|
+
code = await readFile(stripQuery(id), "utf8");
|
|
1208
|
+
} catch {
|
|
1209
|
+
return [];
|
|
1210
|
+
}
|
|
1211
|
+
let program;
|
|
1212
|
+
try {
|
|
1213
|
+
program = parse(stripQuery(id), code);
|
|
1214
|
+
} catch {
|
|
1215
|
+
return [];
|
|
1216
|
+
}
|
|
1217
|
+
const sources = /* @__PURE__ */ new Set();
|
|
1218
|
+
for (const statement of program.body) if (statement.type === "ImportDeclaration" && statement.importKind !== "type" || (statement.type === "ExportNamedDeclaration" || statement.type === "ExportAllDeclaration") && statement.source && statement.exportKind !== "type") {
|
|
1219
|
+
const value = statement.source?.value;
|
|
1220
|
+
if (value !== void 0 && !moduleSources.includes(value)) sources.add(value);
|
|
1221
|
+
}
|
|
1222
|
+
return (await Promise.all([...sources].map(async (source) => context.resolve(source, id)))).filter((target) => target && !target.external && isJSXModule(target.id)).map((target) => target?.id ?? "");
|
|
1223
|
+
})();
|
|
1224
|
+
jsxImports.set(id, pending);
|
|
1225
|
+
}
|
|
1226
|
+
return pending;
|
|
1227
|
+
}
|
|
1228
|
+
/** Whether `from` imports `to`, directly or through other modules with JSX. */
|
|
1229
|
+
async function reaches(context, from, to) {
|
|
1230
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1231
|
+
let frontier = [from];
|
|
1232
|
+
while (frontier.length > 0) {
|
|
1233
|
+
if (frontier.includes(to)) return true;
|
|
1234
|
+
for (const id of frontier) seen.add(id);
|
|
1235
|
+
const next = await Promise.all(frontier.map(async (id) => jsxImportsOf(context, id)));
|
|
1236
|
+
frontier = [...new Set(next.flat())].filter((id) => !seen.has(id));
|
|
1237
|
+
}
|
|
1238
|
+
return false;
|
|
1239
|
+
}
|
|
1240
|
+
/**
|
|
1241
|
+
* The code of a module with JSX before Solid's JSX transform, with its
|
|
1242
|
+
* types stripped. A module that imports the importer back is skipped, so
|
|
1243
|
+
* no two transforms wait for each other, and the server and client builds
|
|
1244
|
+
* skip the same ones.
|
|
1245
|
+
*/
|
|
1246
|
+
async function loadRecorded(context, importer, target) {
|
|
1247
|
+
if (await reaches(context, target, importer)) return;
|
|
1248
|
+
await context.load({ id: target });
|
|
1249
|
+
const code = recorded.get(environmentKey(context, target));
|
|
1250
|
+
if (code === void 0) return;
|
|
1251
|
+
return (await transformWithOxc(code, stripQuery(target), {
|
|
1252
|
+
jsx: "preserve",
|
|
1253
|
+
sourcemap: false
|
|
1254
|
+
})).code;
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* The scripts an entry runs: the entry itself, or the module scripts of an
|
|
1258
|
+
* HTML entry. `undefined` when an HTML entry has an inline module script,
|
|
1259
|
+
* whose imports the usage index cannot read.
|
|
1260
|
+
*/
|
|
1261
|
+
async function scriptEntries(context, id) {
|
|
1262
|
+
if (/\.[mc]?[jt]sx?(?:\?|$)/.test(id)) return [id];
|
|
1263
|
+
let html;
|
|
1264
|
+
try {
|
|
1265
|
+
html = await readFile(stripQuery(id), "utf8");
|
|
1266
|
+
} catch {
|
|
1267
|
+
return;
|
|
1268
|
+
}
|
|
1269
|
+
const scripts = [];
|
|
1270
|
+
for (const [tag] of html.matchAll(/<script\b[^>]*>/gi)) {
|
|
1271
|
+
if (!/\btype\s*=\s*["']?module/i.test(tag)) continue;
|
|
1272
|
+
const src = /\bsrc\s*=\s*["']([^"']+)["']/i.exec(tag)?.[1];
|
|
1273
|
+
if (src === void 0) return;
|
|
1274
|
+
const resolved = await context.resolve(src, id);
|
|
1275
|
+
if (!resolved || resolved.external) return;
|
|
1276
|
+
scripts.push(resolved.id);
|
|
1277
|
+
}
|
|
1278
|
+
return scripts;
|
|
1279
|
+
}
|
|
1280
|
+
/** How the app uses each export, built once per environment and build. */
|
|
1281
|
+
const usageIndexes = /* @__PURE__ */ new Map();
|
|
1282
|
+
/**
|
|
1283
|
+
* How the app uses each export, read from the modules the entries reach.
|
|
1284
|
+
*/
|
|
1285
|
+
async function usageIndex(context) {
|
|
1286
|
+
const key = environmentKey(context, "");
|
|
1287
|
+
let pending = usageIndexes.get(key);
|
|
1288
|
+
if (!pending) {
|
|
1289
|
+
pending = (async () => {
|
|
1290
|
+
const entries = await Promise.all([...context.getModuleIds()].filter((id) => context.getModuleInfo(id)?.isEntry === true).map(async (id) => scriptEntries(context, id)));
|
|
1291
|
+
return buildUsageIndex(entries.every((scripts) => scripts !== void 0) ? entries.flat() : [], {
|
|
1292
|
+
resolve: async (source, importer) => {
|
|
1293
|
+
const resolved = await context.resolve(source, importer);
|
|
1294
|
+
return !resolved || resolved.external || resolved.id.includes("/node_modules/") ? void 0 : resolved.id;
|
|
1295
|
+
},
|
|
1296
|
+
read: async (id) => {
|
|
1297
|
+
try {
|
|
1298
|
+
return await readFile(stripQuery(id), "utf8");
|
|
1299
|
+
} catch {
|
|
1300
|
+
return;
|
|
1301
|
+
}
|
|
1302
|
+
}
|
|
1303
|
+
});
|
|
1304
|
+
})();
|
|
1305
|
+
usageIndexes.set(key, pending);
|
|
1306
|
+
}
|
|
1307
|
+
return pending;
|
|
1308
|
+
}
|
|
1309
|
+
/**
|
|
1310
|
+
* The text that imports a binding under `local`.
|
|
1311
|
+
*/
|
|
1312
|
+
function importText(local, imported, source) {
|
|
1313
|
+
const from = JSON.stringify(source);
|
|
1314
|
+
if (imported === "*") return `import * as ${local} from ${from};`;
|
|
1315
|
+
if (imported === "default") return `import ${local} from ${from};`;
|
|
1316
|
+
return `import { ${imported} as ${local} } from ${from};`;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Reads the component `source` exports as `imported`, and imports what it
|
|
1320
|
+
* needs into the importer. `undefined` when it cannot be copied.
|
|
1321
|
+
*/
|
|
1322
|
+
async function copyImported(context, id, source, imported, state) {
|
|
1323
|
+
const skip = (reason) => {
|
|
1324
|
+
state.skips?.push({
|
|
1325
|
+
pass: "inline",
|
|
1326
|
+
reason,
|
|
1327
|
+
name: `${imported} (${source})`
|
|
1328
|
+
});
|
|
1329
|
+
};
|
|
1330
|
+
const resolved = await context.resolve(source, id);
|
|
1331
|
+
if (!resolved || resolved.external) {
|
|
1332
|
+
skip("copy-external");
|
|
1333
|
+
return;
|
|
1334
|
+
}
|
|
1335
|
+
if (resolved.id.includes("/node_modules/")) {
|
|
1336
|
+
skip("copy-package");
|
|
1337
|
+
return;
|
|
1338
|
+
}
|
|
1339
|
+
if (resolved.id === id) return;
|
|
1340
|
+
if (!isJSXModule(resolved.id)) {
|
|
1341
|
+
skip("copy-not-jsx");
|
|
1342
|
+
return;
|
|
1343
|
+
}
|
|
1344
|
+
const key = `${resolved.id}\0${imported}`;
|
|
1345
|
+
if (state.excluded.has(key)) return;
|
|
1346
|
+
const loaded = await state.load(resolved.id);
|
|
1347
|
+
if (loaded === void 0) {
|
|
1348
|
+
state.excluded.add(key);
|
|
1349
|
+
skip("copy-cycle");
|
|
1350
|
+
return;
|
|
1351
|
+
}
|
|
1352
|
+
const component = readExportedComponent(loaded, stripQuery(resolved.id), imported, moduleSources);
|
|
1353
|
+
if (!component) {
|
|
1354
|
+
state.excluded.add(key);
|
|
1355
|
+
skip("copy-shape");
|
|
1356
|
+
return;
|
|
1357
|
+
}
|
|
1358
|
+
if (component.wrapsLocal) {
|
|
1359
|
+
state.excluded.add(key);
|
|
1360
|
+
skip("copy-wrapper");
|
|
1361
|
+
return;
|
|
1362
|
+
}
|
|
1363
|
+
const targets = /* @__PURE__ */ new Map();
|
|
1364
|
+
for (const dependency of component.dependencies.values()) if (dependency.kind === "import" && !moduleSources.includes(dependency.source)) {
|
|
1365
|
+
const target = await context.resolve(dependency.source, resolved.id);
|
|
1366
|
+
if (!target) {
|
|
1367
|
+
state.excluded.add(key);
|
|
1368
|
+
skip("copy-external");
|
|
1369
|
+
return;
|
|
1370
|
+
}
|
|
1371
|
+
targets.set(dependency.source, target.external ? dependency.source : target.id);
|
|
1372
|
+
}
|
|
1373
|
+
const rename = /* @__PURE__ */ new Map();
|
|
1374
|
+
for (const [local, dependency] of component.dependencies) {
|
|
1375
|
+
if (dependency.kind === "import") {
|
|
1376
|
+
const from = targets.get(dependency.source) ?? dependency.source;
|
|
1377
|
+
rename.set(local, state.importAs(local, dependency.imported, from));
|
|
1378
|
+
continue;
|
|
1379
|
+
}
|
|
1380
|
+
rename.set(local, state.importAs(local, dependency.exported, resolved.id));
|
|
1381
|
+
if (dependency.context) {
|
|
1382
|
+
const known = state.contexts.get(resolved.id) ?? /* @__PURE__ */ new Set();
|
|
1383
|
+
known.add(dependency.exported);
|
|
1384
|
+
state.contexts.set(resolved.id, known);
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
return {
|
|
1388
|
+
key,
|
|
1389
|
+
text: (name) => component.copy(name, rename)
|
|
1390
|
+
};
|
|
1391
|
+
}
|
|
1392
|
+
/**
|
|
1393
|
+
* Copies the components a module imports from other modules with JSX into
|
|
1394
|
+
* it, and inlines them there. A copy the inline pass cannot inline at
|
|
1395
|
+
* every call is left out, so a component is never in both places. Copies
|
|
1396
|
+
* can import components in turn, which a few more rounds take in.
|
|
1397
|
+
*/
|
|
1398
|
+
async function inlineImports(context, source, id, compileOptionsOfModule, load, copySkips) {
|
|
1399
|
+
const filename = stripQuery(id);
|
|
1400
|
+
const maps = [];
|
|
1401
|
+
let skipped;
|
|
1402
|
+
const excluded = /* @__PURE__ */ new Set();
|
|
1403
|
+
const usage = await usageIndex(context);
|
|
1404
|
+
const absorbed = /* @__PURE__ */ new Map();
|
|
1405
|
+
const usersOf = (copy) => {
|
|
1406
|
+
const [module = "", exported = ""] = copy.key.split("\0");
|
|
1407
|
+
return usage.users(module, exported, id, absorbed);
|
|
1408
|
+
};
|
|
1409
|
+
const contexts = /* @__PURE__ */ new Map();
|
|
1410
|
+
let code = source;
|
|
1411
|
+
const copyNames = /* @__PURE__ */ new Map();
|
|
1412
|
+
for (let round = 0; round < 4; round += 1) {
|
|
1413
|
+
const program = parse(filename, code);
|
|
1414
|
+
const scopes = analyzeScopes(program);
|
|
1415
|
+
const parents = collectParents(program);
|
|
1416
|
+
const names = new Set(scopes.names);
|
|
1417
|
+
const fresh = (base) => {
|
|
1418
|
+
let name = base;
|
|
1419
|
+
for (let index = 1; names.has(name); index += 1) name = `${base}$${String(index)}`;
|
|
1420
|
+
names.add(name);
|
|
1421
|
+
return name;
|
|
1422
|
+
};
|
|
1423
|
+
const existing = importedNames(program);
|
|
1424
|
+
const imports = [];
|
|
1425
|
+
const added = /* @__PURE__ */ new Map();
|
|
1426
|
+
const importAs = (base, imported, from) => {
|
|
1427
|
+
const key = `${from}\0${imported}`;
|
|
1428
|
+
const known = existing.get(key) ?? added.get(key);
|
|
1429
|
+
if (known !== void 0) return known;
|
|
1430
|
+
const name = fresh(base);
|
|
1431
|
+
added.set(key, name);
|
|
1432
|
+
imports.push(importText(name, imported, from));
|
|
1433
|
+
return name;
|
|
1434
|
+
};
|
|
1435
|
+
const copies = [];
|
|
1436
|
+
for (const statement of program.body) {
|
|
1437
|
+
if (statement.type !== "ImportDeclaration" || statement.importKind === "type" || moduleSources.includes(statement.source.value)) continue;
|
|
1438
|
+
for (const specifier of statement.specifiers) {
|
|
1439
|
+
const binding = scopes.root.bindings.get(specifier.local.name);
|
|
1440
|
+
const tags = (binding?.references ?? []).filter((reference) => {
|
|
1441
|
+
const parent = parents.get(reference);
|
|
1442
|
+
return (parent?.type === "JSXOpeningElement" || parent?.type === "JSXClosingElement") && parent.name === reference;
|
|
1443
|
+
});
|
|
1444
|
+
if (specifier.type === "ImportNamespaceSpecifier" || binding?.imported === void 0 || tags.length === 0) continue;
|
|
1445
|
+
const copy = await copyImported(context, id, statement.source.value, binding.imported, {
|
|
1446
|
+
excluded,
|
|
1447
|
+
contexts,
|
|
1448
|
+
importAs,
|
|
1449
|
+
load,
|
|
1450
|
+
skips: copySkips
|
|
1451
|
+
});
|
|
1452
|
+
if (copy && copySkips) copyNames.set(copy.key, `${binding.imported} (${statement.source.value})`);
|
|
1453
|
+
if (copy) {
|
|
1454
|
+
const name = fresh(specifier.local.name);
|
|
1455
|
+
copies.push({
|
|
1456
|
+
key: copy.key,
|
|
1457
|
+
name,
|
|
1458
|
+
tags,
|
|
1459
|
+
text: copy.text(name)
|
|
1460
|
+
});
|
|
1461
|
+
}
|
|
1462
|
+
}
|
|
1463
|
+
}
|
|
1464
|
+
if (copies.length === 0) break;
|
|
1465
|
+
let result;
|
|
1466
|
+
let edit;
|
|
1467
|
+
for (let attempt = 0; attempt < 4 && copies.length > 0; attempt += 1) {
|
|
1468
|
+
edit = new MagicString(code);
|
|
1469
|
+
for (const copy of copies) {
|
|
1470
|
+
for (const tag of copy.tags) edit.overwrite(tag.start, tag.end, copy.name);
|
|
1471
|
+
edit.append(`\n${copy.text}\n`);
|
|
1472
|
+
}
|
|
1473
|
+
edit.append(`\n${imports.join("\n")}\n`);
|
|
1474
|
+
result = compile(edit.toString(), {
|
|
1475
|
+
...compileOptionsOfModule,
|
|
1476
|
+
filename,
|
|
1477
|
+
sourceMap: wantsMaps(),
|
|
1478
|
+
importedContexts: Object.fromEntries([...contexts].map(([module, exported]) => [module, [...exported]])),
|
|
1479
|
+
sharedComponents: Object.fromEntries(copies.map((copy) => [copy.name, usersOf(copy)]).filter(([, users]) => users !== 1))
|
|
1480
|
+
});
|
|
1481
|
+
const left = analyzeScopes(parse(filename, result.code)).root.bindings;
|
|
1482
|
+
const stuck = copies.filter((copy) => left.has(copy.name));
|
|
1483
|
+
if (stuck.length === 0) break;
|
|
1484
|
+
for (const copy of stuck) {
|
|
1485
|
+
excluded.add(copy.key);
|
|
1486
|
+
copies.splice(copies.indexOf(copy), 1);
|
|
1487
|
+
const reason = result.skipped?.find((entry) => entry.name === copy.name)?.reason;
|
|
1488
|
+
copySkips?.push({
|
|
1489
|
+
pass: "inline",
|
|
1490
|
+
reason: `copy-${reason ?? "left"}`,
|
|
1491
|
+
name: copyNames.get(copy.key) ?? copy.name
|
|
1492
|
+
});
|
|
1493
|
+
}
|
|
1494
|
+
result = void 0;
|
|
1495
|
+
}
|
|
1496
|
+
if (!result || !edit) break;
|
|
1497
|
+
for (const copy of copies.filter((item) => usersOf(item) === 1)) {
|
|
1498
|
+
const [module = "", exported = ""] = copy.key.split("\0");
|
|
1499
|
+
absorbed.set(module, /* @__PURE__ */ new Set([...absorbed.get(module) ?? [], exported]));
|
|
1500
|
+
}
|
|
1501
|
+
if (wantsMaps()) maps.push(edit.generateMap({
|
|
1502
|
+
source: filename,
|
|
1503
|
+
hires: true,
|
|
1504
|
+
includeContent: true
|
|
1505
|
+
}).toString());
|
|
1506
|
+
if (result.map) maps.push(result.map.toString());
|
|
1507
|
+
code = result.code;
|
|
1508
|
+
({skipped} = result);
|
|
1509
|
+
}
|
|
1510
|
+
return code === source ? void 0 : {
|
|
1511
|
+
code,
|
|
1512
|
+
maps,
|
|
1513
|
+
skipped
|
|
1514
|
+
};
|
|
1515
|
+
}
|
|
1516
|
+
/**
|
|
1517
|
+
* Prepares a client module for chunk mode. It adds the helper marker
|
|
1518
|
+
* instead of lowering JSX. Vite strips the types afterwards.
|
|
1519
|
+
*/
|
|
1520
|
+
async function keepJSX(context, source, id) {
|
|
1521
|
+
const filename = stripQuery(id);
|
|
1522
|
+
const moduleCompileOptions = await moduleOptions(context, source, id);
|
|
1523
|
+
const local = compile(source, {
|
|
1524
|
+
...moduleCompileOptions,
|
|
1525
|
+
inline: false
|
|
1526
|
+
});
|
|
1527
|
+
let code = local.code;
|
|
1528
|
+
const maps = [local.map?.toString()];
|
|
1529
|
+
const named = nameNamespaceTags(code, filename);
|
|
1530
|
+
if (named) {
|
|
1531
|
+
code = named.code;
|
|
1532
|
+
maps.push(named.map);
|
|
1533
|
+
}
|
|
1534
|
+
if (moduleCompileOptions.inline !== false) {
|
|
1535
|
+
const copySkips = compileOptions.report ? [] : void 0;
|
|
1536
|
+
const imported = await inlineImports(context, code, id, moduleCompileOptions, async (target) => loadModule(context, id, target), copySkips);
|
|
1537
|
+
addSkips(context, copySkips);
|
|
1538
|
+
if (imported) {
|
|
1539
|
+
code = imported.code;
|
|
1540
|
+
maps.push(...imported.maps);
|
|
1541
|
+
}
|
|
1542
|
+
}
|
|
1543
|
+
const exposed = context.getModuleInfo(id)?.isEntry ? void 0 : exposeLocals(code, filename);
|
|
1544
|
+
if (exposed) {
|
|
1545
|
+
code = exposed.code;
|
|
1546
|
+
maps.push(exposed.map);
|
|
1547
|
+
}
|
|
1548
|
+
const inlined = moduleCompileOptions.inline === false ? void 0 : compile(code, {
|
|
1549
|
+
...moduleCompileOptions,
|
|
1550
|
+
sourceMap: false
|
|
1551
|
+
});
|
|
1552
|
+
const needed = /* @__PURE__ */ new Set();
|
|
1553
|
+
for (const version of /* @__PURE__ */ new Set([code, inlined?.code ?? code])) for (const helper of helpersOf(getCompiler(), version, filename, jsxOptions(false), moduleName)) needed.add(helper);
|
|
1554
|
+
if (moduleCompileOptions.inline !== false && spreadsOntoElement(code, filename)) for (const helper of attributeHelpers()) needed.add(helper);
|
|
1555
|
+
const protectedRefs = protectRefs(code, filename);
|
|
1556
|
+
if (protectedRefs) {
|
|
1557
|
+
code = protectedRefs.code;
|
|
1558
|
+
maps.push(protectedRefs.map);
|
|
1559
|
+
}
|
|
1560
|
+
preserved.add(id);
|
|
1561
|
+
if (needed.size === 0) return code === source ? null : {
|
|
1562
|
+
code,
|
|
1563
|
+
map: combineMaps(wantsMaps(), maps)
|
|
1564
|
+
};
|
|
1565
|
+
const marked = addMarker(code, filename, {
|
|
1566
|
+
moduleName,
|
|
1567
|
+
helpers: withRelated([...needed]),
|
|
1568
|
+
moduleSources,
|
|
1569
|
+
builtIns: /* @__PURE__ */ new Set([
|
|
1570
|
+
...builtIns,
|
|
1571
|
+
"createContext",
|
|
1572
|
+
...CONTEXT_SAFE_PRIMITIVES
|
|
1573
|
+
])
|
|
1574
|
+
});
|
|
1575
|
+
if (!marked) return code === source ? null : {
|
|
1576
|
+
code,
|
|
1577
|
+
map: combineMaps(wantsMaps(), maps)
|
|
1578
|
+
};
|
|
1579
|
+
return {
|
|
1580
|
+
code: marked.code,
|
|
1581
|
+
map: combineMaps(wantsMaps(), [...maps, marked.map])
|
|
1582
|
+
};
|
|
1583
|
+
}
|
|
1584
|
+
const originalTransform = main.transform;
|
|
1585
|
+
const originalHandler = typeof originalTransform === "function" ? originalTransform : originalTransform?.handler;
|
|
1586
|
+
if (originalHandler) main.transform = async function transform(code, id, transformOptions) {
|
|
1587
|
+
if (chunkMode() && isClient(this) && isJSXModule(id)) return keepJSX(this, code, id);
|
|
1588
|
+
return originalHandler.call(this, code, id, transformOptions);
|
|
1589
|
+
};
|
|
1590
|
+
const modulePlugin = {
|
|
1591
|
+
name: "solid-optimizer:module",
|
|
1592
|
+
enforce: "pre",
|
|
1593
|
+
configResolved(resolved) {
|
|
1594
|
+
config = resolved;
|
|
1595
|
+
},
|
|
1596
|
+
buildStart() {
|
|
1597
|
+
moduleConstants.clear();
|
|
1598
|
+
jsxImports.clear();
|
|
1599
|
+
usageIndexes.clear();
|
|
1600
|
+
skips.delete(this.environment.name);
|
|
1601
|
+
},
|
|
1602
|
+
watchChange() {
|
|
1603
|
+
moduleConstants.clear();
|
|
1604
|
+
jsxImports.clear();
|
|
1605
|
+
usageIndexes.clear();
|
|
1606
|
+
},
|
|
1607
|
+
async transform(source, id) {
|
|
1608
|
+
if (!isBuild() && optimizer.dev !== true) return null;
|
|
1609
|
+
if (chunkMode() && isClient(this) || !isJSXModule(id)) return null;
|
|
1610
|
+
const filename = stripQuery(id);
|
|
1611
|
+
const sourceOptions = {
|
|
1612
|
+
...await moduleOptions(this, source, id),
|
|
1613
|
+
server: optimizer.server !== false && !isClient(this)
|
|
1614
|
+
};
|
|
1615
|
+
const result = compile(source, sourceOptions);
|
|
1616
|
+
let code = result.code;
|
|
1617
|
+
const maps = [result.map?.toString()];
|
|
1618
|
+
let { skipped } = result;
|
|
1619
|
+
if (isBuild() && sourceOptions.inline !== false) {
|
|
1620
|
+
const copySkips = compileOptions.report ? [] : void 0;
|
|
1621
|
+
const imported = await inlineImports(this, code, id, sourceOptions, async (target) => loadRecorded(this, id, target), copySkips);
|
|
1622
|
+
addSkips(this, copySkips);
|
|
1623
|
+
if (imported) {
|
|
1624
|
+
code = imported.code;
|
|
1625
|
+
maps.push(...imported.maps);
|
|
1626
|
+
skipped = imported.skipped ?? skipped;
|
|
1627
|
+
}
|
|
1628
|
+
const exposed = exposeLocals(code, filename);
|
|
1629
|
+
if (exposed) {
|
|
1630
|
+
code = exposed.code;
|
|
1631
|
+
maps.push(exposed.map);
|
|
1632
|
+
}
|
|
1633
|
+
}
|
|
1634
|
+
addSkips(this, skipped);
|
|
1635
|
+
recorded.set(environmentKey(this, id), code);
|
|
1636
|
+
if (code === source) return null;
|
|
1637
|
+
return {
|
|
1638
|
+
code,
|
|
1639
|
+
map: combineMaps(wantsMaps(), maps)
|
|
1640
|
+
};
|
|
1641
|
+
}
|
|
1642
|
+
};
|
|
1643
|
+
const chunkPlugin = {
|
|
1644
|
+
name: "solid-optimizer:chunk",
|
|
1645
|
+
enforce: "post",
|
|
1646
|
+
config(_, env) {
|
|
1647
|
+
if (env.command !== "build") return;
|
|
1648
|
+
return {
|
|
1649
|
+
oxc: { jsx: "preserve" },
|
|
1650
|
+
build: { rolldownOptions: { transform: { jsx: "preserve" } } }
|
|
1651
|
+
};
|
|
1652
|
+
},
|
|
1653
|
+
renderChunk: {
|
|
1654
|
+
order: "pre",
|
|
1655
|
+
handler(code, chunk) {
|
|
1656
|
+
if (!chunkMode() || !isClient(this) || !code.includes("__SOLID_OPTIMIZER_KEEP__")) return null;
|
|
1657
|
+
const filename = chunk.fileName;
|
|
1658
|
+
let repaired;
|
|
1659
|
+
let runtime;
|
|
1660
|
+
try {
|
|
1661
|
+
runtime = readMarkers(code, filename);
|
|
1662
|
+
} catch (error) {
|
|
1663
|
+
repaired = error instanceof SyntaxError ? repairJSXSequences(code, filename) : void 0;
|
|
1664
|
+
if (!repaired) throw error;
|
|
1665
|
+
runtime = readMarkers(repaired.code, filename);
|
|
1666
|
+
}
|
|
1667
|
+
if (!runtime) return null;
|
|
1668
|
+
const restored = restoreRefs(runtime.code, filename);
|
|
1669
|
+
const chunkCode = restored?.code ?? runtime.code;
|
|
1670
|
+
let optimized = compile(chunkCode, {
|
|
1671
|
+
...compileOptions,
|
|
1672
|
+
filename,
|
|
1673
|
+
sourceMap: wantsMaps(),
|
|
1674
|
+
constantVars: true,
|
|
1675
|
+
builtInAliases: runtime.builtInAliases
|
|
1676
|
+
});
|
|
1677
|
+
let lowered = lower(getCompiler(), optimized.code, filename, jsxOptions(false), wantsMaps());
|
|
1678
|
+
let linked;
|
|
1679
|
+
try {
|
|
1680
|
+
linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
|
|
1681
|
+
addSkips(this, optimized.skipped);
|
|
1682
|
+
} catch (error) {
|
|
1683
|
+
if (!(error instanceof MissingHelperError)) throw error;
|
|
1684
|
+
this.warn(`${error.message} ${filename} is not optimized.`);
|
|
1685
|
+
optimized = void 0;
|
|
1686
|
+
addSkips(this, [{
|
|
1687
|
+
pass: "inline",
|
|
1688
|
+
reason: "missing-helper",
|
|
1689
|
+
name: filename
|
|
1690
|
+
}]);
|
|
1691
|
+
lowered = lower(getCompiler(), chunkCode, filename, jsxOptions(false), wantsMaps());
|
|
1692
|
+
linked = linkHelpers(lowered.code, filename, moduleName, runtime.helpers);
|
|
1693
|
+
}
|
|
1694
|
+
return {
|
|
1695
|
+
code: linked.code,
|
|
1696
|
+
map: combineMaps(wantsMaps(), [
|
|
1697
|
+
repaired?.map,
|
|
1698
|
+
runtime.map,
|
|
1699
|
+
restored?.map,
|
|
1700
|
+
optimized?.map?.toString(),
|
|
1701
|
+
lowered.map,
|
|
1702
|
+
linked.map
|
|
1703
|
+
])
|
|
1704
|
+
};
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
};
|
|
1708
|
+
chunkPlugin.generateBundle = function generateBundle() {
|
|
1709
|
+
const { report } = optimizer;
|
|
1710
|
+
if (report === void 0 || report === false) return;
|
|
1711
|
+
const environment = this.environment.name;
|
|
1712
|
+
const result = {
|
|
1713
|
+
environment,
|
|
1714
|
+
skips: skips.get(environment) ?? []
|
|
1715
|
+
};
|
|
1716
|
+
if (typeof report === "function") report(result);
|
|
1717
|
+
else this.environment.logger.info(formatReport(result));
|
|
1718
|
+
};
|
|
1719
|
+
return [
|
|
1720
|
+
modulePlugin,
|
|
1721
|
+
main,
|
|
1722
|
+
{
|
|
1723
|
+
name: "solid-optimizer:module-type",
|
|
1724
|
+
transform(code, id) {
|
|
1725
|
+
if (!preserved.has(id)) return null;
|
|
1726
|
+
const repaired = repairJSXSequences(code, stripQuery(id));
|
|
1727
|
+
return repaired ? {
|
|
1728
|
+
code: repaired.code,
|
|
1729
|
+
map: repaired.map,
|
|
1730
|
+
moduleType: "jsx"
|
|
1731
|
+
} : {
|
|
1732
|
+
code,
|
|
1733
|
+
moduleType: "jsx"
|
|
1734
|
+
};
|
|
1735
|
+
}
|
|
1736
|
+
},
|
|
1737
|
+
chunkPlugin
|
|
1738
|
+
];
|
|
1739
|
+
}
|
|
1740
|
+
//#endregion
|
|
1741
|
+
export { solidOptimizer as default };
|
|
1742
|
+
|
|
1743
|
+
//# sourceMappingURL=vite.mjs.map
|