solid-optimizer 0.1.2 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/LICENSE +18 -4
  2. package/README.md +269 -14
  3. package/dist/compile-BroGlagZ.d.mts +172 -0
  4. package/dist/compile-BroGlagZ.d.mts.map +1 -0
  5. package/dist/compile-ocDYvJUW.mjs +3910 -0
  6. package/dist/compile-ocDYvJUW.mjs.map +1 -0
  7. package/dist/index.d.mts +2 -0
  8. package/dist/index.mjs +2 -0
  9. package/dist/vite.d.mts +35 -0
  10. package/dist/vite.d.mts.map +1 -0
  11. package/dist/vite.mjs +1465 -0
  12. package/dist/vite.mjs.map +1 -0
  13. package/package.json +60 -58
  14. package/src/ast.ts +263 -0
  15. package/src/compile.ts +304 -0
  16. package/src/constants.ts +249 -0
  17. package/src/context.ts +87 -0
  18. package/src/fold.ts +850 -0
  19. package/src/index.ts +4 -319
  20. package/src/inline.ts +2028 -0
  21. package/src/jsx.ts +170 -0
  22. package/src/memo.ts +383 -0
  23. package/src/provider.ts +842 -0
  24. package/src/scope.ts +588 -0
  25. package/src/server.ts +275 -0
  26. package/src/size.ts +307 -0
  27. package/src/value.ts +386 -0
  28. package/src/vite/index.ts +1135 -0
  29. package/src/vite/inject.ts +311 -0
  30. package/src/vite/namespace.ts +66 -0
  31. package/src/vite/runtime.ts +390 -0
  32. package/src/vite/usage.ts +405 -0
  33. package/dist/cjs/development/index.cjs +0 -316
  34. package/dist/cjs/development/index.cjs.map +0 -7
  35. package/dist/cjs/production/index.cjs +0 -1
  36. package/dist/esm/development/index.mjs +0 -285
  37. package/dist/esm/development/index.mjs.map +0 -7
  38. package/dist/esm/production/index.mjs +0 -1
  39. package/dist/types/index.d.ts +0 -12
  40. package/dist/types/index.d.ts.map +0 -1
  41. package/dist/types/unwrap-node.d.ts +0 -7
  42. package/dist/types/unwrap-node.d.ts.map +0 -1
  43. package/src/unwrap-node.ts +0 -27
package/src/ast.ts ADDED
@@ -0,0 +1,263 @@
1
+ import type { Expression, JSXChild, Node, Program } from 'oxc-parser';
2
+ import { parseSync, visitorKeys } from 'oxc-parser';
3
+
4
+ /**
5
+ * Keys that only hold TypeScript types. Types never run, so no pass reads or rewrites them.
6
+ */
7
+ const TYPE_KEYS = new Set([
8
+ 'typeAnnotation',
9
+ 'typeParameters',
10
+ 'typeArguments',
11
+ 'returnType',
12
+ 'superTypeArguments',
13
+ 'implements',
14
+ ]);
15
+
16
+ /**
17
+ * TypeScript nodes that wrap a runtime expression.
18
+ * Every other TypeScript node is skipped along with its children.
19
+ */
20
+ const TS_EXPRESSION_WRAPPERS = new Set([
21
+ 'TSAsExpression',
22
+ 'TSSatisfiesExpression',
23
+ 'TSNonNullExpression',
24
+ 'TSTypeAssertion',
25
+ 'TSInstantiationExpression',
26
+ 'TSExportAssignment',
27
+ ]);
28
+
29
+ export function isNode(value: unknown): value is Node {
30
+ return (
31
+ typeof value === 'object' && value !== null && 'type' in value && typeof value.type === 'string'
32
+ );
33
+ }
34
+
35
+ /**
36
+ * Calls `visit` for each child node of `node`, in source order.
37
+ */
38
+ export function forEachChild(node: Node, visit: (child: Node) => void): void {
39
+ if (node.type.startsWith('TS')) {
40
+ if (TS_EXPRESSION_WRAPPERS.has(node.type)) {
41
+ const expression: unknown = Reflect.get(node, 'expression');
42
+ if (isNode(expression)) {
43
+ visit(expression);
44
+ }
45
+ } else if (node.type === 'TSParameterProperty') {
46
+ visit(node.parameter);
47
+ }
48
+ return;
49
+ }
50
+ if (!Object.hasOwn(visitorKeys, node.type)) {
51
+ return;
52
+ }
53
+ for (const key of visitorKeys[node.type]) {
54
+ if (TYPE_KEYS.has(key)) {
55
+ continue;
56
+ }
57
+ const value: unknown = Reflect.get(node, key);
58
+ if (Array.isArray(value)) {
59
+ const items: unknown[] = value;
60
+ for (const item of items) {
61
+ if (isNode(item)) {
62
+ visit(item);
63
+ }
64
+ }
65
+ } else if (isNode(value)) {
66
+ visit(value);
67
+ }
68
+ }
69
+ }
70
+
71
+ export type Parents = Map<Node, Node>;
72
+
73
+ export function collectParents(program: Program): Parents {
74
+ const parents: Parents = new Map();
75
+ const visit = (node: Node): void => {
76
+ forEachChild(node, (child) => {
77
+ parents.set(child, node);
78
+ visit(child);
79
+ });
80
+ };
81
+ visit(program);
82
+ return parents;
83
+ }
84
+
85
+ export function parse(filename: string, code: string): Program {
86
+ const result = parseSync(filename, code, {
87
+ lang: languageOf(filename),
88
+ sourceType: 'module',
89
+ preserveParens: true,
90
+ });
91
+ const error = result.errors.at(0);
92
+ if (error) {
93
+ throw new SyntaxError(`[solid-optimizer] ${filename}: ${error.codeframe ?? error.message}`);
94
+ }
95
+ return result.program;
96
+ }
97
+
98
+ function languageOf(filename: string): 'jsx' | 'ts' | 'tsx' {
99
+ if (/\.tsx$/i.test(filename)) {
100
+ return 'tsx';
101
+ }
102
+ if (/\.[cm]?ts$/i.test(filename)) {
103
+ return 'ts';
104
+ }
105
+ // Plain `.js` files are parsed as JSX, since bundled chunks keep the JSX they preserved.
106
+ return 'jsx';
107
+ }
108
+
109
+ /**
110
+ * Removes the parentheses and TypeScript wrappers around an expression.
111
+ */
112
+ export function unwrap(node: Expression): Expression {
113
+ let current = node;
114
+ while (
115
+ current.type === 'ParenthesizedExpression' ||
116
+ current.type === 'TSAsExpression' ||
117
+ current.type === 'TSSatisfiesExpression' ||
118
+ current.type === 'TSNonNullExpression' ||
119
+ current.type === 'TSTypeAssertion'
120
+ ) {
121
+ current = current.expression;
122
+ }
123
+ return current;
124
+ }
125
+
126
+ export function isFunctionNode(node: Node): boolean {
127
+ return (
128
+ node.type === 'FunctionDeclaration' ||
129
+ node.type === 'FunctionExpression' ||
130
+ node.type === 'ArrowFunctionExpression'
131
+ );
132
+ }
133
+
134
+ /**
135
+ * An intrinsic element name, such as `div` or `my-element`.
136
+ * JSX treats a lowercase first letter as an intrinsic element.
137
+ */
138
+ export function isIntrinsicTag(name: string): boolean {
139
+ return /^[a-z][\w-]*$/.test(name);
140
+ }
141
+
142
+ /**
143
+ * Whether JSX drops this text: whitespace that contains a line break.
144
+ */
145
+ export function isFilteredText(child: JSXChild): boolean {
146
+ return child.type === 'JSXText' && /^\s*$/.test(child.value) && /[\r\n]/.test(child.value);
147
+ }
148
+
149
+ /**
150
+ * Whether a JSX child renders nothing: dropped whitespace, or a container
151
+ * that only holds a comment, like `{/* note *\/}`.
152
+ */
153
+ export function isInsignificant(child: JSXChild): boolean {
154
+ return (
155
+ isFilteredText(child) ||
156
+ (child.type === 'JSXExpressionContainer' && child.expression.type === 'JSXEmptyExpression')
157
+ );
158
+ }
159
+
160
+ /**
161
+ * Whether a JSX element or fragment sits in a list of JSX children.
162
+ */
163
+ export function isJSXChild(node: Node, parents: Parents): boolean {
164
+ const parent = parents.get(node);
165
+ return parent?.type === 'JSXElement' || parent?.type === 'JSXFragment';
166
+ }
167
+
168
+ /**
169
+ * Node types that bind tighter than any operator, so their text can replace
170
+ * any expression without parentheses.
171
+ */
172
+ const PRIMARY_TYPES = new Set([
173
+ 'Identifier',
174
+ 'Literal',
175
+ 'ThisExpression',
176
+ 'ArrayExpression',
177
+ 'TemplateLiteral',
178
+ 'ParenthesizedExpression',
179
+ 'JSXElement',
180
+ 'JSXFragment',
181
+ ]);
182
+
183
+ export function isPrimary(node: Node): boolean {
184
+ if (node.type === 'Literal') {
185
+ // `-1` is a unary expression, but a literal like `1` is primary.
186
+ return typeof node.value !== 'number' || node.value >= 0;
187
+ }
188
+ return PRIMARY_TYPES.has(node.type);
189
+ }
190
+
191
+ /**
192
+ * The node that starts an expression's text, such as `a` in `a.b()`.
193
+ */
194
+ function leftmost(node: Node): Node {
195
+ switch (node.type) {
196
+ case 'MemberExpression':
197
+ return leftmost(node.object);
198
+ case 'CallExpression':
199
+ return leftmost(node.callee);
200
+ case 'TaggedTemplateExpression':
201
+ return leftmost(node.tag);
202
+ case 'BinaryExpression':
203
+ case 'LogicalExpression':
204
+ return leftmost(node.left);
205
+ case 'AssignmentExpression':
206
+ return leftmost(node.left);
207
+ case 'ConditionalExpression':
208
+ return leftmost(node.test);
209
+ case 'SequenceExpression':
210
+ return node.expressions[0] ? leftmost(node.expressions[0]) : node;
211
+ case 'ChainExpression':
212
+ return leftmost(node.expression);
213
+ case 'UpdateExpression':
214
+ return node.prefix ? node : leftmost(node.argument);
215
+ case 'TSAsExpression':
216
+ case 'TSSatisfiesExpression':
217
+ case 'TSNonNullExpression':
218
+ return leftmost(node.expression);
219
+ default:
220
+ return node;
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Whether `replacement` needs parentheses to take the place of `target`.
226
+ *
227
+ * Replacing an expression with one of its own operands never needs them, since an operand
228
+ * binds at least as tightly as the expression around it. The exceptions are the positions
229
+ * where the first token decides what the parser reads: a statement cannot start with `{`,
230
+ * `function`, or `class`, and neither can an arrow function body.
231
+ */
232
+ export function needsParensAt(target: Node, replacement: Node, parents: Parents): boolean {
233
+ const parent = parents.get(target);
234
+ if (parent === undefined) {
235
+ return false;
236
+ }
237
+ const statementStart =
238
+ parent.type === 'ExpressionStatement' ||
239
+ parent.type === 'ExportDefaultDeclaration' ||
240
+ (parent.type === 'ArrowFunctionExpression' && parent.body === target);
241
+ if (!statementStart) {
242
+ return false;
243
+ }
244
+ const first = leftmost(replacement);
245
+ return (
246
+ startsLikeStatement(first) ||
247
+ // A string at the start of a statement can turn into a directive, like `"use strict"`.
248
+ (first.type === 'Literal' && typeof first.value === 'string')
249
+ );
250
+ }
251
+
252
+ /**
253
+ * Whether an expression statement starting with `node` would parse as
254
+ * something else: a block, a function declaration, or a class declaration.
255
+ */
256
+ export function startsLikeStatement(node: Node): boolean {
257
+ const first = leftmost(node);
258
+ return (
259
+ first.type === 'ObjectExpression' ||
260
+ first.type === 'FunctionExpression' ||
261
+ first.type === 'ClassExpression'
262
+ );
263
+ }
package/src/compile.ts ADDED
@@ -0,0 +1,304 @@
1
+ import type { SourceMap } from '@jridgewell/remapping';
2
+ import remapping from '@jridgewell/remapping';
3
+ import MagicString from 'magic-string';
4
+ import { collectParents, parse } from './ast';
5
+ import type { ImportedConstants } from './constants';
6
+ import { constantExports, namedImportSources, resolveImportedConstants } from './constants';
7
+ import type { PassContext, ResolvedOptions } from './context';
8
+ import { fold } from './fold';
9
+ import { inline } from './inline';
10
+ import { inlineMemos } from './memo';
11
+ import { simplifyServer } from './server';
12
+ import { removeProviders } from './provider';
13
+ import { analyzeScopes } from './scope';
14
+ import type { Primitive } from './value';
15
+
16
+ export interface CompileOptions {
17
+ /**
18
+ * The file name, used to pick the parser (`.ts` and `.tsx` parse as
19
+ * TypeScript, anything else as JSX) and as the source in the source map.
20
+ *
21
+ * @default 'input.jsx'
22
+ */
23
+ filename?: string;
24
+ /**
25
+ * Fold constants, remove unreachable code, and resolve control-flow
26
+ * components whose props are constants.
27
+ *
28
+ * @default true
29
+ */
30
+ fold?: boolean;
31
+ /**
32
+ * Replace component calls with the component's body.
33
+ *
34
+ * @default true
35
+ */
36
+ inline?: boolean;
37
+ /**
38
+ * Compile for the server: remove `createEffect` and `onMount`, and reduce
39
+ * `untrack`, `batch`, `startTransition`, `createDeferred`, `getListener`,
40
+ * `createMemo`, `createRenderEffect`, and `createComputed` to what they do
41
+ * on the server.
42
+ *
43
+ * This runs once, after the other passes. The server and client build
44
+ * make the same folding and inlining decisions from the same code, so the
45
+ * server renders the tree the client hydrates.
46
+ *
47
+ * @default false
48
+ */
49
+ server?: boolean;
50
+ /**
51
+ * Remove context providers whose reads are all visible, and give each
52
+ * read the provider's value.
53
+ *
54
+ * @default true
55
+ */
56
+ contexts?: boolean;
57
+ /**
58
+ * Replace a `createMemo` that always produces a new value and is read once
59
+ * with its computation.
60
+ *
61
+ * @default true
62
+ */
63
+ memos?: boolean;
64
+ /**
65
+ * The names of Solid's built-in components. A tag only folds when it is
66
+ * one of these, and an empty list turns control-flow folding off.
67
+ *
68
+ * @default ['For', 'Show', 'Switch', 'Match', 'Suspense', 'SuspenseList', 'Portal', 'Index', 'Dynamic', 'ErrorBoundary']
69
+ */
70
+ builtIns?: readonly string[];
71
+ /**
72
+ * The modules that export Solid's built-in components. A tag imported from
73
+ * anywhere else is a different component.
74
+ *
75
+ * @default ['solid-js', 'solid-js/web']
76
+ */
77
+ moduleSources?: readonly string[];
78
+ /**
79
+ * Top-level names that refer to Solid's built-in components, mapped to the
80
+ * built-in's name. A bundler renames bindings, so a chunk can call `Show`
81
+ * something else, or declare it instead of importing it.
82
+ */
83
+ builtInAliases?: Readonly<Record<string, string>>;
84
+ /**
85
+ * Treat a top-level `var` that nothing writes to as a constant. Bundlers
86
+ * turn top-level `const` into `var`, so this is on for bundled chunks.
87
+ *
88
+ * @default false
89
+ */
90
+ constantVars?: boolean;
91
+ /**
92
+ * The constants imported modules export, keyed by the import specifier as
93
+ * the code writes it, then by export name. An import of one of them folds
94
+ * like a local `const`. `constantExports` reads them from a module.
95
+ */
96
+ importedConstants?: ImportedConstants;
97
+ /**
98
+ * The exports of imported modules that are contexts made by Solid's
99
+ * `createContext`, keyed by the import specifier as the code writes it.
100
+ * A provider of an imported context can be removed like a local one.
101
+ */
102
+ importedContexts?: Readonly<Record<string, readonly string[]>>;
103
+ /**
104
+ * Top-level components that other modules use too, by the number of
105
+ * modules that use them, this one included. Inlining one here only counts
106
+ * its share of the declaration, which goes away once every one of them
107
+ * inlines it. `0` keeps it whatever is inlined, like a component that is
108
+ * also passed as a value.
109
+ */
110
+ sharedComponents?: Readonly<Record<string, number>>;
111
+ /**
112
+ * Inline every component that can be, even where the copies are larger
113
+ * than the calls and declaration they replace. By default, a component is
114
+ * only inlined where its copies are estimated to be no larger.
115
+ *
116
+ * @default false
117
+ */
118
+ alwaysInline?: boolean;
119
+ /**
120
+ * The most passes to run. One pass can expose work for the next, such as
121
+ * an inlined component whose props now fold. Compilation stops early once
122
+ * a pass changes nothing.
123
+ *
124
+ * @default 10
125
+ */
126
+ maxPasses?: number;
127
+ /**
128
+ * Generate a source map.
129
+ *
130
+ * @default true
131
+ */
132
+ sourceMap?: boolean;
133
+ }
134
+
135
+ export interface CompileResult {
136
+ code: string;
137
+ /** The map from the output back to the input, or `null` when nothing changed or maps are off. */
138
+ map: SourceMap | null;
139
+ }
140
+
141
+ const DEFAULT_BUILT_INS = [
142
+ 'For',
143
+ 'Show',
144
+ 'Switch',
145
+ 'Match',
146
+ 'Suspense',
147
+ 'SuspenseList',
148
+ 'Portal',
149
+ 'Index',
150
+ 'Dynamic',
151
+ 'ErrorBoundary',
152
+ ];
153
+
154
+ const DEFAULT_MODULE_SOURCES = ['solid-js', 'solid-js/web'];
155
+
156
+ function resolveOptions(options: CompileOptions): ResolvedOptions {
157
+ return {
158
+ builtIns: new Set(options.builtIns ?? DEFAULT_BUILT_INS),
159
+ moduleSources: options.moduleSources ?? DEFAULT_MODULE_SOURCES,
160
+ builtInAliases: new Map(Object.entries(options.builtInAliases ?? {})),
161
+ constantVars: options.constantVars ?? false,
162
+ importedConstants: resolveImportedConstants(options.importedConstants),
163
+ importedContexts: new Map(
164
+ Object.entries(options.importedContexts ?? {}).map(([source, names]) => [
165
+ source,
166
+ new Set(names),
167
+ ]),
168
+ ),
169
+ sharedComponents: new Map(Object.entries(options.sharedComponents ?? {})),
170
+ alwaysInline: options.alwaysInline ?? false,
171
+ };
172
+ }
173
+
174
+ type Pass = (context: PassContext) => boolean;
175
+
176
+ interface PassResult {
177
+ code: string;
178
+ map: string | undefined;
179
+ }
180
+
181
+ function runPass(
182
+ code: string,
183
+ filename: string,
184
+ options: ResolvedOptions,
185
+ sourceMap: boolean,
186
+ pass: Pass,
187
+ ): PassResult | undefined {
188
+ const program = parse(filename, code);
189
+ const context: PassContext = {
190
+ code,
191
+ filename,
192
+ s: new MagicString(code),
193
+ program,
194
+ parents: collectParents(program),
195
+ scopes: analyzeScopes(program),
196
+ options,
197
+ };
198
+ if (!pass(context)) {
199
+ return undefined;
200
+ }
201
+ return {
202
+ code: context.s.toString(),
203
+ map: sourceMap
204
+ ? context.s.generateMap({ source: filename, hires: true, includeContent: true }).toString()
205
+ : undefined,
206
+ };
207
+ }
208
+
209
+ /**
210
+ * Optimizes JSX before it is lowered by Solid's JSX transform.
211
+ *
212
+ * The input is JavaScript or TypeScript with JSX, such as a module, or a
213
+ * bundled chunk that kept its JSX. The output keeps JSX too, so the JSX
214
+ * transform runs after this.
215
+ *
216
+ * The output changes the shape of the rendered tree, and with it the
217
+ * hydration keys. A server build and its client build must compile the same
218
+ * code with the same options.
219
+ */
220
+ export function compile(code: string, options: CompileOptions = {}): CompileResult {
221
+ const filename = options.filename ?? 'input.jsx';
222
+ const sourceMap = options.sourceMap ?? true;
223
+ const resolved = resolveOptions(options);
224
+ const passes: Pass[] = [];
225
+ if (options.fold ?? true) {
226
+ passes.push(fold);
227
+ }
228
+ if (options.inline ?? true) {
229
+ passes.push(inline);
230
+ }
231
+ if (options.contexts ?? true) {
232
+ passes.push(removeProviders);
233
+ }
234
+ if (options.memos ?? true) {
235
+ passes.push(inlineMemos);
236
+ }
237
+
238
+ const maps: string[] = [];
239
+ let current = code;
240
+ const maxPasses = options.maxPasses ?? 10;
241
+ for (let round = 0; round < maxPasses; round += 1) {
242
+ let changed = false;
243
+ for (const pass of passes) {
244
+ const result = runPass(current, filename, resolved, sourceMap, pass);
245
+ if (result) {
246
+ changed = true;
247
+ current = result.code;
248
+ if (result.map !== undefined) {
249
+ maps.push(result.map);
250
+ }
251
+ }
252
+ }
253
+ if (!changed) {
254
+ break;
255
+ }
256
+ }
257
+
258
+ if (options.server ?? false) {
259
+ const result = runPass(current, filename, resolved, sourceMap, simplifyServer);
260
+ if (result) {
261
+ current = result.code;
262
+ if (result.map !== undefined) {
263
+ maps.push(result.map);
264
+ }
265
+ }
266
+ }
267
+
268
+ if (maps.length === 0) {
269
+ return { code: current, map: null };
270
+ }
271
+ // Each map points at the output of the pass before it, so they chain from the last one.
272
+ return { code: current, map: remapping(maps.reverse(), () => null) };
273
+ }
274
+
275
+ export interface ModuleConstants {
276
+ /**
277
+ * The modules this module imports or re-exports named bindings from, as
278
+ * written. `importedConstants` of `compile` takes their constants.
279
+ */
280
+ imports: string[];
281
+ /**
282
+ * The constants this module exports, by export name: `export const`
283
+ * bindings whose value folds, names exported from them, and names
284
+ * re-exported from `importedConstants`.
285
+ */
286
+ exports: Record<string, Primitive>;
287
+ }
288
+
289
+ /**
290
+ * Reads what a module imports and the constants it exports, so that
291
+ * `compile` can fold them in the modules that import it.
292
+ *
293
+ * Only `filename` and `importedConstants` of the options are used.
294
+ */
295
+ export function readModuleConstants(
296
+ code: string,
297
+ options: Pick<CompileOptions, 'filename' | 'importedConstants'> = {},
298
+ ): ModuleConstants {
299
+ const program = parse(options.filename ?? 'input.jsx', code);
300
+ return {
301
+ imports: namedImportSources(program),
302
+ exports: constantExports(program, resolveOptions(options)),
303
+ };
304
+ }