solid-optimizer 1.0.0 → 1.1.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 CHANGED
@@ -43,7 +43,7 @@ The input and the output both keep their JSX. Run the JSX transform after `compi
43
43
 
44
44
  ### Options
45
45
 
46
- - `filename` sets the parser and the source map source. `.ts` and `.tsx` parse as TypeScript. Anything else parses as JSX. Defaults to `input.jsx`.
46
+ - `filename` sets the parser and the source map source. `.ts`, `.tsx`, `.mts`, and `.cts` parse as TypeScript. Anything else parses as JSX. Defaults to `input.jsx`.
47
47
  - `fold` turns constant folding and control-flow resolution on or off. Defaults to `true`.
48
48
  - `inline` turns component inlining on or off. Defaults to `true`.
49
49
  - `alwaysInline` inlines every component that can be, even where the copies are larger than the calls they replace. Defaults to `false`. See [Only where it is smaller](#only-where-it-is-smaller).
@@ -54,9 +54,13 @@ The input and the output both keep their JSX. Run the JSX transform after `compi
54
54
  - `conditionals` turns `<Show>` and `<Switch>` lowering on or off. A `<Show>` without `keyed` becomes a ternary, which Solid's JSX transform compiles to one memo instead of a component and three memos. A callback child like `{(user) => <b>{user().name}</b>}` becomes its body, with `user()` read as `when` again, when `when` reads names, members, and signal or memo getters. A `<Switch>` of such `<Match>`es becomes a chain of ternaries. Defaults to `true`.
55
55
  - `builtIns` lists the names of Solid's built-in components. A tag only folds when it is one of them. An empty list turns control-flow folding off.
56
56
  - `moduleSources` lists the modules Solid's built-ins are imported from. Defaults to `['solid-js', '@solidjs/web']`.
57
+ - `builtInAliases` maps top-level names that refer to Solid's built-ins to the built-in's name, like `{ Show$1: 'Show' }`. A bundler can rename a built-in in a chunk, or declare it instead of importing it.
58
+ - `constantVars` treats a top-level `var` that nothing writes to as a constant. Bundlers turn top-level `const` into `var`, so turn this on for bundled chunks. Defaults to `false`.
57
59
  - `importedConstants` holds the constants of imported modules, keyed by the import specifier as the code writes it, then by export name. An import of one of them folds like a local `const`. See [Constants from other modules](#constants-from-other-modules).
60
+ - `importedContexts` lists the exports of imported modules that are contexts made by `createContext`, keyed by the import specifier as the code writes it. A provider of an imported context can then be removed like a local one.
58
61
  - `globalConstants` holds values of global names and paths, such as `{ __DEV__: false, 'import.meta.env.MODE': 'production' }`. A path starts at `import.meta` or at a name the module does not declare, and folds like a constant.
59
62
  - `maxPasses` limits how many rounds run. Compilation stops early once a round changes nothing. Defaults to `10`.
63
+ - `tidy` tidies the output JSX: it drops empty `{}` children, writes strings in braces such as `class={'card'}` as plain JSX, and unwraps a fragment that holds one element in a branch of `? :`, `&&`, `||` or `??`. The tests lower the tidied and untidied JSX with Solid's JSX transform and expect the same code. It only runs on a module the passes changed. Defaults to `true`.
60
64
  - `sourceMap` turns the source map on or off. Defaults to `true`.
61
65
  - `report` records what the inline, provider, and memo passes leave alone, and why. The result lists them in `skipped`, each with its pass, a reason code, and a name. Defaults to `false`.
62
66
 
@@ -95,7 +99,7 @@ export default defineConfig({
95
99
  });
96
100
  ```
97
101
 
98
- `@solidjs/vite-plugin` and `vite` are peer dependencies.
102
+ `@solidjs/vite-plugin` and `vite` are optional peer dependencies. Only `solid-optimizer/vite` needs them.
99
103
 
100
104
  The plugin optimizes in one of two modes.
101
105
 
@@ -133,18 +137,9 @@ solid-optimizer: what stays as written in client
133
137
  inline no-host 1 Home
134
138
  ```
135
139
 
136
- Each line is a pass, a reason, how many times it happened, and the names it happened to. A package's own modules are compiled too, but what they leave alone is not reported, since the app cannot change it. The app's calls of a package's components are. In chunk mode, a chunk is reported as a whole, so it also lists the package code bundled into it. The reasons for the inline pass:
140
+ Each line is a pass, a reason, how many times it happened, and the names it happened to. A package's own modules are compiled too, but what they leave alone is not reported, since the app cannot change it. The app's calls of a package's components are. In chunk mode, a chunk is reported as a whole, so it also lists the package code bundled into it.
137
141
 
138
- - `props-use` and `view-use` mean the component uses its props in a way other than `props.name`, a spread onto an element, or a `merge()` or `omit()` view, such as passing them to a function.
139
- - `component-params`, `component-body`, `component-return`, `component-async`, `component-recursive`, and `component-this` mean the component's own shape is not supported.
140
- - `component-write` means the component's statements assign to something declared outside it, like a counter at the top of the module. A copy's statements run before the JSX around the call, so that JSX would see the write too early.
141
- - `call-spread` and `call-namespace` mean the call site passes a spread or a namespaced attribute. `call-ref` means its `ref` is an expression other than a name, a function, or an array of them, and `ref-use` means the component uses `props.ref` other than as a `ref`.
142
- - `no-host` means the component has statements, and the call is not in JSX that a component or one of Solid's callbacks returns. A `<Show>` child or a `fallback` is one such place.
143
- - `size` means the copies would be larger than the calls.
144
- - `lazy`, `imported`, `nested`, and `not-a-function` mean the tag is not a component declared at the top of the same module or chunk.
145
- - A reason that starts with `copy-` is about copying a component from another module. `copy-package` means it comes from a package in `node_modules` that `optimizer.packages` does not list, `copy-cycle` means the component's module imports the importer back, directly or through other modules, a listed package, or a virtual module, `copy-virtual` means the copy would import a virtual module that its specifier does not reach from the importer, `copy-wrapper` means the component only returns a call of another component in its module, and `copy-size` means the copy was larger.
146
-
147
- The provider pass reports `open-component`, `open-call`, `open-new`, `open-spread`, and `open-outer` for code under the provider that it cannot see into, and `provider-value`, `provider-undefined`, and `provider-shape` for a value or provider it cannot handle. The memo pass reports `memo-reads`, `memo-read-place`, `memo-constant`, and a few more for a memo it keeps, and `signal-constant` for a signal that nothing writes but that is used other than by calling it.
142
+ `skip.pass` is `'inline'`, `'contexts'` for the provider pass, or `'memos'`. The [Report reasons](https://solid-optimizer.vercel.app/docs/reference/reasons/) page of the docs lists every reason code and what it means.
148
143
 
149
144
  ### Limits
150
145
 
@@ -152,7 +147,7 @@ The provider pass reports `open-component`, `open-call`, `open-new`, `open-sprea
152
147
  - An export named `__so_local$name` is added to a module for each local binding its exported components need, so a copy in another module can import it. In chunk mode, entry modules get none.
153
148
  - A component used in several chunks is copied into each of them, where each copy is no larger than its call.
154
149
  - Components from dependencies in `node_modules` are only copied from the packages `optimizer.packages` lists.
155
- - `.tsrx` modules are lowered by the official plugin and are not optimized.
150
+ - The plugin optimizes the modules the official plugin lowers: `.jsx` and `.tsx` (with their `.m` and `.c` forms), plus the `extensions` it registers, such as `.mdx`, filtered by `include` and `exclude`. `.tsrx` modules are the exception: the official plugin lowers them on its own path, and they are not optimized.
156
151
 
157
152
  ## Features
158
153
 
@@ -144,6 +144,15 @@ interface CompileOptions {
144
144
  * @default 10
145
145
  */
146
146
  maxPasses?: number;
147
+ /**
148
+ * Tidy the JSX the passes write: drop empty braces, write strings in
149
+ * braces as plain JSX, and unwrap fragments that hold one element. It only
150
+ * changes how the output reads: Solid's JSX transform lowers it to the same
151
+ * code. It runs only on a module the passes changed.
152
+ *
153
+ * @default true
154
+ */
155
+ tidy?: boolean;
147
156
  /**
148
157
  * Generate a source map.
149
158
  *
@@ -202,4 +211,4 @@ interface ModuleConstants {
202
211
  declare function readModuleConstants(code: string, options?: Pick<CompileOptions, 'filename' | 'importedConstants' | 'globalConstants'>): ModuleConstants;
203
212
  //#endregion
204
213
  export { readModuleConstants as a, SkipPass as c, compile as i, Primitive as l, CompileResult as n, ImportedConstants as o, ModuleConstants as r, Skip as s, CompileOptions as t };
205
- //# sourceMappingURL=compile-ioIkBKzR.d.mts.map
214
+ //# sourceMappingURL=compile-BKA77zb8.d.mts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"compile-BKA77zb8.d.mts","names":[],"sources":["../src/value.ts","../src/context.ts","../src/constants.ts","../src/compile.ts"],"mappings":";;;KAUY;;;;KC4DA;;;;;UAMK;WACN,MAAM;;WAEN;;WAEA;;;;;;;;KC9DC,oBAAoB,SAAS,eAAe,SAAS,eAAe;;;UCE/D;;;;;;;EAOf;;;;;;;EAOA;;;;;;EAMA;;;;;;;EAOA;;;;;;;EAOA;;;;;;;;EAQA;;;;;;;EAOA;;;;;;;EAOA;;;;;;EAMA,iBAAiB,SAAS;;;;;;;EAO1B;;;;;;EAMA,oBAAoB;;;;;;EAMpB,kBAAkB,SAAS,eAAe;;;;;;EAM1C,mBAAmB,SAAS;;;;;;;;EAQ5B,mBAAmB,SAAS;;;;;;;;EAQ5B;;;;;;EAMA;;;;;;;;EAQA;;;;;;;;;EASA;;;;;;EAMA;;;;;;;EAOA;;UAGe;EACf;;EAEA,KAAK;;;;;EAKL,UAAU;;;;;;;;;;;;;iBAmGI,QAAQ,cAAc,UAAS,iBAAsB;UAqIpD;;;;;EAKf;;;;;;EAMA,SAAS,eAAe;;;;;;;;iBASV,oBACd,cACA,UAAS,KAAK,wEACb"}
@@ -1451,7 +1451,7 @@ function isStaticText(node) {
1451
1451
  if (inner.type === "TemplateLiteral") return inner.expressions.length === 0;
1452
1452
  return inner.type === "UnaryExpression" && inner.operator === "-" && inner.argument.type === "Literal" && typeof inner.argument.value === "number";
1453
1453
  }
1454
- function isIntrinsic(element) {
1454
+ function isIntrinsic$1(element) {
1455
1455
  const { name } = element.openingElement;
1456
1456
  return name.type === "JSXIdentifier" && isIntrinsicTag(name.name);
1457
1457
  }
@@ -1492,7 +1492,7 @@ var SizeEstimator = class {
1492
1492
  */
1493
1493
  jsx(node, inTemplate) {
1494
1494
  if (node.type === "JSXFragment") return this.children(node.children) + 2;
1495
- if (!isIntrinsic(node)) return (inTemplate ? 24 : 0) + this.component(node);
1495
+ if (!isIntrinsic$1(node)) return (inTemplate ? 24 : 0) + this.component(node);
1496
1496
  const tag = nameLength(node.openingElement.name);
1497
1497
  let size = (inTemplate ? 0 : TEMPLATE) + tag * 2 + 5;
1498
1498
  let dynamic = false;
@@ -5899,6 +5899,236 @@ function terminateStatements(context) {
5899
5899
  return changed;
5900
5900
  }
5901
5901
  //#endregion
5902
+ //#region src/tidy.ts
5903
+ /**
5904
+ * The text Solid's JSX transform makes of a raw text child: when the text
5905
+ * has a line break, each line after the first loses its leading spaces, lines
5906
+ * of only spaces drop out and the rest join with a space; then every run of
5907
+ * spaces becomes one space. This differs from React's rule, which keeps runs
5908
+ * of spaces on one line.
5909
+ */
5910
+ function cleanText(raw) {
5911
+ let text = raw.replaceAll("\r", "");
5912
+ if (text.includes("\n")) {
5913
+ const kept = [];
5914
+ for (const [index, line] of text.split("\n").entries()) {
5915
+ const trimmed = index === 0 ? line : line.replace(/^[ \t]+/, "");
5916
+ if (/[^ \t]/.test(trimmed)) kept.push(trimmed);
5917
+ }
5918
+ text = kept.join(" ");
5919
+ }
5920
+ return text.replaceAll(/[ \t\n]+/g, " ");
5921
+ }
5922
+ /**
5923
+ * Whether a text holds whitespace or format characters other than space,
5924
+ * tab and line breaks, such as U+0085 or a byte order mark. Solid's JSX
5925
+ * transform and JavaScript disagree on some of them, so such text stays as it is.
5926
+ */
5927
+ function hasUnusualSpace(text) {
5928
+ return /(?![ \t\n\r])[\s\p{White_Space}\p{Cf}]/u.test(text);
5929
+ }
5930
+ /**
5931
+ * The string a container holds when it is a plain string written without
5932
+ * escapes, such as `{'a'}` or `{`a`}`. The characters between the quotes are
5933
+ * then the string itself, so tidying keeps them, and their source map
5934
+ * positions, and only drops what is around them.
5935
+ */
5936
+ function readString(container, code) {
5937
+ const { expression } = container;
5938
+ let value;
5939
+ if (expression.type === "Literal" && typeof expression.value === "string") value = expression.value;
5940
+ else if (expression.type === "TemplateLiteral" && expression.expressions.length === 0 && expression.quasis.length === 1) value = expression.quasis[0].value.cooked ?? void 0;
5941
+ if (value === void 0 || code.slice(expression.start + 1, expression.end - 1) !== value) return;
5942
+ if ((code.slice(container.start + 1, expression.start) + code.slice(expression.end, container.end - 1)).trim() !== "") return;
5943
+ return value;
5944
+ }
5945
+ /**
5946
+ * Replaces the braces and quotes around a string with `before` and `after`,
5947
+ * keeping the string's own characters where they are.
5948
+ */
5949
+ function unwrapString(container, before, after, context) {
5950
+ const { expression } = container;
5951
+ const { code, s } = context;
5952
+ s.remove(container.start, expression.start);
5953
+ s.remove(expression.end, container.end);
5954
+ const open = code[expression.start];
5955
+ const close = code[expression.end - 1];
5956
+ if (before === open) {} else if (before === "") s.remove(expression.start, expression.start + 1);
5957
+ else s.overwrite(expression.start, expression.start + 1, s.written(before, expression.start));
5958
+ if (after === close) {} else if (after === "") s.remove(expression.end - 1, expression.end);
5959
+ else s.overwrite(expression.end - 1, expression.end, s.written(after, expression.end - 1));
5960
+ }
5961
+ /** Whether a container holds nothing, not even a comment. */
5962
+ function isEmpty(container, code) {
5963
+ return container.expression.type === "JSXEmptyExpression" && code.slice(container.start + 1, container.end - 1).trim() === "";
5964
+ }
5965
+ /**
5966
+ * The pieces a list of children renders: each text that is not empty, and a
5967
+ * mark for each child that is not text.
5968
+ */
5969
+ function renderPieces(parts) {
5970
+ const pieces = [];
5971
+ let raw;
5972
+ const flush = () => {
5973
+ if (raw !== void 0) {
5974
+ const text = cleanText(raw);
5975
+ if (text !== "") pieces.push(text);
5976
+ raw = void 0;
5977
+ }
5978
+ };
5979
+ for (const part of parts) {
5980
+ if (!part) continue;
5981
+ if ("raw" in part) raw = (raw ?? "") + part.raw;
5982
+ else if ("literal" in part) {
5983
+ flush();
5984
+ if (part.literal !== "") pieces.push(part.literal);
5985
+ } else {
5986
+ flush();
5987
+ pieces.push(`\0${String(part.other)}`);
5988
+ }
5989
+ }
5990
+ flush();
5991
+ return pieces;
5992
+ }
5993
+ /**
5994
+ * What a list of children renders. In an element, Solid's JSX transform
5995
+ * writes the texts next to each other into the template as one text, so
5996
+ * only the joined text counts. Anywhere else, such as a fragment, each text
5997
+ * stays its own string, so the pieces must stay apart too.
5998
+ */
5999
+ function render(parts, inElement) {
6000
+ const pieces = renderPieces(parts);
6001
+ if (!inElement) return JSON.stringify(pieces);
6002
+ let joined = "";
6003
+ for (const piece of pieces) joined += piece.startsWith("\0") ? `${piece}\0` : piece;
6004
+ return joined;
6005
+ }
6006
+ /** Whether an element is an HTML or SVG element, which Solid lowers into a template. */
6007
+ function isIntrinsic(element) {
6008
+ const { name } = element.openingElement;
6009
+ if (name.type === "JSXNamespacedName") return true;
6010
+ return name.type === "JSXIdentifier" && /^[a-z]/.test(name.name);
6011
+ }
6012
+ /** A string that can be written as JSX text: no syntax, no entities, no line breaks. */
6013
+ function isPlainText(value) {
6014
+ return value !== "" && !/[{}<>&\r\n\t]/.test(value) && !hasUnusualSpace(value) && value.trim() === value;
6015
+ }
6016
+ /** A string that can be written as a JSX attribute in double quotes. */
6017
+ function isPlainAttribute(value) {
6018
+ return !/["&\r\n]/.test(value) && !hasUnusualSpace(value);
6019
+ }
6020
+ /**
6021
+ * Attributes whose string Solid's JSX transform treats differently once it
6022
+ * is written as a plain value: it moves a static `style` last, and `ref`,
6023
+ * `classList`, event handlers (`on` in any case) and namespaced attributes do
6024
+ * not take a string.
6025
+ */
6026
+ function isTidyAttribute(attribute) {
6027
+ const { name } = attribute;
6028
+ return name.type === "JSXIdentifier" && name.name !== "style" && name.name !== "ref" && name.name !== "classList" && !name.name.startsWith("on");
6029
+ }
6030
+ /**
6031
+ * Whether an element can get children from an attribute: a `children`
6032
+ * attribute or a spread. Its own children then decide whether those show, so
6033
+ * even an empty `{}` among them counts, and they stay as they are.
6034
+ */
6035
+ function hasChildrenAttribute(element) {
6036
+ for (const attribute of element.openingElement.attributes) if (attribute.type === "JSXSpreadAttribute" || attribute.name.type === "JSXIdentifier" && attribute.name.name === "children") return true;
6037
+ return false;
6038
+ }
6039
+ /**
6040
+ * Removes empty braces and writes plain strings as text, one at a time. Each
6041
+ * edit is kept only when the children still render the same with every edit
6042
+ * kept so far.
6043
+ */
6044
+ function tidyChildren(children, inElement, context) {
6045
+ const { code, s } = context;
6046
+ for (const child of children) if (child.type === "JSXText" && hasUnusualSpace(code.slice(child.start, child.end))) return false;
6047
+ const parts = [];
6048
+ for (const [index, child] of children.entries()) if (child.type === "JSXText") parts.push({ raw: code.slice(child.start, child.end) });
6049
+ else if (child.type === "JSXExpressionContainer" && isEmpty(child, code)) parts.push({ literal: "" });
6050
+ else if (child.type === "JSXExpressionContainer" && readString(child, code) !== void 0) parts.push({ literal: readString(child, code) ?? "" });
6051
+ else parts.push({ other: index });
6052
+ const expected = render(parts, inElement);
6053
+ let changed = false;
6054
+ for (const [index, child] of children.entries()) {
6055
+ if (child.type !== "JSXExpressionContainer") continue;
6056
+ const empty = isEmpty(child, code);
6057
+ const value = empty ? void 0 : readString(child, code);
6058
+ if (!empty && (value === void 0 || !isPlainText(value))) continue;
6059
+ const before = parts[index];
6060
+ parts[index] = empty ? void 0 : { raw: value ?? "" };
6061
+ if (render(parts, inElement) === expected) {
6062
+ if (empty) s.remove(child.start, child.end);
6063
+ else unwrapString(child, "", "", context);
6064
+ changed = true;
6065
+ } else parts[index] = before;
6066
+ }
6067
+ return changed;
6068
+ }
6069
+ /** The one element a fragment holds, when everything else in it is line breaks or empty braces. */
6070
+ function findOnlyElement(fragment, code) {
6071
+ let only;
6072
+ for (const child of fragment.children) if (child.type === "JSXElement") {
6073
+ if (only) return;
6074
+ only = child;
6075
+ } else if (child.type === "JSXText") {
6076
+ if (!/^[ \t\r\n]*$/.test(child.value) || cleanText(child.value) !== "") return;
6077
+ } else if (!(child.type === "JSXExpressionContainer" && isEmpty(child, code))) return;
6078
+ return only;
6079
+ }
6080
+ function tidyAttribute(attribute, context) {
6081
+ const { value } = attribute;
6082
+ if (value?.type !== "JSXExpressionContainer" || !isTidyAttribute(attribute)) return false;
6083
+ const text = readString(value, context.code);
6084
+ if (text === void 0 || !isPlainAttribute(text)) return false;
6085
+ unwrapString(value, "\"", "\"", context);
6086
+ return true;
6087
+ }
6088
+ /**
6089
+ * Whether a fragment is a branch of `? :`, or the right side of `&&`, `||`
6090
+ * or `??`, where the lowering of `<Show>` and `<Switch>` leaves them. There a
6091
+ * fragment around one element lowers the same as the element. Elsewhere,
6092
+ * such as a function's return, Solid's JSX transform writes different code.
6093
+ */
6094
+ function isBranch(fragment, context) {
6095
+ let node = fragment;
6096
+ let parent = context.parents.get(node);
6097
+ while (parent?.type === "ParenthesizedExpression") {
6098
+ node = parent;
6099
+ parent = context.parents.get(node);
6100
+ }
6101
+ if (parent?.type === "ConditionalExpression") return parent.consequent === node || parent.alternate === node;
6102
+ return parent?.type === "LogicalExpression" && parent.right === node;
6103
+ }
6104
+ function tidyJSX(context) {
6105
+ let changed = false;
6106
+ const visit = (node) => {
6107
+ if (node.type === "JSXFragment" && isBranch(node, context)) {
6108
+ const only = findOnlyElement(node, context.code);
6109
+ if (only) {
6110
+ context.s.remove(node.start, only.start);
6111
+ context.s.remove(only.end, node.end);
6112
+ changed = true;
6113
+ visit(only);
6114
+ return;
6115
+ }
6116
+ }
6117
+ const childrenFixed = node.type === "JSXElement" && hasChildrenAttribute(node);
6118
+ if ((node.type === "JSXElement" || node.type === "JSXFragment") && !childrenFixed) {
6119
+ const inElement = node.type === "JSXElement" && isIntrinsic(node);
6120
+ if (tidyChildren(node.children, inElement, context)) changed = true;
6121
+ }
6122
+ if (node.type === "JSXAttribute" && tidyAttribute(node, context)) {
6123
+ changed = true;
6124
+ return;
6125
+ }
6126
+ forEachChild(node, visit);
6127
+ };
6128
+ visit(context.program);
6129
+ return changed;
6130
+ }
6131
+ //#endregion
5902
6132
  //#region src/compile.ts
5903
6133
  const DEFAULT_BUILT_INS = [
5904
6134
  "For",
@@ -6019,6 +6249,11 @@ function compile(code, options = {}) {
6019
6249
  current = result.code;
6020
6250
  if (result.map !== void 0) maps.push(result.map);
6021
6251
  }
6252
+ const tidied = options.tidy ?? true ? runPass(parsedCurrent(), filename, resolved, sourceMap, tidyJSX, void 0) : void 0;
6253
+ if (tidied) {
6254
+ current = tidied.code;
6255
+ if (tidied.map !== void 0) maps.push(tidied.map);
6256
+ }
6022
6257
  }
6023
6258
  const report = skipped ? { skipped } : {};
6024
6259
  if (current === start) return {
@@ -6054,4 +6289,4 @@ function readModuleConstants(code, options = {}) {
6054
6289
  //#endregion
6055
6290
  export { analyzeScopes as a, collectParents as c, parse$1 as d, unwrap as f, runtimeImportSources as i, forEachChild as l, readModuleConstants as n, lookup as o, CONTEXT_SAFE_PRIMITIVES as r, scopeAt as s, compile as t, isIntrinsicTag as u };
6056
6291
 
6057
- //# sourceMappingURL=compile-Cvjy2e11.mjs.map
6292
+ //# sourceMappingURL=compile-D2f8eXFk.mjs.map