@sigil-dev/compiler 0.9.25 → 0.9.27

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.
@@ -1,307 +1,317 @@
1
- import { types as t } from "@babel/core";
2
- import { STATIC_USES } from "../../analysis/hydration.ts";
3
- import { isGlobalComponent } from "../handlers/dom/globals";
4
- import { getTagName } from "../util/helpers";
5
- import { jsxText } from "./utils";
6
-
7
- const VOID_ELEMENTS = new Set([
8
- "area",
9
- "base",
10
- "br",
11
- "col",
12
- "embed",
13
- "hr",
14
- "img",
15
- "input",
16
- "link",
17
- "meta",
18
- "param",
19
- "source",
20
- "track",
21
- "wbr",
22
- ]);
23
-
24
- const ATTR_MAP_SSR: Record<string, string> = {
25
- className: "class",
26
- htmlFor: "for",
27
- };
28
- //biome-ignore lint/suspicious/noShadowRestrictedNames: shut up
29
- function escape(expr: t.Expression): t.CallExpression {
30
- return t.callExpression(t.identifier("__e"), [expr]);
31
- }
32
-
33
- /** Compile-time HTML escaping for static JSX text and attribute strings. */
34
- function escapeText(s: string): string {
35
- return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
36
- }
37
- function escapeAttr(s: string): string {
38
- return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
39
- }
40
-
41
- // builds a template literal from alternating string parts and expressions
42
- function buildTemplate(parts: Array<string | t.Expression>): t.TemplateLiteral {
43
- const quasis: t.TemplateElement[] = [];
44
- const exprs: t.Expression[] = [];
45
- let current = "";
46
- // raw must be valid template source: a backslash, backtick or ${ in
47
- // the page text would otherwise end or corrupt the literal
48
- const element = (cooked: string, tail = false) =>
49
- t.templateElement(
50
- { raw: cooked.replace(/\\|`|\$\{/g, (m) => `\\${m}`), cooked },
51
- tail,
52
- );
53
-
54
- for (const part of parts) {
55
- if (typeof part === "string") {
56
- current += part;
57
- } else {
58
- quasis.push(element(current));
59
- current = "";
60
- exprs.push(part);
61
- }
62
- }
63
- quasis.push(element(current, true));
64
- return t.templateLiteral(quasis, exprs);
65
- }
66
-
67
- /**
68
- * Children of an element, component or fragment as HTML parts. `raw` is for
69
- * <script>: its text is code, so it is neither escaped nor marked for
70
- * hydration (see processElementSSR).
71
- */
72
- function childrenSSR(
73
- children: t.JSXElement["children"],
74
- signals: Set<string>,
75
- hash: string | undefined,
76
- raw?: string,
77
- ): Array<string | t.Expression> {
78
- const parts: Array<string | t.Expression> = [];
79
- for (const child of children) {
80
- if (t.isJSXText(child)) {
81
- // raw text (<script>, <style>) has no inline neighbours
82
- const text = jsxText(child, raw ? undefined : children);
83
- if (text !== null) parts.push(raw ? text : escapeText(text));
84
- continue;
85
- }
86
- let node: t.Node = child;
87
- if (t.isJSXExpressionContainer(child)) {
88
- if (t.isJSXEmptyExpression(child.expression)) continue;
89
- node = child.expression;
90
- }
91
- if (t.isJSXElement(node)) {
92
- // A use that produces only HTML is fenced, so hydration can cut it out
93
- // of the pool and never run the component. The set is filled from the
94
- // file's own source, identically for the server and browser builds.
95
- if (STATIC_USES.has(node)) {
96
- parts.push("<!--s-->");
97
- parts.push(processElementSSR(node, signals, hash));
98
- parts.push("<!--/s-->");
99
- } else {
100
- parts.push(processElementSSR(node, signals, hash));
101
- }
102
- } else if (t.isJSXFragment(node)) {
103
- parts.push(processFragmentSSR(node, signals, hash));
104
- } else if (raw) {
105
- parts.push(
106
- t.callExpression(t.identifier("__r"), [
107
- node as t.Expression,
108
- t.stringLiteral(raw),
109
- ]),
110
- );
111
- } else if (!t.isJSXSpreadChild(node)) {
112
- // Delimit dynamic text segments so SSR produces separate text
113
- // nodes that the hydrate compiler can claim individually.
114
- parts.push("<!--g-->");
115
- parts.push(escape(node as t.Expression));
116
- parts.push("<!--/g-->");
117
- }
118
- }
119
- return parts;
120
- }
121
-
122
- export function processElementSSR(
123
- node: t.JSXElement,
124
- signals: Set<string>,
125
- hash?: string,
126
- ): t.TemplateLiteral {
127
- const tagName = getTagName(node.openingElement.name);
128
- const isComponent = /^[A-Z]/.test(tagName);
129
-
130
- if (isComponent) {
131
- // Global components (Window/Document/Body) produce no SSR output
132
- if (isGlobalComponent(tagName)) {
133
- return t.templateLiteral(
134
- [t.templateElement({ raw: "", cooked: "" }, true)],
135
- [],
136
- );
137
- }
138
- return processComponentSSR(node, tagName, signals, hash);
139
- }
140
- let dangerousHTML: t.Expression | null = null;
141
- // <textarea value> is its content; <select value> picks an <option>
142
- let textareaValue: t.Expression | null = null;
143
- let selectValue: t.Expression | null = null;
144
- let hasClass = false;
145
- const parts: Array<string | t.Expression> = [];
146
- parts.push(`<${tagName}`);
147
-
148
- for (const attr of node.openingElement.attributes) {
149
- if (t.isJSXSpreadAttribute(attr)) {
150
- parts.push(t.callExpression(t.identifier("__s"), [attr.argument]));
151
- continue;
152
- }
153
-
154
- // namespaced attributes are client-only directives
155
- // (transition:/in:/out:/bind:) — SSR drops them entirely
156
- if (t.isJSXNamespacedName(attr.name)) continue;
157
-
158
- const attrName = attr.name.name;
159
- // drop event handlers and client-only props
160
- if (/^on[A-Z]/.test(attrName)) continue;
161
- if (attrName === "use" || /^bind[A-Z]/.test(attrName)) continue;
162
-
163
- const value: t.Expression | null = t.isStringLiteral(attr.value)
164
- ? attr.value
165
- : t.isJSXExpressionContainer(attr.value) &&
166
- !t.isJSXEmptyExpression(attr.value.expression)
167
- ? attr.value.expression
168
- : null;
169
-
170
- if (attrName === "innerHTML") {
171
- dangerousHTML = value;
172
- continue; // don't output as attribute
173
- }
174
- if (tagName === "textarea" && attrName === "value") {
175
- textareaValue = value;
176
- continue;
177
- }
178
- if (tagName === "select" && attrName === "value") {
179
- selectValue = value;
180
- continue;
181
- }
182
-
183
- const domAttr = ATTR_MAP_SSR[attrName] ?? attrName;
184
- const isClass = domAttr === "class" && !!hash;
185
- if (domAttr === "class") hasClass = true;
186
-
187
- if (attr.value === null) {
188
- // bare attribute: <input disabled>, <script defer>
189
- parts.push(` ${domAttr}`);
190
- } else if (t.isStringLiteral(attr.value)) {
191
- const v = escapeAttr(attr.value.value);
192
- parts.push(` ${domAttr}="${isClass ? `${v} ${hash}` : v}"`);
193
- } else if (value && isClass) {
194
- parts.push(` class="`, escape(value), ` ${hash}"`);
195
- } else if (value) {
196
- parts.push(
197
- t.callExpression(t.identifier("__a"), [
198
- t.stringLiteral(domAttr),
199
- value,
200
- ]),
201
- );
202
- }
203
- }
204
- if (hash && !hasClass) parts.push(` class="${hash}"`);
205
-
206
- if (VOID_ELEMENTS.has(tagName)) {
207
- parts.push(">");
208
- return buildTemplate(parts);
209
- }
210
-
211
- parts.push(">");
212
-
213
- if (dangerousHTML) {
214
- parts.push(dangerousHTML);
215
- } else if (textareaValue) {
216
- parts.push(escape(textareaValue));
217
- } else {
218
- // <script> holds raw text: HTML escaping would corrupt the code (&& →
219
- // &amp;&amp;), and <!--g--> markers are just text inside it, not
220
- // comments, so there is nothing for hydration to find. __r only guards
221
- // against the code closing its own element. (<style> never gets here:
222
- // scoped style blocks are stripped from the source before compiling.)
223
- const children = childrenSSR(
224
- node.children,
225
- signals,
226
- hash,
227
- tagName === "script" ? tagName : undefined,
228
- );
229
- if (selectValue) {
230
- parts.push(
231
- t.callExpression(t.identifier("__sel"), [
232
- buildTemplate(children),
233
- selectValue,
234
- ]),
235
- );
236
- } else {
237
- parts.push(...children);
238
- }
239
- }
240
-
241
- parts.push(`</${tagName}>`);
242
- return buildTemplate(parts);
243
- }
244
-
245
- function processComponentSSR(
246
- node: t.JSXElement,
247
- tagName: string,
248
- signals: Set<string>,
249
- hash: string | undefined,
250
- ): t.TemplateLiteral {
251
- const props = t.objectExpression([]);
252
-
253
- for (const attr of node.openingElement.attributes) {
254
- if (t.isJSXSpreadAttribute(attr)) {
255
- props.properties.push(t.spreadElement(attr.argument));
256
- continue;
257
- }
258
- const attrName = (attr.name as t.JSXIdentifier).name;
259
- // data-key is a framework-internal attribute for HTML elements only; skip for components
260
- if (attrName === "data-key" || attrName === "key") continue;
261
- // use StringLiteral key for hyphenated names, Identifier otherwise
262
- const propKey = /[^a-zA-Z_$0-9]/.test(attrName)
263
- ? t.stringLiteral(attrName)
264
- : t.identifier(attrName);
265
- if (attr.value === null) {
266
- props.properties.push(t.objectProperty(propKey, t.booleanLiteral(true)));
267
- } else if (t.isStringLiteral(attr.value)) {
268
- props.properties.push(t.objectProperty(propKey, attr.value));
269
- } else if (t.isJSXExpressionContainer(attr.value)) {
270
- props.properties.push(
271
- t.objectProperty(propKey, attr.value.expression as t.Expression),
272
- );
273
- }
274
- }
275
-
276
- const childParts = childrenSSR(node.children, signals, hash);
277
- if (childParts.length > 0) {
278
- props.properties.push(
279
- t.objectProperty(
280
- t.identifier("children"),
281
- t.callExpression(t.identifier("__h"), [buildTemplate(childParts)]),
282
- ),
283
- );
284
- }
285
-
286
- // Component({ ...props }) - result is already a string
287
- const call = t.callExpression(t.identifier("__h"), [
288
- t.callExpression(t.identifier(tagName), [props]),
289
- ]);
290
-
291
- // wrap in template so return type is consistent
292
- return t.templateLiteral(
293
- [
294
- t.templateElement({ raw: "", cooked: "" }),
295
- t.templateElement({ raw: "", cooked: "" }, true),
296
- ],
297
- [call],
298
- );
299
- }
300
-
301
- export function processFragmentSSR(
302
- node: t.JSXFragment,
303
- signals: Set<string>,
304
- hash?: string,
305
- ): t.TemplateLiteral {
306
- return buildTemplate(childrenSSR(node.children, signals, hash));
307
- }
1
+ import { types as t } from "@babel/core";
2
+ import { STATIC_USES } from "../../analysis/hydration.ts";
3
+ import { isGlobalComponent } from "../handlers/dom/globals";
4
+ import { compileState } from "../util/compile-state.ts";
5
+ import { getTagName } from "../util/helpers";
6
+ import { SVG_ATTR } from "../util/svg-attrs.ts";
7
+ import { jsxText } from "./utils";
8
+
9
+ const VOID_ELEMENTS = new Set([
10
+ "area",
11
+ "base",
12
+ "br",
13
+ "col",
14
+ "embed",
15
+ "hr",
16
+ "img",
17
+ "input",
18
+ "link",
19
+ "meta",
20
+ "param",
21
+ "source",
22
+ "track",
23
+ "wbr",
24
+ ]);
25
+
26
+ const ATTR_MAP_SSR: Record<string, string> = {
27
+ className: "class",
28
+ htmlFor: "for",
29
+ };
30
+ //biome-ignore lint/suspicious/noShadowRestrictedNames: shut up
31
+ function escape(expr: t.Expression): t.CallExpression {
32
+ return t.callExpression(t.identifier("__e"), [expr]);
33
+ }
34
+
35
+ /** Compile-time HTML escaping for static JSX text and attribute strings. */
36
+ function escapeText(s: string): string {
37
+ return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
38
+ }
39
+ function escapeAttr(s: string): string {
40
+ return s.replace(/&/g, "&amp;").replace(/"/g, "&quot;");
41
+ }
42
+
43
+ // builds a template literal from alternating string parts and expressions
44
+ function buildTemplate(parts: Array<string | t.Expression>): t.TemplateLiteral {
45
+ const quasis: t.TemplateElement[] = [];
46
+ const exprs: t.Expression[] = [];
47
+ let current = "";
48
+ // raw must be valid template source: a backslash, backtick or ${ in
49
+ // the page text would otherwise end or corrupt the literal
50
+ const element = (cooked: string, tail = false) =>
51
+ t.templateElement(
52
+ { raw: cooked.replace(/\\|`|\$\{/g, (m) => `\\${m}`), cooked },
53
+ tail,
54
+ );
55
+
56
+ for (const part of parts) {
57
+ if (typeof part === "string") {
58
+ current += part;
59
+ } else {
60
+ quasis.push(element(current));
61
+ current = "";
62
+ exprs.push(part);
63
+ }
64
+ }
65
+ quasis.push(element(current, true));
66
+ return t.templateLiteral(quasis, exprs);
67
+ }
68
+
69
+ /**
70
+ * Children of an element, component or fragment as HTML parts. `raw` is for
71
+ * <script>: its text is code, so it is neither escaped nor marked for
72
+ * hydration (see processElementSSR).
73
+ */
74
+ function childrenSSR(
75
+ children: t.JSXElement["children"],
76
+ signals: Set<string>,
77
+ hash: string | undefined,
78
+ raw?: string,
79
+ ): Array<string | t.Expression> {
80
+ const parts: Array<string | t.Expression> = [];
81
+ for (const child of children) {
82
+ if (t.isJSXText(child)) {
83
+ // raw text (<script>, <style>) has no inline neighbours
84
+ const text = jsxText(child, raw ? undefined : children);
85
+ if (text !== null) parts.push(raw ? text : escapeText(text));
86
+ continue;
87
+ }
88
+ let node: t.Node = child;
89
+ if (t.isJSXExpressionContainer(child)) {
90
+ if (t.isJSXEmptyExpression(child.expression)) continue;
91
+ node = child.expression;
92
+ }
93
+ if (t.isJSXElement(node)) {
94
+ // A use that produces only HTML is fenced, so hydration can cut it out
95
+ // of the pool and never run the component. The set is filled from the
96
+ // file's own source, identically for the server and browser builds.
97
+ if (STATIC_USES.has(node)) {
98
+ parts.push("<!--s-->");
99
+ parts.push(processElementSSR(node, signals, hash));
100
+ parts.push("<!--/s-->");
101
+ } else {
102
+ parts.push(processElementSSR(node, signals, hash));
103
+ }
104
+ } else if (t.isJSXFragment(node)) {
105
+ parts.push(processFragmentSSR(node, signals, hash));
106
+ } else if (raw) {
107
+ parts.push(
108
+ t.callExpression(t.identifier("__r"), [
109
+ node as t.Expression,
110
+ t.stringLiteral(raw),
111
+ ]),
112
+ );
113
+ } else if (!t.isJSXSpreadChild(node)) {
114
+ // Delimit dynamic text segments so SSR produces separate text
115
+ // nodes that the hydrate compiler can claim individually.
116
+ parts.push("<!--g-->");
117
+ parts.push(escape(node as t.Expression));
118
+ parts.push("<!--/g-->");
119
+ }
120
+ }
121
+ return parts;
122
+ }
123
+
124
+ export function processElementSSR(
125
+ node: t.JSXElement,
126
+ signals: Set<string>,
127
+ hash?: string,
128
+ ): t.TemplateLiteral {
129
+ const tagName = getTagName(node.openingElement.name);
130
+ const isComponent = /^[A-Z]/.test(tagName);
131
+
132
+ if (isComponent) {
133
+ // Global components (Window/Document/Body) produce no SSR output
134
+ if (isGlobalComponent(tagName)) {
135
+ return t.templateLiteral(
136
+ [t.templateElement({ raw: "", cooked: "" }, true)],
137
+ [],
138
+ );
139
+ }
140
+ return processComponentSSR(node, tagName, signals, hash);
141
+ }
142
+ let dangerousHTML: t.Expression | null = null;
143
+ // <textarea value> is its content; <select value> picks an <option>
144
+ let textareaValue: t.Expression | null = null;
145
+ let selectValue: t.Expression | null = null;
146
+ let hasClass = false;
147
+ const parts: Array<string | t.Expression> = [];
148
+ parts.push(`<${tagName}`);
149
+
150
+ for (const attr of node.openingElement.attributes) {
151
+ if (t.isJSXSpreadAttribute(attr)) {
152
+ parts.push(t.callExpression(t.identifier("__s"), [attr.argument]));
153
+ continue;
154
+ }
155
+
156
+ // namespaced attributes are client-only directives
157
+ // (transition:/in:/out:/bind:) — SSR drops them entirely
158
+ if (t.isJSXNamespacedName(attr.name)) continue;
159
+
160
+ const attrName = attr.name.name;
161
+ // drop event handlers and client-only props
162
+ if (/^on[A-Z]/.test(attrName)) continue;
163
+ if (attrName === "use" || /^bind[A-Z]/.test(attrName)) continue;
164
+
165
+ const value: t.Expression | null = t.isStringLiteral(attr.value)
166
+ ? attr.value
167
+ : t.isJSXExpressionContainer(attr.value) &&
168
+ !t.isJSXEmptyExpression(attr.value.expression)
169
+ ? attr.value.expression
170
+ : null;
171
+
172
+ if (attrName === "innerHTML") {
173
+ dangerousHTML = value;
174
+ continue; // don't output as attribute
175
+ }
176
+ if (tagName === "textarea" && attrName === "value") {
177
+ textareaValue = value;
178
+ continue;
179
+ }
180
+ if (tagName === "select" && attrName === "value") {
181
+ selectValue = value;
182
+ continue;
183
+ }
184
+
185
+ const domAttr = ATTR_MAP_SSR[attrName] ?? SVG_ATTR[attrName] ?? attrName;
186
+ const isClass = domAttr === "class" && !!hash;
187
+ if (domAttr === "class") hasClass = true;
188
+
189
+ if (attr.value === null) {
190
+ // bare attribute: <input disabled>, <script defer>
191
+ parts.push(` ${domAttr}`);
192
+ } else if (t.isStringLiteral(attr.value)) {
193
+ const v = escapeAttr(attr.value.value);
194
+ parts.push(` ${domAttr}="${isClass ? `${v} ${hash}` : v}"`);
195
+ } else if (value && isClass) {
196
+ parts.push(` class="`, escape(value), ` ${hash}"`);
197
+ } else if (value) {
198
+ parts.push(
199
+ t.callExpression(t.identifier("__a"), [
200
+ t.stringLiteral(domAttr),
201
+ value,
202
+ ]),
203
+ );
204
+ }
205
+ }
206
+ if (hash && !hasClass) parts.push(` class="${hash}"`);
207
+
208
+ if (VOID_ELEMENTS.has(tagName)) {
209
+ parts.push(">");
210
+ return buildTemplate(parts);
211
+ }
212
+
213
+ parts.push(">");
214
+
215
+ if (dangerousHTML) {
216
+ parts.push(dangerousHTML);
217
+ } else if (textareaValue) {
218
+ parts.push(escape(textareaValue));
219
+ } else {
220
+ // <script> holds raw text: HTML escaping would corrupt the code (&& →
221
+ // &amp;&amp;), and <!--g--> markers are just text inside it, not
222
+ // comments, so there is nothing for hydration to find. __r only guards
223
+ // against the code closing its own element. (<style> never gets here:
224
+ // scoped style blocks are stripped from the source before compiling.)
225
+ const children = childrenSSR(
226
+ node.children,
227
+ signals,
228
+ hash,
229
+ tagName === "script" ? tagName : undefined,
230
+ );
231
+ if (selectValue) {
232
+ parts.push(
233
+ t.callExpression(t.identifier("__sel"), [
234
+ buildTemplate(children),
235
+ selectValue,
236
+ ]),
237
+ );
238
+ } else {
239
+ parts.push(...children);
240
+ }
241
+ }
242
+
243
+ parts.push(`</${tagName}>`);
244
+ return buildTemplate(parts);
245
+ }
246
+
247
+ function processComponentSSR(
248
+ node: t.JSXElement,
249
+ tagName: string,
250
+ signals: Set<string>,
251
+ hash: string | undefined,
252
+ ): t.TemplateLiteral {
253
+ const props = t.objectExpression([]);
254
+
255
+ for (const attr of node.openingElement.attributes) {
256
+ if (t.isJSXSpreadAttribute(attr)) {
257
+ props.properties.push(t.spreadElement(attr.argument));
258
+ continue;
259
+ }
260
+ const attrName = (attr.name as t.JSXIdentifier).name;
261
+ // data-key is a framework-internal attribute for HTML elements only; skip for components
262
+ if (attrName === "data-key" || attrName === "key") continue;
263
+ // use StringLiteral key for hyphenated names, Identifier otherwise
264
+ const propKey = /[^a-zA-Z_$0-9]/.test(attrName)
265
+ ? t.stringLiteral(attrName)
266
+ : t.identifier(attrName);
267
+ if (attr.value === null) {
268
+ props.properties.push(t.objectProperty(propKey, t.booleanLiteral(true)));
269
+ } else if (t.isStringLiteral(attr.value)) {
270
+ props.properties.push(t.objectProperty(propKey, attr.value));
271
+ } else if (t.isJSXExpressionContainer(attr.value)) {
272
+ props.properties.push(
273
+ t.objectProperty(propKey, attr.value.expression as t.Expression),
274
+ );
275
+ }
276
+ }
277
+
278
+ const childParts = childrenSSR(node.children, signals, hash);
279
+ if (childParts.length > 0) {
280
+ // rendered when the component outputs them, inside its own call, so
281
+ // they see the context it sets (as on the client, where they are thunks)
282
+ props.properties.push(
283
+ t.objectProperty(
284
+ t.identifier("children"),
285
+ t.callExpression(t.identifier("__lazy"), [
286
+ t.arrowFunctionExpression([], buildTemplate(childParts)),
287
+ ]),
288
+ ),
289
+ );
290
+ }
291
+
292
+ // __component(Component, { ...props }) - result is already a string
293
+ compileState.ssrImports.add("__component");
294
+ const call = t.callExpression(t.identifier("__h"), [
295
+ t.callExpression(t.identifier("__component"), [
296
+ t.identifier(tagName),
297
+ props,
298
+ ]),
299
+ ]);
300
+
301
+ // wrap in template so return type is consistent
302
+ return t.templateLiteral(
303
+ [
304
+ t.templateElement({ raw: "", cooked: "" }),
305
+ t.templateElement({ raw: "", cooked: "" }, true),
306
+ ],
307
+ [call],
308
+ );
309
+ }
310
+
311
+ export function processFragmentSSR(
312
+ node: t.JSXFragment,
313
+ signals: Set<string>,
314
+ hash?: string,
315
+ ): t.TemplateLiteral {
316
+ return buildTemplate(childrenSSR(node.children, signals, hash));
317
+ }