@sigil-dev/compiler 0.9.26 → 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,1027 +1,1034 @@
1
- import { types as t } from "@babel/core";
2
- //@ts-expect-error Not our problem babel forgot tp export types.
3
- import { generate } from "@babel/generator";
4
- import {
5
- handleGlobalComponent,
6
- isGlobalComponent,
7
- } from "../handlers/dom/globals";
8
- import { STATIC_USES } from "../../analysis/hydration.ts";
9
- import { buildBind, buildProxyBind } from "../util/bind";
10
- import { compileState } from "../util/compile-state.ts";
11
- import { isPropRead } from "../util/props.ts";
12
- import { buildAnchorMount } from "./anchor-mount";
13
- import { collectChildren } from "./children";
14
- import { processFragment } from "./fragment";
15
- import { buildKeyedList, findKeyedMapExpr } from "./keyed-list";
16
- import { buildTextNode } from "./text-node";
17
- import {
18
- ATTR_MAP,
19
- buildHydrationScope,
20
- containsSignal,
21
- getCreateElement,
22
- hasJSX,
23
- isPrimitive,
24
- jsxText,
25
- } from "./utils";
26
-
27
- /**
28
- * Dashed names (data-*, aria-*, custom attributes) have no IDL property —
29
- * `el["data-x"] = v` sets a bare JS property the DOM never reflects, so the
30
- * attribute is invisible to selectors, getAttribute, and CSS. They must go
31
- * through setAttribute.
32
- */
33
- function isDashedAttr(attrName: string): boolean {
34
- return attrName.includes("-");
35
- }
36
-
37
- function setAttrCall(
38
- varName: string,
39
- attrName: string,
40
- value: t.Expression,
41
- ): t.CallExpression {
42
- return t.callExpression(
43
- t.memberExpression(t.identifier(varName), t.identifier("setAttribute")),
44
- [t.stringLiteral(attrName), value],
45
- );
46
- }
47
-
48
- /**
49
- * Route a prop write through the runtime setProp() helper. On HTML elements
50
- * this is today's blind `el[name] = value`; on SVG-namespace elements it
51
- * goes through setAttribute instead — IDL property assignment throws on real
52
- * SVG elements (`svg.width = 15` hits a getter-only property), which crashed
53
- * CSR renders the moment claim() started creating true-namespaced SVG.
54
- */
55
- function setPropCall(
56
- varName: string,
57
- attrName: string,
58
- value: t.Expression,
59
- ): t.CallExpression {
60
- return t.callExpression(t.identifier("setProp"), [
61
- t.identifier(varName),
62
- t.stringLiteral(attrName),
63
- value,
64
- ]);
65
- }
66
-
67
- function isClaimedCall(varName: string): t.CallExpression {
68
- return t.callExpression(t.identifier("isClaimed"), [t.identifier(varName)]);
69
- }
70
-
71
- function effect(body: t.Statement[]): t.ExpressionStatement {
72
- return t.expressionStatement(
73
- t.callExpression(t.identifier("createEffect"), [
74
- t.arrowFunctionExpression([], t.blockStatement(body)),
75
- ]),
76
- );
77
- }
78
-
79
- /** Emit fresh-element-only writes; hydration guards them with isClaimed(). */
80
- function pushInit(
81
- varName: string,
82
- init: t.Statement[],
83
- statements: t.Statement[],
84
- hydrate?: boolean,
85
- ): void {
86
- if (!init.length) return;
87
- if (hydrate) {
88
- statements.push(
89
- t.ifStatement(
90
- t.unaryExpression("!", isClaimedCall(varName)),
91
- t.blockStatement(init),
92
- ),
93
- );
94
- } else {
95
- statements.push(...init);
96
- }
97
- }
98
-
99
- /** A <script>'s children as one string expression, or null if it has none. */
100
- function scriptText(node: t.JSXElement): t.Expression | null {
101
- const parts: t.Expression[] = [];
102
- for (const child of node.children) {
103
- if (t.isJSXText(child)) {
104
- const text = jsxText(child);
105
- if (text !== null) parts.push(t.stringLiteral(text));
106
- } else if (
107
- t.isJSXExpressionContainer(child) &&
108
- !t.isJSXEmptyExpression(child.expression)
109
- ) {
110
- parts.push(
111
- t.logicalExpression("??", child.expression, t.stringLiteral("")),
112
- );
113
- }
114
- }
115
- if (!parts.length) return null;
116
- return parts.reduce(
117
- (a, b) => t.binaryExpression("+", a, b),
118
- t.stringLiteral(""),
119
- );
120
- }
121
-
122
- /**
123
- * Build an object property key (identifier for valid names, string literal for dashed).
124
- */
125
- function attrKey(attrName: string): t.Identifier | t.StringLiteral {
126
- if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName)) {
127
- return t.identifier(attrName);
128
- }
129
- return t.stringLiteral(attrName);
130
- }
131
-
132
- /**
133
- * Add classList.add(hash) statement for scoped CSS.
134
- */
135
- function addScopedClass(
136
- varName: string,
137
- hash: string,
138
- statements: t.Statement[],
139
- ): void {
140
- statements.push(
141
- t.expressionStatement(
142
- t.callExpression(
143
- t.memberExpression(
144
- t.memberExpression(t.identifier(varName), t.identifier("classList")),
145
- t.identifier("add"),
146
- ),
147
- [t.stringLiteral(hash)],
148
- ),
149
- ),
150
- );
151
- }
152
-
153
- export function processElement(
154
- node: t.JSXElement,
155
- statements: t.Statement[],
156
- genId: () => string,
157
- signals: Set<string>,
158
- hash?: string,
159
- hydrate?: boolean,
160
- nodesVar?: string,
161
- parentVar?: string,
162
- ): string {
163
- const varName = genId();
164
- const tag = (node.openingElement.name as t.JSXIdentifier).name;
165
- const isComponent = /^[A-Z]/.test(tag);
166
-
167
- if (isComponent) {
168
- // Global components: Window, Document, Body
169
- if (isGlobalComponent(tag)) {
170
- return handleGlobalComponent(tag, node, statements, genId);
171
- }
172
-
173
- // Component: call the function with a props object
174
- const propsObj = t.objectExpression([]);
175
-
176
- // Add attributes to props (including spread)
177
- for (const attr of node.openingElement.attributes) {
178
- if (t.isJSXSpreadAttribute(attr)) {
179
- // {…obj} — spread into props
180
- propsObj.properties.push(t.spreadElement(attr.argument));
181
- continue;
182
- }
183
- if (!t.isJSXAttribute(attr)) continue;
184
- const attrName = (attr.name as t.JSXIdentifier).name;
185
-
186
- if (attr.value === null) {
187
- // <Comp disabled /> → { disabled: true }
188
- propsObj.properties.push(
189
- t.objectProperty(attrKey(attrName), t.booleanLiteral(true)),
190
- );
191
- } else if (t.isStringLiteral(attr.value)) {
192
- propsObj.properties.push(
193
- t.objectProperty(attrKey(attrName), attr.value),
194
- );
195
- } else if (t.isJSXExpressionContainer(attr.value)) {
196
- const expr = attr.value.expression as t.Expression;
197
- // JSX in a prop (icon={<Icon />}, actions={<>…</>}) belongs
198
- // wherever the component puts it, inside its own root. Built
199
- // now, during hydration, it would claim from the caller's pool
200
- // and could take the component's root element. Defer it like
201
- // children: the component's {prop} slot runs the thunk against
202
- // the right nodes.
203
- if (hydrate && hasJSX(expr)) {
204
- propsObj.properties.push(
205
- t.objectProperty(
206
- attrKey(attrName),
207
- t.arrowFunctionExpression([], expr),
208
- ),
209
- );
210
- } else if (containsSignal(expr, signals)) {
211
- // a prop that reads state is passed as a getter, so the
212
- // component reads the current value wherever it uses it
213
- propsObj.properties.push(
214
- t.objectMethod(
215
- "get",
216
- attrKey(attrName),
217
- [],
218
- t.blockStatement([t.returnStatement(expr)]),
219
- ),
220
- );
221
- } else {
222
- propsObj.properties.push(t.objectProperty(attrKey(attrName), expr));
223
- }
224
- }
225
- }
226
-
227
- // Add children to props
228
- const childrenExpr = collectChildren(
229
- node,
230
- statements,
231
- genId,
232
- signals,
233
- hash,
234
- hydrate,
235
- nodesVar,
236
- );
237
- if (childrenExpr) {
238
- propsObj.properties.push(
239
- t.objectProperty(t.identifier("children"), childrenExpr),
240
- );
241
- }
242
-
243
- const componentCall = t.callExpression(t.identifier(tag), [propsObj]);
244
-
245
- if (hydrate && nodesVar && STATIC_USES.has(node)) {
246
- // The analysis proved this use produces only HTML, and the server
247
- // fenced it in <!--s-->…<!--/s-->. Cut that run out of the pool and
248
- // never call the component: no claiming, no effects, no listeners.
249
- // With nothing to skip (a client render, an empty pool) skipStatic
250
- // returns null and the component runs as it always did.
251
- statements.push(
252
- t.variableDeclaration("let", [
253
- t.variableDeclarator(
254
- t.identifier(varName),
255
- t.callExpression(t.identifier("skipStatic"), [t.identifier(nodesVar)]),
256
- ),
257
- ]),
258
- );
259
- const render: t.Statement[] = [
260
- t.expressionStatement(
261
- t.callExpression(t.identifier("pushHydrationNodes"), [t.identifier(nodesVar)]),
262
- ),
263
- t.expressionStatement(
264
- t.assignmentExpression("=", t.identifier(varName), componentCall),
265
- ),
266
- t.expressionStatement(
267
- t.callExpression(t.identifier("popHydrationNodes"), []),
268
- ),
269
- ];
270
- if (parentVar) {
271
- render.push(
272
- t.ifStatement(
273
- t.binaryExpression(
274
- "===",
275
- t.memberExpression(t.identifier(nodesVar), t.identifier("length")),
276
- t.numericLiteral(0),
277
- ),
278
- t.expressionStatement(
279
- t.callExpression(t.identifier("insert"), [
280
- t.identifier(parentVar),
281
- t.identifier(varName),
282
- ]),
283
- ),
284
- ),
285
- );
286
- }
287
- // Dev: render the skipped component once, detached, and throw if it was
288
- // not really static. The analysis is conservative, and this is how a
289
- // mistake in it shows up before it reaches production.
290
- const probe = compileState.dev
291
- ? t.blockStatement([
292
- t.expressionStatement(
293
- t.callExpression(t.identifier("probeStatic"), [
294
- t.stringLiteral(tag),
295
- t.arrowFunctionExpression([], t.cloneNode(componentCall, true)),
296
- ]),
297
- ),
298
- ])
299
- : null;
300
- statements.push(
301
- t.ifStatement(
302
- t.unaryExpression("!", t.identifier(varName)),
303
- t.blockStatement(render),
304
- probe,
305
- ),
306
- );
307
- return varName;
308
- }
309
-
310
- if (hydrate && nodesVar) {
311
- // Push the parent's child pool before calling the component so that
312
- // getHydrationNodes() inside the component returns the right scope.
313
- // In SSR hydration the component claims its root node from that pool
314
- // (it's already in the DOM). In empty-pool / SPA mode the component
315
- // creates a fresh node, so we explicitly insert it when the pool is empty.
316
- statements.push(
317
- t.expressionStatement(
318
- t.callExpression(t.identifier("pushHydrationNodes"), [
319
- t.identifier(nodesVar),
320
- ]),
321
- ),
322
- );
323
- statements.push(
324
- t.variableDeclaration("const", [
325
- t.variableDeclarator(t.identifier(varName), componentCall),
326
- ]),
327
- );
328
- statements.push(
329
- t.expressionStatement(
330
- t.callExpression(t.identifier("popHydrationNodes"), []),
331
- ),
332
- );
333
- if (parentVar) {
334
- // Insert only when the pool was empty (fresh DOM); if the pool had
335
- // nodes the component already claimed its SSR element (already in DOM).
336
- statements.push(
337
- t.ifStatement(
338
- t.binaryExpression(
339
- "===",
340
- t.memberExpression(
341
- t.identifier(nodesVar),
342
- t.identifier("length"),
343
- ),
344
- t.numericLiteral(0),
345
- ),
346
- t.expressionStatement(
347
- t.callExpression(t.identifier("insert"), [
348
- t.identifier(parentVar),
349
- t.identifier(varName),
350
- ]),
351
- ),
352
- ),
353
- );
354
- }
355
- } else {
356
- statements.push(
357
- t.variableDeclaration("const", [
358
- t.variableDeclarator(t.identifier(varName), componentCall),
359
- ]),
360
- );
361
- }
362
-
363
- return varName;
364
- }
365
-
366
- // Native element: claim (hydrate) or create (dom)
367
- const currentNodesVar = nodesVar ?? "__nodes";
368
- statements.push(
369
- t.variableDeclaration("const", [
370
- t.variableDeclarator(
371
- t.identifier(varName),
372
- getCreateElement(
373
- tag,
374
- !!hydrate,
375
- currentNodesVar,
376
- hydrate ? parentVar : undefined,
377
- ),
378
- ),
379
- ]),
380
- );
381
-
382
- // In hydrate mode, scope to this element's children for descendants
383
- let childNodesVar: string | undefined;
384
- if (hydrate) {
385
- childNodesVar = genId();
386
- buildHydrationScope(varName, statements, childNodesVar);
387
- }
388
-
389
- // Attribute writes that only matter on a fresh element. When hydration
390
- // claims server HTML they already happened there, and redoing them would
391
- // wipe whatever a page script changed in the meantime.
392
- const init: t.Statement[] = [];
393
- // <select value> needs its options to exist first.
394
- const initAfter: t.Statement[] = [];
395
- const liveAfter: t.Statement[] = [];
396
-
397
- // attributes
398
- const seenAttrs = new Set<string>();
399
- for (const attr of node.openingElement.attributes) {
400
- if (t.isJSXSpreadAttribute(attr)) {
401
- // {…obj}: listeners always, attributes unless hydration claimed
402
- // the element (then the server already rendered them)
403
- const args: t.Expression[] = [t.identifier(varName), attr.argument];
404
- if (hydrate) args.push(t.unaryExpression("!", isClaimedCall(varName)));
405
- statements.push(
406
- t.expressionStatement(t.callExpression(t.identifier("spread"), args)),
407
- );
408
- continue;
409
- }
410
- if (!t.isJSXAttribute(attr)) continue;
411
- let attrName: string;
412
- let attrNamespace: string | undefined;
413
- if (t.isJSXNamespacedName(attr.name)) {
414
- attrNamespace = attr.name.namespace.name;
415
- attrName = attr.name.name.name;
416
- } else {
417
- attrName = (attr.name as t.JSXIdentifier).name;
418
- // bindValue -> bind:value, bindChecked -> bind:checked
419
- if (/^bind[A-Z]/.test(attrName)) {
420
- attrNamespace = "bind";
421
- // bindScrollTop -> bind:scrollTop: only the first letter lowers
422
- attrName = attrName.charAt(4).toLowerCase() + attrName.slice(5);
423
- }
424
- }
425
- const realAttr = ATTR_MAP[attrName] ?? attrName;
426
-
427
- if (seenAttrs.has(realAttr)) {
428
- throw new TypeError(
429
- `Duplicate attribute "${realAttr}" (via "${attrName}"). Use class or className, not both.`,
430
- );
431
- }
432
- seenAttrs.add(realAttr);
433
- if (
434
- (attrNamespace === "transition" ||
435
- attrNamespace === "in" ||
436
- attrNamespace === "out") &&
437
- t.isJSXExpressionContainer(attr.value)
438
- ) {
439
- // transition:fade={fade} / in:appear={x} / out:leave={[y, params]}
440
- const expr = attr.value.expression as t.Expression;
441
- statements.push(
442
- t.expressionStatement(
443
- t.callExpression(t.identifier("mountTransition"), [
444
- t.identifier(varName),
445
- expr,
446
- t.stringLiteral(attrNamespace as "transition" | "in" | "out"),
447
- ]),
448
- ),
449
- );
450
- } else if (attrName === "use") {
451
- // use={directive} or use={[directive, params]}
452
- const expr = (attr.value as t.JSXExpressionContainer)
453
- .expression as t.Expression;
454
- statements.push(
455
- t.expressionStatement(
456
- t.callExpression(t.identifier("applyDirective"), [
457
- t.identifier(varName),
458
- expr,
459
- ]),
460
- ),
461
- );
462
- } else if (/^on[A-Z]/.test(attrName)) {
463
- // Standard JSX: onClick, onSubmit, onMouseenter, etc.
464
- // Convert camelCase to lowercase: onClick -> click, onMouseenter -> mouseenter
465
- const event = attrName.slice(2).toLowerCase();
466
- const handler = (attr.value as t.JSXExpressionContainer)
467
- .expression as t.Expression;
468
- statements.push(
469
- t.expressionStatement(
470
- t.callExpression(
471
- t.memberExpression(
472
- t.identifier(varName),
473
- t.identifier("addEventListener"),
474
- ),
475
- [t.stringLiteral(event), handler],
476
- ),
477
- ),
478
- );
479
- } else if (attrNamespace === "bind") {
480
- const bindProp = attrName;
481
- const signal = (attr.value as t.JSXExpressionContainer)
482
- .expression as t.Expression;
483
-
484
- if (bindProp === "this") {
485
- statements.push(
486
- t.expressionStatement(
487
- t.callExpression(
488
- t.memberExpression(
489
- (signal as t.CallExpression).callee as t.Expression,
490
- t.identifier("set"),
491
- ),
492
- [t.identifier(varName)],
493
- ),
494
- ),
495
- );
496
- continue;
497
- }
498
-
499
- if (bindProp === "group") {
500
- // Scan element attributes for type and value
501
- let inputType = "";
502
- let _inputValue: t.StringLiteral | undefined;
503
- for (const a of node.openingElement.attributes) {
504
- if (t.isJSXAttribute(a) && t.isJSXIdentifier(a.name)) {
505
- if (a.name.name === "type" && t.isStringLiteral(a.value)) {
506
- inputType = a.value.value;
507
- }
508
- if (a.name.name === "value" && t.isStringLiteral(a.value)) {
509
- _inputValue = a.value;
510
- }
511
- }
512
- }
513
-
514
- if (inputType === "radio" || inputType === "") {
515
- const isTopLevel =
516
- t.isCallExpression(signal) &&
517
- t.isIdentifier((signal as t.CallExpression).callee) &&
518
- signals.has(
519
- ((signal as t.CallExpression).callee as t.Identifier).name,
520
- );
521
-
522
- if (isTopLevel) {
523
- const signalId = (signal as t.CallExpression)
524
- .callee as t.Identifier;
525
- statements.push(
526
- t.expressionStatement(
527
- t.callExpression(
528
- t.memberExpression(
529
- t.identifier(varName),
530
- t.identifier("addEventListener"),
531
- ),
532
- [
533
- t.stringLiteral("change"),
534
- t.arrowFunctionExpression(
535
- [],
536
- t.callExpression(
537
- t.memberExpression(signalId, t.identifier("set")),
538
- [
539
- t.memberExpression(
540
- t.identifier(varName),
541
- t.identifier("value"),
542
- ),
543
- ],
544
- ),
545
- ),
546
- ],
547
- ),
548
- ),
549
- );
550
- }
551
- } else if (inputType === "checkbox") {
552
- const isTopLevel =
553
- t.isCallExpression(signal) &&
554
- t.isIdentifier((signal as t.CallExpression).callee) &&
555
- signals.has(
556
- ((signal as t.CallExpression).callee as t.Identifier).name,
557
- );
558
-
559
- if (isTopLevel) {
560
- const callExpr = signal as t.CallExpression;
561
- statements.push(
562
- t.expressionStatement(
563
- t.callExpression(
564
- t.memberExpression(
565
- t.identifier(varName),
566
- t.identifier("addEventListener"),
567
- ),
568
- [
569
- t.stringLiteral("change"),
570
- t.arrowFunctionExpression(
571
- [],
572
- t.blockStatement([
573
- t.ifStatement(
574
- t.memberExpression(
575
- t.identifier(varName),
576
- t.identifier("checked"),
577
- ),
578
- // checked: push value into array
579
- t.blockStatement([
580
- t.expressionStatement(
581
- t.callExpression(
582
- t.memberExpression(
583
- t.callExpression(callExpr, []),
584
- t.identifier("push"),
585
- ),
586
- [
587
- t.memberExpression(
588
- t.identifier(varName),
589
- t.identifier("value"),
590
- ),
591
- ],
592
- ),
593
- ),
594
- ]),
595
- // unchecked: splice value out of array
596
- t.blockStatement([
597
- t.expressionStatement(
598
- t.callExpression(
599
- t.memberExpression(
600
- t.callExpression(callExpr, []),
601
- t.identifier("splice"),
602
- ),
603
- [
604
- t.callExpression(
605
- t.memberExpression(
606
- t.callExpression(callExpr, []),
607
- t.identifier("indexOf"),
608
- ),
609
- [
610
- t.memberExpression(
611
- t.identifier(varName),
612
- t.identifier("value"),
613
- ),
614
- ],
615
- ),
616
- t.numericLiteral(1),
617
- ],
618
- ),
619
- ),
620
- ]),
621
- ),
622
- ]),
623
- ),
624
- ],
625
- ),
626
- ),
627
- );
628
- }
629
- } else {
630
- console.warn(
631
- `[sigil] bind:group requires type="radio" or type="checkbox" on the element. ` +
632
- `Got: type="${inputType}".`,
633
- );
634
- }
635
- continue;
636
- }
637
-
638
- // Generic bind:innerHTML, bind:textContent, bind:value, bind:checked, etc.
639
- const isTopLevelSignal =
640
- t.isCallExpression(signal) &&
641
- t.isIdentifier((signal as t.CallExpression).callee) &&
642
- signals.has(((signal as t.CallExpression).callee as t.Identifier).name);
643
-
644
- const isMemberOfSignal =
645
- t.isMemberExpression(signal) &&
646
- t.isCallExpression((signal as t.MemberExpression).object) &&
647
- t.isIdentifier(
648
- ((signal as t.MemberExpression).object as t.CallExpression).callee,
649
- ) &&
650
- signals.has(
651
- (
652
- ((signal as t.MemberExpression).object as t.CallExpression)
653
- .callee as t.Identifier
654
- ).name,
655
- );
656
-
657
- // bind:checked={item.done} in a list row, or {book.read} where `book`
658
- // is a prop: the chain is rooted at a row item or a props object,
659
- // and what it ends in is a property of a $state proxy
660
- let root: t.Node = signal;
661
- while (t.isMemberExpression(root)) root = root.object;
662
- const isMemberOfItem =
663
- t.isMemberExpression(signal) &&
664
- t.isIdentifier(root) &&
665
- signals.has(root.name);
666
-
667
- if (isTopLevelSignal) {
668
- buildBind(varName, bindProp, attr, statements);
669
- } else if (isMemberOfSignal || isMemberOfItem) {
670
- buildProxyBind(varName, bindProp, attr, statements, signal);
671
- } else {
672
- console.warn(
673
- `[sigil] bind:${bindProp}={...} requires a $state signal or $state object property. ` +
674
- `Got: ${generate(signal).code}. ` +
675
- `Hint: change to a $state() call.`,
676
- );
677
- }
678
- } else if (attr.value === null) {
679
- // bare attribute (<input disabled>, <div data-beacon>)
680
- init.push(
681
- t.expressionStatement(
682
- isDashedAttr(realAttr)
683
- ? setAttrCall(varName, realAttr, t.stringLiteral(""))
684
- : setPropCall(varName, realAttr, t.booleanLiteral(true)),
685
- ),
686
- );
687
- } else if (t.isStringLiteral(attr.value)) {
688
- const stmt = t.expressionStatement(
689
- setPropCall(varName, realAttr, t.stringLiteral(attr.value.value)),
690
- );
691
- (tag === "select" && realAttr === "value" ? initAfter : init).push(stmt);
692
- } else if (t.isJSXExpressionContainer(attr.value)) {
693
- const expr = attr.value.expression as t.Expression;
694
- const afterChildren = tag === "select" && realAttr === "value";
695
- // style={{ color: "red", fontSize: val }} — per-property writes
696
- if (attrName === "style" && t.isObjectExpression(expr)) {
697
- for (const prop of expr.properties) {
698
- if (!t.isObjectProperty(prop)) continue;
699
- const key = t.isIdentifier(prop.key)
700
- ? prop.key.name
701
- : t.isStringLiteral(prop.key)
702
- ? prop.key.value
703
- : null;
704
- if (!key) continue;
705
- const val = prop.value as t.Expression;
706
- const write = t.expressionStatement(
707
- t.callExpression(t.identifier("setStyleProp"), [
708
- t.identifier(varName),
709
- t.stringLiteral(key),
710
- val,
711
- ]),
712
- );
713
- if (containsSignal(val, signals)) {
714
- statements.push(effect([write]));
715
- } else {
716
- init.push(write);
717
- }
718
- }
719
- } else if (containsSignal(expr, signals)) {
720
- // Dynamic class with scoped CSS: use classList.value to preserve hash
721
- if (attrName === "class" && hash) {
722
- statements.push(
723
- effect([
724
- t.expressionStatement(
725
- t.assignmentExpression(
726
- "=",
727
- t.memberExpression(
728
- t.memberExpression(
729
- t.identifier(varName),
730
- t.identifier("classList"),
731
- ),
732
- t.identifier("value"),
733
- ),
734
- expr,
735
- ),
736
- ),
737
- t.expressionStatement(
738
- t.callExpression(
739
- t.memberExpression(
740
- t.memberExpression(
741
- t.identifier(varName),
742
- t.identifier("classList"),
743
- ),
744
- t.identifier("add"),
745
- ),
746
- [t.stringLiteral(hash)],
747
- ),
748
- ),
749
- ]),
750
- );
751
- } else {
752
- const stmt = effect([
753
- t.expressionStatement(setPropCall(varName, realAttr, expr)),
754
- ]);
755
- (afterChildren ? liveAfter : statements).push(stmt);
756
- }
757
- } else {
758
- const stmt = t.expressionStatement(
759
- setPropCall(varName, realAttr, expr),
760
- );
761
- (afterChildren ? initAfter : init).push(stmt);
762
- }
763
- }
764
- }
765
-
766
- pushInit(varName, init, statements, hydrate);
767
-
768
- // Add scoped CSS hash to classList (if hash is present)
769
- if (hash) {
770
- addScopedClass(varName, hash, statements);
771
- }
772
-
773
- // children. <script> text is already in the server HTML, raw and unmarked
774
- // (see ssr.ts), so hydration has nothing to claim there: the marker search
775
- // would miss and append a second copy of the code.
776
- if (hydrate && tag === "script") {
777
- // ...but SPA navigation creates the element fresh and needs the text.
778
- const text = scriptText(node);
779
- if (text) {
780
- const write = [
781
- t.expressionStatement(
782
- t.assignmentExpression(
783
- "=",
784
- t.memberExpression(
785
- t.identifier(varName),
786
- t.identifier("textContent"),
787
- ),
788
- text,
789
- ),
790
- ),
791
- ];
792
- pushInit(varName, write, statements, hydrate);
793
- }
794
- }
795
- for (const child of hydrate && tag === "script" ? [] : node.children) {
796
- if (t.isJSXElement(child)) {
797
- const childVar = processElement(
798
- child,
799
- statements,
800
- genId,
801
- signals,
802
- hash,
803
- hydrate,
804
- childNodesVar,
805
- hydrate ? varName : undefined,
806
- );
807
- if (!hydrate) {
808
- statements.push(
809
- t.expressionStatement(
810
- t.callExpression(
811
- t.memberExpression(t.identifier(varName), t.identifier("append")),
812
- [t.identifier(childVar)],
813
- ),
814
- ),
815
- );
816
- }
817
- } else if (t.isJSXFragment(child)) {
818
- const childVar = processFragment(
819
- child,
820
- statements,
821
- genId,
822
- signals,
823
- hash,
824
- hydrate,
825
- childNodesVar,
826
- hydrate ? varName : undefined,
827
- );
828
- if (!hydrate) {
829
- statements.push(
830
- t.expressionStatement(
831
- t.callExpression(
832
- t.memberExpression(t.identifier(varName), t.identifier("append")),
833
- [t.identifier(childVar)],
834
- ),
835
- ),
836
- );
837
- }
838
- } else if (t.isJSXText(child)) {
839
- const text = jsxText(child, node.children);
840
- if (text === null) continue;
841
- if (hydrate) {
842
- // SSR hydration: text already in DOM from SSR, do nothing.
843
- // SPA navigation: childNodesVar pool is empty, create text node.
844
- const poolLen = t.memberExpression(
845
- t.identifier(childNodesVar!),
846
- t.identifier("length"),
847
- );
848
- statements.push(
849
- t.ifStatement(
850
- t.binaryExpression("===", poolLen, t.numericLiteral(0)),
851
- t.expressionStatement(
852
- t.callExpression(
853
- t.memberExpression(
854
- t.identifier(varName),
855
- t.identifier("append"),
856
- ),
857
- [
858
- t.callExpression(
859
- t.memberExpression(
860
- t.identifier("document"),
861
- t.identifier("createTextNode"),
862
- ),
863
- [t.stringLiteral(text)],
864
- ),
865
- ],
866
- ),
867
- ),
868
- ),
869
- );
870
- } else {
871
- statements.push(
872
- t.expressionStatement(
873
- t.callExpression(
874
- t.memberExpression(t.identifier(varName), t.identifier("append")),
875
- [
876
- t.callExpression(
877
- t.memberExpression(
878
- t.identifier("document"),
879
- t.identifier("createTextNode"),
880
- ),
881
- [t.stringLiteral(text)],
882
- ),
883
- ],
884
- ),
885
- ),
886
- );
887
- }
888
- } else if (t.isJSXExpressionContainer(child)) {
889
- if (t.isJSXEmptyExpression(child.expression)) continue;
890
- const expr = child.expression as t.Expression;
891
- if (t.isJSXElement(expr)) {
892
- const childVar = processElement(
893
- expr,
894
- statements,
895
- genId,
896
- signals,
897
- hash,
898
- hydrate,
899
- childNodesVar,
900
- hydrate ? varName : undefined,
901
- );
902
- if (!hydrate) {
903
- statements.push(
904
- t.expressionStatement(
905
- t.callExpression(
906
- t.memberExpression(
907
- t.identifier(varName),
908
- t.identifier("append"),
909
- ),
910
- [t.identifier(childVar)],
911
- ),
912
- ),
913
- );
914
- }
915
- } else if (t.isJSXFragment(expr)) {
916
- const childVar = processFragment(
917
- expr,
918
- statements,
919
- genId,
920
- signals,
921
- hash,
922
- hydrate,
923
- childNodesVar,
924
- hydrate ? varName : undefined,
925
- );
926
- if (!hydrate) {
927
- statements.push(
928
- t.expressionStatement(
929
- t.callExpression(
930
- t.memberExpression(
931
- t.identifier(varName),
932
- t.identifier("append"),
933
- ),
934
- [t.identifier(childVar)],
935
- ),
936
- ),
937
- );
938
- }
939
- } else if (isPropRead(expr)) {
940
- // a prop may hold text, nodes or a deferred child, and may be a
941
- // getter over state: a live slot handles all of them
942
- statements.push(
943
- t.expressionStatement(
944
- t.callExpression(t.identifier("liveSlot"), [
945
- hydrate ? t.identifier(childNodesVar!) : t.arrayExpression([]),
946
- t.identifier(varName),
947
- t.arrowFunctionExpression([], expr),
948
- ]),
949
- ),
950
- );
951
- } else if (containsSignal(expr, signals)) {
952
- if (isPrimitive(expr)) {
953
- // fast path: text node + textContent
954
- buildTextNode(
955
- varName,
956
- expr,
957
- statements,
958
- genId,
959
- hydrate,
960
- childNodesVar,
961
- hydrate ? varName : undefined,
962
- );
963
- } else {
964
- // Check for keyed list pattern
965
- const keyed = findKeyedMapExpr(expr, signals);
966
- if (keyed) {
967
- buildKeyedList(
968
- varName,
969
- keyed,
970
- statements,
971
- genId,
972
- signals,
973
- processElement,
974
- hash,
975
- hydrate,
976
- childNodesVar,
977
- hydrate ? varName : undefined,
978
- );
979
- } else {
980
- buildAnchorMount(
981
- varName,
982
- expr,
983
- statements,
984
- genId,
985
- hydrate,
986
- childNodesVar,
987
- hydrate ? varName : undefined,
988
- );
989
- }
990
- }
991
- } else {
992
- // non-reactive: set once
993
- if (hydrate) {
994
- // hydrateSlot consumes the <!--g-->…<!--/g--> run and runs the
995
- // value against the content SSR put inside it, so both deferred
996
- // component children and inline JSX (`{list.map(…)}`) claim that
997
- // subtree. The value must stay lazy: evaluating it as an argument
998
- // would claim from the enclosing pool instead. Empty pool
999
- // (SPA nav) falls back to a fresh insert.
1000
- statements.push(
1001
- t.expressionStatement(
1002
- t.callExpression(t.identifier("hydrateSlot"), [
1003
- t.identifier(childNodesVar!),
1004
- t.identifier(varName),
1005
- t.arrowFunctionExpression([], expr),
1006
- ]),
1007
- ),
1008
- );
1009
- } else {
1010
- statements.push(
1011
- t.expressionStatement(
1012
- t.callExpression(t.identifier("insert"), [
1013
- t.identifier(varName),
1014
- expr,
1015
- ]),
1016
- ),
1017
- );
1018
- }
1019
- }
1020
- }
1021
- }
1022
-
1023
- pushInit(varName, initAfter, statements, hydrate);
1024
- statements.push(...liveAfter);
1025
-
1026
- return varName;
1027
- }
1
+ import { types as t } from "@babel/core";
2
+ //@ts-expect-error Not our problem babel forgot tp export types.
3
+ import { generate } from "@babel/generator";
4
+ import {
5
+ handleGlobalComponent,
6
+ isGlobalComponent,
7
+ } from "../handlers/dom/globals";
8
+ import { STATIC_USES } from "../../analysis/hydration.ts";
9
+ import { buildBind, buildProxyBind } from "../util/bind";
10
+ import { compileState } from "../util/compile-state.ts";
11
+ import { isPropRead } from "../util/props.ts";
12
+ import { warn } from "../util/warn.ts";
13
+ import { buildAnchorMount } from "./anchor-mount";
14
+ import { collectChildren } from "./children";
15
+ import { processFragment } from "./fragment";
16
+ import { buildKeyedList, findKeyedMapExpr } from "./keyed-list";
17
+ import { buildTextNode } from "./text-node";
18
+ import {
19
+ ATTR_MAP,
20
+ buildHydrationScope,
21
+ containsSignal,
22
+ getCreateElement,
23
+ hasJSX,
24
+ isPrimitive,
25
+ jsxText,
26
+ } from "./utils";
27
+
28
+ /**
29
+ * Dashed names (data-*, aria-*, custom attributes) have no IDL property —
30
+ * `el["data-x"] = v` sets a bare JS property the DOM never reflects, so the
31
+ * attribute is invisible to selectors, getAttribute, and CSS. They must go
32
+ * through setAttribute.
33
+ */
34
+ function isDashedAttr(attrName: string): boolean {
35
+ return attrName.includes("-");
36
+ }
37
+
38
+ function setAttrCall(
39
+ varName: string,
40
+ attrName: string,
41
+ value: t.Expression,
42
+ ): t.CallExpression {
43
+ return t.callExpression(
44
+ t.memberExpression(t.identifier(varName), t.identifier("setAttribute")),
45
+ [t.stringLiteral(attrName), value],
46
+ );
47
+ }
48
+
49
+ /**
50
+ * Route a prop write through the runtime setProp() helper. On HTML elements
51
+ * this is today's blind `el[name] = value`; on SVG-namespace elements it
52
+ * goes through setAttribute instead — IDL property assignment throws on real
53
+ * SVG elements (`svg.width = 15` hits a getter-only property), which crashed
54
+ * CSR renders the moment claim() started creating true-namespaced SVG.
55
+ */
56
+ function setPropCall(
57
+ varName: string,
58
+ attrName: string,
59
+ value: t.Expression,
60
+ ): t.CallExpression {
61
+ return t.callExpression(t.identifier("setProp"), [
62
+ t.identifier(varName),
63
+ t.stringLiteral(attrName),
64
+ value,
65
+ ]);
66
+ }
67
+
68
+ function isClaimedCall(varName: string): t.CallExpression {
69
+ return t.callExpression(t.identifier("isClaimed"), [t.identifier(varName)]);
70
+ }
71
+
72
+ function effect(body: t.Statement[]): t.ExpressionStatement {
73
+ return t.expressionStatement(
74
+ t.callExpression(t.identifier("createEffect"), [
75
+ t.arrowFunctionExpression([], t.blockStatement(body)),
76
+ ]),
77
+ );
78
+ }
79
+
80
+ /** Emit fresh-element-only writes; hydration guards them with isClaimed(). */
81
+ function pushInit(
82
+ varName: string,
83
+ init: t.Statement[],
84
+ statements: t.Statement[],
85
+ hydrate?: boolean,
86
+ ): void {
87
+ if (!init.length) return;
88
+ if (hydrate) {
89
+ statements.push(
90
+ t.ifStatement(
91
+ t.unaryExpression("!", isClaimedCall(varName)),
92
+ t.blockStatement(init),
93
+ ),
94
+ );
95
+ } else {
96
+ statements.push(...init);
97
+ }
98
+ }
99
+
100
+ /** A <script>'s children as one string expression, or null if it has none. */
101
+ function scriptText(node: t.JSXElement): t.Expression | null {
102
+ const parts: t.Expression[] = [];
103
+ for (const child of node.children) {
104
+ if (t.isJSXText(child)) {
105
+ const text = jsxText(child);
106
+ if (text !== null) parts.push(t.stringLiteral(text));
107
+ } else if (
108
+ t.isJSXExpressionContainer(child) &&
109
+ !t.isJSXEmptyExpression(child.expression)
110
+ ) {
111
+ parts.push(
112
+ t.logicalExpression("??", child.expression, t.stringLiteral("")),
113
+ );
114
+ }
115
+ }
116
+ if (!parts.length) return null;
117
+ return parts.reduce(
118
+ (a, b) => t.binaryExpression("+", a, b),
119
+ t.stringLiteral(""),
120
+ );
121
+ }
122
+
123
+ /**
124
+ * Build an object property key (identifier for valid names, string literal for dashed).
125
+ */
126
+ function attrKey(attrName: string): t.Identifier | t.StringLiteral {
127
+ if (/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(attrName)) {
128
+ return t.identifier(attrName);
129
+ }
130
+ return t.stringLiteral(attrName);
131
+ }
132
+
133
+ /**
134
+ * Add classList.add(hash) statement for scoped CSS.
135
+ */
136
+ function addScopedClass(
137
+ varName: string,
138
+ hash: string,
139
+ statements: t.Statement[],
140
+ ): void {
141
+ statements.push(
142
+ t.expressionStatement(
143
+ t.callExpression(
144
+ t.memberExpression(
145
+ t.memberExpression(t.identifier(varName), t.identifier("classList")),
146
+ t.identifier("add"),
147
+ ),
148
+ [t.stringLiteral(hash)],
149
+ ),
150
+ ),
151
+ );
152
+ }
153
+
154
+ export function processElement(
155
+ node: t.JSXElement,
156
+ statements: t.Statement[],
157
+ genId: () => string,
158
+ signals: Set<string>,
159
+ hash?: string,
160
+ hydrate?: boolean,
161
+ nodesVar?: string,
162
+ parentVar?: string,
163
+ ): string {
164
+ const varName = genId();
165
+ const tag = (node.openingElement.name as t.JSXIdentifier).name;
166
+ const isComponent = /^[A-Z]/.test(tag);
167
+
168
+ if (isComponent) {
169
+ // Global components: Window, Document, Body
170
+ if (isGlobalComponent(tag)) {
171
+ return handleGlobalComponent(tag, node, statements, genId);
172
+ }
173
+
174
+ // Component: call the function with a props object
175
+ const propsObj = t.objectExpression([]);
176
+
177
+ // Add attributes to props (including spread)
178
+ for (const attr of node.openingElement.attributes) {
179
+ if (t.isJSXSpreadAttribute(attr)) {
180
+ // {…obj} — spread into props
181
+ propsObj.properties.push(t.spreadElement(attr.argument));
182
+ continue;
183
+ }
184
+ if (!t.isJSXAttribute(attr)) continue;
185
+ const attrName = (attr.name as t.JSXIdentifier).name;
186
+
187
+ if (attr.value === null) {
188
+ // <Comp disabled /> → { disabled: true }
189
+ propsObj.properties.push(
190
+ t.objectProperty(attrKey(attrName), t.booleanLiteral(true)),
191
+ );
192
+ } else if (t.isStringLiteral(attr.value)) {
193
+ propsObj.properties.push(
194
+ t.objectProperty(attrKey(attrName), attr.value),
195
+ );
196
+ } else if (t.isJSXExpressionContainer(attr.value)) {
197
+ const expr = attr.value.expression as t.Expression;
198
+ // JSX in a prop (icon={<Icon />}, actions={<>…</>}) belongs
199
+ // wherever the component puts it, inside its own root. Built
200
+ // now, during hydration, it would claim from the caller's pool
201
+ // and could take the component's root element. Defer it like
202
+ // children: the component's {prop} slot runs the thunk against
203
+ // the right nodes.
204
+ if (hydrate && hasJSX(expr)) {
205
+ propsObj.properties.push(
206
+ t.objectProperty(
207
+ attrKey(attrName),
208
+ t.arrowFunctionExpression([], expr),
209
+ ),
210
+ );
211
+ } else if (containsSignal(expr, signals)) {
212
+ // a prop that reads state is passed as a getter, so the
213
+ // component reads the current value wherever it uses it
214
+ propsObj.properties.push(
215
+ t.objectMethod(
216
+ "get",
217
+ attrKey(attrName),
218
+ [],
219
+ t.blockStatement([t.returnStatement(expr)]),
220
+ ),
221
+ );
222
+ } else {
223
+ propsObj.properties.push(t.objectProperty(attrKey(attrName), expr));
224
+ }
225
+ }
226
+ }
227
+
228
+ // Add children to props
229
+ const childrenExpr = collectChildren(
230
+ node,
231
+ statements,
232
+ genId,
233
+ signals,
234
+ hash,
235
+ hydrate,
236
+ nodesVar,
237
+ );
238
+ if (childrenExpr) {
239
+ propsObj.properties.push(
240
+ t.objectProperty(t.identifier("children"), childrenExpr),
241
+ );
242
+ }
243
+
244
+ // through __component, so the call gets an owner for context
245
+ const componentCall = t.callExpression(t.identifier("__component"), [
246
+ t.identifier(tag),
247
+ propsObj,
248
+ ]);
249
+
250
+ if (hydrate && nodesVar && STATIC_USES.has(node)) {
251
+ // The analysis proved this use produces only HTML, and the server
252
+ // fenced it in <!--s-->…<!--/s-->. Cut that run out of the pool and
253
+ // never call the component: no claiming, no effects, no listeners.
254
+ // With nothing to skip (a client render, an empty pool) skipStatic
255
+ // returns null and the component runs as it always did.
256
+ statements.push(
257
+ t.variableDeclaration("let", [
258
+ t.variableDeclarator(
259
+ t.identifier(varName),
260
+ t.callExpression(t.identifier("skipStatic"), [t.identifier(nodesVar)]),
261
+ ),
262
+ ]),
263
+ );
264
+ const render: t.Statement[] = [
265
+ t.expressionStatement(
266
+ t.callExpression(t.identifier("pushHydrationNodes"), [t.identifier(nodesVar)]),
267
+ ),
268
+ t.expressionStatement(
269
+ t.assignmentExpression("=", t.identifier(varName), componentCall),
270
+ ),
271
+ t.expressionStatement(
272
+ t.callExpression(t.identifier("popHydrationNodes"), []),
273
+ ),
274
+ ];
275
+ if (parentVar) {
276
+ render.push(
277
+ t.ifStatement(
278
+ t.binaryExpression(
279
+ "===",
280
+ t.memberExpression(t.identifier(nodesVar), t.identifier("length")),
281
+ t.numericLiteral(0),
282
+ ),
283
+ t.expressionStatement(
284
+ t.callExpression(t.identifier("insert"), [
285
+ t.identifier(parentVar),
286
+ t.identifier(varName),
287
+ ]),
288
+ ),
289
+ ),
290
+ );
291
+ }
292
+ // Dev: render the skipped component once, detached, and throw if it was
293
+ // not really static. The analysis is conservative, and this is how a
294
+ // mistake in it shows up before it reaches production.
295
+ const probe = compileState.dev
296
+ ? t.blockStatement([
297
+ t.expressionStatement(
298
+ t.callExpression(t.identifier("probeStatic"), [
299
+ t.stringLiteral(tag),
300
+ t.arrowFunctionExpression([], t.cloneNode(componentCall, true)),
301
+ ]),
302
+ ),
303
+ ])
304
+ : null;
305
+ statements.push(
306
+ t.ifStatement(
307
+ t.unaryExpression("!", t.identifier(varName)),
308
+ t.blockStatement(render),
309
+ probe,
310
+ ),
311
+ );
312
+ return varName;
313
+ }
314
+
315
+ if (hydrate && nodesVar) {
316
+ // Push the parent's child pool before calling the component so that
317
+ // getHydrationNodes() inside the component returns the right scope.
318
+ // In SSR hydration the component claims its root node from that pool
319
+ // (it's already in the DOM). In empty-pool / SPA mode the component
320
+ // creates a fresh node, so we explicitly insert it when the pool is empty.
321
+ statements.push(
322
+ t.expressionStatement(
323
+ t.callExpression(t.identifier("pushHydrationNodes"), [
324
+ t.identifier(nodesVar),
325
+ ]),
326
+ ),
327
+ );
328
+ statements.push(
329
+ t.variableDeclaration("const", [
330
+ t.variableDeclarator(t.identifier(varName), componentCall),
331
+ ]),
332
+ );
333
+ statements.push(
334
+ t.expressionStatement(
335
+ t.callExpression(t.identifier("popHydrationNodes"), []),
336
+ ),
337
+ );
338
+ if (parentVar) {
339
+ // Insert only when the pool was empty (fresh DOM); if the pool had
340
+ // nodes the component already claimed its SSR element (already in DOM).
341
+ statements.push(
342
+ t.ifStatement(
343
+ t.binaryExpression(
344
+ "===",
345
+ t.memberExpression(
346
+ t.identifier(nodesVar),
347
+ t.identifier("length"),
348
+ ),
349
+ t.numericLiteral(0),
350
+ ),
351
+ t.expressionStatement(
352
+ t.callExpression(t.identifier("insert"), [
353
+ t.identifier(parentVar),
354
+ t.identifier(varName),
355
+ ]),
356
+ ),
357
+ ),
358
+ );
359
+ }
360
+ } else {
361
+ statements.push(
362
+ t.variableDeclaration("const", [
363
+ t.variableDeclarator(t.identifier(varName), componentCall),
364
+ ]),
365
+ );
366
+ }
367
+
368
+ return varName;
369
+ }
370
+
371
+ // Native element: claim (hydrate) or create (dom)
372
+ const currentNodesVar = nodesVar ?? "__nodes";
373
+ statements.push(
374
+ t.variableDeclaration("const", [
375
+ t.variableDeclarator(
376
+ t.identifier(varName),
377
+ getCreateElement(
378
+ tag,
379
+ !!hydrate,
380
+ currentNodesVar,
381
+ hydrate ? parentVar : undefined,
382
+ ),
383
+ ),
384
+ ]),
385
+ );
386
+
387
+ // In hydrate mode, scope to this element's children for descendants
388
+ let childNodesVar: string | undefined;
389
+ if (hydrate) {
390
+ childNodesVar = genId();
391
+ buildHydrationScope(varName, statements, childNodesVar);
392
+ }
393
+
394
+ // Attribute writes that only matter on a fresh element. When hydration
395
+ // claims server HTML they already happened there, and redoing them would
396
+ // wipe whatever a page script changed in the meantime.
397
+ const init: t.Statement[] = [];
398
+ // <select value> needs its options to exist first.
399
+ const initAfter: t.Statement[] = [];
400
+ const liveAfter: t.Statement[] = [];
401
+
402
+ // attributes
403
+ const seenAttrs = new Set<string>();
404
+ for (const attr of node.openingElement.attributes) {
405
+ if (t.isJSXSpreadAttribute(attr)) {
406
+ // {…obj}: listeners always, attributes unless hydration claimed
407
+ // the element (then the server already rendered them)
408
+ const args: t.Expression[] = [t.identifier(varName), attr.argument];
409
+ if (hydrate) args.push(t.unaryExpression("!", isClaimedCall(varName)));
410
+ statements.push(
411
+ t.expressionStatement(t.callExpression(t.identifier("spread"), args)),
412
+ );
413
+ continue;
414
+ }
415
+ if (!t.isJSXAttribute(attr)) continue;
416
+ let attrName: string;
417
+ let attrNamespace: string | undefined;
418
+ if (t.isJSXNamespacedName(attr.name)) {
419
+ attrNamespace = attr.name.namespace.name;
420
+ attrName = attr.name.name.name;
421
+ } else {
422
+ attrName = (attr.name as t.JSXIdentifier).name;
423
+ // bindValue -> bind:value, bindChecked -> bind:checked
424
+ if (/^bind[A-Z]/.test(attrName)) {
425
+ attrNamespace = "bind";
426
+ // bindScrollTop -> bind:scrollTop: only the first letter lowers
427
+ attrName = attrName.charAt(4).toLowerCase() + attrName.slice(5);
428
+ }
429
+ }
430
+ const realAttr = ATTR_MAP[attrName] ?? attrName;
431
+
432
+ if (seenAttrs.has(realAttr)) {
433
+ throw new TypeError(
434
+ `Duplicate attribute "${realAttr}" (via "${attrName}"). Use class or className, not both.`,
435
+ );
436
+ }
437
+ seenAttrs.add(realAttr);
438
+ if (
439
+ (attrNamespace === "transition" ||
440
+ attrNamespace === "in" ||
441
+ attrNamespace === "out") &&
442
+ t.isJSXExpressionContainer(attr.value)
443
+ ) {
444
+ // transition:fade={fade} / in:appear={x} / out:leave={[y, params]}
445
+ const expr = attr.value.expression as t.Expression;
446
+ statements.push(
447
+ t.expressionStatement(
448
+ t.callExpression(t.identifier("mountTransition"), [
449
+ t.identifier(varName),
450
+ expr,
451
+ t.stringLiteral(attrNamespace as "transition" | "in" | "out"),
452
+ ]),
453
+ ),
454
+ );
455
+ } else if (attrName === "use") {
456
+ // use={directive} or use={[directive, params]}
457
+ const expr = (attr.value as t.JSXExpressionContainer)
458
+ .expression as t.Expression;
459
+ statements.push(
460
+ t.expressionStatement(
461
+ t.callExpression(t.identifier("applyDirective"), [
462
+ t.identifier(varName),
463
+ expr,
464
+ ]),
465
+ ),
466
+ );
467
+ } else if (/^on[A-Z]/.test(attrName)) {
468
+ // Standard JSX: onClick, onSubmit, onMouseenter, etc.
469
+ // Convert camelCase to lowercase: onClick -> click, onMouseenter -> mouseenter
470
+ const event = attrName.slice(2).toLowerCase();
471
+ const handler = (attr.value as t.JSXExpressionContainer)
472
+ .expression as t.Expression;
473
+ statements.push(
474
+ t.expressionStatement(
475
+ t.callExpression(
476
+ t.memberExpression(
477
+ t.identifier(varName),
478
+ t.identifier("addEventListener"),
479
+ ),
480
+ [t.stringLiteral(event), handler],
481
+ ),
482
+ ),
483
+ );
484
+ } else if (attrNamespace === "bind") {
485
+ const bindProp = attrName;
486
+ const signal = (attr.value as t.JSXExpressionContainer)
487
+ .expression as t.Expression;
488
+
489
+ if (bindProp === "this") {
490
+ statements.push(
491
+ t.expressionStatement(
492
+ t.callExpression(
493
+ t.memberExpression(
494
+ (signal as t.CallExpression).callee as t.Expression,
495
+ t.identifier("set"),
496
+ ),
497
+ [t.identifier(varName)],
498
+ ),
499
+ ),
500
+ );
501
+ continue;
502
+ }
503
+
504
+ if (bindProp === "group") {
505
+ // Scan element attributes for type and value
506
+ let inputType = "";
507
+ let _inputValue: t.StringLiteral | undefined;
508
+ for (const a of node.openingElement.attributes) {
509
+ if (t.isJSXAttribute(a) && t.isJSXIdentifier(a.name)) {
510
+ if (a.name.name === "type" && t.isStringLiteral(a.value)) {
511
+ inputType = a.value.value;
512
+ }
513
+ if (a.name.name === "value" && t.isStringLiteral(a.value)) {
514
+ _inputValue = a.value;
515
+ }
516
+ }
517
+ }
518
+
519
+ if (inputType === "radio" || inputType === "") {
520
+ const isTopLevel =
521
+ t.isCallExpression(signal) &&
522
+ t.isIdentifier((signal as t.CallExpression).callee) &&
523
+ signals.has(
524
+ ((signal as t.CallExpression).callee as t.Identifier).name,
525
+ );
526
+
527
+ if (isTopLevel) {
528
+ const signalId = (signal as t.CallExpression)
529
+ .callee as t.Identifier;
530
+ statements.push(
531
+ t.expressionStatement(
532
+ t.callExpression(
533
+ t.memberExpression(
534
+ t.identifier(varName),
535
+ t.identifier("addEventListener"),
536
+ ),
537
+ [
538
+ t.stringLiteral("change"),
539
+ t.arrowFunctionExpression(
540
+ [],
541
+ t.callExpression(
542
+ t.memberExpression(signalId, t.identifier("set")),
543
+ [
544
+ t.memberExpression(
545
+ t.identifier(varName),
546
+ t.identifier("value"),
547
+ ),
548
+ ],
549
+ ),
550
+ ),
551
+ ],
552
+ ),
553
+ ),
554
+ );
555
+ }
556
+ } else if (inputType === "checkbox") {
557
+ const isTopLevel =
558
+ t.isCallExpression(signal) &&
559
+ t.isIdentifier((signal as t.CallExpression).callee) &&
560
+ signals.has(
561
+ ((signal as t.CallExpression).callee as t.Identifier).name,
562
+ );
563
+
564
+ if (isTopLevel) {
565
+ const callExpr = signal as t.CallExpression;
566
+ statements.push(
567
+ t.expressionStatement(
568
+ t.callExpression(
569
+ t.memberExpression(
570
+ t.identifier(varName),
571
+ t.identifier("addEventListener"),
572
+ ),
573
+ [
574
+ t.stringLiteral("change"),
575
+ t.arrowFunctionExpression(
576
+ [],
577
+ t.blockStatement([
578
+ t.ifStatement(
579
+ t.memberExpression(
580
+ t.identifier(varName),
581
+ t.identifier("checked"),
582
+ ),
583
+ // checked: push value into array
584
+ t.blockStatement([
585
+ t.expressionStatement(
586
+ t.callExpression(
587
+ t.memberExpression(
588
+ t.callExpression(callExpr, []),
589
+ t.identifier("push"),
590
+ ),
591
+ [
592
+ t.memberExpression(
593
+ t.identifier(varName),
594
+ t.identifier("value"),
595
+ ),
596
+ ],
597
+ ),
598
+ ),
599
+ ]),
600
+ // unchecked: splice value out of array
601
+ t.blockStatement([
602
+ t.expressionStatement(
603
+ t.callExpression(
604
+ t.memberExpression(
605
+ t.callExpression(callExpr, []),
606
+ t.identifier("splice"),
607
+ ),
608
+ [
609
+ t.callExpression(
610
+ t.memberExpression(
611
+ t.callExpression(callExpr, []),
612
+ t.identifier("indexOf"),
613
+ ),
614
+ [
615
+ t.memberExpression(
616
+ t.identifier(varName),
617
+ t.identifier("value"),
618
+ ),
619
+ ],
620
+ ),
621
+ t.numericLiteral(1),
622
+ ],
623
+ ),
624
+ ),
625
+ ]),
626
+ ),
627
+ ]),
628
+ ),
629
+ ],
630
+ ),
631
+ ),
632
+ );
633
+ }
634
+ } else {
635
+ warn(
636
+ attr,
637
+ `bind:group requires type="radio" or type="checkbox" on the element. ` +
638
+ `Got: type="${inputType}".`,
639
+ );
640
+ }
641
+ continue;
642
+ }
643
+
644
+ // Generic bind:innerHTML, bind:textContent, bind:value, bind:checked, etc.
645
+ const isTopLevelSignal =
646
+ t.isCallExpression(signal) &&
647
+ t.isIdentifier((signal as t.CallExpression).callee) &&
648
+ signals.has(((signal as t.CallExpression).callee as t.Identifier).name);
649
+
650
+ const isMemberOfSignal =
651
+ t.isMemberExpression(signal) &&
652
+ t.isCallExpression((signal as t.MemberExpression).object) &&
653
+ t.isIdentifier(
654
+ ((signal as t.MemberExpression).object as t.CallExpression).callee,
655
+ ) &&
656
+ signals.has(
657
+ (
658
+ ((signal as t.MemberExpression).object as t.CallExpression)
659
+ .callee as t.Identifier
660
+ ).name,
661
+ );
662
+
663
+ // bind:checked={item.done} in a list row, or {book.read} where `book`
664
+ // is a prop: the chain is rooted at a row item or a props object,
665
+ // and what it ends in is a property of a $state proxy
666
+ let root: t.Node = signal;
667
+ while (t.isMemberExpression(root)) root = root.object;
668
+ const isMemberOfItem =
669
+ t.isMemberExpression(signal) &&
670
+ t.isIdentifier(root) &&
671
+ signals.has(root.name);
672
+
673
+ if (isTopLevelSignal) {
674
+ buildBind(varName, bindProp, attr, statements);
675
+ } else if (isMemberOfSignal || isMemberOfItem) {
676
+ buildProxyBind(varName, bindProp, attr, statements, signal);
677
+ } else {
678
+ warn(
679
+ attr,
680
+ `bind:${bindProp}={...} requires a $state signal or $state object property. ` +
681
+ `Got: ${generate(signal).code}. ` +
682
+ `Hint: change to a $state() call.`,
683
+ );
684
+ }
685
+ } else if (attr.value === null) {
686
+ // bare attribute (<input disabled>, <div data-beacon>)
687
+ init.push(
688
+ t.expressionStatement(
689
+ isDashedAttr(realAttr)
690
+ ? setAttrCall(varName, realAttr, t.stringLiteral(""))
691
+ : setPropCall(varName, realAttr, t.booleanLiteral(true)),
692
+ ),
693
+ );
694
+ } else if (t.isStringLiteral(attr.value)) {
695
+ const stmt = t.expressionStatement(
696
+ setPropCall(varName, realAttr, t.stringLiteral(attr.value.value)),
697
+ );
698
+ (tag === "select" && realAttr === "value" ? initAfter : init).push(stmt);
699
+ } else if (t.isJSXExpressionContainer(attr.value)) {
700
+ const expr = attr.value.expression as t.Expression;
701
+ const afterChildren = tag === "select" && realAttr === "value";
702
+ // style={{ color: "red", fontSize: val }} — per-property writes
703
+ if (attrName === "style" && t.isObjectExpression(expr)) {
704
+ for (const prop of expr.properties) {
705
+ if (!t.isObjectProperty(prop)) continue;
706
+ const key = t.isIdentifier(prop.key)
707
+ ? prop.key.name
708
+ : t.isStringLiteral(prop.key)
709
+ ? prop.key.value
710
+ : null;
711
+ if (!key) continue;
712
+ const val = prop.value as t.Expression;
713
+ const write = t.expressionStatement(
714
+ t.callExpression(t.identifier("setStyleProp"), [
715
+ t.identifier(varName),
716
+ t.stringLiteral(key),
717
+ val,
718
+ ]),
719
+ );
720
+ if (containsSignal(val, signals)) {
721
+ statements.push(effect([write]));
722
+ } else {
723
+ init.push(write);
724
+ }
725
+ }
726
+ } else if (containsSignal(expr, signals)) {
727
+ // Dynamic class with scoped CSS: use classList.value to preserve hash
728
+ if (attrName === "class" && hash) {
729
+ statements.push(
730
+ effect([
731
+ t.expressionStatement(
732
+ t.assignmentExpression(
733
+ "=",
734
+ t.memberExpression(
735
+ t.memberExpression(
736
+ t.identifier(varName),
737
+ t.identifier("classList"),
738
+ ),
739
+ t.identifier("value"),
740
+ ),
741
+ expr,
742
+ ),
743
+ ),
744
+ t.expressionStatement(
745
+ t.callExpression(
746
+ t.memberExpression(
747
+ t.memberExpression(
748
+ t.identifier(varName),
749
+ t.identifier("classList"),
750
+ ),
751
+ t.identifier("add"),
752
+ ),
753
+ [t.stringLiteral(hash)],
754
+ ),
755
+ ),
756
+ ]),
757
+ );
758
+ } else {
759
+ const stmt = effect([
760
+ t.expressionStatement(setPropCall(varName, realAttr, expr)),
761
+ ]);
762
+ (afterChildren ? liveAfter : statements).push(stmt);
763
+ }
764
+ } else {
765
+ const stmt = t.expressionStatement(
766
+ setPropCall(varName, realAttr, expr),
767
+ );
768
+ (afterChildren ? initAfter : init).push(stmt);
769
+ }
770
+ }
771
+ }
772
+
773
+ pushInit(varName, init, statements, hydrate);
774
+
775
+ // Add scoped CSS hash to classList (if hash is present)
776
+ if (hash) {
777
+ addScopedClass(varName, hash, statements);
778
+ }
779
+
780
+ // children. <script> text is already in the server HTML, raw and unmarked
781
+ // (see ssr.ts), so hydration has nothing to claim there: the marker search
782
+ // would miss and append a second copy of the code.
783
+ if (hydrate && tag === "script") {
784
+ // ...but SPA navigation creates the element fresh and needs the text.
785
+ const text = scriptText(node);
786
+ if (text) {
787
+ const write = [
788
+ t.expressionStatement(
789
+ t.assignmentExpression(
790
+ "=",
791
+ t.memberExpression(
792
+ t.identifier(varName),
793
+ t.identifier("textContent"),
794
+ ),
795
+ text,
796
+ ),
797
+ ),
798
+ ];
799
+ pushInit(varName, write, statements, hydrate);
800
+ }
801
+ }
802
+ for (const child of hydrate && tag === "script" ? [] : node.children) {
803
+ if (t.isJSXElement(child)) {
804
+ const childVar = processElement(
805
+ child,
806
+ statements,
807
+ genId,
808
+ signals,
809
+ hash,
810
+ hydrate,
811
+ childNodesVar,
812
+ hydrate ? varName : undefined,
813
+ );
814
+ if (!hydrate) {
815
+ statements.push(
816
+ t.expressionStatement(
817
+ t.callExpression(
818
+ t.memberExpression(t.identifier(varName), t.identifier("append")),
819
+ [t.identifier(childVar)],
820
+ ),
821
+ ),
822
+ );
823
+ }
824
+ } else if (t.isJSXFragment(child)) {
825
+ const childVar = processFragment(
826
+ child,
827
+ statements,
828
+ genId,
829
+ signals,
830
+ hash,
831
+ hydrate,
832
+ childNodesVar,
833
+ hydrate ? varName : undefined,
834
+ );
835
+ if (!hydrate) {
836
+ statements.push(
837
+ t.expressionStatement(
838
+ t.callExpression(
839
+ t.memberExpression(t.identifier(varName), t.identifier("append")),
840
+ [t.identifier(childVar)],
841
+ ),
842
+ ),
843
+ );
844
+ }
845
+ } else if (t.isJSXText(child)) {
846
+ const text = jsxText(child, node.children);
847
+ if (text === null) continue;
848
+ if (hydrate) {
849
+ // SSR hydration: text already in DOM from SSR, do nothing.
850
+ // SPA navigation: childNodesVar pool is empty, create text node.
851
+ const poolLen = t.memberExpression(
852
+ t.identifier(childNodesVar!),
853
+ t.identifier("length"),
854
+ );
855
+ statements.push(
856
+ t.ifStatement(
857
+ t.binaryExpression("===", poolLen, t.numericLiteral(0)),
858
+ t.expressionStatement(
859
+ t.callExpression(
860
+ t.memberExpression(
861
+ t.identifier(varName),
862
+ t.identifier("append"),
863
+ ),
864
+ [
865
+ t.callExpression(
866
+ t.memberExpression(
867
+ t.identifier("document"),
868
+ t.identifier("createTextNode"),
869
+ ),
870
+ [t.stringLiteral(text)],
871
+ ),
872
+ ],
873
+ ),
874
+ ),
875
+ ),
876
+ );
877
+ } else {
878
+ statements.push(
879
+ t.expressionStatement(
880
+ t.callExpression(
881
+ t.memberExpression(t.identifier(varName), t.identifier("append")),
882
+ [
883
+ t.callExpression(
884
+ t.memberExpression(
885
+ t.identifier("document"),
886
+ t.identifier("createTextNode"),
887
+ ),
888
+ [t.stringLiteral(text)],
889
+ ),
890
+ ],
891
+ ),
892
+ ),
893
+ );
894
+ }
895
+ } else if (t.isJSXExpressionContainer(child)) {
896
+ if (t.isJSXEmptyExpression(child.expression)) continue;
897
+ const expr = child.expression as t.Expression;
898
+ if (t.isJSXElement(expr)) {
899
+ const childVar = processElement(
900
+ expr,
901
+ statements,
902
+ genId,
903
+ signals,
904
+ hash,
905
+ hydrate,
906
+ childNodesVar,
907
+ hydrate ? varName : undefined,
908
+ );
909
+ if (!hydrate) {
910
+ statements.push(
911
+ t.expressionStatement(
912
+ t.callExpression(
913
+ t.memberExpression(
914
+ t.identifier(varName),
915
+ t.identifier("append"),
916
+ ),
917
+ [t.identifier(childVar)],
918
+ ),
919
+ ),
920
+ );
921
+ }
922
+ } else if (t.isJSXFragment(expr)) {
923
+ const childVar = processFragment(
924
+ expr,
925
+ statements,
926
+ genId,
927
+ signals,
928
+ hash,
929
+ hydrate,
930
+ childNodesVar,
931
+ hydrate ? varName : undefined,
932
+ );
933
+ if (!hydrate) {
934
+ statements.push(
935
+ t.expressionStatement(
936
+ t.callExpression(
937
+ t.memberExpression(
938
+ t.identifier(varName),
939
+ t.identifier("append"),
940
+ ),
941
+ [t.identifier(childVar)],
942
+ ),
943
+ ),
944
+ );
945
+ }
946
+ } else if (isPropRead(expr)) {
947
+ // a prop may hold text, nodes or a deferred child, and may be a
948
+ // getter over state: a live slot handles all of them
949
+ statements.push(
950
+ t.expressionStatement(
951
+ t.callExpression(t.identifier("liveSlot"), [
952
+ hydrate ? t.identifier(childNodesVar!) : t.arrayExpression([]),
953
+ t.identifier(varName),
954
+ t.arrowFunctionExpression([], expr),
955
+ ]),
956
+ ),
957
+ );
958
+ } else if (containsSignal(expr, signals)) {
959
+ if (isPrimitive(expr)) {
960
+ // fast path: text node + textContent
961
+ buildTextNode(
962
+ varName,
963
+ expr,
964
+ statements,
965
+ genId,
966
+ hydrate,
967
+ childNodesVar,
968
+ hydrate ? varName : undefined,
969
+ );
970
+ } else {
971
+ // Check for keyed list pattern
972
+ const keyed = findKeyedMapExpr(expr, signals);
973
+ if (keyed) {
974
+ buildKeyedList(
975
+ varName,
976
+ keyed,
977
+ statements,
978
+ genId,
979
+ signals,
980
+ processElement,
981
+ hash,
982
+ hydrate,
983
+ childNodesVar,
984
+ hydrate ? varName : undefined,
985
+ );
986
+ } else {
987
+ buildAnchorMount(
988
+ varName,
989
+ expr,
990
+ statements,
991
+ genId,
992
+ hydrate,
993
+ childNodesVar,
994
+ hydrate ? varName : undefined,
995
+ );
996
+ }
997
+ }
998
+ } else {
999
+ // non-reactive: set once
1000
+ if (hydrate) {
1001
+ // hydrateSlot consumes the <!--g-->…<!--/g--> run and runs the
1002
+ // value against the content SSR put inside it, so both deferred
1003
+ // component children and inline JSX (`{list.map(…)}`) claim that
1004
+ // subtree. The value must stay lazy: evaluating it as an argument
1005
+ // would claim from the enclosing pool instead. Empty pool
1006
+ // (SPA nav) falls back to a fresh insert.
1007
+ statements.push(
1008
+ t.expressionStatement(
1009
+ t.callExpression(t.identifier("hydrateSlot"), [
1010
+ t.identifier(childNodesVar!),
1011
+ t.identifier(varName),
1012
+ t.arrowFunctionExpression([], expr),
1013
+ ]),
1014
+ ),
1015
+ );
1016
+ } else {
1017
+ statements.push(
1018
+ t.expressionStatement(
1019
+ t.callExpression(t.identifier("insert"), [
1020
+ t.identifier(varName),
1021
+ expr,
1022
+ ]),
1023
+ ),
1024
+ );
1025
+ }
1026
+ }
1027
+ }
1028
+ }
1029
+
1030
+ pushInit(varName, initAfter, statements, hydrate);
1031
+ statements.push(...liveAfter);
1032
+
1033
+ return varName;
1034
+ }