solid-optimizer 1.0.0-next.1 → 1.0.0-next.10

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/src/nesting.ts ADDED
@@ -0,0 +1,325 @@
1
+ /**
2
+ * Keeps every template valid HTML.
3
+ *
4
+ * Solid's JSX transform puts an element and the elements written inside it
5
+ * into one HTML template. It rejects a template that a browser would parse
6
+ * into another tree, such as `<p><div></div></p>`, which parses as
7
+ * `<p></p><div></div><p></p>`. Before the passes, such an element is often
8
+ * apart from the template: `<p><Box /></p>` inserts the `<div>` that `Box`
9
+ * returns at runtime, which works. Inlining `Box`, resolving `<Show>`,
10
+ * unrolling `<For>`, or resolving `<Dynamic>` puts the `<div>` into the
11
+ * `<p>`'s template, and the build fails.
12
+ *
13
+ * This pass checks each template the way Solid does: it parses the
14
+ * template's tags as the body's `innerHTML` and compares the result. When
15
+ * the tree changes, the element that changes it is wrapped in `{}`. An
16
+ * element in an expression container starts its own template and is
17
+ * inserted at runtime, as it was before the pass.
18
+ */
19
+ import type { JSXChild, JSXElement, Node } from 'oxc-parser';
20
+ import type { DefaultTreeAdapterMap } from 'parse5';
21
+ import { parseFragment, parse as parseHTML, serialize } from 'parse5';
22
+ import { forEachChild, isIntrinsicTag } from './ast';
23
+ import type { PassContext } from './context';
24
+
25
+ const VOID_ELEMENTS = new Set([
26
+ 'area',
27
+ 'base',
28
+ 'br',
29
+ 'col',
30
+ 'embed',
31
+ 'hr',
32
+ 'img',
33
+ 'input',
34
+ 'keygen',
35
+ 'link',
36
+ 'meta',
37
+ 'param',
38
+ 'source',
39
+ 'track',
40
+ 'wbr',
41
+ ]);
42
+
43
+ // Solid's list of SVG tags, from dom-expressions. `a`, `script`, `style`, and
44
+ // `title` are in both namespaces, so a template rooted at one is HTML.
45
+ const SVG_ELEMENTS = new Set([
46
+ 'altGlyph',
47
+ 'altGlyphDef',
48
+ 'altGlyphItem',
49
+ 'animate',
50
+ 'animateColor',
51
+ 'animateMotion',
52
+ 'animateTransform',
53
+ 'circle',
54
+ 'clipPath',
55
+ 'cursor',
56
+ 'defs',
57
+ 'desc',
58
+ 'ellipse',
59
+ 'feBlend',
60
+ 'feColorMatrix',
61
+ 'feComponentTransfer',
62
+ 'feComposite',
63
+ 'feConvolveMatrix',
64
+ 'feDiffuseLighting',
65
+ 'feDisplacementMap',
66
+ 'feDistantLight',
67
+ 'feDropShadow',
68
+ 'feFlood',
69
+ 'feFuncA',
70
+ 'feFuncB',
71
+ 'feFuncG',
72
+ 'feFuncR',
73
+ 'feGaussianBlur',
74
+ 'feImage',
75
+ 'feMerge',
76
+ 'feMergeNode',
77
+ 'feMorphology',
78
+ 'feOffset',
79
+ 'fePointLight',
80
+ 'feSpecularLighting',
81
+ 'feSpotLight',
82
+ 'feTile',
83
+ 'feTurbulence',
84
+ 'filter',
85
+ 'font',
86
+ 'foreignObject',
87
+ 'g',
88
+ 'glyph',
89
+ 'glyphRef',
90
+ 'hkern',
91
+ 'image',
92
+ 'line',
93
+ 'linearGradient',
94
+ 'marker',
95
+ 'mask',
96
+ 'metadata',
97
+ 'mpath',
98
+ 'path',
99
+ 'pattern',
100
+ 'polygon',
101
+ 'polyline',
102
+ 'radialGradient',
103
+ 'rect',
104
+ 'set',
105
+ 'stop',
106
+ 'switch',
107
+ 'symbol',
108
+ 'text',
109
+ 'textPath',
110
+ 'tref',
111
+ 'tspan',
112
+ 'use',
113
+ 'view',
114
+ 'vkern',
115
+ ]);
116
+
117
+ type ParentNode = DefaultTreeAdapterMap['parentNode'];
118
+
119
+ function findElement(parent: ParentNode, name: string): ParentNode {
120
+ for (const child of parent.childNodes) {
121
+ if (child.nodeName === name && 'childNodes' in child) {
122
+ return child;
123
+ }
124
+ }
125
+ throw new Error(`[solid-optimizer] no <${name}> in an empty document`);
126
+ }
127
+
128
+ let body: ParentNode | undefined;
129
+
130
+ /** What a browser makes of `html` set as the body's `innerHTML`. */
131
+ function parseAsBody(html: string): string {
132
+ body ??= findElement(
133
+ findElement(parseHTML('<!DOCTYPE html><html><body></body></html>'), 'html'),
134
+ 'body',
135
+ );
136
+ return serialize(parseFragment(body, html, {}));
137
+ }
138
+
139
+ /** The tag of an intrinsic element, or `undefined` for a component or a namespaced tag. */
140
+ function readIntrinsicTag(element: JSXElement): string | undefined {
141
+ const name = element.openingElement.name;
142
+ return name.type === 'JSXIdentifier' && isIntrinsicTag(name.name) ? name.name : undefined;
143
+ }
144
+
145
+ /** A template element and the elements in the same template. */
146
+ interface TemplateNode {
147
+ readonly element: JSXElement;
148
+ readonly tag: string;
149
+ readonly children: TemplateNode[];
150
+ }
151
+
152
+ /**
153
+ * The template rooted at `element`. Elements inside fragments join it.
154
+ * Elements in expression containers or under a component start their own.
155
+ */
156
+ function collectTemplate(element: JSXElement, tag: string): TemplateNode {
157
+ const node: TemplateNode = { element, tag, children: [] };
158
+ addTemplateChildren(node, element.children);
159
+ return node;
160
+ }
161
+
162
+ function addTemplateChildren(node: TemplateNode, children: readonly JSXChild[]): void {
163
+ for (const child of children) {
164
+ if (child.type === 'JSXFragment') {
165
+ addTemplateChildren(node, child.children);
166
+ } else if (child.type === 'JSXElement') {
167
+ const tag = readIntrinsicTag(child);
168
+ if (tag !== undefined) {
169
+ node.children.push(collectTemplate(child, tag));
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ /**
176
+ * The tags of a template, without text or attributes. Elements not in
177
+ * `included` are left out with what they hold.
178
+ */
179
+ function writeTags(node: TemplateNode, included: ReadonlySet<TemplateNode>): string {
180
+ if (VOID_ELEMENTS.has(node.tag)) {
181
+ return `<${node.tag}>`;
182
+ }
183
+ let inner = '';
184
+ for (const child of node.children) {
185
+ if (included.has(child)) {
186
+ inner += writeTags(child, included);
187
+ }
188
+ }
189
+ return `<${node.tag}>${inner}</${node.tag}>`;
190
+ }
191
+
192
+ /**
193
+ * Table parts parse only inside a table, and SVG parts only inside an
194
+ * `<svg>`, so a template rooted at one is checked inside one, as Solid
195
+ * creates it.
196
+ */
197
+ function placeInContext(tag: string, html: string): string {
198
+ if (SVG_ELEMENTS.has(tag)) {
199
+ return `<svg>${html}</svg>`;
200
+ }
201
+ switch (tag) {
202
+ case 'td':
203
+ case 'th':
204
+ return `<table><tbody><tr>${html}</tr></tbody></table>`;
205
+ case 'tr':
206
+ return `<table><tbody>${html}</tbody></table>`;
207
+ case 'col':
208
+ return `<table><colgroup>${html}</colgroup></table>`;
209
+ case 'thead':
210
+ case 'tbody':
211
+ case 'tfoot':
212
+ case 'colgroup':
213
+ case 'caption':
214
+ return `<table>${html}</table>`;
215
+ default:
216
+ return html;
217
+ }
218
+ }
219
+
220
+ /** Whether a `<template>` in the template holds an element, which Solid rejects. */
221
+ function hasTemplateContent(node: TemplateNode, included: ReadonlySet<TemplateNode>): boolean {
222
+ for (const child of node.children) {
223
+ if (included.has(child) && (node.tag === 'template' || hasTemplateContent(child, included))) {
224
+ return true;
225
+ }
226
+ }
227
+ return false;
228
+ }
229
+
230
+ function isValidTemplate(root: TemplateNode, included: ReadonlySet<TemplateNode>): boolean {
231
+ if (hasTemplateContent(root, included)) {
232
+ return false;
233
+ }
234
+ const html = placeInContext(root.tag, writeTags(root, included));
235
+ return parseAsBody(html).toLowerCase() === html.toLowerCase();
236
+ }
237
+
238
+ function collectAll(node: TemplateNode, into: Set<TemplateNode>): Set<TemplateNode> {
239
+ into.add(node);
240
+ for (const child of node.children) {
241
+ collectAll(child, into);
242
+ }
243
+ return into;
244
+ }
245
+
246
+ /**
247
+ * Wraps the elements that make `root`'s template parse differently, and
248
+ * returns the wrapped elements, each the root of a template of its own.
249
+ */
250
+ function wrapInvalidElements(context: PassContext, root: TemplateNode): TemplateNode[] {
251
+ if (isValidTemplate(root, collectAll(root, new Set()))) {
252
+ return [];
253
+ }
254
+ // A template that is already wrong without its children is the source's own.
255
+ const included = new Set([root]);
256
+ if (!isValidTemplate(root, included)) {
257
+ return [];
258
+ }
259
+ // Add the elements one at a time, in source order, and keep apart each one
260
+ // that changes the parse. A kept-apart element takes what it holds along.
261
+ const wrapped: TemplateNode[] = [];
262
+ const pending: TemplateNode[] = [];
263
+ pushChildren(pending, root);
264
+ for (let node = pending.pop(); node; node = pending.pop()) {
265
+ included.add(node);
266
+ if (!isValidTemplate(root, included)) {
267
+ included.delete(node);
268
+ // Each brace sticks to its own element, so two wrapped neighbors read `}{`.
269
+ context.s.prependRight(node.element.start, '{');
270
+ context.s.appendLeft(node.element.end, '}');
271
+ wrapped.push(node);
272
+ continue;
273
+ }
274
+ pushChildren(pending, node);
275
+ }
276
+ return wrapped;
277
+ }
278
+
279
+ /** Pushes the children of `node` so that they pop in source order. */
280
+ function pushChildren(pending: TemplateNode[], node: TemplateNode): void {
281
+ for (let index = node.children.length - 1; index >= 0; index -= 1) {
282
+ pending.push(node.children[index]);
283
+ }
284
+ }
285
+
286
+ export function repairNesting(context: PassContext): boolean {
287
+ const roots: TemplateNode[] = [];
288
+ const visit = (node: Node, inTemplate: boolean): void => {
289
+ if (node.type === 'JSXElement') {
290
+ const tag = readIntrinsicTag(node);
291
+ if (tag !== undefined && !inTemplate) {
292
+ roots.push(collectTemplate(node, tag));
293
+ }
294
+ // An intrinsic element's children join its template. A component's
295
+ // children, an expression container, and an attribute value start over.
296
+ for (const child of node.children) {
297
+ visit(child, tag !== undefined);
298
+ }
299
+ for (const attribute of node.openingElement.attributes) {
300
+ visit(attribute, false);
301
+ }
302
+ return;
303
+ }
304
+ if (node.type === 'JSXFragment') {
305
+ for (const child of node.children) {
306
+ visit(child, inTemplate);
307
+ }
308
+ return;
309
+ }
310
+ forEachChild(node, (child) => {
311
+ visit(child, false);
312
+ });
313
+ };
314
+ visit(context.program, false);
315
+
316
+ let changed = false;
317
+ for (let root = roots.pop(); root; root = roots.pop()) {
318
+ const wrapped = wrapInvalidElements(context, root);
319
+ if (wrapped.length > 0) {
320
+ changed = true;
321
+ roots.push(...wrapped);
322
+ }
323
+ }
324
+ return changed;
325
+ }
package/src/provider.ts CHANGED
@@ -86,7 +86,7 @@ export interface Provider {
86
86
  * `useContext` throws when the value and the default are both `undefined`,
87
87
  * so a value that could be `undefined` keeps its provider.
88
88
  */
89
- export function providerOf(context: PassContext, element: JSXElement): Provider | undefined {
89
+ export function findProvider(context: PassContext, element: JSXElement): Provider | undefined {
90
90
  const binding = contextBinding(context, element.openingElement.name);
91
91
  if (!binding || element.openingElement.selfClosing) {
92
92
  return undefined;
@@ -278,8 +278,13 @@ function isAccessor(context: PassContext, binding: Binding): boolean {
278
278
  if (id.type !== 'ArrayPattern' || callee === undefined || !ACCESSOR_PAIRS.has(callee)) {
279
279
  return false;
280
280
  }
281
- const index = id.elements.findIndex((element) => element === binding.identifier);
282
- return index === 0 || index === 1;
281
+ // Only the first two slots of the pair are accessors.
282
+ for (const [index, element] of id.elements.entries()) {
283
+ if (element === binding.identifier) {
284
+ return index === 0 || index === 1;
285
+ }
286
+ }
287
+ return false;
283
288
  }
284
289
 
285
290
  export interface ClosedOptions {
@@ -457,17 +462,20 @@ function isOwnView(
457
462
  if (callee !== 'merge' && callee !== 'omit') {
458
463
  return false;
459
464
  }
460
- return call.arguments.every((argument) => {
465
+ for (const argument of call.arguments) {
461
466
  if (argument.type === 'SpreadElement') {
462
467
  return false;
463
468
  }
464
469
  const inner = unwrap(argument);
465
- return (
466
- inner.type === 'ObjectExpression' ||
467
- (inner.type === 'Literal' && typeof inner.value === 'string') ||
468
- isOwnView(context, inner, props, depth + 1)
469
- );
470
- });
470
+ if (
471
+ inner.type !== 'ObjectExpression' &&
472
+ !(inner.type === 'Literal' && typeof inner.value === 'string') &&
473
+ !isOwnView(context, inner, props, depth + 1)
474
+ ) {
475
+ return false;
476
+ }
477
+ }
478
+ return true;
471
479
  }
472
480
 
473
481
  function isVisibleElement(
@@ -533,7 +541,7 @@ function isAccessorValue(
533
541
  return false;
534
542
  }
535
543
  if (expression.type === 'CallExpression') {
536
- const value = contextValueOf(context, expression, options);
544
+ const value = findContextValue(context, expression, options);
537
545
  return value !== undefined && isAccessorValue(context, value, options, depth + 1);
538
546
  }
539
547
  if (expression.type !== 'Identifier') {
@@ -569,7 +577,7 @@ function constantInit(context: PassContext, binding: Binding): Expression | unde
569
577
  /**
570
578
  * The value `useContext(Ctx)` returns, when the provider is known.
571
579
  */
572
- function contextValueOf(
580
+ function findContextValue(
573
581
  context: PassContext,
574
582
  call: CallExpression,
575
583
  options: ClosedOptions,
@@ -600,18 +608,20 @@ function isVisibleMethod(
600
608
  if (member.computed || member.property.type !== 'Identifier' || member.optional) {
601
609
  return false;
602
610
  }
603
- const object = objectLiteralOf(context, member.object, options, 0);
604
- if (!object || object.properties.some((property) => property.type !== 'Property')) {
611
+ const object = findObjectLiteral(context, member.object, options, 0);
612
+ if (!object) {
605
613
  return false;
606
614
  }
607
615
  const { name } = member.property;
608
- const matches = object.properties.filter(
609
- (property) =>
610
- property.type === 'Property' &&
611
- !property.computed &&
612
- property.key.type === 'Identifier' &&
613
- property.key.name === name,
614
- );
616
+ const matches: typeof object.properties = [];
617
+ for (const property of object.properties) {
618
+ if (property.type !== 'Property') {
619
+ return false;
620
+ }
621
+ if (!property.computed && property.key.type === 'Identifier' && property.key.name === name) {
622
+ matches.push(property);
623
+ }
624
+ }
615
625
  const property = matches.at(0);
616
626
  if (matches.length !== 1 || property?.type !== 'Property' || property.kind !== 'init') {
617
627
  return false;
@@ -637,7 +647,7 @@ function isVisibleMethod(
637
647
  * The object literal an expression evaluates to, through bindings that
638
648
  * never change and reads of a context whose value is known.
639
649
  */
640
- function objectLiteralOf(
650
+ function findObjectLiteral(
641
651
  context: PassContext,
642
652
  node: Expression,
643
653
  options: ClosedOptions,
@@ -651,15 +661,15 @@ function objectLiteralOf(
651
661
  return expression;
652
662
  }
653
663
  if (expression.type === 'CallExpression') {
654
- const value = contextValueOf(context, expression, options);
655
- return value ? objectLiteralOf(context, value, options, depth + 1) : undefined;
664
+ const value = findContextValue(context, expression, options);
665
+ return value ? findObjectLiteral(context, value, options, depth + 1) : undefined;
656
666
  }
657
667
  if (expression.type !== 'Identifier') {
658
668
  return undefined;
659
669
  }
660
670
  const binding = context.scopes.references.get(expression);
661
671
  const init = binding ? constantInit(context, binding) : undefined;
662
- return init ? objectLiteralOf(context, init, options, depth + 1) : undefined;
672
+ return init ? findObjectLiteral(context, init, options, depth + 1) : undefined;
663
673
  }
664
674
 
665
675
  /**
@@ -731,7 +741,7 @@ export function findProviders(context: PassContext): Provider[] {
731
741
  const providers: Provider[] = [];
732
742
  const visit = (node: Node): void => {
733
743
  if (node.type === 'JSXElement') {
734
- const provider = providerOf(context, node);
744
+ const provider = findProvider(context, node);
735
745
  if (provider) {
736
746
  providers.push(provider);
737
747
  }
@@ -754,9 +764,13 @@ class ProviderRemover {
754
764
  // A provider inside one removed in this pass waits for the next pass,
755
765
  // so their edits do not overlap.
756
766
  const { element } = provider;
757
- const overlaps = this.removed.some(
758
- (other) => element.start < other.end && other.start < element.end,
759
- );
767
+ let overlaps = false;
768
+ for (const other of this.removed) {
769
+ if (element.start < other.end && other.start < element.end) {
770
+ overlaps = true;
771
+ break;
772
+ }
773
+ }
760
774
  if (overlaps) {
761
775
  continue;
762
776
  }
@@ -783,7 +797,7 @@ class ProviderRemover {
783
797
  const visit = (node: Node): void => {
784
798
  if (node.type === 'JSXElement') {
785
799
  const binding = contextBinding(this.context, node.openingElement.name);
786
- if (binding && !providerOf(this.context, node)) {
800
+ if (binding && !findProvider(this.context, node)) {
787
801
  // A lone `value` is turned down because it could be `undefined`.
788
802
  const { attributes } = node.openingElement;
789
803
  const attribute = attributes.at(0);
@@ -809,20 +823,28 @@ class ProviderRemover {
809
823
  const { element } = provider;
810
824
  const children = element.children;
811
825
  let reason = 'open-other';
812
- const closed = children.every((child) =>
813
- isClosed(this.context, child, {
814
- component: () => false,
815
- contextValue: (target) => (target === provider.context ? provider.value : undefined),
816
- onOpen: (open) => {
817
- reason = open;
818
- },
819
- }),
820
- );
826
+ const closure: ClosedOptions = {
827
+ component: () => false,
828
+ contextValue: (target) => (target === provider.context ? provider.value : undefined),
829
+ onOpen: (open) => {
830
+ reason = open;
831
+ },
832
+ };
833
+ let closed = true;
834
+ for (const child of children) {
835
+ if (!isClosed(this.context, child, closure)) {
836
+ closed = false;
837
+ break;
838
+ }
839
+ }
821
840
  if (!closed) {
822
841
  this.skip(provider, reason);
823
842
  return false;
824
843
  }
825
- const reads = children.flatMap((child) => contextReads(this.context, child, provider.context));
844
+ const reads: ReturnType<typeof contextReads> = [];
845
+ for (const child of children) {
846
+ reads.push(...contextReads(this.context, child, provider.context));
847
+ }
826
848
  const texts: string[] = [];
827
849
  for (const read of reads) {
828
850
  const text = stableValueText(this.context, provider, read);