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