what-compiler 0.14.0 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +181 -2
  3. package/babel.d.ts +78 -2
  4. package/dist/babel/auto-selector.min.js +94 -0
  5. package/dist/babel/common.min.js +2053 -0
  6. package/dist/babel/dev-metadata.min.js +106 -0
  7. package/dist/babel/dom.min.js +1669 -0
  8. package/dist/babel/jsx-root.min.js +13 -0
  9. package/dist/babel/lists.min.js +492 -0
  10. package/dist/babel/nesting.min.js +328 -0
  11. package/dist/babel/reactivity.min.js +1218 -0
  12. package/dist/babel/server-actions.min.js +85 -0
  13. package/dist/babel/ssr.min.js +496 -0
  14. package/dist/babel/types.min.js +9 -0
  15. package/dist/babel-plugin.min.js +101 -1
  16. package/dist/file-router.min.js +368 -12
  17. package/dist/framework-files.min.js +62 -0
  18. package/dist/hot.min.js +315 -0
  19. package/dist/index.min.js +13 -414
  20. package/dist/release.min.js +78 -0
  21. package/dist/runtime.min.js +9 -1
  22. package/dist/tables/import-changes.min.js +272 -0
  23. package/dist/tables/markup-rules.min.js +213 -0
  24. package/dist/vite-plugin.min.js +432 -399
  25. package/file-router.d.ts +3 -1
  26. package/index.d.ts +1 -1
  27. package/package.json +11 -2
  28. package/runtime.d.ts +2 -1
  29. package/src/babel/auto-selector.js +248 -0
  30. package/src/babel/common.js +3800 -0
  31. package/src/babel/dev-metadata.js +167 -0
  32. package/src/babel/dom.js +3386 -0
  33. package/src/babel/jsx-root.js +27 -0
  34. package/src/babel/lists.js +704 -0
  35. package/src/babel/nesting.js +260 -0
  36. package/src/babel/reactivity.js +1998 -0
  37. package/src/babel/server-actions.js +144 -0
  38. package/src/babel/ssr.js +870 -0
  39. package/src/babel/types.js +10 -0
  40. package/src/babel-plugin.js +185 -3598
  41. package/src/file-router.js +58 -38
  42. package/src/framework-files.js +106 -0
  43. package/src/hot.js +523 -0
  44. package/src/release.js +127 -0
  45. package/src/runtime.js +7 -7
  46. package/src/tables/import-changes.js +157 -0
  47. package/src/tables/markup-rules.js +388 -0
  48. package/src/vite-plugin.js +460 -175
  49. package/vite.d.ts +47 -3
  50. package/src/error-overlay.js +0 -428
@@ -0,0 +1,3386 @@
1
+ // The DOM back end: JSX lowered to cloned templates, fine-grained bindings and
2
+ // keyed list inserters (what-framework/render).
3
+
4
+ import { RAW_TEXT_ELEMENTS, TEXT_ONLY_ELEMENTS, INNER_HTML_PROPS, ATTRIBUTE_ALIASES, attributeName, markupName, isEnumeratedAttr } from '../tables/markup-rules.js';
5
+ import { t } from './types.js';
6
+ import {
7
+ EVENT_OPTION_MODIFIERS, captureEventName, compileError, componentCallee, createEventHandler, eventType,
8
+ getAttrName, getAttributeValue, getBindingProperty, hasEventModifiers, controlFlowTag,
9
+ isBindingAttribute, isComponentElement, isConditionallyEvaluated, isDynamicAttr,
10
+ isEventAttrName, isFieldProp, isHydrateRootArgument, isShadowedAttr, isSlotAttribute, isStaticChild,
11
+ isVoidHtmlElement, normalizeJsxText, parseEventModifiers, propKey,
12
+ addImports, helper, helperLocals, readSwitch, uniqueName,
13
+ checkElementName, checkIslandProp, checkStaticAttribute, checkStaticRawText, directiveValue,
14
+ islandOptions, renderFunctionChild, diagnosticRecord, hostSpreadArgument,
15
+ } from './common.js';
16
+ import {
17
+ buildEachValue, buildWhenCondition, isHookResultRead, isPotentiallyReactive, isSignalIdentifier, isUncertainReactive,
18
+ } from './reactivity.js';
19
+ import { enterJsxRoot } from './jsx-root.js';
20
+ import { bindingMetadata, componentMetadata } from './dev-metadata.js';
21
+ import { findMappedJsx, islandKey, keyIndex, listSlot, liveKey, readItemThroughAccessor, rowField, rowItemUnread, withItem } from './lists.js';
22
+ import { hasNoSelectorPragma, lowerRowSelectors } from './auto-selector.js';
23
+
24
+
25
+ // Events that use document-level delegation for performance.
26
+ // The compiler emits `el.$$click = handler` instead of addEventListener.
27
+ // A one-time document listener walks event.target upward to find the handler.
28
+ // `$$change` is onChange, React's change event: a module that sets one
29
+ // installs it (`_$changes()`, what-core render.js), and a text field's
30
+ // `input` reaches it too.
31
+ const DELEGATED_EVENTS = new Set([
32
+ 'click', 'input', 'change', 'keydown', 'keyup', 'submit',
33
+ 'focusin', 'focusout', 'mousedown', 'mouseup',
34
+ ]);
35
+
36
+ const _forInfoWarned = new Set();
37
+
38
+ // --- Child layout ---
39
+ //
40
+ // An element's child positions, with fragments flattened (a fragment renders
41
+ // no node of its own, so its children are siblings of the fragment's
42
+ // siblings) and adjacent static text merged (two strings next to each other
43
+ // in the template parse as one text node). Static text and intrinsic elements
44
+ // are written into the template. A dynamic child (an expression, a component,
45
+ // <For>/<Show>) is inserted at runtime before a marker:
46
+ // - the next element, when one follows;
47
+ // - the next text node, when one follows and the template has no text right
48
+ // before this child (the two would merge into one node);
49
+ // - otherwise a `<!>` comment placeholder written right after it;
50
+ // - nothing (append, `null`) in the last position;
51
+ // - no marker at all (`undefined`) when it is the element's only child,
52
+ // which lets the runtime set text with a single textContent write.
53
+ // Each entry carries the template node index it occupies (text, element) or
54
+ // inserts before (dynamic), and a dynamic entry whether that node is the `<!>`
55
+ // written for it (`placeholder`). extractStaticHTML() builds the template from
56
+ // this layout and applyDynamicChildren() addresses nodes with it, so the two
57
+ // can never disagree.
58
+ // Rule credit: dom-expressions' marker placement (MIT, Ryan Carniato).
59
+ //
60
+ // With `withHtml`, `rawTag` names the <script> or <style> whose children these
61
+ // are, if any: its text is raw text, written as it is (checkStaticRawText).
62
+ //
63
+ // In an element whose content is text (`textOnly`: <title>, <textarea>,
64
+ // <script>, <style> in HTML) a comment is text too, so no `<!>` can stand
65
+ // there: where one would be written, the layout is made again (`textOnly`
66
+ // 2) with the children from the first dynamic one on as one dynamic child,
67
+ // an array of them, the static text as strings, and the template holds only
68
+ // the text before it.
69
+ /**
70
+ * @param {any[]} children
71
+ * @param {boolean} withHtml
72
+ * @param {any} state
73
+ * @param {string | null} [rawTag]
74
+ * @param {boolean | 2} [textOnly]
75
+ */
76
+ function layoutChildren(children, withHtml, state, rawTag = null, textOnly = false) {
77
+ const slots = [];
78
+ const flatten = (list) => {
79
+ for (const child of list) {
80
+ if (t.isJSXText(child)) {
81
+ const text = normalizeJsxText(child.value);
82
+ if (!text) continue;
83
+ const last = slots[slots.length - 1];
84
+ if (last && last.kind === 'text') last.text += text;
85
+ else slots.push({ kind: 'text', text, node: child });
86
+ } else if (t.isJSXFragment(child)) {
87
+ flatten(child.children);
88
+ } else if (t.isJSXExpressionContainer(child)) {
89
+ if (!t.isJSXEmptyExpression(child.expression)) slots.push({ kind: 'dynamic', node: child });
90
+ } else if (t.isJSXElement(child)) {
91
+ slots.push({ kind: isComponentElement(child) || liveKey(child, state) !== null ? 'dynamic' : 'element', node: child });
92
+ }
93
+ }
94
+ };
95
+ flatten(children);
96
+
97
+ let html = '';
98
+ let index = 0;
99
+ let afterText = false;
100
+ const entries = [];
101
+ for (let i = 0; i < slots.length; i++) {
102
+ const slot = slots[i];
103
+ if (textOnly === 2 && slot.kind !== 'text') {
104
+ const rest = slots.slice(i).map((r) => (r.kind === 'text' ? t.stringLiteral(r.text) : t.isJSXExpressionContainer(r.node) ? r.node.expression : r.node));
105
+ const node = rest.length === 1 ? slot.node : t.jsxExpressionContainer(t.arrayExpression(rest));
106
+ entries.push({ kind: 'dynamic', node, marker: i === 0 ? undefined : null, placeholder: false });
107
+ break;
108
+ }
109
+ if (slot.kind === 'text') {
110
+ if (withHtml && rawTag !== null) {
111
+ checkStaticRawText(slot.node, rawTag, slot.text, state);
112
+ html += slot.text;
113
+ } else if (withHtml) {
114
+ html += escapeHTML(slot.text);
115
+ }
116
+ entries.push({ kind: 'text', index });
117
+ index++;
118
+ afterText = true;
119
+ } else if (slot.kind === 'element') {
120
+ if (withHtml) html += extractStaticHTML(slot.node, state);
121
+ entries.push({ kind: 'element', node: slot.node, index });
122
+ index++;
123
+ afterText = false;
124
+ } else {
125
+ const next = slots[i + 1];
126
+ let marker;
127
+ let placeholder = false;
128
+ if (next === undefined) {
129
+ marker = slots.length === 1 ? undefined : null;
130
+ } else if (next.kind === 'element' || (next.kind === 'text' && !afterText)) {
131
+ marker = index;
132
+ } else {
133
+ if (textOnly) return layoutChildren(children, withHtml, state, rawTag, 2);
134
+ if (withHtml) html += '<!>';
135
+ marker = index;
136
+ placeholder = true;
137
+ index++;
138
+ afterText = false;
139
+ }
140
+ entries.push({ kind: 'dynamic', node: slot.node, marker, placeholder });
141
+ }
142
+ }
143
+ return { html, entries };
144
+ }
145
+
146
+ // --- Auto-lower .map() to mapArray ---
147
+ // Detects: source().map((item) => <Comp key={expr} .../>)
148
+ // or wrapped in an arrow: () => source().map(...)
149
+ // Also walks into ternary (cond ? a.map(...) : fallback) and
150
+ // logical (cond && a.map(...)) expressions so React-style
151
+ // conditional list patterns get keyed reconciliation.
152
+ // Produces: _$mapArray(source, (item) => <Comp .../>, { key: item => expr })
153
+ function tryLowerMapToMapArray(expr, state) {
154
+ state._noSelector = hasNoSelectorPragma(expr);
155
+ // Unwrap arrow function: () => source().map(...)
156
+ let mapCall = expr;
157
+ let wrappedInArrow = false;
158
+ if (t.isArrowFunctionExpression(expr) && expr.params.length === 0) {
159
+ mapCall = expr.body;
160
+ wrappedInArrow = true;
161
+ }
162
+
163
+ // Walk into ternary: cond ? arr().map(...) : fallback
164
+ if (t.isConditionalExpression(mapCall)) {
165
+ const loweredCon = tryLowerMapCall(mapCall.consequent, state);
166
+ const loweredAlt = tryLowerMapCall(mapCall.alternate, state);
167
+ if (loweredCon || loweredAlt) {
168
+ const result = t.conditionalExpression(
169
+ mapCall.test,
170
+ loweredCon || mapCall.consequent,
171
+ loweredAlt || mapCall.alternate
172
+ );
173
+ return wrappedInArrow ? t.arrowFunctionExpression([], result) : result;
174
+ }
175
+ return null;
176
+ }
177
+
178
+ // Walk into logical: cond && arr().map(...)
179
+ if (t.isLogicalExpression(mapCall) && (mapCall.operator === '&&' || mapCall.operator === '||')) {
180
+ const loweredRight = tryLowerMapCall(mapCall.right, state);
181
+ if (loweredRight) {
182
+ const result = t.logicalExpression(mapCall.operator, mapCall.left, loweredRight);
183
+ return wrappedInArrow ? t.arrowFunctionExpression([], result) : result;
184
+ }
185
+ return null;
186
+ }
187
+
188
+ // Direct .map() call
189
+ const lowered = tryLowerMapCall(mapCall, state);
190
+ return lowered;
191
+ }
192
+
193
+ // Core .map() lowering — extracted so it can be called per-branch
194
+ function tryLowerMapCall(mapCall, state) {
195
+ const found = findMappedJsx(mapCall, state, true);
196
+ if (!found) return null;
197
+ const { mapFn, returnExpr, keyAttr, keyValue } = found;
198
+ const attrs = returnExpr.openingElement.attributes;
199
+
200
+ // Remove the key prop from the JSX element (mapArray handles keying, not the DOM)
201
+ returnExpr.openingElement.attributes = attrs.filter(a => a !== keyAttr);
202
+
203
+ // `sel() === row.id` in the row's bindings → an O(1) selector lookup.
204
+ let leftmost = mapCall;
205
+ let optedOut = state._noSelector || state.opts?.autoSelector === false;
206
+ while (!optedOut && leftmost) {
207
+ optedOut = hasNoSelectorPragma(leftmost);
208
+ leftmost = t.isCallExpression(leftmost) || t.isOptionalCallExpression(leftmost) ? leftmost.callee
209
+ : t.isMemberExpression(leftmost) || t.isOptionalMemberExpression(leftmost) ? leftmost.object : null;
210
+ }
211
+ if (!optedOut) lowerRowSelectors(returnExpr, mapFn, state);
212
+
213
+ // Build the source: the object before .map() — wrap in an arrow for reactive access
214
+ const sourceObj = mapCall.callee.object;
215
+ const source = t.arrowFunctionExpression([], sourceObj);
216
+
217
+ // Build the key function: (item) => keyExpr.
218
+ // Clone both the parameter and the key expression — the parameter is shared
219
+ // with the user's map callback AST and keyValue may be referenced elsewhere
220
+ // in the tree. Cloning insulates this new arrow from later mutations.
221
+ const itemParam = mapFn.params[0] ? t.cloneNode(mapFn.params[0], true) : t.identifier('_item');
222
+ // A key that reads the index takes it too (lists.js keyIndex; what-core
223
+ // hands every key function the item's index).
224
+ const index = keyIndex(found);
225
+ const keyFn = t.arrowFunctionExpression(index === null ? [itemParam] : [itemParam, t.identifier(index)], t.cloneNode(keyValue, true));
226
+
227
+ // Build: _$mapArray(source, mapFn, { key: keyFn, follow: true }). A row that
228
+ // reads its item for more than its key reads it through an accessor
229
+ // (lists.js readItemThroughAccessor) and follows an item replaced under the
230
+ // same key (mapArray's follow mode); a row that reads only the key gets the
231
+ // raw item (`raw: true`).
232
+ const cellName = uniqueName(state, '_item$');
233
+ const follow = readItemThroughAccessor(mapFn, keyValue, () => helper(state, '_$item'), cellName, uniqueName(state, '_i$'));
234
+ // The element the row's callback returns is built with the row, in the
235
+ // row's own scope: a field in its template is the row's (fieldCall).
236
+ if (follow) returnExpr._whatRowCell = cellName;
237
+ // A row whose reads of its item cannot be found (lists.js rowItemUnread) is
238
+ // handed its item from the cell where it is built, `(cell, i) =>
239
+ // fn(_$item(cell), i)`: a read of the whole item while the row is built,
240
+ // so follow mode builds the row again for an item replaced under its key.
241
+ let rowFn = mapFn;
242
+ if (!follow && rowItemUnread(mapFn, keyValue)) {
243
+ const index = uniqueName(state, '_i$');
244
+ rowFn = t.arrowFunctionExpression([t.identifier(cellName), t.identifier(index)],
245
+ t.callExpression(mapFn, [t.callExpression(helper(state, '_$item'), [t.identifier(cellName)]), t.identifier(index)]));
246
+ }
247
+ const options = [
248
+ t.objectProperty(t.identifier('key'), keyFn),
249
+ t.objectProperty(t.identifier(follow || rowFn !== mapFn ? 'follow' : 'raw'), t.booleanLiteral(true)),
250
+ ];
251
+ if (follow && rowHoldsPlainFields(mapFn)) options.push(rowFieldsOption(state));
252
+ // The server's list has the same number (lists.js listSlot).
253
+ const slot = listSlot(mapCall);
254
+ if (slot !== null) options.push(t.objectProperty(t.identifier('slot'), slot));
255
+ const list = t.callExpression(helper(state, '_$mapArray'), [source, rowFn, t.objectExpression(options)]);
256
+ list._whatList = true;
257
+ return list;
258
+ }
259
+
260
+ // Whether a row built by `fn` (a keyed list's callback, its item reads already
261
+ // lowered) can hold a plain child that is a field of the row (what-core
262
+ // render.js _$plain, _$rowFields): it renders a component, which may read the
263
+ // item it is handed in a child of its own, or it holds a child that only
264
+ // reads, reads the item, and is not one field of it (`{row.a + row.b}`; one
265
+ // field is _$field's). A row with neither reaches no such child.
266
+ function rowHoldsPlainFields(fn) {
267
+ let found = false;
268
+ t.traverseFast(fn, (node) => {
269
+ if (found) return;
270
+ if (t.isJSXElement(node) && isComponentElement(node)) found = true;
271
+ else if (t.isJSXElement(node) || t.isJSXFragment(node)) {
272
+ found = node.children.some((child) => t.isJSXExpressionContainer(child) && isPlainRowRead(child.expression));
273
+ }
274
+ });
275
+ return found;
276
+ }
277
+
278
+ function isPlainRowRead(expr) {
279
+ if (!isPlainRead(expr) || rowField(expr) !== null) return false;
280
+ let reads = false;
281
+ t.traverseFast(expr, (node) => {
282
+ if (t.isCallExpression(node) && node.callee._whatRowItem === true) reads = true;
283
+ });
284
+ return reads;
285
+ }
286
+
287
+ // `fields: _$rowFields()`, in the options of a list whose rows can hold plain
288
+ // fields: the call installs the code that binds them when the list is made,
289
+ // so a program with no such list does not carry it. The runtime reads no
290
+ // option of that name.
291
+ function rowFieldsOption(state) {
292
+ return t.objectProperty(t.identifier('fields'), t.callExpression(helper(state, '_$rowFields'), []));
293
+ }
294
+
295
+
296
+ // An attribute value written without quotes: non-empty, none of the characters
297
+ // that end or change an unquoted value, and no `&` (left to the quoted form).
298
+ const UNQUOTED_ATTR_VALUE = /^[^\s"'=<>`&]+$/;
299
+
300
+ // The names an element's attributes after the spread at `index` write, as
301
+ // the spread's third argument (render.js spread skips them): `<a {...rest}
302
+ // href="/x" />` means href "/x" whatever `rest.href` becomes, as the later
303
+ // attribute wins in React, and a live `rest.href` re-bound by the spread
304
+ // overwrote it. A name and its alias (`class`, `className`) are one.
305
+ // Nothing when no attribute follows.
306
+ function writtenAfter(attributes, index) {
307
+ const names = new Set();
308
+ for (let i = index + 1; i < attributes.length; i++) {
309
+ const attr = attributes[i];
310
+ if (t.isJSXSpreadAttribute(attr)) continue;
311
+ const name = getAttrName(attr);
312
+ if (name === 'key' || isDirective(name)) continue;
313
+ // An event in lower case, the name the runtime compares (render.js spread).
314
+ if (isEventAttrName(name)) { names.add(name.toLowerCase()); continue; }
315
+ names.add(name);
316
+ const alias = attributeName(name);
317
+ if (alias !== name) names.add(alias);
318
+ for (const [prop, attrName] of ATTRIBUTE_ALIASES) if (attrName === name) names.add(prop);
319
+ // An XLink attribute in both spellings (`xlink:href`, `xlinkHref`).
320
+ if (name.startsWith('xlink') && name.length > 6) {
321
+ const local = name.slice(name[5] === ':' ? 6 : 5).toLowerCase();
322
+ names.add('xlink:' + local).add('xlink' + local[0].toUpperCase() + local.slice(1));
323
+ }
324
+ }
325
+ return names.size === 0 ? [] : [t.arrayExpression([...names].map((n) => t.stringLiteral(n)))];
326
+ }
327
+
328
+ // `bind:value`, `client:load`: compiler directives, never an element's prop.
329
+ function isDirective(name) {
330
+ return name.startsWith('bind:') || name.startsWith('client:');
331
+ }
332
+
333
+
334
+ // A spread whose object the code may build again with other keys
335
+ // (`{...attrs()}`, `{...props.attrs}`, a keyed row's item, a literal that
336
+ // reads state, a call whose arguments do): the runtime reads its sources
337
+ // again when what they read changes (render.js _$spreads). A name is read
338
+ // once, a props object or a rest of it keeping its own getters live.
339
+ function liveSpread(arg, state) {
340
+ if (t.isIdentifier(arg)) return false;
341
+ const reads = (node) => isPotentiallyReactive(node, state.signalNames, state.importedIdentifiers);
342
+ // A call handed arguments is made again where its callee or an argument
343
+ // reads state (`{...make(state())}`, `{...pick(props.kind)}`), as React
344
+ // calls it again in the render the state change causes; with arguments
345
+ // that read none (`{...register('title')}`) it is made once. So is a
346
+ // method named on what a hook returned (`{...form.register('title')}`):
347
+ // the object's field reads are live, its method is the same one.
348
+ if (t.isCallExpression(arg) && arg.arguments.length > 0 && arg.callee._whatRowItem !== true) {
349
+ const method = t.isMemberExpression(arg.callee) && !arg.callee.computed && t.isIdentifier(arg.callee.object)
350
+ && isHookResultRead(arg.callee, state.signalNames);
351
+ return (!method && reads(arg.callee)) || arg.arguments.some((a) => reads(t.isSpreadElement(a) ? a.argument : a));
352
+ }
353
+ return reads(arg);
354
+ }
355
+
356
+ // Whether the element's spreads are written as one merge of everything in
357
+ // source order (applyDynamicAttrs): two spreads or more, or one with an
358
+ // attribute before it that the template does not hold, so each name has one
359
+ // writer, the last (`<button {...rest} {...{ title: 'last', onClick: b }} />`,
360
+ // `<button onClick={own} {...rest} />`), as the props object React builds.
361
+ // One spread with attributes only after it skips their names instead
362
+ // (writtenAfter). An attribute that is not a plain prop (`bind:`, an event
363
+ // modifier) stays out of the merge (unmerged); a namespaced attribute
364
+ // (`xlink:href`) is one.
365
+ function mergesSpreads(attributes, tagName, state) {
366
+ const last = attributes.findLastIndex((a) => t.isJSXSpreadAttribute(a));
367
+ if (last === -1) return false;
368
+ let contested = false;
369
+ for (let i = 0; i < attributes.length; i++) {
370
+ const attr = attributes[i];
371
+ if (t.isJSXSpreadAttribute(attr)) {
372
+ if (i < last) contested = true;
373
+ continue;
374
+ }
375
+ const name = getAttrName(attr);
376
+ if (unmerged(name, state)) continue;
377
+ // A ref is applied as it is, beside the spreads' own (`ref={input}
378
+ // {...register('title')}` hands both the element).
379
+ if (i < last && name !== 'key' && name !== 'ref' && (!inTemplate(attributes, i, tagName) || fallsBack(attributes, i, state)) && !isShadowedAttr(attributes, i)) contested = true;
380
+ }
381
+ return contested;
382
+ }
383
+
384
+ // An attribute that is not a plain prop (`bind:value`, an event with
385
+ // modifiers): it has no place in a props object, and is applied as it is
386
+ // beside the merge of the others.
387
+ function unmerged(name, state) {
388
+ return isDirective(name) || name.includes('|') || (isEventAttrName(name) && hasEventModifiers(name, state));
389
+ }
390
+
391
+ // Whether a spread after `index` is read again (liveSpread): it may drop a
392
+ // name, and the attribute at `index` shows again (`<div title="fallback"
393
+ // {...attrs()} />`), so the attribute is one of its sources too, beside the
394
+ // template that holds it from the start (`multiple` before the options).
395
+ function fallsBack(attributes, index, state) {
396
+ return attributes.some((a, i) => i > index && t.isJSXSpreadAttribute(a) && liveSpread(a.argument, state));
397
+ }
398
+
399
+ // Whether the template holds the attribute at `index` (extractStaticHTML).
400
+ function inTemplate(attributes, index, tagName) {
401
+ const attr = attributes[index];
402
+ const name = getAttrName(attr);
403
+ return !t.isJSXExpressionContainer(attr.value) && isTemplateAttr(attributes, index, tagName) && !isShadowedAttr(attributes, index)
404
+ && name !== 'key' && !isEventAttrName(name) && !name.startsWith('bind:') && !name.includes('|');
405
+ }
406
+
407
+ // Extract the template markup for an intrinsic JSX element. The markup is
408
+ // minified the way the HTML parser allows: simple attribute values unquoted,
409
+ // no space after a quoted value, and (in getOrCreateTemplate) no closing tags
410
+ // at the end of the template, where end-of-input closes them.
411
+ // May a static attribute be baked into the template? The template is applied
412
+ // before anything else touches the element, so an attribute whose writer is
413
+ // ordered after another runtime writer of the same thing cannot be:
414
+ // - anything after a spread: `<div {...{id:'a'}} id="b"/>` means id="b",
415
+ // and baking it let the spread overwrite it;
416
+ // - class/className after a classList: `classList={{a: on()}} class="b"`
417
+ // means class "b" (the later write replaces the toggled class, as in h()
418
+ // and on the server), and baking it applied "b" first.
419
+ // - a form field's value, checked and defaults (isFieldProp).
420
+ // Those are set in source order by applyDynamicAttrs instead.
421
+ function isTemplateAttr(attributes, index, tagName) {
422
+ if (isFieldProp(tagName, attributes, index)) return false;
423
+ for (let i = 0; i < index; i++) {
424
+ const earlier = attributes[i];
425
+ if (t.isJSXSpreadAttribute(earlier)) return false;
426
+ if (getAttrName(earlier) === 'classList' && attributeName(getAttrName(attributes[index])) === 'class') return false;
427
+ }
428
+ return true;
429
+ }
430
+
431
+ function extractStaticHTML(node, state) {
432
+ if (!t.isJSXElement(node) || isComponentElement(node)) return '';
433
+ checkElementName(node, state);
434
+ const el = node.openingElement;
435
+ const tagName = el.name.name;
436
+ if (buildsField(tagName, el.attributes)) state.carriesFields = true;
437
+
438
+ let html = `<${tagName}`;
439
+ let afterQuote = false;
440
+
441
+ for (const [attrIndex, attr] of el.attributes.entries()) {
442
+ if (t.isJSXSpreadAttribute(attr)) continue;
443
+ if (!isTemplateAttr(el.attributes, attrIndex, tagName)) continue;
444
+ if (isShadowedAttr(el.attributes, attrIndex)) continue;
445
+ const name = getAttrName(attr);
446
+ if (name === 'key') continue;
447
+ // Case-insensitive: a static template is applied via innerHTML, so an
448
+ // `ONCLICK="alert(1)"` baked into the string becomes a live handler.
449
+ // Lowercase handlers are compiled separately; uppercase ones are dropped,
450
+ // matching how the runtime and SSR paths treat them.
451
+ if (isEventAttrName(name) || name.startsWith('bind:') || name.includes('|')) continue;
452
+ if (t.isJSXExpressionContainer(attr.value)) continue; // Dynamic attr — set via effect
453
+
454
+ const domName = markupName(name);
455
+ checkStaticAttribute(attr, domName, name, t.isStringLiteral(attr.value) ? attr.value.value : true, state);
456
+ const sep = afterQuote ? '' : ' ';
457
+ if (!attr.value && isEnumeratedAttr(domName)) {
458
+ // A valueless aria-* or data-* attribute is `true`, which those write
459
+ // as "true" (aria-hidden="" would mean no value at all), as the server
460
+ // target and the runtime write it.
461
+ html += `${sep}${domName}=true`;
462
+ afterQuote = false;
463
+ } else if (!attr.value) {
464
+ html += sep + domName;
465
+ afterQuote = false;
466
+ } else if (t.isStringLiteral(attr.value)) {
467
+ const value = attr.value.value;
468
+ if (UNQUOTED_ATTR_VALUE.test(value)) {
469
+ html += `${sep}${domName}=${value}`;
470
+ afterQuote = false;
471
+ } else {
472
+ html += `${sep}${domName}="${escapeAttr(value)}"`;
473
+ afterQuote = true;
474
+ }
475
+ }
476
+ }
477
+
478
+ // An HTML void element has no closing tag and no children. A closing tag
479
+ // would not be ignored either: `</br>` parses as a second <br>.
480
+ if (node._whatNs !== 'svg' && node._whatNs !== 'math' && isVoidHtmlElement(tagName)) {
481
+ return html + '>';
482
+ }
483
+ const rawTag = RAW_TEXT_ELEMENTS.has(tagName) && node._whatNs === 'html' ? tagName : null;
484
+ return `${html}>${layoutChildren(node.children, true, state, rawTag, isTextOnly(node)).html}</${tagName}>`;
485
+ }
486
+
487
+ // Whether `node`'s content is text, a comment included (layoutChildren).
488
+ function isTextOnly(node) {
489
+ const tag = node.openingElement.name.name;
490
+ return node._whatNs === 'html' && (RAW_TEXT_ELEMENTS.has(tag) || TEXT_ONLY_ELEMENTS.has(tag));
491
+ }
492
+
493
+ function escapeHTML(str) {
494
+ return str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
495
+ }
496
+
497
+ function escapeAttr(str) {
498
+ return str.replace(/&/g, '&amp;').replace(/"/g, '&quot;').replace(/</g, '&lt;').replace(/>/g, '&gt;');
499
+ }
500
+
501
+ // Analyze JSX tree and generate fine-grained output
502
+ function transformElementFineGrained(path, state) {
503
+ const { node } = path;
504
+ const openingElement = node.openingElement;
505
+ const tagName = openingElement.name.name;
506
+
507
+ // Control flow components, checked before generic isComponent since they start uppercase.
508
+ // What's own, under the name the file imported it as (common.js
509
+ // controlFlowTag); a tag imported from somewhere other than What is that
510
+ // package's component, whatever it is called, so it goes to the component
511
+ // path untouched, unless its own arms prove otherwise.
512
+ const flow = controlFlowTag(node, state);
513
+ if (flow === 'For') return transformForFineGrained(path, state);
514
+ if (flow === 'Show') return transformShowFineGrained(path, state);
515
+ if (flow === 'Switch') return transformSwitchFineGrained(path, state);
516
+
517
+ if (isComponentElement(node)) {
518
+ return transformComponentFineGrained(path, state);
519
+ }
520
+
521
+ // A key outside a list that can change (lists.js liveKey): the element is
522
+ // built in a reactive child that builds it again whenever the key's value
523
+ // changes (render.js _$keyed), as a component with one is.
524
+ const key = node._whatKeyed === true ? null : liveKey(node, state);
525
+ if (key !== null) {
526
+ node._whatKeyed = true;
527
+ const from = state._pendingSetup.length;
528
+ const el = transformElementFineGrained(path, state);
529
+ const setup = state._pendingSetup.splice(from);
530
+ const build = setup.length === 0 ? el : t.blockStatement([...setup, t.returnStatement(el)]);
531
+ return t.callExpression(helper(state, '_$keyed'), [t.arrowFunctionExpression([], key), t.arrowFunctionExpression([], build)]);
532
+ }
533
+
534
+ const attributes = openingElement.attributes;
535
+ const children = node.children;
536
+
537
+ // Check if this entire subtree is purely static
538
+ const allChildrenStatic = children.every(isStaticChild);
539
+ const allAttrsStatic = attributes.every((attr, i) => !isDynamicAttr(attr) && !isFieldProp(tagName, attributes, i));
540
+ const noEvents = attributes.every(attr => {
541
+ if (t.isJSXSpreadAttribute(attr)) return false;
542
+ const name = getAttrName(attr);
543
+ return !name?.startsWith('on') && !name?.startsWith('bind:');
544
+ });
545
+
546
+ if (allChildrenStatic && allAttrsStatic && noEvents) {
547
+ // Fully static element — extract to template, return clone call
548
+ const html = extractStaticHTML(node, state);
549
+ if (html) {
550
+ const tmplId = getOrCreateTemplate(state, html, node._whatNs, tagName);
551
+ return state.hydratable
552
+ ? t.callExpression(helper(state, '_$claim'), [t.identifier(tmplId)])
553
+ : t.callExpression(t.identifier(tmplId), []);
554
+ }
555
+ }
556
+
557
+ // Mixed static/dynamic element — extract template, add effects for dynamic parts
558
+ const html = extractStaticHTML(node, state);
559
+ if (!html) {
560
+ // Template extraction failed — emit a detailed compile warning and use h() as fallback
561
+ const loc = node.loc;
562
+ const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
563
+ const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
564
+ console.warn(
565
+ `[what-compiler] Could not extract template for <${tagName}> at ${fileName}${lineInfo}. ` +
566
+ `Falling back to h() for this element. ` +
567
+ `This element could not be statically analyzed. Consider simplifying the JSX.`
568
+ );
569
+ return transformElementAsH(path, state);
570
+ }
571
+
572
+ const tmplId = getOrCreateTemplate(state, html, node._whatNs, tagName);
573
+
574
+ const elId = state.nextVarId();
575
+
576
+ // Build statements: _el$ = _tmpl$1()
577
+ // NO IIFE wrapping — statements are inlined into the containing function.
578
+ // A hydratable build claims the root instead (see applyDynamicChildren).
579
+ const acquire = state.hydratable
580
+ ? t.callExpression(helper(state, FORM_CONTROLS.has(tagName) ? '_$claimControl' : '_$claim'), [t.identifier(tmplId)])
581
+ : t.callExpression(t.identifier(tmplId), []);
582
+ const statements = [
583
+ t.variableDeclaration('const', [
584
+ t.variableDeclarator(t.identifier(elId), acquire)
585
+ ])
586
+ ];
587
+
588
+ // Apply dynamic attributes and events
589
+ applyDynamicAttrs(statements, elId, attributes, state, tagName, node._whatNs);
590
+
591
+ // Handle dynamic children
592
+ const rootFlags = (applyDynamicChildren(statements, elId, children, node, state, node._whatRowCell) ? 1 : 0) | (writesContent(attributes) ? 2 : 0);
593
+ if (state.hydratable) claimArguments(acquire, rootFlags, FORM_CONTROLS.has(tagName) ? null : ownedAttrs(attributes, tagName, node._whatNs));
594
+
595
+ // Instead of wrapping in an IIFE, store setup statements for hoisting.
596
+ // The JSXElement visitor will insert them before the enclosing statement.
597
+ if (!state._pendingSetup) state._pendingSetup = [];
598
+ state._pendingSetup.push(...statements);
599
+ return t.identifier(elId);
600
+ }
601
+
602
+ // A hydratable claim's arguments after the template or the count of static
603
+ // children it steps over: its flags (what-core render.js _$claim, _$next),
604
+ // then the attributes its bindings own (ownedAttrs), when there are any.
605
+ function claimArguments(call, flags, owned) {
606
+ if (flags !== 0 || owned !== null) call.arguments.push(t.numericLiteral(flags));
607
+ if (owned !== null) call.arguments.push(t.stringLiteral(owned));
608
+ }
609
+
610
+ // The attributes of a claimed element whose bindings write them in full on
611
+ // their first run, whatever the server wrote: a class (_$className,
612
+ // _$setClass), a data-* or aria-* attribute (_$setAttr), and an id or a title
613
+ // (_$setProp, through a property the attribute reflects, or the attribute).
614
+ // Hydration leaves the server's to them (what-core render.js
615
+ // keepTemplateAttrs) instead of removing it for the binding to write again.
616
+ // Their names separated by spaces, or null: none on an element with a spread
617
+ // or a classList, a custom element, a select or an option, or outside HTML
618
+ // and SVG.
619
+ function ownedAttrs(attributes, tagName, ns) {
620
+ if ((ns !== 'html' && ns !== 'svg') || tagName.includes('-') || SELECT_TAGS.has(tagName)) return null;
621
+ const names = [];
622
+ for (const [index, attr] of attributes.entries()) {
623
+ if (t.isJSXSpreadAttribute(attr)) return null;
624
+ const name = getAttrName(attr);
625
+ if (name === 'classList') return null;
626
+ if (!t.isJSXExpressionContainer(attr.value) || isShadowedAttr(attributes, index) || isBindingAttribute(name)) continue;
627
+ const written = attributeName(name);
628
+ if ((written === 'class' || written === 'id' || written === 'title' || isEnumeratedAttr(written)) && !names.includes(written)) names.push(written);
629
+ }
630
+ return names.length > 0 ? names.join(' ') : null;
631
+ }
632
+
633
+ // Fallback: transform element using h() when template extraction fails
634
+ function transformElementAsH(path, state) {
635
+ const { node } = path;
636
+ const openingElement = node.openingElement;
637
+ const tagName = openingElement.name.name;
638
+ const attributes = openingElement.attributes;
639
+ const children = node.children;
640
+
641
+ const props = [];
642
+ for (const attr of attributes) {
643
+ if (t.isJSXSpreadAttribute(attr)) continue;
644
+ const attrName = getAttrName(attr);
645
+ const value = getAttributeValue(attr.value);
646
+ let domAttrName = attributeName(attrName);
647
+ props.push(
648
+ t.objectProperty(
649
+ /^[a-zA-Z_$][a-zA-Z0-9_$]*$/.test(domAttrName)
650
+ ? t.identifier(domAttrName)
651
+ : t.stringLiteral(domAttrName),
652
+ value
653
+ )
654
+ );
655
+ }
656
+
657
+ const transformedChildren = [];
658
+ for (const child of children) {
659
+ if (t.isJSXText(child)) {
660
+ const text = normalizeJsxText(child.value);
661
+ if (text) transformedChildren.push(t.stringLiteral(text));
662
+ } else if (t.isJSXExpressionContainer(child)) {
663
+ if (!t.isJSXEmptyExpression(child.expression)) {
664
+ transformedChildren.push(child.expression);
665
+ }
666
+ } else if (t.isJSXElement(child)) {
667
+ transformedChildren.push(transformElementFineGrained({ node: child }, state));
668
+ } else if (t.isJSXFragment(child)) {
669
+ transformedChildren.push(transformFragmentFineGrained({ node: child }, state));
670
+ }
671
+ }
672
+
673
+ const propsExpr = props.length > 0 ? t.objectExpression(props) : t.nullLiteral();
674
+ return t.callExpression(helper(state, 'h'), [t.stringLiteral(tagName), propsExpr, ...transformedChildren]);
675
+ }
676
+
677
+ // ref={...}. An inline function is called with the element. Anything else
678
+ // goes through applyRef, evaluated once: a callback is called, a ref object
679
+ // gets `.current`. A `let`/`var` binding is assigned the element when it does
680
+ // not already hold a callback or a ref object (`let el; <div ref={el}>`),
681
+ // which needs the assignment written out here.
682
+ function buildRef(refExpr, elId, state) {
683
+ if (t.isArrowFunctionExpression(refExpr) || t.isFunctionExpression(refExpr)) {
684
+ return t.callExpression(refExpr, [t.identifier(elId)]);
685
+ }
686
+ const call = t.callExpression(helper(state, '_$applyRef'), [refExpr, t.identifier(elId)]);
687
+ if (t.isIdentifier(refExpr)) {
688
+ const binding = state._jsxScope && state._jsxScope.getBinding(refExpr.name);
689
+ if (binding && (binding.kind === 'let' || binding.kind === 'var')) {
690
+ // Once the variable holds the element of an earlier render (a branch
691
+ // that re-creates it), it is an object, and applyRef would treat it as
692
+ // a ref object and write `.current` onto the detached element. An
693
+ // element is replaced; a callback or a ref object it still holds is
694
+ // applied as usual.
695
+ // el = el != null && el.nodeType > 0 ? _el$0 : _$applyRef(el, _el$0)
696
+ const name = refExpr.name;
697
+ return t.assignmentExpression('=', t.identifier(name), t.conditionalExpression(
698
+ t.logicalExpression('&&',
699
+ t.binaryExpression('!=', t.identifier(name), t.nullLiteral()),
700
+ t.binaryExpression('>', t.memberExpression(t.identifier(name), t.identifier('nodeType')), t.numericLiteral(0))),
701
+ t.identifier(elId),
702
+ call,
703
+ ));
704
+ }
705
+ }
706
+ return call;
707
+ }
708
+
709
+ // Tags where `value` / `checked` are live DOM properties the user expects a
710
+ // dynamic binding to drive (input.value, select.value, input.checked, ...).
711
+ // Other tags keep the generic setProp path (e.g. <div value={x}> sets an
712
+ // attribute, <li value={n}> hits the `key in el` property branch).
713
+ const VALUE_PROP_TAGS = new Set(['input', 'textarea', 'select', 'option']);
714
+ // The form fields a `value` or `checked` prop controls.
715
+ const FIELD_TAGS = new Set(['input', 'textarea', 'select']);
716
+ // The elements whose props the selection code of what-core keeps in step.
717
+ const SELECT_TAGS = new Set(['select', 'option']);
718
+
719
+ function applyDynamicAttrs(statements, elId, attributes, state, tagName, ns) {
720
+ if (ns === 'svg' && attributes.some((a) => t.isJSXSpreadAttribute(a) || (/^x(?:link|ml(?!ns))/.test(getAttrName(a)) && t.isJSXExpressionContainer(a.value)))) state.writesXlink = true;
721
+ // Specialized monomorphic setters for statically-known attribute names.
722
+ // The generic _$setProp re-dispatches on the key string
723
+ // (ref/key/url/class/style/innerHTML/boolean/...) on EVERY reactive update;
724
+ // when the compiler knows the name it emits the direct helper instead.
725
+ // SECURITY: URL attributes (href/src/action/formaction) and innerHTML/
726
+ // dangerouslySetInnerHTML intentionally fall through to _$setProp — URL
727
+ // sanitization and the { __html } enforcement live there.
728
+ // `bound`: the call is made in the effect of a binding (bindingEffect).
729
+ function buildSetPropCall(propName, valueExpr, bound) {
730
+ // A prop of a select or an option brings the code that keeps the
731
+ // selection (what-core _$selects, written once at module scope).
732
+ if (SELECT_TAGS.has(tagName)) state.makesSelects = true;
733
+ // A value or checked a binding writes to a form field: the field shows it
734
+ // again after each of its events when the binding read state (what-core
735
+ // setValue, _controlFields). A value written once is where the field
736
+ // starts.
737
+ const binding = bound && FIELD_TAGS.has(tagName) ? [t.numericLiteral(1)] : [];
738
+ if (propName === 'class') {
739
+ // attributeName already mapped className → class. The template
740
+ // decided this element's namespace, so only an SVG element needs the
741
+ // setter that writes the attribute instead of `className`.
742
+ if (ns === 'svg') {
743
+ return t.callExpression(helper(state, '_$setClass'), [t.identifier(elId), valueExpr]);
744
+ }
745
+ return t.callExpression(helper(state, '_$className'), [t.identifier(elId), valueExpr]);
746
+ }
747
+ if (propName === 'classList') {
748
+ return t.callExpression(helper(state, '_$setClassList'), [t.identifier(elId), valueExpr]);
749
+ }
750
+ if (propName === 'style') {
751
+ return t.callExpression(helper(state, '_$setStyle'), [t.identifier(elId), valueExpr]);
752
+ }
753
+ if (propName === 'value' && tagName && VALUE_PROP_TAGS.has(tagName)) {
754
+ return t.callExpression(helper(state, '_$setValue'), [t.identifier(elId), valueExpr, ...binding]);
755
+ }
756
+ if (propName === 'checked' && tagName === 'input') {
757
+ // Live property write — matches bind:checked semantics. (The old
758
+ // setAttribute('checked') path only set the DEFAULT-checked state,
759
+ // which stops reflecting once the user has toggled the input.)
760
+ // A helper (not a raw `.checked =`) so function values still get
761
+ // reactive-accessor treatment, like every other setter.
762
+ return t.callExpression(helper(state, '_$setChecked'), [t.identifier(elId), valueExpr, ...binding]);
763
+ }
764
+ // An input's type and a select's multiple: a write that changes one
765
+ // writes the field's value and checked again (what-core _$retype), as
766
+ // `type={kind()} value="abc"` shows `abc` again once `date` gives way to
767
+ // `text`. An HTML element's attribute names fold their case (`TYPE`).
768
+ const folded = propName.toLowerCase();
769
+ if ((folded === 'type' && tagName === 'input') || (folded === 'multiple' && tagName === 'select')) {
770
+ return t.callExpression(helper(state, '_$retype'), [t.identifier(elId), t.stringLiteral(propName), valueExpr]);
771
+ }
772
+ if (isEnumeratedAttr(propName)) {
773
+ return t.callExpression(helper(state, '_$setAttr'), [
774
+ t.identifier(elId),
775
+ t.stringLiteral(propName),
776
+ valueExpr
777
+ ]);
778
+ }
779
+ return t.callExpression(helper(state, '_$setProp'), [
780
+ t.identifier(elId),
781
+ t.stringLiteral(propName),
782
+ valueExpr
783
+ ]);
784
+ }
785
+
786
+ // _$effect(fn), named "tag.prop@loc" in a development build.
787
+ function bindingEffect(fn, what, node) {
788
+ const args = [fn];
789
+ const name = bindingMetadata(tagName, what, node, state);
790
+ if (name) args.push(t.objectExpression([
791
+ t.objectProperty(t.identifier('name'), name),
792
+ t.objectProperty(t.identifier('binding'), t.identifier(elId)),
793
+ ]));
794
+ return t.callExpression(helper(state, '_$effect'), args);
795
+ }
796
+
797
+ // Lazy delegation init (C6): an element that is assigned a delegated
798
+ // `$$event` handler calls the module's once-guarded _$delegate$() helper at
799
+ // construction time, which also marks the element's handlers as the current
800
+ // owner's (render.js _$own). Emitted at most once per element.
801
+ let delegateInitEmitted = false;
802
+ function emitDelegateInit() {
803
+ if (delegateInitEmitted) return;
804
+ delegateInitEmitted = true;
805
+ statements.push(
806
+ t.expressionStatement(t.callExpression(helper(state, '_$delegate$'), [t.identifier(elId)]))
807
+ );
808
+ }
809
+
810
+ // Spreads with other writers before them: one props object, merged in
811
+ // source order (mergesSpreads). An attribute is a property of it, a getter
812
+ // where its value reads state; a ref written on the element is applied
813
+ // after it, as it is (one after the last spread is the only one: the
814
+ // merge's own is skipped).
815
+ if (mergesSpreads(attributes, tagName, state)) {
816
+ if (SELECT_TAGS.has(tagName)) state.makesSelects = true;
817
+ const parts = [];
818
+ /** @type {any} */
819
+ let literal = null;
820
+ const refs = [];
821
+ const separate = [];
822
+ const last = attributes.findLastIndex((a) => t.isJSXSpreadAttribute(a));
823
+ for (const [attrIndex, attr] of attributes.entries()) {
824
+ if (t.isJSXSpreadAttribute(attr)) {
825
+ parts.push(hostSpreadArgument(attr));
826
+ literal = null;
827
+ continue;
828
+ }
829
+ const name = getAttrName(attr);
830
+ if (unmerged(name, state)) {
831
+ separate.push(attr);
832
+ continue;
833
+ }
834
+ // A later attribute of the same name is its only writer (isShadowedAttr).
835
+ if (name === 'key' || (inTemplate(attributes, attrIndex, tagName) && !fallsBack(attributes, attrIndex, state)) || isShadowedAttr(attributes, attrIndex)) continue;
836
+ const value = getAttributeValue(attr.value);
837
+ if (name === 'ref') {
838
+ refs.push([t.expressionStatement(buildRef(value, elId, state)), attrIndex > last]);
839
+ continue;
840
+ }
841
+ const live = t.isJSXExpressionContainer(attr.value) && !t.isFunction(value) && isPotentiallyReactive(value, state.signalNames, state.importedIdentifiers);
842
+ if (literal === null) parts.push(literal = t.objectExpression([t.objectProperty(t.identifier('__proto__'), t.nullLiteral())]));
843
+ literal.properties.push(live
844
+ ? t.objectMethod('get', propKey(name), [], t.blockStatement([t.returnStatement(value)]))
845
+ : t.objectProperty(propKey(name), value));
846
+ }
847
+ // The sources in source order; read again where one may be built again
848
+ // with other keys (liveSpread).
849
+ const sources = t.arrayExpression(parts);
850
+ statements.push(t.expressionStatement(t.callExpression(helper(state, '_$spreads'), [
851
+ FIELD_TAGS.has(tagName) ? t.callExpression(helper(state, '_$controlled'), [t.identifier(elId)]) : t.identifier(elId),
852
+ attributes.some((a) => t.isJSXSpreadAttribute(a) && liveSpread(a.argument, state)) ? t.arrowFunctionExpression([], sources) : sources,
853
+ // A ref after the last spread is the element's only one.
854
+ ...(refs.some(([, after]) => after) ? [t.arrayExpression([t.stringLiteral('ref')])] : []),
855
+ ])), ...refs.map(([statement]) => statement));
856
+ if (separate.length > 0) applyDynamicAttrs(statements, elId, separate, state, tagName, ns);
857
+ return;
858
+ }
859
+
860
+ // Static attributes the template holds are already applied (isTemplateAttr).
861
+ // The rest are set here, in source order, so the last write for a key wins
862
+ // exactly as it does in the h() call.
863
+ for (const [attrIndex, attr] of attributes.entries()) {
864
+ if (t.isJSXSpreadAttribute(attr)) {
865
+ if (SELECT_TAGS.has(tagName)) state.makesSelects = true;
866
+ statements.push(
867
+ t.expressionStatement(
868
+ // A spread on a form field may bind its value or checked to state:
869
+ // the field then shows what they hold after its events (what-core
870
+ // _$controlled).
871
+ // One that may be built again with other keys is read again
872
+ // (liveSpread, what-core _$spreads).
873
+ liveSpread(attr.argument, state)
874
+ ? t.callExpression(helper(state, '_$spreads'), [FIELD_TAGS.has(tagName) ? t.callExpression(helper(state, '_$controlled'), [t.identifier(elId)]) : t.identifier(elId),
875
+ t.arrowFunctionExpression([], t.arrayExpression([hostSpreadArgument(attr)])), ...writtenAfter(attributes, attrIndex)])
876
+ : t.callExpression(helper(state, '_$spread'), [FIELD_TAGS.has(tagName) ? t.callExpression(helper(state, '_$controlled'), [t.identifier(elId)]) : t.identifier(elId), hostSpreadArgument(attr), ...writtenAfter(attributes, attrIndex)])
877
+ )
878
+ );
879
+ continue;
880
+ }
881
+
882
+ // A later attribute of the same name is the only writer that matters.
883
+ // Emitting this one too would apply it after the template and let it win.
884
+ if (isShadowedAttr(attributes, attrIndex)) continue;
885
+
886
+ const attrName = getAttrName(attr);
887
+
888
+ // `key` is not an attribute: the list lowering reads a .map() row's key
889
+ // before this runs, and on any other element it does nothing.
890
+ if (attrName === 'key') continue;
891
+
892
+ // Ref handling — assign element to ref object/callback
893
+ if (attrName === 'ref') {
894
+ statements.push(t.expressionStatement(buildRef(getAttributeValue(attr.value), elId, state)));
895
+ continue;
896
+ }
897
+
898
+ // Event handlers
899
+ if (attrName.startsWith('on') && !attrName.includes('|') && !hasEventModifiers(attrName, state)) {
900
+ // `onClickCapture` is a listener in the capture phase, which delegation
901
+ // (the bubble phase, at the document) cannot give.
902
+ const captured = captureEventName(attrName);
903
+ const event = eventType(captured ?? attrName);
904
+ const handler = getAttributeValue(attr.value);
905
+ const metadata = bindingMetadata(tagName, attrName, attr, state);
906
+ if (metadata) {
907
+ statements.push(t.expressionStatement(t.assignmentExpression('=',
908
+ t.memberExpression(t.identifier(elId), t.stringLiteral(`_$source_${event}`), true),
909
+ metadata
910
+ )));
911
+ }
912
+
913
+ if (captured === null && DELEGATED_EVENTS.has(event)) {
914
+ // Use event delegation: el.$$click = handler (matches runtime lookup)
915
+ if (!state.delegatedEvents) state.delegatedEvents = new Set();
916
+ state.delegatedEvents.add(event);
917
+ emitDelegateInit();
918
+ statements.push(
919
+ t.expressionStatement(
920
+ t.assignmentExpression('=',
921
+ t.memberExpression(
922
+ t.identifier(elId),
923
+ t.identifier(`$$${event}`)
924
+ ),
925
+ handler
926
+ )
927
+ )
928
+ );
929
+ } else {
930
+ // Non-delegated: a listener per element, which its owner removes.
931
+ statements.push(
932
+ t.expressionStatement(
933
+ t.callExpression(helper(state, '_$on'), [t.identifier(elId), t.stringLiteral(event), handler,
934
+ ...(captured === null ? [] : [t.booleanLiteral(true)])])
935
+ )
936
+ );
937
+ }
938
+ continue;
939
+ }
940
+
941
+ // Event with modifiers (pipe '|' or JSX-safe double underscore '__')
942
+ if (attrName.startsWith('on') && (attrName.includes('|') || hasEventModifiers(attrName, state))) {
943
+ const { eventName, modifiers } = parseEventModifiers(attrName);
944
+ const handler = getAttributeValue(attr.value);
945
+ const wrappedHandler = createEventHandler(handler, modifiers);
946
+ const captured = captureEventName(eventName);
947
+ const event = eventType(captured ?? eventName);
948
+
949
+ const optionMods = modifiers.filter(m => EVENT_OPTION_MODIFIERS.has(m));
950
+ if (captured !== null && !optionMods.includes('capture')) optionMods.push('capture');
951
+ const addEventArgs = [t.stringLiteral(event), wrappedHandler];
952
+ if (optionMods.length > 0) {
953
+ const optsProps = optionMods.map(m =>
954
+ t.objectProperty(t.identifier(m), t.booleanLiteral(true))
955
+ );
956
+ addEventArgs.push(t.objectExpression(optsProps));
957
+ }
958
+
959
+ // onChange is React's change event, which a spread's listener is
960
+ // (what-core render.js listen): `_$spread(el, { onchange }, null,
961
+ // options)`. It listens for two events, so `once` is the handler's: it
962
+ // runs for the first change, whichever event brings it.
963
+ if (event === 'change') {
964
+ const options = optionMods.filter(m => m !== 'once').map(m => t.objectProperty(t.identifier(m), t.booleanLiteral(true)));
965
+ let changeHandler = wrappedHandler;
966
+ if (optionMods.includes('once')) {
967
+ // ((h, done) => (e) => done || (done = true, h(e)))(handler)
968
+ const [h, done, e] = [t.identifier('h'), t.identifier('done'), t.identifier('e')];
969
+ changeHandler = t.callExpression(t.arrowFunctionExpression([h, done], t.arrowFunctionExpression([e],
970
+ t.logicalExpression('||', done, t.sequenceExpression([t.assignmentExpression('=', t.cloneNode(done), t.booleanLiteral(true)), t.callExpression(t.cloneNode(h), [e])])))), [wrappedHandler]);
971
+ }
972
+ statements.push(t.expressionStatement(t.callExpression(helper(state, '_$spread'), [
973
+ t.identifier(elId),
974
+ t.objectExpression([t.objectProperty(t.identifier('onchange'), changeHandler)]),
975
+ ...(options.length > 0 ? [t.nullLiteral(), t.objectExpression(options)] : []),
976
+ ])));
977
+ continue;
978
+ }
979
+
980
+ statements.push(
981
+ t.expressionStatement(
982
+ t.callExpression(helper(state, '_$on'), [t.identifier(elId), ...addEventArgs])
983
+ )
984
+ );
985
+ continue;
986
+ }
987
+
988
+ // Binding
989
+ if (isBindingAttribute(attrName)) {
990
+ const bindProp = getBindingProperty(attrName);
991
+ const signalExpr = attr.value.expression;
992
+
993
+ if (bindProp === 'value') {
994
+ statements.push(
995
+ t.expressionStatement(
996
+ bindingEffect(t.arrowFunctionExpression([], t.assignmentExpression('=',
997
+ t.memberExpression(t.identifier(elId), t.identifier('value')),
998
+ t.callExpression(t.cloneNode(signalExpr), [])
999
+ )), 'value', attr)
1000
+ )
1001
+ );
1002
+ statements.push(
1003
+ t.expressionStatement(
1004
+ t.callExpression(
1005
+ t.memberExpression(t.identifier(elId), t.identifier('addEventListener')),
1006
+ [
1007
+ t.stringLiteral('input'),
1008
+ t.arrowFunctionExpression(
1009
+ [t.identifier('e')],
1010
+ t.callExpression(
1011
+ t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
1012
+ [t.memberExpression(
1013
+ t.memberExpression(t.identifier('e'), t.identifier('target')),
1014
+ t.identifier('value')
1015
+ )]
1016
+ )
1017
+ )
1018
+ ]
1019
+ )
1020
+ )
1021
+ );
1022
+ } else if (bindProp === 'checked') {
1023
+ statements.push(
1024
+ t.expressionStatement(
1025
+ bindingEffect(t.arrowFunctionExpression([], t.assignmentExpression('=',
1026
+ t.memberExpression(t.identifier(elId), t.identifier('checked')),
1027
+ t.callExpression(t.cloneNode(signalExpr), [])
1028
+ )), 'checked', attr)
1029
+ )
1030
+ );
1031
+ statements.push(
1032
+ t.expressionStatement(
1033
+ t.callExpression(
1034
+ t.memberExpression(t.identifier(elId), t.identifier('addEventListener')),
1035
+ [
1036
+ t.stringLiteral('change'),
1037
+ t.arrowFunctionExpression(
1038
+ [t.identifier('e')],
1039
+ t.callExpression(
1040
+ t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
1041
+ [t.memberExpression(
1042
+ t.memberExpression(t.identifier('e'), t.identifier('target')),
1043
+ t.identifier('checked')
1044
+ )]
1045
+ )
1046
+ )
1047
+ ]
1048
+ )
1049
+ )
1050
+ );
1051
+ }
1052
+ continue;
1053
+ }
1054
+
1055
+ // Dynamic attribute (expression)
1056
+ if (t.isJSXExpressionContainer(attr.value)) {
1057
+ const expr = attr.value.expression;
1058
+ const domName = attributeName(attrName);
1059
+
1060
+ if (isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers)) {
1061
+ // Auto-invoke a bare identifier only when it is a PROVEN signal:
1062
+ // value={count} -> count() for a local `const count = signal(...)`.
1063
+ //
1064
+ // Never a destructured prop or an import. Either one can hold any
1065
+ // value: a prop is whatever the parent passed, and an import is
1066
+ // whatever the other module exported (`href={DOCS_URL}` with a string
1067
+ // constant is the common case). Calling one of those threw
1068
+ // "X is not a function". The runtime setters resolve a function value
1069
+ // as a reactive accessor themselves, exactly as h() does, so the
1070
+ // uncalled identifier is correct for a plain value AND keeps an
1071
+ // imported signal live.
1072
+ const fromProps = state.signalNames && state.signalNames.fromDestructuredProps;
1073
+ const valueExpr = t.isIdentifier(expr) &&
1074
+ !(fromProps && fromProps.has(expr.name)) &&
1075
+ isSignalIdentifier(expr.name, state.signalNames)
1076
+ ? t.callExpression(expr, [])
1077
+ : expr;
1078
+ const effectCall = bindingEffect(t.arrowFunctionExpression([], buildSetPropCall(domName, valueExpr, true)), domName, attr);
1079
+ // In dev mode, add a leading comment when the effect wrapping is uncertain
1080
+ // (non-signal function call whose args happen to contain signal reads)
1081
+ if (isUncertainReactive(expr, state.signalNames, state.importedIdentifiers)) {
1082
+ t.addComment(effectCall, 'leading',
1083
+ ' @what-dev: effect wrapping may be unnecessary — expression contains a non-signal function call with reactive args ',
1084
+ false
1085
+ );
1086
+ }
1087
+ statements.push(t.expressionStatement(effectCall));
1088
+ } else {
1089
+ // Static expression (no signal calls) — set once
1090
+ statements.push(t.expressionStatement(buildSetPropCall(domName, expr)));
1091
+ }
1092
+ continue;
1093
+ }
1094
+
1095
+ // A literal attribute the template could not hold (see isTemplateAttr):
1096
+ // applied here, in the order the author wrote it. A valueless attribute is
1097
+ // `true` in JSX, which is what the h() spelling passes.
1098
+ if (!isTemplateAttr(attributes, attrIndex, tagName)) {
1099
+ statements.push(
1100
+ t.expressionStatement(
1101
+ buildSetPropCall(attributeName(attrName), getAttributeValue(attr.value))
1102
+ )
1103
+ );
1104
+ }
1105
+ }
1106
+ }
1107
+
1108
+ // =====================================================
1109
+ // Branch Memoization
1110
+ // =====================================================
1111
+ // `_$insert(el, () => cond() ? <A/> : <B/>)` re-creates the taken branch's
1112
+ // DOM tree (and re-registers every effect inside it) on EVERY re-evaluation
1113
+ // of the insert effect — including writes to signals read by the condition
1114
+ // that do NOT flip which branch is taken (e.g. `count() > 5` while count
1115
+ // goes 6 → 7). Solid solves this by memoizing the condition: route the
1116
+ // condition through an eager, equality-gated memo so the insert effect
1117
+ // depends on the *memo* instead of the raw signals:
1118
+ //
1119
+ // const _c$0 = _$memo(() => !!(count() > 5));
1120
+ // _$insert(_el$, () => _c$0() ? <A/> : <B/>, marker);
1121
+ //
1122
+ // The memo re-evaluates on every count write, but only NOTIFIES when its
1123
+ // value changes — so branch DOM is recreated exactly on real flips.
1124
+ //
1125
+ // Semantics preserved:
1126
+ // - Ternary tests only matter for truthiness → memoize `!!test`.
1127
+ // - `a && b` / `a || b` render the LEFT operand's VALUE when it
1128
+ // short-circuits (`{0 && <div/>}` renders "0"), so the left side is
1129
+ // memoized by value (Object.is) — never coerced.
1130
+ // - Branch-internal reactivity (signals read inside <A/>) is fine-grained
1131
+ // and unaffected; plain-value branches read in the insert arrow are
1132
+ // still tracked by the insert effect directly.
1133
+
1134
+ // A keyed list inserter: one this back end built (_$mapArray), or a
1135
+ // hand-written mapArray() call, which is handed the same import.
1136
+ function isListInserterCall(node) {
1137
+ return t.isCallExpression(node)
1138
+ && (node._whatList === true || t.isIdentifier(node.callee, { name: 'mapArray' }));
1139
+ }
1140
+
1141
+ function adoptMapArrayCall(call, state) {
1142
+ state.needsGeneralMapArray = true;
1143
+ if (call._whatList !== true) {
1144
+ call.callee = helper(state, '_$mapArray');
1145
+ call._whatList = true;
1146
+ }
1147
+ }
1148
+
1149
+ // Does this expression produce DOM when evaluated? (raw JSX still present at
1150
+ // this stage, or an already-lowered _$mapArray list). Only then is branch
1151
+ // memoization worth the extra memo node.
1152
+ function buildsDOM(node) {
1153
+ if (!node || typeof node !== 'object') return false;
1154
+ if (Array.isArray(node)) return node.some(buildsDOM);
1155
+ if (node.type === 'JSXElement' || node.type === 'JSXFragment') return true;
1156
+ if (isListInserterCall(node)) return true;
1157
+ for (const key of Object.keys(node)) {
1158
+ if (key === 'loc' || key === 'start' || key === 'end' || key === 'leadingComments' ||
1159
+ key === 'trailingComments' || key === 'innerComments') continue;
1160
+ const v = node[key];
1161
+ if (v && typeof v === 'object' && buildsDOM(v)) return true;
1162
+ }
1163
+ return false;
1164
+ }
1165
+
1166
+ // --- Ternary trees ---
1167
+ //
1168
+ // `a() ? <A /> : b() ? <B /> : <C />` picks one of its leaves by its tests.
1169
+ // With only its first test memoized, the inner `b()` is read by the region
1170
+ // itself, and <C /> is built again whenever b's inputs change, truthiness or
1171
+ // not. The whole tree's choice is one memo instead: the tree with each leaf
1172
+ // replaced by its index (`a() ? 0 : b() ? 1 : 2`), which evaluates exactly
1173
+ // the tests the original evaluates, in its order, so a test an outer one
1174
+ // guards (`q.data().items.length` behind `q.isLoading()`) is never read
1175
+ // unguarded. The memo is lazy (_$lazyMemo), read first where the region
1176
+ // first runs, so a tree handed over unplaced (a <Show> fallback, a slot) is
1177
+ // not evaluated before its place renders. The region then reads the index
1178
+ // and builds a leaf only when the index changes: what <Switch> lowers to.
1179
+
1180
+ function ternaryTree(expr, leaves, tests) {
1181
+ if (!t.isConditionalExpression(expr)) {
1182
+ leaves.push(expr);
1183
+ return t.numericLiteral(leaves.length - 1);
1184
+ }
1185
+ tests.push(expr.test);
1186
+ return t.conditionalExpression(expr.test, ternaryTree(expr.consequent, leaves, tests), ternaryTree(expr.alternate, leaves, tests));
1187
+ }
1188
+
1189
+ /**
1190
+ * `expr` (a ternary with a reactive test and a leaf that builds DOM) as a
1191
+ * read of one lazy memo of the leaf it takes, the memo's declaration pushed
1192
+ * onto `statements`; null for any other expression.
1193
+ */
1194
+ function memoizeTernaryTree(expr, statements, state) {
1195
+ if (!t.isConditionalExpression(expr)) return null;
1196
+ const leaves = [];
1197
+ const tests = [];
1198
+ const selector = ternaryTree(expr, leaves, tests);
1199
+ if (!tests.some((test) => isPotentiallyReactive(test, state.signalNames, state.importedIdentifiers))) return null;
1200
+ if (!leaves.some(buildsDOM)) return null;
1201
+ const id = state.nextMemoId();
1202
+ statements.push(t.variableDeclaration('const', [
1203
+ t.variableDeclarator(t.identifier(id), t.callExpression(helper(state, '_$lazyMemo'), [t.arrowFunctionExpression([], selector)])),
1204
+ ]));
1205
+ // A leaf `b() && <B />` keeps <B> the same way (memoizeLogical); its memo
1206
+ // is lazy too, read only when the tree takes that leaf.
1207
+ for (let i = 0; i < leaves.length; i++) leaves[i] = memoizeLogical(leaves[i], statements, state) ?? leaves[i];
1208
+ let out = leaves[leaves.length - 1];
1209
+ for (let i = leaves.length - 2; i >= 0; i--) {
1210
+ out = t.conditionalExpression(t.binaryExpression('===', t.callExpression(t.identifier(id), []), t.numericLiteral(i)), leaves[i], out);
1211
+ }
1212
+ return out;
1213
+ }
1214
+
1215
+ // --- `&&` and `||` ---
1216
+ //
1217
+ // `{user() && <Profile user={user()} />}` is how React code renders a part
1218
+ // that needs a value. Gated on the left VALUE, the region ran again, and
1219
+ // rebuilt <Profile> with its state, whenever user() returned another object.
1220
+ // The arm is picked by the left side's truthiness instead, a lazy memo, and
1221
+ // the left value itself is read only where it renders, React's way: falsy
1222
+ // for `&&` (`{count() && <X />}` with 0 renders "0"; false, null, undefined
1223
+ // and '' render nothing), truthy for `||`. `||` lowers so only when its right
1224
+ // side builds DOM and its left side does not (a left side that is JSX is
1225
+ // rendered, and built, on every read). The server renders `left && right`
1226
+ // itself, which is the same output.
1227
+
1228
+ /**
1229
+ * `expr` (a `&&`/`||` with a reactive left side and a right side that builds
1230
+ * DOM) as a ternary over a lazy memo of the left side's truthiness, the
1231
+ * memo's declaration pushed onto `statements`; null otherwise.
1232
+ */
1233
+ function memoizeLogical(expr, statements, state) {
1234
+ if (!t.isLogicalExpression(expr) || (expr.operator !== '&&' && expr.operator !== '||')) return null;
1235
+ if (!isPotentiallyReactive(expr.left, state.signalNames, state.importedIdentifiers)) return null;
1236
+ if (!buildsDOM(expr.right)) return null;
1237
+ if (expr.operator === '||' && buildsDOM(expr.left)) return null;
1238
+ const id = state.nextMemoId();
1239
+ statements.push(t.variableDeclaration('const', [
1240
+ t.variableDeclarator(t.identifier(id), t.callExpression(helper(state, '_$lazyMemo'), [
1241
+ t.arrowFunctionExpression([], t.unaryExpression('!', t.unaryExpression('!', expr.left))),
1242
+ ])),
1243
+ ]));
1244
+ const truthy = t.callExpression(t.identifier(id), []);
1245
+ const left = t.cloneNode(expr.left, true);
1246
+ return expr.operator === '&&'
1247
+ ? t.conditionalExpression(truthy, expr.right, left)
1248
+ : t.conditionalExpression(truthy, left, expr.right);
1249
+ }
1250
+
1251
+ // If `expr` is a conditional (ternary / && / ||) with a reactive test and a
1252
+ // DOM-producing branch, hoist the test into `const _c$N = _$memo(...)` (pushed
1253
+ // onto `statements`) and return the expression rewritten to read the memo.
1254
+ // A ternary with ternaries for arms is one memo of the arm it takes
1255
+ // (memoizeTernaryTree), and `&&`/`||` a memo of the left side's truthiness
1256
+ // (memoizeLogical). Otherwise returns `expr` unchanged.
1257
+ function memoizeBranchCondition(expr, statements, state) {
1258
+ if (t.isConditionalExpression(expr) && (t.isConditionalExpression(expr.consequent) || t.isConditionalExpression(expr.alternate))) {
1259
+ const tree = memoizeTernaryTree(expr, statements, state);
1260
+ if (tree !== null) return tree;
1261
+ }
1262
+ const logical = memoizeLogical(expr, statements, state);
1263
+ if (logical !== null) return logical;
1264
+ let testExpr = null;
1265
+ let isTernary = false;
1266
+ if (t.isConditionalExpression(expr)) {
1267
+ testExpr = expr.test;
1268
+ isTernary = true;
1269
+ } else if (t.isLogicalExpression(expr) && (expr.operator === '&&' || expr.operator === '||')) {
1270
+ testExpr = expr.left;
1271
+ } else {
1272
+ return expr;
1273
+ }
1274
+
1275
+ if (!isPotentiallyReactive(testExpr, state.signalNames, state.importedIdentifiers)) return expr;
1276
+
1277
+ const branches = isTernary ? [expr.consequent, expr.alternate] : [expr.right];
1278
+ if (!branches.some(buildsDOM)) return expr;
1279
+
1280
+ const condId = state.nextMemoId();
1281
+ // Ternary: only truthiness matters in test position → gate on !!test so
1282
+ // value changes that don't flip truthiness (5 → 6) never notify.
1283
+ // Logical: the left VALUE is rendered on short-circuit → gate on the value.
1284
+ const memoBody = isTernary
1285
+ ? t.unaryExpression('!', t.unaryExpression('!', testExpr))
1286
+ : testExpr;
1287
+ statements.push(
1288
+ t.variableDeclaration('const', [
1289
+ t.variableDeclarator(
1290
+ t.identifier(condId),
1291
+ t.callExpression(helper(state, '_$memo'), [
1292
+ t.arrowFunctionExpression([], memoBody)
1293
+ ])
1294
+ )
1295
+ ])
1296
+ );
1297
+
1298
+ const condRead = t.callExpression(t.identifier(condId), []);
1299
+ // An arm `b() && <B />` keeps <B> by a lazy memo of its own (memoizeLogical).
1300
+ return isTernary
1301
+ ? t.conditionalExpression(condRead, memoizeLogical(expr.consequent, statements, state) ?? expr.consequent, memoizeLogical(expr.alternate, statements, state) ?? expr.alternate)
1302
+ : t.logicalExpression(expr.operator, condRead, expr.right);
1303
+ }
1304
+
1305
+ // Whether an element can be or hold a form field: a field's tag, or inner
1306
+ // HTML its props write (innerHTML, dangerouslySetInnerHTML, or a spread that
1307
+ // can give either). Its module installs the carrying of what the user changed
1308
+ // in a form before hydration into the fields built before the walk reached
1309
+ // them (what-core _$carryFields, once at module scope).
1310
+ function buildsField(tagName, attributes) {
1311
+ return FIELD_TAGS.has(tagName.toLowerCase()) || attributes.some((attr) => t.isJSXSpreadAttribute(attr) || INNER_HTML_PROPS.has(getAttrName(attr)));
1312
+ }
1313
+
1314
+ // Whether a binding writes the element's content as raw HTML: a hydratable
1315
+ // claim then keeps what the server put in it (render.js claimNode, flag 2).
1316
+ function writesContent(attributes) {
1317
+ return attributes.some((attr) => t.isJSXAttribute(attr) && INNER_HTML_PROPS.has(getAttrName(attr)));
1318
+ }
1319
+
1320
+ // The bindings for an element's children. A hydratable build reaches the
1321
+ // children in document order through the hydration cursor instead of by
1322
+ // firstChild/nextSibling paths (render.js _$claim): `_$skip(k)` passes k static
1323
+ // children, `_$next(k, 1?)` takes the next element with bindings (1: entering
1324
+ // it), `_$hole(el, value, flag)` is a dynamic child, and `_$exit()` leaves the
1325
+ // element. Returns whether it emitted such steps, in which case the caller
1326
+ // enters the element when it takes it.
1327
+ // `rowCell`: the item cell of the keyed row whose callback returns this
1328
+ // template, when it is one.
1329
+ function applyDynamicChildren(statements, elId, children, parentNode, state, rowCell) {
1330
+ const { entries } = layoutChildren(children, false, state, null, isTextOnly(parentNode));
1331
+ const hydratable = state.hydratable;
1332
+ // Static children since the last step (hydratable output).
1333
+ let skip = 0;
1334
+ let stepped = false;
1335
+ const flushSkip = () => {
1336
+ if (skip > 0) statements.push(t.expressionStatement(t.callExpression(helper(state, '_$skip'), [t.numericLiteral(skip)])));
1337
+ skip = 0;
1338
+ };
1339
+
1340
+ // Template nodes the code below must reach: each dynamic child's marker,
1341
+ // and every element child with something dynamic of its own.
1342
+ const uses = [];
1343
+ for (const entry of entries) {
1344
+ if (entry.kind === 'dynamic') {
1345
+ if (typeof entry.marker === 'number') uses.push(entry.marker);
1346
+ } else if (entry.kind === 'element') {
1347
+ const attrs = entry.node.openingElement.attributes;
1348
+ entry.hasAnythingDynamic = attrs.some((attr, i) => isDynamicAttr(attr) || isFieldProp(entry.node.openingElement.name.name, attrs, i)) ||
1349
+ attrs.some(a => !t.isJSXSpreadAttribute(a) && getAttrName(a)?.startsWith('on')) ||
1350
+ !entry.node.children.every(isStaticChild);
1351
+ if (entry.hasAnythingDynamic) uses.push(entry.index);
1352
+ }
1353
+ }
1354
+ const refIndices = [...new Set(uses)].sort((a, b) => a - b);
1355
+
1356
+ // An insert puts nodes before its marker, which moves every later node
1357
+ // relative to `firstChild`. So when more than one node is needed, or one
1358
+ // node is needed twice (as a marker, then as an element), all of them are
1359
+ // captured up front, before any insert runs. The capture is one cursor
1360
+ // walk, each reference chained from the previous one: O(n) in compile
1361
+ // time and emitted size rather than O(n^2).
1362
+ const markerVars = new Map(); // template node index → variable name
1363
+ if (!hydratable && (refIndices.length >= 2 || uses.length > refIndices.length)) {
1364
+ let prevVar = null;
1365
+ let prevIndex = 0;
1366
+ for (const idx of refIndices) {
1367
+ const markerVar = state.nextVarId();
1368
+ markerVars.set(idx, markerVar);
1369
+ let init;
1370
+ if (prevVar === null) {
1371
+ init = buildChildAccess(elId, idx);
1372
+ } else {
1373
+ init = t.identifier(prevVar);
1374
+ for (let i = prevIndex; i < idx; i++) {
1375
+ init = t.memberExpression(init, t.identifier('nextSibling'));
1376
+ }
1377
+ }
1378
+ statements.push(
1379
+ t.variableDeclaration('const', [
1380
+ t.variableDeclarator(t.identifier(markerVar), init)
1381
+ ])
1382
+ );
1383
+ prevVar = markerVar;
1384
+ prevIndex = idx;
1385
+ }
1386
+ }
1387
+
1388
+ // `_$insert(el, value[, marker])`: no third argument when the child is the
1389
+ // element's only content, `null` when it is appended. A development build
1390
+ // adds the binding's name, "tag.children@loc", as a fourth argument.
1391
+ // Hydratable: `_$hole(el, value, flag)`, the flag saying where a client
1392
+ // render inserts (3 only child, 2 appended, 1 before its `<!>`, 0 before
1393
+ // the next node).
1394
+ // `plain`: the value is a thunk over an expression that only reads
1395
+ // (isPlainRead), which the runtime reads once before it decides whether an
1396
+ // effect is needed (`_$plain`, `_$hplain`, same arguments).
1397
+ function insertCall(value, marker, node, placeholder, plain) {
1398
+ if (hydratable) {
1399
+ flushSkip();
1400
+ stepped = true;
1401
+ // The value is placed where it is evaluated: its JSX claims (transformJsxRoot).
1402
+ value._whatInPlace = true;
1403
+ placeFlat(value);
1404
+ const flag = marker === undefined ? 3 : marker === null ? 2 : placeholder ? 1 : 0;
1405
+ const args = [t.identifier(elId), value, t.numericLiteral(flag)];
1406
+ const name = bindingMetadata(parentNode.openingElement.name.name, 'children', node, state);
1407
+ if (name) args.push(name);
1408
+ return t.callExpression(helper(state, plain ? '_$hplain' : '_$hole'), args);
1409
+ }
1410
+ const args = [t.identifier(elId), value];
1411
+ if (marker === null) args.push(t.nullLiteral());
1412
+ else if (marker !== undefined) {
1413
+ args.push(markerVars.has(marker) ? t.identifier(markerVars.get(marker)) : buildChildAccess(elId, marker));
1414
+ }
1415
+ const name = bindingMetadata(parentNode.openingElement.name.name, 'children', node, state);
1416
+ if (name) {
1417
+ if (marker === undefined) args.push(t.unaryExpression('void', t.numericLiteral(0)));
1418
+ args.push(name);
1419
+ }
1420
+ // A function written where it is inserted is no list and no children
1421
+ // factory, so insert() could only hand it to its reactive region. A
1422
+ // module whose every insert is one imports that region under insert's
1423
+ // name (renderExport), and does not bring insert() itself.
1424
+ if (!plain && !t.isArrowFunctionExpression(value) && !t.isFunctionExpression(value)) state.needsGeneralInsert = true;
1425
+ return t.callExpression(helper(state, plain ? '_$plain' : '_$insert'), args);
1426
+ }
1427
+
1428
+ // A plain field of a keyed row's item (`{row.label}`): a text node the
1429
+ // row's item cell writes (render.js _$field), read now from the item the
1430
+ // row is built from, with its reader hoisted to the module. A field in the
1431
+ // template the row's callback returns is built with the row and goes with
1432
+ // it. Anywhere else (a region of the row, a row of a list inside it, a
1433
+ // component's children) it gets a last argument, 1: the runtime then binds
1434
+ // it to the row only when what builds it lives as long as the row.
1435
+ function fieldCall(expr, root, marker, placeholder) {
1436
+ const id = uniqueName(state, '_f$');
1437
+ state.rowFieldReaders.push({ id, fn: t.arrowFunctionExpression([t.identifier('r')], withItem(expr, root, t.identifier('r'))) });
1438
+ const value = withItem(expr, root, t.identifier(root._whatRowItemName));
1439
+ const cell = t.cloneNode(root.arguments[0]);
1440
+ const elsewhere = rowCell !== undefined && t.isIdentifier(cell, { name: rowCell }) ? [] : [t.numericLiteral(1)];
1441
+ if (hydratable) {
1442
+ flushSkip();
1443
+ stepped = true;
1444
+ const flag = marker === undefined ? 3 : marker === null ? 2 : placeholder ? 1 : 0;
1445
+ return t.callExpression(helper(state, '_$hfield'), [t.identifier(elId), cell, value, t.numericLiteral(flag), t.identifier(id), ...elsewhere]);
1446
+ }
1447
+ const at = marker === undefined ? t.unaryExpression('void', t.numericLiteral(0))
1448
+ : marker === null ? t.nullLiteral()
1449
+ : markerVars.has(marker) ? t.identifier(markerVars.get(marker)) : buildChildAccess(elId, marker);
1450
+ return t.callExpression(helper(state, '_$field'), [t.identifier(elId), cell, value, at, t.identifier(id), ...elsewhere]);
1451
+ }
1452
+
1453
+ for (const entry of entries) {
1454
+ if (entry.kind === 'dynamic' && t.isJSXExpressionContainer(entry.node)) {
1455
+ let expr = entry.node.expression;
1456
+
1457
+ const field = rowField(expr);
1458
+ if (field !== null && t.isCallExpression(field) && field._whatRowItemName) {
1459
+ statements.push(t.expressionStatement(fieldCall(expr, field, entry.marker, entry.placeholder)));
1460
+ continue;
1461
+ }
1462
+
1463
+ // Auto-lower .map() to mapArray when the callback returns keyed JSX.
1464
+ // Pattern: source().map(item => <Comp key={...} />) or source().map((item, i) => ...)
1465
+ let mapResult = tryLowerMapToMapArray(expr, state);
1466
+ if (mapResult) {
1467
+ // A bare _$mapArray(...) call is a self-managing inserter (it tracks
1468
+ // its source internally) and an arrow is already reactive — pass both
1469
+ // raw. But when lowering produced a ternary/logical wrapping the call
1470
+ // (e.g. cond ? _$mapArray(...) : fallback), the surrounding condition
1471
+ // must stay reactive, so wrap the whole expression in () => and let
1472
+ // _$insert re-evaluate it on change. Without this the condition is read
1473
+ // exactly once and never re-tracks.
1474
+ const isBareMapArray = isListInserterCall(mapResult);
1475
+ const isArrowAlready = t.isArrowFunctionExpression(mapResult);
1476
+ // Branch memoization (C1): when the lowered result is a conditional
1477
+ // around the list (cond ? _$mapArray(...) : fallback), memoize the
1478
+ // condition so non-flip writes don't tear down and recreate the
1479
+ // entire list inserter.
1480
+ if (isArrowAlready && t.isExpression(mapResult.body)) {
1481
+ mapResult.body = memoizeBranchCondition(mapResult.body, statements, state);
1482
+ } else if (!isBareMapArray && !isArrowAlready) {
1483
+ mapResult = memoizeBranchCondition(mapResult, statements, state);
1484
+ }
1485
+ const insertArg = (isBareMapArray || isArrowAlready)
1486
+ ? mapResult
1487
+ : t.arrowFunctionExpression([], mapResult);
1488
+ statements.push(t.expressionStatement(insertCall(insertArg, entry.marker, entry.node, entry.placeholder)));
1489
+ continue;
1490
+ }
1491
+
1492
+ // mapArray() calls return self-managing inserters — pass directly, never wrap in () =>
1493
+ if (isListInserterCall(expr)) {
1494
+ adoptMapArrayCall(expr, state);
1495
+ statements.push(t.expressionStatement(insertCall(expr, entry.marker, entry.node, entry.placeholder)));
1496
+ continue;
1497
+ }
1498
+
1499
+ if (isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers)) {
1500
+ // Branch memoization (C1): conditional children only rebuild branch
1501
+ // DOM when the condition actually flips.
1502
+ expr = memoizeBranchCondition(expr, statements, state);
1503
+ // Hydratable output hands a signal written as a child (`{count}`) to
1504
+ // the hole as itself: the server renders it as one region, and a
1505
+ // thunk returning it would be a region holding another.
1506
+ const value = hydratable && t.isIdentifier(expr) ? expr : t.arrowFunctionExpression([], orderedRows(expr, state, true));
1507
+ // An expression that only reads (`{props.title}`, `{item.price *
1508
+ // item.qty}`) needs no effect when what it reads is not reactive, or
1509
+ // is a list row's item alone (render.js _$plain). A bare name is a
1510
+ // signal handed on as it is, never a read.
1511
+ const plain = t.isArrowFunctionExpression(value) && !t.isIdentifier(value.body) && isPlainRead(value.body);
1512
+ const call = insertCall(value, entry.marker, entry.node, entry.placeholder, plain);
1513
+ if (isUncertainReactive(expr, state.signalNames, state.importedIdentifiers)) {
1514
+ t.addComment(call, 'leading',
1515
+ ' @what-dev: reactive wrapping may be unnecessary — expression contains a non-signal function call with reactive args ',
1516
+ false
1517
+ );
1518
+ }
1519
+ statements.push(t.expressionStatement(call));
1520
+ } else {
1521
+ statements.push(t.expressionStatement(insertCall(orderedRows(expr, state, false), entry.marker, entry.node, entry.placeholder)));
1522
+ }
1523
+ continue;
1524
+ }
1525
+
1526
+ if (entry.kind === 'dynamic') {
1527
+ const transformed = transformElementFineGrained({ node: entry.node }, state);
1528
+ statements.push(t.expressionStatement(insertCall(transformed, entry.marker, entry.node, entry.placeholder)));
1529
+ continue;
1530
+ }
1531
+
1532
+ if (hydratable && entry.kind !== 'dynamic') {
1533
+ if (!entry.hasAnythingDynamic) {
1534
+ skip++;
1535
+ continue;
1536
+ }
1537
+ // An element with bindings: taken in its place, entered when its own
1538
+ // children have steps.
1539
+ const childElRef = state.nextVarId();
1540
+ const childEl = entry.node.openingElement;
1541
+ const next = t.callExpression(helper(state, FORM_CONTROLS.has(childEl.name.name) ? '_$control' : '_$next'), [t.numericLiteral(skip)]);
1542
+ skip = 0;
1543
+ stepped = true;
1544
+ statements.push(t.variableDeclaration('const', [t.variableDeclarator(t.identifier(childElRef), next)]));
1545
+ applyDynamicAttrs(statements, childElRef, childEl.attributes, state, childEl.name.name, entry.node._whatNs);
1546
+ const flags = (applyDynamicChildren(statements, childElRef, entry.node.children, entry.node, state, rowCell) ? 1 : 0) | (writesContent(childEl.attributes) ? 2 : 0);
1547
+ claimArguments(next, flags, FORM_CONTROLS.has(childEl.name.name) ? null : ownedAttrs(childEl.attributes, childEl.name.name, entry.node._whatNs));
1548
+ continue;
1549
+ }
1550
+
1551
+ if (entry.kind === 'element' && entry.hasAnythingDynamic) {
1552
+ // Static child with dynamic content — get element reference
1553
+ let childElRef;
1554
+ if (markerVars.has(entry.index)) {
1555
+ childElRef = markerVars.get(entry.index);
1556
+ } else {
1557
+ childElRef = state.nextVarId();
1558
+ statements.push(
1559
+ t.variableDeclaration('const', [
1560
+ t.variableDeclarator(
1561
+ t.identifier(childElRef),
1562
+ buildChildAccess(elId, entry.index)
1563
+ )
1564
+ ])
1565
+ );
1566
+ }
1567
+ const childEl = entry.node.openingElement;
1568
+ applyDynamicAttrs(statements, childElRef, childEl.attributes, state, childEl.name.name, entry.node._whatNs);
1569
+ applyDynamicChildren(statements, childElRef, entry.node.children, entry.node, state, rowCell);
1570
+ }
1571
+ }
1572
+ if (stepped) statements.push(t.expressionStatement(t.callExpression(helper(state, '_$exit'), [])));
1573
+ return stepped;
1574
+ }
1575
+
1576
+ // A hydratable template claims a form control with _$control (_$claimControl
1577
+ // for its root): what the user changed in it before hydration stays.
1578
+ const FORM_CONTROLS = new Set(['input', 'select', 'textarea']);
1579
+
1580
+ function buildChildAccess(elId, index) {
1581
+ // Use firstChild/nextSibling chains instead of childNodes[N]
1582
+ // This is more robust with whitespace text nodes
1583
+ if (index === 0) {
1584
+ return t.memberExpression(t.identifier(elId), t.identifier('firstChild'));
1585
+ }
1586
+ // Chain .nextSibling for subsequent indices
1587
+ let expr = t.memberExpression(t.identifier(elId), t.identifier('firstChild'));
1588
+ for (let i = 0; i < index; i++) {
1589
+ expr = t.memberExpression(expr, t.identifier('nextSibling'));
1590
+ }
1591
+ return expr;
1592
+ }
1593
+
1594
+ // The factory a slot prop's JSX is built by (render.js _$slots). A ternary
1595
+ // with a reactive test (`header={b() ? <X /> : <Y />}`) hands the component a
1596
+ // reactive child instead of the arm it found first: the arm is picked by a
1597
+ // lazy memo (memoizeTernaryTree) the slot creates when it builds, so the arm
1598
+ // placed stays while the choice holds and the other one shows when it
1599
+ // changes. Read once, as before, the slot showed its first arm forever.
1600
+ // what-server hands the same function (ssr.js slotValue), so hydration finds
1601
+ // the region it brackets. Only when every arm is JSX: a component may test
1602
+ // the prop instead of placing it (`props.icon ? ... : ...`), and an arm that
1603
+ // is null has to read as false there, which a function never does
1604
+ // (core test lazy-props, "a condition the run never read").
1605
+ function slotFactory(value, state) {
1606
+ if (!everyArmIsJsx(value)) return t.arrowFunctionExpression([], value);
1607
+ const setup = [];
1608
+ const tree = memoizeTernaryTree(value, setup, state);
1609
+ if (tree === null) return t.arrowFunctionExpression([], value);
1610
+ return t.arrowFunctionExpression([], t.blockStatement([...setup, t.returnStatement(t.arrowFunctionExpression([], tree))]));
1611
+ }
1612
+
1613
+ /** Whether every arm of the ternary `expr` is a JSX element or fragment. */
1614
+ function everyArmIsJsx(expr) {
1615
+ if (t.isConditionalExpression(expr)) return everyArmIsJsx(expr.consequent) && everyArmIsJsx(expr.alternate);
1616
+ return t.isJSXElement(expr) || t.isJSXFragment(expr);
1617
+ }
1618
+
1619
+ function transformComponentFineGrained(path, state) {
1620
+ const { node } = path;
1621
+ const openingElement = node.openingElement;
1622
+ const componentRef = componentCallee(openingElement.name);
1623
+ // The tag's own reference, for isPlainFunctionComponent.
1624
+ componentRef._whatTag = true;
1625
+ const attributes = openingElement.attributes;
1626
+ const children = node.children;
1627
+
1628
+ // Check for client: directive (islands)
1629
+ /** @type {{ type: string, value?: any } | null} */
1630
+ let clientDirective = null;
1631
+ const filteredAttrs = [];
1632
+
1633
+ for (const attr of attributes) {
1634
+ if (t.isJSXAttribute(attr)) {
1635
+ // Handle both simple names and namespaced names (client:idle)
1636
+ let name;
1637
+ if (t.isJSXNamespacedName(attr.name)) {
1638
+ name = `${attr.name.namespace.name}:${attr.name.name.name}`;
1639
+ } else {
1640
+ name = attr.name.name;
1641
+ }
1642
+ if (name && typeof name === 'string' && name.startsWith('client:')) {
1643
+ clientDirective = { type: name.slice(7), value: directiveValue(attr) };
1644
+ continue;
1645
+ }
1646
+ }
1647
+ filteredAttrs.push(attr);
1648
+ }
1649
+
1650
+ // Transform children.
1651
+ // Element children build their DOM at the call site, i.e. before the parent
1652
+ // component ever runs, so a <Provider> publishes its context value too late
1653
+ // for its own subtree. Collect the element setup and emit it behind a
1654
+ // zero-arg factory instead; the runtime calls the factory while the parent's
1655
+ // owner is current. An expression child is deferred for the same
1656
+ // reason: it is the shape a wrapper forwards its own children through, and
1657
+ // reading it while the argument list is built happens before the component
1658
+ // it is being handed to has run. Text children have nothing to defer.
1659
+ //
1660
+ // Shared by the island branch and the regular component branch: an island is
1661
+ // still a component, and `<Panel client:visible>...</Panel>` must keep its
1662
+ // children rather than silently dropping them.
1663
+ function transformComponentChildren() {
1664
+ const setupMark = state._pendingSetup ? state._pendingSetup.length : 0;
1665
+ const members = [];
1666
+ let deferChildren = false;
1667
+ for (const child of children) {
1668
+ if (t.isJSXText(child)) {
1669
+ const text = normalizeJsxText(child.value);
1670
+ if (text) members.push({ expr: t.stringLiteral(text), setup: [] });
1671
+ } else if (t.isJSXExpressionContainer(child)) {
1672
+ if (!t.isJSXEmptyExpression(child.expression)) {
1673
+ deferChildren = true;
1674
+ // The same lowering an element child and a fragment child get.
1675
+ // Without it `<Box>{count()}</Box>` was evaluated once and never
1676
+ // again, while `<div>{count()}</div>` right beside it stayed live —
1677
+ // the auto-thunk docs/GOTCHAS.md section 2 promises for "any call
1678
+ // with no arguments" reached every JSX position EXCEPT this one.
1679
+ //
1680
+ // Nothing about it is component-specific: a component's children
1681
+ // are built into an array with no host element to _$insert into,
1682
+ // which is exactly the situation lowerFragmentExprChild exists for,
1683
+ // and it is where `.map()` picks up keyed reconciliation too.
1684
+ members.push(arrayMember(state, () => lowerFragmentExprChild(child.expression, state)));
1685
+ }
1686
+ } else if (t.isJSXElement(child)) {
1687
+ // <For>/<Show>/<Switch> lower to an inserter or a thunk (already lazy).
1688
+ const childFlow = controlFlowTag(child, state);
1689
+ if (childFlow !== 'For' && childFlow !== 'Show' && childFlow !== 'Switch') deferChildren = true;
1690
+ members.push(arrayMember(state, () => transformElementFineGrained({ node: child }, state)));
1691
+ } else if (t.isJSXFragment(child)) {
1692
+ deferChildren = true;
1693
+ members.push(arrayMember(state, () => transformFragmentFineGrained({ node: child }, state)));
1694
+ }
1695
+ }
1696
+
1697
+ // Several children have markers of their own where they are placed as an
1698
+ // array (the value of a component or of a reactive child, a member of an
1699
+ // array), before those of a component among them; placed in an element's
1700
+ // hole or among other members they have none, and the first may bring
1701
+ // markers of its own (render.js _$members, dom.js _place). One child is
1702
+ // handed over as itself, so it never has markers but its own.
1703
+ const first = members[0];
1704
+ let childrenArg = membersArray(members, state, false, true,
1705
+ members.length > 1 && !createdClaims(first, state) && !t.isStringLiteral(first.expr));
1706
+ if (isMembersCall(childrenArg, state)) childrenArg.arguments.push(t.numericLiteral(members.length > 1 ? 2 : 1));
1707
+ // An array built in order claims where it is built: where the component
1708
+ // places its children.
1709
+ if (deferChildren || !t.isArrayExpression(childrenArg)) {
1710
+ // Hoisted element setup emitted while transforming these children belongs
1711
+ // inside the factory, not before the enclosing statement.
1712
+ const setup = state._pendingSetup ? state._pendingSetup.splice(setupMark) : [];
1713
+ childrenArg = t.arrowFunctionExpression(
1714
+ [],
1715
+ setup.length > 0
1716
+ ? t.blockStatement([...setup, t.returnStatement(childrenArg)])
1717
+ : childrenArg
1718
+ );
1719
+ }
1720
+ return childrenArg;
1721
+ }
1722
+
1723
+ if (clientDirective) {
1724
+ // User props in source order — same rule, and the same reasons, as the
1725
+ // regular component path below. An island IS a component, so
1726
+ // `<Chart client:load {...a} {...b} />` has to mean `{ ...a, ...b }` for
1727
+ // exactly the reason `<Chart {...a} {...b} />` does. They travel apart
1728
+ // from the island's own options (common.js islandOptions), so no prop
1729
+ // name, and nothing a caller spreads in, can reach the component or the
1730
+ // mode.
1731
+ const islandParts = [];
1732
+ let islandUserProps = [];
1733
+ const flushIslandUserProps = () => {
1734
+ if (islandUserProps.length > 0) {
1735
+ islandParts.push(t.objectExpression(islandUserProps));
1736
+ islandUserProps = [];
1737
+ }
1738
+ };
1739
+
1740
+ for (const attr of filteredAttrs) {
1741
+ if (t.isJSXSpreadAttribute(attr)) {
1742
+ // Every spread is its own part of the island's props, in source order,
1743
+ // so `<Chart client:visible {...a} {...b} />` keeps the keys of both.
1744
+ if (t.isObjectExpression(attr.argument)) {
1745
+ for (const prop of attr.argument.properties) {
1746
+ if (t.isObjectProperty(prop)) checkIslandProp(t.isIdentifier(prop.key) ? prop.key.name : String(prop.key.value), prop.value, node, state);
1747
+ }
1748
+ }
1749
+ flushIslandUserProps();
1750
+ islandParts.push(attr.argument);
1751
+ continue;
1752
+ }
1753
+ const attrName = getAttrName(attr);
1754
+ if (attrName === 'key') continue;
1755
+ checkIslandProp(attrName, attr.value, node, state);
1756
+ const value = getAttributeValue(attr.value);
1757
+ // `data-x` and `aria-label` are not identifiers: propKey quotes them.
1758
+ islandUserProps.push(t.objectProperty(propKey(attrName), value));
1759
+ }
1760
+
1761
+ let islandPropsExpr = null;
1762
+ if (islandParts.length === 0) {
1763
+ // No spread anywhere: one object literal, the shape nearly every island has.
1764
+ if (islandUserProps.length > 0) islandPropsExpr = t.objectExpression(islandUserProps);
1765
+ } else {
1766
+ flushIslandUserProps();
1767
+ islandPropsExpr = t.callExpression(
1768
+ t.memberExpression(t.identifier('Object'), t.identifier('assign')),
1769
+ [t.objectExpression([]), ...islandParts]
1770
+ );
1771
+ }
1772
+
1773
+ const islandChildren = transformComponentChildren();
1774
+ if (!isEmptyArray(islandChildren)) state.needsLazyProps = true;
1775
+ const islandArgs = [helper(state, '_$Island'), islandOptions(openingElement.name, clientDirective.type, clientDirective.value, islandPropsExpr), islandChildren];
1776
+ const islandMeta = componentMetadata(node, state);
1777
+ // Hydratable output's component call takes the JSX's number before its
1778
+ // development location (below); an island has none, as on the server.
1779
+ if (islandMeta) islandArgs.push(...(state.hydratable ? [t.unaryExpression('void', t.numericLiteral(0))] : []), islandMeta);
1780
+ const island = t.callExpression(helper(state, '_$createComponent'), islandArgs);
1781
+ // A key that can change builds the island again, as a component's does
1782
+ // (lists.js islandKey); the new island hydrates by its trigger.
1783
+ const key = islandKey(node, clientDirective.type, state);
1784
+ return key === null ? island : t.callExpression(helper(state, '_$keyed'), [t.arrowFunctionExpression([], key), t.arrowFunctionExpression([], island)]);
1785
+ }
1786
+
1787
+ // Regular component — use _$createComponent to instantiate, component runs once.
1788
+ // Unless this element IS the tree handed to hydrate(), in which case it has
1789
+ // to arrive unbuilt: see isHydrateRootArgument.
1790
+ //
1791
+ // The root, and only the root. A host element lowers to a template clone, so
1792
+ // "unbuilt" is not something the children of an arbitrary tree can inherit —
1793
+ // <App><p>hi</p></App> would still build the <p>, and pushing the choice down
1794
+ // through component children only would produce a tree that hydrates in
1795
+ // patches. The root is the one position where the answer is unambiguous and
1796
+ // it is where the documented entry point lives.
1797
+ const isHydrateRoot = isHydrateRootArgument(path);
1798
+
1799
+ // Props resolve in SOURCE order. `<Box a {...s} b />` is one spelling of
1800
+ // `{ a, ...s, b }`, which is what h(), the JSX runtime, every other JSX
1801
+ // toolchain, and this compiler's own ELEMENT path all produce.
1802
+ // `parts` is that argument list: runs of explicit attributes, separated by
1803
+ // the spreads written between them.
1804
+ //
1805
+ // A single `spreadExpr` with every explicit prop appended last would get
1806
+ // both halves wrong: `<Box {...a} {...b} />` would keep only `b`, so every
1807
+ // key `a` carried and `b` did not would vanish — data loss, not merely
1808
+ // precedence — and an attribute written BEFORE a spread would beat it, which
1809
+ // no other JSX implementation does.
1810
+ //
1811
+ // The merge is a shallow copy, deliberately: a prop is reactive here when
1812
+ // its VALUE is an accessor, and Object.assign copies that function through
1813
+ // untouched. A lone non-literal spread is copied too, the same
1814
+ // Object.assign path a multi-prop merge already used, so two
1815
+ // `<Box {...reused}>` sites do not share one identity. createComponent
1816
+ // (dom.js) copies again before the component sees the props.
1817
+ const parts = [];
1818
+ let props = [];
1819
+ const slots = [];
1820
+ const propMemos = [];
1821
+ // Whether a prop is live (a getter): the literal then has no prototype.
1822
+ let live = false;
1823
+ const flushProps = () => {
1824
+ if (props.length > 0) {
1825
+ parts.push(t.objectExpression(props));
1826
+ props = [];
1827
+ }
1828
+ };
1829
+
1830
+ for (const attr of filteredAttrs) {
1831
+ if (t.isJSXSpreadAttribute(attr)) {
1832
+ flushProps();
1833
+ parts.push(attr.argument);
1834
+ continue;
1835
+ }
1836
+
1837
+ const attrName = getAttrName(attr);
1838
+
1839
+ // `key` is not a prop: the list lowering reads a .map() row's key before
1840
+ // this runs, and on any other component it does nothing.
1841
+ if (attrName === 'key') continue;
1842
+
1843
+ // Handle bind: attributes for components
1844
+ if (isBindingAttribute(attrName)) {
1845
+ const bindProp = getBindingProperty(attrName);
1846
+ const signalExpr = attr.value.expression;
1847
+
1848
+ if (bindProp === 'value') {
1849
+ props.push(
1850
+ t.objectProperty(t.identifier('value'), t.callExpression(t.cloneNode(signalExpr), []))
1851
+ );
1852
+ props.push(
1853
+ t.objectProperty(
1854
+ t.identifier('onInput'),
1855
+ t.arrowFunctionExpression(
1856
+ [t.identifier('e')],
1857
+ t.callExpression(
1858
+ t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
1859
+ [t.memberExpression(
1860
+ t.memberExpression(t.identifier('e'), t.identifier('target')),
1861
+ t.identifier('value')
1862
+ )]
1863
+ )
1864
+ )
1865
+ )
1866
+ );
1867
+ } else if (bindProp === 'checked') {
1868
+ props.push(
1869
+ t.objectProperty(t.identifier('checked'), t.callExpression(t.cloneNode(signalExpr), []))
1870
+ );
1871
+ props.push(
1872
+ t.objectProperty(
1873
+ t.identifier('onChange'),
1874
+ t.arrowFunctionExpression(
1875
+ [t.identifier('e')],
1876
+ t.callExpression(
1877
+ t.memberExpression(t.cloneNode(signalExpr), t.identifier('set')),
1878
+ [t.memberExpression(
1879
+ t.memberExpression(t.identifier('e'), t.identifier('target')),
1880
+ t.identifier('checked')
1881
+ )]
1882
+ )
1883
+ )
1884
+ )
1885
+ );
1886
+ }
1887
+ continue;
1888
+ }
1889
+
1890
+ // Handle event modifiers on components
1891
+ if (attrName.startsWith('on') && (attrName.includes('|') || hasEventModifiers(attrName, state))) {
1892
+ const { eventName, modifiers } = parseEventModifiers(attrName);
1893
+ const handler = getAttributeValue(attr.value);
1894
+ const wrappedHandler = createEventHandler(handler, modifiers);
1895
+ props.push(t.objectProperty(t.identifier(eventName), wrappedHandler));
1896
+ continue;
1897
+ }
1898
+
1899
+ const value = getAttributeValue(attr.value);
1900
+ // JSX handed to a component in a prop, and a prop handed on to one
1901
+ // (`fallback={props.fallback}`, a placing read), are built where the
1902
+ // component reads them, as its children are: a lazy getter over a
1903
+ // factory (render.js _$slots, dom.js _installLazyChildren). While
1904
+ // hydrating, the factory's JSX claims the server's nodes where the
1905
+ // component places it.
1906
+ if (isSlotAttribute(node, attr, state) && (yieldsJsx(value) || isPlacingRead(value))) {
1907
+ slots.push(t.objectProperty(propKey(attrName), slotFactory(value, state)));
1908
+ continue;
1909
+ }
1910
+
1911
+ // A value that reads a signal is a live prop: a getter over the
1912
+ // expression, which the component reads again wherever it reads it
1913
+ // (what-core dom.js _isLiveProp), so `<Badge on={count() > 0} />` shows
1914
+ // the current count as `<b>{count() > 0}</b>` would.
1915
+ if (isLivePropValue(attrName, value, state)) {
1916
+ let read = value;
1917
+ if (readsHookValue(value, state.signalNames)) {
1918
+ const name = uniqueName(state, '_prop$');
1919
+ propMemos.push(t.variableDeclarator(t.identifier(name), t.callExpression(helper(state, '_$lazyMemo'), [
1920
+ t.arrowFunctionExpression([], value),
1921
+ ])));
1922
+ read = t.callExpression(t.identifier(name), []);
1923
+ }
1924
+ props.push(t.objectMethod('get', propKey(attrName), [], t.blockStatement([t.returnStatement(read)])));
1925
+ live = true;
1926
+ continue;
1927
+ }
1928
+
1929
+ props.push(t.objectProperty(propKey(attrName), value));
1930
+ }
1931
+
1932
+ flushProps();
1933
+
1934
+ let propsExpr;
1935
+ if (parts.length === 0) {
1936
+ propsExpr = t.nullLiteral();
1937
+ } else if (parts.length === 1 && t.isObjectExpression(parts[0])) {
1938
+ // A lone object literal (no spread, or an inline `{...}`) is already a
1939
+ // fresh props object. A lone identifier/member/call spread is the
1940
+ // CALLER'S object and goes through the merge below. One holding a getter
1941
+ // is the component's own, taken as it is so its getters stay live
1942
+ // (render.js ownProps): it is marked (`_$marked({ ... })`, the mark
1943
+ // hidden). Not built with no prototype: setting a prototype in place gives
1944
+ // each object a hidden class of its own in V8 (prop reads about 13x
1945
+ // slower). Not marked in the literal (`[_$props]: true`) either: V8 builds
1946
+ // every property after a computed key one at a time, and the mark is then
1947
+ // hidden in place.
1948
+ propsExpr = live ? markedProps(parts[0], state) : parts[0];
1949
+ } else {
1950
+ // Merged in source order, getters kept: a wrapper's `{...props}` stays
1951
+ // live (render.js _$merge).
1952
+ propsExpr = t.callExpression(helper(state, '_$merge'), parts.map((part) => (
1953
+ t.isObjectExpression(part) && part.properties.some((p) => t.isObjectMethod(p)) ? withoutPrototype(part) : part
1954
+ )));
1955
+ }
1956
+
1957
+ if (slots.length > 0) {
1958
+ propsExpr = t.callExpression(helper(state, '_$slots'), [
1959
+ t.isNullLiteral(propsExpr) ? t.objectExpression([]) : propsExpr,
1960
+ t.objectExpression(slots),
1961
+ ]);
1962
+ }
1963
+
1964
+ const childrenArg = transformComponentChildren();
1965
+ // Children, or JSX in a prop, are built where the component reads them
1966
+ // (render.js lazyProps). A module with neither imports the call that
1967
+ // installs no lazy getter (renderExport).
1968
+ if (slots.length > 0 || !isEmptyArray(childrenArg)) state.needsLazyProps = true;
1969
+ // And one whose every component is a plain function imports the call that
1970
+ // does not look for a class component.
1971
+ const scope = path.scope ?? state.file?.path?.scope;
1972
+ const plain = isPlainFunctionComponent(scope, openingElement.name, state.translatedMarks);
1973
+ if (!plain) state.classComponents = true;
1974
+ // A tag held in a binding can name a form field (render.js tagComponent).
1975
+ const holdsTag = !plain && mayHoldTag(scope, openingElement.name);
1976
+ if (holdsTag) state.carriesFields = true;
1977
+
1978
+ const componentArgs = [componentRef, propsExpr, childrenArg];
1979
+ const meta = componentMetadata(node, state);
1980
+ // Hydratable output gives the component the number of the JSX that renders
1981
+ // it (lists.js listSlot), the server target's too: its place among the keyed
1982
+ // rows (what-core hydration-data.js). The root handed to hydrate() has none,
1983
+ // as the page the server renders has none.
1984
+ const site = state.hydratable && !isHydrateRoot ? listSlot(node) : null;
1985
+ if (site !== null || (meta && state.hydratable && !isHydrateRoot)) componentArgs.push(site ?? t.unaryExpression('void', t.numericLiteral(0)));
1986
+ if (meta) componentArgs.push(meta);
1987
+ // The root handed to hydrate() arrives unbuilt; one whose tag may be a
1988
+ // string claims the server's element when hydrate() runs it.
1989
+ const vnodeCall = holdsTag ? '_$hcomponentVNode' : '_$componentVNode';
1990
+ let call = t.callExpression(helper(state, isHydrateRoot ? vnodeCall : '_$createComponent'), componentArgs);
1991
+ // A component placed in SVG or MathML is told so, for a tag held in a
1992
+ // binding that it builds (render.js _$inNs). Not one this module defines
1993
+ // whose JSX, and that of the components it calls, names no such tag: the
1994
+ // compiler places its elements itself.
1995
+ if (node._whatPlacedNs !== undefined && !isHydrateRoot && node._whatMayBuildTag !== false) {
1996
+ call = t.callExpression(helper(state, '_$inNs'), [t.numericLiteral(node._whatPlacedNs), t.arrowFunctionExpression([], call)]);
1997
+ }
1998
+ // A key outside a list that can change (lists.js liveKey): a reactive
1999
+ // child that builds the component again whenever the key's value changes
2000
+ // (render.js _$keyed). An element with one is built the same way
2001
+ // (transformElementFineGrained).
2002
+ if (propMemos.length > 0) {
2003
+ call = t.callExpression(t.arrowFunctionExpression([], t.blockStatement([
2004
+ t.variableDeclaration('const', propMemos), t.returnStatement(call),
2005
+ ])), []);
2006
+ }
2007
+ const key = isHydrateRoot ? null : liveKey(node, state);
2008
+ if (key !== null) call = t.callExpression(helper(state, '_$keyed'), [t.arrowFunctionExpression([], key), t.arrowFunctionExpression([], call)]);
2009
+ return call;
2010
+ }
2011
+
2012
+ // Whether the component JSX tag `name` names can build a tag held in a
2013
+ // binding: anything but What's own and a function this module defines whose
2014
+ // JSX names only elements and such functions. Read before any JSX is lowered
2015
+ // (babel-plugin.js marks each component element, `_whatMayBuildTag`).
2016
+ export function mayBuildTag(scope, name, seen = new Set()) {
2017
+ if (!t.isJSXIdentifier(name) || scope == null) return true;
2018
+ const binding = scope.getBinding(name.name);
2019
+ if (!binding || !binding.constant) return true;
2020
+ const node = binding.path.node;
2021
+ if (binding.kind === 'module') return !(t.isImportSpecifier(node) && FRAMEWORK_SOURCES.has(binding.path.parent.source.value));
2022
+ const fn = t.isFunctionDeclaration(node) ? binding.path : t.isVariableDeclarator(node) && t.isFunction(node.init) ? binding.path.get('init') : null;
2023
+ if (fn === null) return true;
2024
+ if (seen.has(fn.node)) return false;
2025
+ seen.add(fn.node);
2026
+ let found = false;
2027
+ fn.traverse({
2028
+ JSXOpeningElement(el) {
2029
+ if (found || !isComponentElement(el.node)) return;
2030
+ if (mayBuildTag(el.scope, el.node.name, seen)) found = true;
2031
+ },
2032
+ });
2033
+ return found;
2034
+ }
2035
+
2036
+ // `_$inNs(ns, () => call)`: the call it places.
2037
+ function placedCall(node, state) {
2038
+ return t.isCallExpression(node) && t.isIdentifier(node.callee) && helperLocals(state).get('_$inNs') === node.callee.name
2039
+ && t.isArrowFunctionExpression(node.arguments[1]) ? node.arguments[1].body : node;
2040
+ }
2041
+
2042
+ // An expression that only reads: names, member reads and literals, and the
2043
+ // operators over them. No call (but a keyed row's read of its item, which the
2044
+ // compiler wrote), no `new`, no assignment, no JSX, no function: evaluating it
2045
+ // once more changes nothing, and it creates nothing that would need an owner.
2046
+ function isPlainRead(node) {
2047
+ switch (node.type) {
2048
+ case 'Identifier':
2049
+ case 'StringLiteral':
2050
+ case 'NumericLiteral':
2051
+ case 'BooleanLiteral':
2052
+ case 'NullLiteral':
2053
+ case 'BigIntLiteral':
2054
+ return true;
2055
+ case 'MemberExpression':
2056
+ case 'OptionalMemberExpression':
2057
+ return isPlainRead(node.object) && (!node.computed || isPlainRead(node.property));
2058
+ case 'TemplateLiteral':
2059
+ return node.expressions.every(isPlainRead);
2060
+ case 'UnaryExpression':
2061
+ return node.operator !== 'delete' && isPlainRead(node.argument);
2062
+ case 'BinaryExpression':
2063
+ case 'LogicalExpression':
2064
+ return isPlainRead(node.left) && isPlainRead(node.right);
2065
+ case 'ConditionalExpression':
2066
+ return isPlainRead(node.test) && isPlainRead(node.consequent) && isPlainRead(node.alternate);
2067
+ case 'ParenthesizedExpression':
2068
+ case 'TSAsExpression':
2069
+ case 'TSSatisfiesExpression':
2070
+ case 'TSNonNullExpression':
2071
+ case 'TSTypeAssertion':
2072
+ return isPlainRead(node.expression);
2073
+ case 'CallExpression':
2074
+ return node.callee._whatRowItem === true;
2075
+ default:
2076
+ return false;
2077
+ }
2078
+ }
2079
+
2080
+ // A hook result may run a getter or factory that allocates a value. Give it
2081
+ // a lazy memo per prop and component instance so every read shares that value.
2082
+ function readsHookValue(node, signalNames) {
2083
+ if (!node || t.isFunction(node)) return false;
2084
+ if ((t.isMemberExpression(node) || t.isOptionalMemberExpression(node)) && isHookResultRead(node, signalNames)) return true;
2085
+ if ((t.isCallExpression(node) || t.isOptionalCallExpression(node)) && isHookResultRead(node.callee, signalNames)) return true;
2086
+ return (t.VISITOR_KEYS[node.type] || []).some((key) => Array.isArray(node[key])
2087
+ ? node[key].some((child) => readsHookValue(child, signalNames))
2088
+ : readsHookValue(node[key], signalNames));
2089
+ }
2090
+
2091
+ // Whether a component prop is passed live, as a getter over its value: an
2092
+ // expression that reads a signal (a call, `props.x`, a store's member),
2093
+ // never a name (an accessor handed on as `count={count}` stays the accessor),
2094
+ // a literal, a function, `ref` or `children`.
2095
+ function isLivePropValue(name, value, state) {
2096
+ // `children={label()}` is the children, as React reads it: live like any
2097
+ // other prop (dom.js _place shows it as a reactive child), so children a
2098
+ // wrapper forwards through its rest follow the parent's state.
2099
+ if (name === 'ref') return false;
2100
+ let expr = value;
2101
+ while (t.isTSAsExpression(expr) || t.isTSSatisfiesExpression(expr) || t.isTSNonNullExpression(expr) || t.isTSTypeAssertion(expr)) expr = expr.expression;
2102
+ // A template literal with holes is not a literal here (Babel's isLiteral
2103
+ // counts it): `label={`Hi ${props.name}`}` reads what its holes read.
2104
+ const literal = t.isLiteral(expr) && !(t.isTemplateLiteral(expr) && expr.expressions.length > 0);
2105
+ if (t.isIdentifier(expr) || literal || t.isFunction(expr) || t.isJSXElement(expr) || t.isJSXFragment(expr)) return false;
2106
+ return isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers);
2107
+ }
2108
+
2109
+ // `{ __proto__: null, ... }`: a props object with no prototype, which the
2110
+ // runtime takes as the component's own (render.js ownProps, _$merge).
2111
+ function withoutPrototype(literal) {
2112
+ literal.properties.unshift(t.objectProperty(t.identifier('__proto__'), t.nullLiteral()));
2113
+ return literal;
2114
+ }
2115
+
2116
+ // `_$marked({ ... })`: the component's own props object, a plain one What's
2117
+ // runtime recognises by its mark (render.js ownProps), so its getters stay
2118
+ // live props.
2119
+ function markedProps(literal, state) {
2120
+ return t.callExpression(helper(state, '_$marked'), [literal]);
2121
+ }
2122
+
2123
+ // JSX, or a conditional that renders JSX in one of its branches.
2124
+ function isJsxValue(node) {
2125
+ if (t.isJSXElement(node) || t.isJSXFragment(node)) return true;
2126
+ if (t.isConditionalExpression(node)) return isJsxValue(node.consequent) || isJsxValue(node.alternate);
2127
+ return t.isLogicalExpression(node) && isJsxValue(node.right);
2128
+ }
2129
+
2130
+ function isPlacingRead(node) {
2131
+ return t.isCallExpression(node) && node.callee._whatPlace === true;
2132
+ }
2133
+
2134
+ // A value that renders JSX it builds: JSX, a condition with JSX in a branch,
2135
+ // an array literal holding some, or a `.map()` / `.flatMap()` whose callback
2136
+ // returns some (`items={links.map((l) => <li>{l}</li>)}`).
2137
+ function yieldsJsx(node) {
2138
+ if (t.isJSXElement(node) || t.isJSXFragment(node)) return true;
2139
+ if (t.isConditionalExpression(node)) return yieldsJsx(node.consequent) || yieldsJsx(node.alternate);
2140
+ if (t.isLogicalExpression(node)) return yieldsJsx(node.right);
2141
+ if (t.isArrayExpression(node)) return node.elements.some((m) => m !== null && yieldsJsx(t.isSpreadElement(m) ? m.argument : m));
2142
+ if (!(t.isCallExpression(node) || t.isOptionalCallExpression(node))) return false;
2143
+ const callee = node.callee;
2144
+ if (!(t.isMemberExpression(callee) || t.isOptionalMemberExpression(callee)) || callee.computed
2145
+ || !t.isIdentifier(callee.property) || (callee.property.name !== 'map' && callee.property.name !== 'flatMap')) return false;
2146
+ const fn = node.arguments[0];
2147
+ return (t.isArrowFunctionExpression(fn) || t.isFunctionExpression(fn)) && returnsJsx(fn);
2148
+ }
2149
+
2150
+ // Whether a function's result renders JSX it builds: its expression body, or
2151
+ // one of its own return statements.
2152
+ function returnsJsx(fn) {
2153
+ if (!t.isBlockStatement(fn.body)) return yieldsJsx(fn.body);
2154
+ let found = false;
2155
+ const visit = (node) => {
2156
+ if (found || node == null || typeof node.type !== 'string' || t.isFunction(node)) return;
2157
+ if (t.isReturnStatement(node) && node.argument != null && yieldsJsx(node.argument)) {
2158
+ found = true;
2159
+ return;
2160
+ }
2161
+ for (const key of t.VISITOR_KEYS[node.type] || []) {
2162
+ const child = node[key];
2163
+ if (Array.isArray(child)) child.forEach(visit);
2164
+ else visit(child);
2165
+ }
2166
+ };
2167
+ fn.body.body.forEach(visit);
2168
+ return found;
2169
+ }
2170
+
2171
+ function transformForFineGrained(path, state) {
2172
+ const { node } = path;
2173
+ const attributes = node.openingElement.attributes;
2174
+ const children = node.children;
2175
+
2176
+ // <For each={data} key={item => item.id}>{(item) => <Row />}</For>
2177
+ // → mapArray(data, (item) => ..., { key: item => item.id })
2178
+ //
2179
+ // <For> and .map() with a key prop compile to the same keyed rows: the
2180
+ // compiler lowers .map() to _$mapArray with the row reading its item through
2181
+ // an accessor, so a row keeps its DOM and follows an item replaced under the
2182
+ // same key, as a <For> row does. Saying so is a note on correct code,
2183
+ // printed only when asked for (the `verbose` option).
2184
+ if (process.env.NODE_ENV !== 'production' && state.opts?.verbose === true && !state.opts?.production) {
2185
+ const fileName = state.filename || state.file?.opts?.filename || '<unknown>';
2186
+ if (!_forInfoWarned.has(fileName)) {
2187
+ _forInfoWarned.add(fileName);
2188
+ const loc = node.loc;
2189
+ const lineInfo = loc ? `:${loc.start.line}:${loc.start.column}` : '';
2190
+ console.info(
2191
+ `[what-compiler] <For> at ${fileName}${lineInfo}: consider using .map() with a key prop instead. ` +
2192
+ `The compiler lowers .map() to the same keyed rows: a row keeps its DOM, and its bindings follow ` +
2193
+ `an item replaced under the same key (an immutable update, a refetch).`
2194
+ );
2195
+ }
2196
+ }
2197
+
2198
+ let eachExpr = null;
2199
+ let keyExpr = null;
2200
+ let fallbackExpr = null;
2201
+ for (const attr of attributes) {
2202
+ if (t.isJSXAttribute(attr)) {
2203
+ const name = getAttrName(attr);
2204
+ if (name === 'each') eachExpr = getAttributeValue(attr.value);
2205
+ else if (name === 'key') keyExpr = getAttributeValue(attr.value);
2206
+ else if (name === 'fallback') fallbackExpr = getAttributeValue(attr.value);
2207
+ }
2208
+ }
2209
+
2210
+ if (!eachExpr) {
2211
+ console.warn('[what-compiler] <For> element missing "each" attribute.');
2212
+ return transformElementAsH(path, state);
2213
+ }
2214
+
2215
+ let renderFn = null;
2216
+ for (const child of children) {
2217
+ if (t.isJSXExpressionContainer(child) && !t.isJSXEmptyExpression(child.expression)) {
2218
+ renderFn = child.expression;
2219
+ break;
2220
+ }
2221
+ }
2222
+
2223
+ if (!renderFn) {
2224
+ console.warn('[what-compiler] <For> element missing render function child.');
2225
+ return transformElementAsH(path, state);
2226
+ }
2227
+
2228
+ state.needsGeneralMapArray = true;
2229
+
2230
+ // An expression that reads reactively is the list's accessor, as in any
2231
+ // other position: each={list()}, each={user()?.orders}. A plain name is
2232
+ // handed over as it is: a signal is an accessor already, and a prop or a
2233
+ // variable may hold an accessor or an array, both of which mapArray takes.
2234
+ if (!t.isIdentifier(eachExpr) && !t.isArrowFunctionExpression(eachExpr) && !t.isFunctionExpression(eachExpr) &&
2235
+ isPotentiallyReactive(eachExpr, state.signalNames, state.importedIdentifiers)) {
2236
+ eachExpr = t.arrowFunctionExpression([], buildEachValue(eachExpr, state));
2237
+ }
2238
+
2239
+ // `_$mapArray(source, renderFn[, { key }])` — built from whichever source
2240
+ // expression the caller wants, because the fallback lowering below has to
2241
+ // read the source twice and therefore binds it to a const first.
2242
+ const buildMapArrayCall = (sourceExpr) => {
2243
+ const args = [sourceExpr, renderFn];
2244
+ if (keyExpr) {
2245
+ const options = [t.objectProperty(t.identifier('key'), keyExpr)];
2246
+ // A keyed <For> row reads its item with a call (`item()`), so only a
2247
+ // component in it can hold a plain field of the row.
2248
+ if (rowHoldsPlainFields(renderFn)) options.push(rowFieldsOption(state));
2249
+ const slot = listSlot(node);
2250
+ if (slot !== null) options.push(t.objectProperty(t.identifier('slot'), slot));
2251
+ args.push(t.objectExpression(options));
2252
+ }
2253
+ const list = t.callExpression(helper(state, '_$mapArray'), args);
2254
+ list._whatList = true;
2255
+ return list;
2256
+ };
2257
+
2258
+ if (!fallbackExpr) {
2259
+ return buildMapArrayCall(eachExpr);
2260
+ }
2261
+
2262
+ // The RUNTIME For (packages/core/src/components.js) implements `fallback`,
2263
+ // so the compiled form does too: an app that moves from a buildless setup
2264
+ // to the Vite compiler keeps its empty state.
2265
+ //
2266
+ // mapArray has no fallback of its own, and the obvious lowering — gate the
2267
+ // WHOLE thing on emptiness, `() => empty() ? _$mapArray(...) : fallback` —
2268
+ // is a trap. `insert()` has a fast path for a mapArray inserter: it
2269
+ // recognises `child._mapArray` and installs the list ONCE for the life of
2270
+ // the component. A thunk is not that, so the gated form falls through to
2271
+ // the generic reactive branch, whose effect calls the thunk again on every
2272
+ // flip and gets a BRAND NEW inserter each time. Nothing disposes the old
2273
+ // one, so it stays subscribed to the source forever: every empty -> fill
2274
+ // cycle permanently adds one more live list. Measured row-render-fn calls
2275
+ // per two writes, over successive cycles, went 2 -> 9 -> 16 -> 23 while
2276
+ // logging "NotFoundError: The child can not be found in the parent" from
2277
+ // the orphans reconciling against the detached fragment they captured. The
2278
+ // DOM stayed correct, which is why it looked fine.
2279
+ //
2280
+ // So keep the list permanent and give the fallback its OWN inserter beside
2281
+ // it, both anchored to the same marker:
2282
+ // _$insert(el, _$mapArray(each, fn), marker) // permanent
2283
+ // _$insert(el, () => empty() ? null : fallback, marker)
2284
+ // Only one of the two ever has content, and each reconciles independently.
2285
+ //
2286
+ // This function has to return a single expression, and a <For> can land in
2287
+ // a component's return, an element child, a component prop or a fragment.
2288
+ // Rather than teach all of those to emit two inserts, wrap the pair in one
2289
+ // inserter that performs both when it is mounted, and copy the list's own
2290
+ // marker properties onto it with Object.assign so it IS a mapArray inserter
2291
+ // to every consumer: `insert`, `createDOM`, `hydrateNode` and the server's
2292
+ // `_mapArrayToArray` all key off `_mapArray` and the `_mapArraySource` /
2293
+ // `_mapArrayFn` / `_mapArrayKeyed` trio. Object.assign copies exactly the
2294
+ // own enumerable properties mapArray sets, so this keeps working if the
2295
+ // runtime adds another one.
2296
+ //
2297
+ // Two more things this has to get right:
2298
+ // - The source expression is evaluated ONCE and shared, so the list and
2299
+ // the emptiness test can never disagree about which list they see.
2300
+ // - The emptiness test is MEMOIZED, so a write that leaves the list
2301
+ // non-empty does not re-run the fallback thunk and rebuild its DOM.
2302
+ if (!state._pendingSetup) state._pendingSetup = [];
2303
+ const eachId = uniqueName(state, '_each$');
2304
+ const listId = uniqueName(state, '_for$');
2305
+ const fallbackId = uniqueName(state, '_fb$');
2306
+ const emptyId = state.nextMemoId();
2307
+
2308
+ // `each` is an accessor or an array, as mapArray takes either: the
2309
+ // emptiness test resolves it the same way.
2310
+ const resolvedId = path.scope
2311
+ ? path.scope.generateUidIdentifier('list')
2312
+ : t.identifier('_list');
2313
+ const resolveList = t.conditionalExpression(
2314
+ t.binaryExpression('===',
2315
+ t.unaryExpression('typeof', t.identifier(eachId)),
2316
+ t.stringLiteral('function')
2317
+ ),
2318
+ t.callExpression(t.identifier(eachId), []),
2319
+ t.identifier(eachId)
2320
+ );
2321
+
2322
+ state._pendingSetup.push(
2323
+ t.variableDeclaration('const', [
2324
+ t.variableDeclarator(t.identifier(eachId), eachExpr)
2325
+ ]),
2326
+ t.variableDeclaration('const', [
2327
+ t.variableDeclarator(
2328
+ t.identifier(emptyId),
2329
+ t.callExpression(helper(state, '_$memo'), [
2330
+ t.arrowFunctionExpression([], t.blockStatement([
2331
+ t.variableDeclaration('const', [
2332
+ t.variableDeclarator(resolvedId, resolveList)
2333
+ ]),
2334
+ t.returnStatement(
2335
+ t.unaryExpression('!', t.unaryExpression('!',
2336
+ t.logicalExpression('&&',
2337
+ t.cloneNode(resolvedId),
2338
+ t.memberExpression(t.cloneNode(resolvedId), t.identifier('length'))
2339
+ )
2340
+ ))
2341
+ )
2342
+ ]))
2343
+ ])
2344
+ )
2345
+ ]),
2346
+ t.variableDeclaration('const', [
2347
+ t.variableDeclarator(t.identifier(listId), buildMapArrayCall(t.identifier(eachId)))
2348
+ ]),
2349
+ // The fallback thunk is hoisted rather than written inline in the
2350
+ // inserter below so that the inserter's body mentions no user code at
2351
+ // all. Its parameters can then be given fixed names without any risk of
2352
+ // capturing an identifier the fallback expression wanted from an outer
2353
+ // scope — this function is also called with a synthetic `{ node }` path
2354
+ // that carries no scope to generate a unique name from.
2355
+ t.variableDeclaration('const', [
2356
+ t.variableDeclarator(
2357
+ t.identifier(fallbackId),
2358
+ t.arrowFunctionExpression([], t.conditionalExpression(
2359
+ t.callExpression(t.identifier(emptyId), []),
2360
+ t.nullLiteral(),
2361
+ fallbackExpr
2362
+ ))
2363
+ )
2364
+ ])
2365
+ );
2366
+
2367
+ // The fallback goes in as an array (below), which only insert() takes.
2368
+ state.needsGeneralInsert = true;
2369
+ const parentParam = t.identifier('_parent');
2370
+ const markerParam = t.identifier('_marker');
2371
+ const endId = t.identifier('_end');
2372
+ return t.callExpression(
2373
+ t.memberExpression(t.identifier('Object'), t.identifier('assign')),
2374
+ [
2375
+ t.arrowFunctionExpression(
2376
+ [parentParam, markerParam],
2377
+ t.blockStatement([
2378
+ // The list goes in first so its `<!--/list-->` end marker sits
2379
+ // BEFORE the fallback: rows render above the empty state, and the
2380
+ // return value stays the end marker every other mapArray inserter
2381
+ // hands back.
2382
+ t.variableDeclaration('const', [
2383
+ t.variableDeclarator(endId, t.callExpression(t.identifier(listId), [
2384
+ t.cloneNode(parentParam),
2385
+ t.cloneNode(markerParam)
2386
+ ]))
2387
+ ]),
2388
+ // The thunk is wrapped in an ARRAY on purpose. `insert()` has two
2389
+ // ways to mount a function and only one of them survives here:
2390
+ // - passed bare, it takes insert's own reactive branch, whose
2391
+ // effect closes over the `parent` it was handed. When this
2392
+ // inserter is mounted through createDOM (a <For> as a component's
2393
+ // return value, at a fragment root, or inside a <Show> arm)
2394
+ // that parent is a throwaway DocumentFragment which is emptied
2395
+ // into the real container straight after. Every later run then
2396
+ // reconciles against a detached node, so the fallback was never
2397
+ // removed once rows arrived and stayed on screen underneath them.
2398
+ // - wrapped in an array, it goes through valuesToNodes -> createDOM,
2399
+ // whose reactive branch re-reads `endMarker.parentNode` on every
2400
+ // run. That is the same live-parent resolution mapArray does for
2401
+ // exactly this reason, so both halves survive being moved.
2402
+ t.expressionStatement(t.callExpression(helper(state, '_$insert'), [
2403
+ t.cloneNode(parentParam),
2404
+ t.arrayExpression([t.identifier(fallbackId)]),
2405
+ t.cloneNode(markerParam)
2406
+ ])),
2407
+ t.returnStatement(t.cloneNode(endId))
2408
+ ])
2409
+ ),
2410
+ t.identifier(listId),
2411
+ // Hydratable output also hands over the fallback, which hydrate()
2412
+ // adopts beside the list's rows (render.js adoptList).
2413
+ ...(state.hydratable ? [t.objectExpression([t.objectProperty(t.identifier('_fallback'), t.identifier(fallbackId))])] : []),
2414
+ ]
2415
+ );
2416
+ }
2417
+
2418
+ function transformShowFineGrained(path, state) {
2419
+ // <Show when={cond} fallback={alt}>{content}</Show>
2420
+ // → () => cond() ? content : (fallback || null)
2421
+ // This compiles to a reactive expression that insert() wraps in an effect.
2422
+ const { node } = path;
2423
+ const attributes = node.openingElement.attributes;
2424
+ const children = node.children;
2425
+
2426
+ let whenExpr = null;
2427
+ let fallbackExpr = null;
2428
+ for (const attr of attributes) {
2429
+ if (t.isJSXAttribute(attr)) {
2430
+ const name = getAttrName(attr);
2431
+ if (name === 'when') whenExpr = getAttributeValue(attr.value);
2432
+ else if (name === 'fallback') fallbackExpr = getAttributeValue(attr.value);
2433
+ }
2434
+ }
2435
+
2436
+ if (!whenExpr) {
2437
+ // <Show> without a when prop has no defined semantics — fail loudly at
2438
+ // build time so the user fixes their source instead of seeing runtime
2439
+ // confusion. compileError pins the message to the JSX location from
2440
+ // either a real NodePath or the synthetic `{ node }` a parent transform
2441
+ // passes; calling path.buildCodeFrameError directly crashed on the
2442
+ // second, which is the shape almost every real <Show> arrives as.
2443
+ throw compileError(
2444
+ path,
2445
+ state,
2446
+ '<Show> requires a "when" prop. Example: <Show when={isOpen} fallback={null}>...</Show>'
2447
+ );
2448
+ }
2449
+
2450
+ // The content: a render function written as the only child
2451
+ // ({(value) => <div>{value}</div>}), or the children themselves, text,
2452
+ // expressions, elements and fragments alike, as in a <Match> arm.
2453
+ let contentExpr = renderFunctionChild(children);
2454
+
2455
+ if (!contentExpr) {
2456
+ // Content children — collect and transform them.
2457
+ //
2458
+ // The arm's element setup belongs INSIDE the arm, exactly as it does for
2459
+ // a <Match> arm (see the identical splice in transformSwitchFineGrained).
2460
+ // transformElementFineGrained pushes `const _el$N = _tmpl$X()` and every
2461
+ // binding it needs into state._pendingSetup, and _pendingSetup is drained
2462
+ // next to the thunk this function returns. So without the splice the arm
2463
+ // was built, and its bindings ran, alongside the enclosing component:
2464
+ // <Show when={user}><p>{() => user().name}</p></Show>
2465
+ // threw at first render with a null user, and logged an uncaught effect
2466
+ // error on every transition back to falsy because the binding stayed
2467
+ // subscribed. Uncompiled, the same JSX is lazy — children of the runtime
2468
+ // Show really are deferred — so this was a compiled-vs-runtime
2469
+ // divergence, not just a bug.
2470
+ if (!state._pendingSetup) state._pendingSetup = [];
2471
+ const setupMark = state._pendingSetup.length;
2472
+ contentExpr = collectControlFlowContent(children, state);
2473
+ const setup = state._pendingSetup.splice(setupMark);
2474
+ if (setup.length > 0) {
2475
+ contentExpr = t.callExpression(
2476
+ t.arrowFunctionExpression([], t.blockStatement([...setup, t.returnStatement(contentExpr)])),
2477
+ []
2478
+ );
2479
+ }
2480
+ }
2481
+
2482
+ // Build:
2483
+ // () => { const _v = <condition>; return _v ? <consequent> : <alternate>; }
2484
+ // Hoisting into a local prevents double-evaluation of the `when` signal
2485
+ // (the consequent's render callback also needs the resolved value).
2486
+ let condition = buildWhenCondition(whenExpr, state);
2487
+
2488
+ const vId = path.scope
2489
+ ? path.scope.generateUidIdentifier('v')
2490
+ : t.identifier('_v');
2491
+
2492
+ const contentIsFn = t.isFunction(contentExpr);
2493
+ const consequent = contentIsFn
2494
+ ? t.callExpression(contentExpr, [t.cloneNode(vId)])
2495
+ : contentExpr;
2496
+ // A ternary fallback picks its arm by a lazy memo of its own, read only
2497
+ // while the fallback shows (memoizeTernaryTree).
2498
+ if (!state._pendingSetup) state._pendingSetup = [];
2499
+ const alternate = (fallbackExpr && memoizeTernaryTree(fallbackExpr, state._pendingSetup, state)) || fallbackExpr || t.nullLiteral();
2500
+
2501
+ // Branch memoization: route a reactive `when` through an
2502
+ // equality-gated memo so the insert effect only re-fires (recreating the
2503
+ // taken branch's DOM) when the condition actually changes — not on every
2504
+ // write to a signal the condition happens to read.
2505
+ // - Render-function children receive the resolved value (`{v => ...}`),
2506
+ // so the memo is VALUE-gated (Object.is): identity changes re-render,
2507
+ // matching pre-memo semantics.
2508
+ // - Static children only use the value for truthiness → gate on !!cond
2509
+ // so e.g. `when={items().length}` doesn't re-render on 2 → 3.
2510
+ if (isPotentiallyReactive(condition, state.signalNames, state.importedIdentifiers)) {
2511
+ const condId = state.nextMemoId();
2512
+ const memoBody = contentIsFn
2513
+ ? condition
2514
+ : t.unaryExpression('!', t.unaryExpression('!', condition));
2515
+ if (!state._pendingSetup) state._pendingSetup = [];
2516
+ state._pendingSetup.push(
2517
+ t.variableDeclaration('const', [
2518
+ t.variableDeclarator(
2519
+ t.identifier(condId),
2520
+ t.callExpression(helper(state, '_$memo'), [
2521
+ t.arrowFunctionExpression([], memoBody)
2522
+ ])
2523
+ )
2524
+ ])
2525
+ );
2526
+ condition = t.callExpression(t.identifier(condId), []);
2527
+ }
2528
+
2529
+ return t.arrowFunctionExpression([], t.blockStatement([
2530
+ t.variableDeclaration('const', [
2531
+ t.variableDeclarator(vId, condition)
2532
+ ]),
2533
+ t.returnStatement(
2534
+ t.conditionalExpression(t.cloneNode(vId), consequent, alternate)
2535
+ )
2536
+ ]));
2537
+ }
2538
+
2539
+ function collectControlFlowContent(children, state) {
2540
+ const parts = [];
2541
+ for (const child of children) {
2542
+ if (t.isJSXText(child)) {
2543
+ const text = normalizeJsxText(child.value);
2544
+ if (text) parts.push({ expr: t.stringLiteral(text), setup: [] });
2545
+ } else if (t.isJSXExpressionContainer(child)) {
2546
+ // The lowering an element's or a fragment's expression child gets: a
2547
+ // reactive one is a reactive child of its own, as the server renders it.
2548
+ if (!t.isJSXEmptyExpression(child.expression)) parts.push(arrayMember(state, () => lowerFragmentExprChild(child.expression, state)));
2549
+ } else if (t.isJSXElement(child)) {
2550
+ parts.push(arrayMember(state, () => transformElementFineGrained({ node: child }, state)));
2551
+ } else if (t.isJSXFragment(child)) {
2552
+ parts.push(arrayMember(state, () => transformFragmentFineGrained({ node: child }, state)));
2553
+ }
2554
+ }
2555
+ if (parts.length === 0) return t.nullLiteral();
2556
+ if (parts.length === 1) return parts[0].expr;
2557
+ return membersArray(parts, state, false, true);
2558
+ }
2559
+
2560
+ function transformSwitchFineGrained(path, state) {
2561
+ // <Switch fallback={alt}><Match when={a}>A</Match><Match when={b}>B</Match></Switch>
2562
+ // → () => a ? A : b ? B : alt
2563
+ //
2564
+ // Same reactive-thunk shape <Show> lowers to, for the same reason: the
2565
+ // component runs once, so the arm has to be picked inside a thunk that
2566
+ // insert() re-evaluates. The runtime Switch matches on Match marker vnodes,
2567
+ // which _$createComponent never produces (calling Match instead recurses),
2568
+ // so compiled JSX has no working runtime path. readSwitch decides whether the
2569
+ // <Switch> is What's and reads its arms.
2570
+ const read = readSwitch(path, state);
2571
+ if (read === null) return transformComponentFineGrained(path, state);
2572
+ const { arms, fallback: fallbackExpr } = read;
2573
+
2574
+ if (!state._pendingSetup) state._pendingSetup = [];
2575
+ const branches = [];
2576
+
2577
+ for (const { when: whenExpr, children } of arms) {
2578
+ // An arm's element setup belongs inside the arm. Hoisting it next to the
2579
+ // thunk, the way a lone element does, would build every arm's DOM on the
2580
+ // way to picking one.
2581
+ const setupMark = state._pendingSetup.length;
2582
+ let content = collectControlFlowContent(children, state);
2583
+ const setup = state._pendingSetup.splice(setupMark);
2584
+ if (setup.length > 0) {
2585
+ content = t.callExpression(
2586
+ t.arrowFunctionExpression([], t.blockStatement([...setup, t.returnStatement(content)])),
2587
+ []
2588
+ );
2589
+ }
2590
+
2591
+ branches.push([buildWhenCondition(whenExpr, state), content]);
2592
+ }
2593
+
2594
+ const anyReactive = branches.some(([condition]) =>
2595
+ isPotentiallyReactive(condition, state.signalNames, state.importedIdentifiers));
2596
+
2597
+ // A ternary fallback picks its arm by a lazy memo of its own, read only
2598
+ // when no arm matches (memoizeTernaryTree).
2599
+ const fallback = (fallbackExpr && memoizeTernaryTree(fallbackExpr, state._pendingSetup, state)) || fallbackExpr || t.nullLiteral();
2600
+
2601
+ if (!anyReactive) {
2602
+ let expr = fallback;
2603
+ for (let i = branches.length - 1; i >= 0; i--) {
2604
+ expr = t.conditionalExpression(branches[i][0], branches[i][1], expr);
2605
+ }
2606
+ return t.arrowFunctionExpression([], expr);
2607
+ }
2608
+
2609
+ // ONE memo over the whole chain, not one per arm. _$memo evaluates its body
2610
+ // immediately, so a memo per arm would evaluate every arm's `when` up front,
2611
+ // while the runtime Switch stops at the first match. A single memo that
2612
+ // resolves to the winning arm's index keeps that short-circuit (`when` props
2613
+ // after the first truthy one are never read) and still gates re-rendering on
2614
+ // the selected arm actually changing.
2615
+ let selector = t.numericLiteral(-1);
2616
+ for (let i = branches.length - 1; i >= 0; i--) {
2617
+ selector = t.conditionalExpression(branches[i][0], t.numericLiteral(i), selector);
2618
+ }
2619
+
2620
+ const armId = state.nextMemoId();
2621
+ state._pendingSetup.push(
2622
+ t.variableDeclaration('const', [
2623
+ t.variableDeclarator(
2624
+ t.identifier(armId),
2625
+ t.callExpression(helper(state, '_$memo'), [t.arrowFunctionExpression([], selector)])
2626
+ )
2627
+ ])
2628
+ );
2629
+
2630
+ let expr = fallback;
2631
+ for (let i = branches.length - 1; i >= 0; i--) {
2632
+ expr = t.conditionalExpression(
2633
+ t.binaryExpression('===', t.callExpression(t.identifier(armId), []), t.numericLiteral(i)),
2634
+ branches[i][1],
2635
+ expr
2636
+ );
2637
+ }
2638
+ return t.arrowFunctionExpression([], expr);
2639
+ }
2640
+
2641
+ // A fragment-as-root returns an array (or single value) that the runtime
2642
+ // mounts element-by-element (createDOM / insert). Unlike the element-child
2643
+ // path there's no host element to _$insert into with a marker, so reactive
2644
+ // children must instead be emitted as `() => expr` arrows — the runtime's
2645
+ // createDOM/insert treat a function array-item as a reactive binding (it
2646
+ // wraps it in an effect with comment markers). Without this, a bare dynamic
2647
+ // expression like `{count()}` is evaluated exactly once and never updates.
2648
+ //
2649
+ // This applies the SAME lowering the element-child expression path uses:
2650
+ // - tryLowerMapToMapArray for keyed `items().map(...)` → _$mapArray
2651
+ // - memoizeBranchCondition for reactive ternary/&&/|| (node-identity stable
2652
+ // branches: the taken branch's DOM is only rebuilt when the condition
2653
+ // actually flips, not on every read of a signal the condition touches)
2654
+ // - reactive expressions wrapped in `() =>` so the runtime tracks them
2655
+ // Memo (_$memo) declarations are pushed into state._pendingSetup, which
2656
+ // transformJsxRoot drains into the enclosing scope.
2657
+ function lowerFragmentExprChild(expr, state) {
2658
+ if (!state._pendingSetup) state._pendingSetup = [];
2659
+ const setup = state._pendingSetup;
2660
+
2661
+ // Auto-lower .map() to mapArray when the callback returns keyed JSX.
2662
+ const mapResult = tryLowerMapToMapArray(expr, state);
2663
+ if (mapResult) {
2664
+ // A bare _$mapArray(...) is a self-managing inserter and an arrow is
2665
+ // already reactive — emit as-is. A ternary/logical wrapping the call
2666
+ // keeps its condition reactive via a () => wrapper (and memoization).
2667
+ const isBareMapArray = isListInserterCall(mapResult);
2668
+ const isArrowAlready = t.isArrowFunctionExpression(mapResult);
2669
+ if (isArrowAlready && t.isExpression(mapResult.body)) {
2670
+ mapResult.body = memoizeBranchCondition(mapResult.body, setup, state);
2671
+ return mapResult;
2672
+ }
2673
+ if (isBareMapArray) return mapResult;
2674
+ const memoized = memoizeBranchCondition(mapResult, setup, state);
2675
+ return t.arrowFunctionExpression([], memoized);
2676
+ }
2677
+
2678
+ // mapArray() calls are self-managing inserters — pass directly.
2679
+ if (isListInserterCall(expr)) {
2680
+ adoptMapArrayCall(expr, state);
2681
+ return expr;
2682
+ }
2683
+
2684
+ if (isPotentiallyReactive(expr, state.signalNames, state.importedIdentifiers)) {
2685
+ // Branch memoization (C1): conditional/logical children only rebuild the
2686
+ // taken branch's DOM when the condition actually flips.
2687
+ expr = memoizeBranchCondition(expr, setup, state);
2688
+ return t.arrowFunctionExpression([], orderedRows(expr, state, true));
2689
+ }
2690
+
2691
+ // Static — emit verbatim.
2692
+ return orderedRows(expr, state, false);
2693
+ }
2694
+
2695
+ // In hydratable output, the arrays an expression child places, built so that
2696
+ // they claim the server's nodes in document order (_$members). `bracketed`:
2697
+ // the child is a reactive one, whose array value the server writes markers
2698
+ // around; the array an element's hole holds directly it writes none for.
2699
+ // - an array literal with JSX among its members: the elements claim as the
2700
+ // literal is evaluated, and the other members are adopted where they
2701
+ // stand;
2702
+ // - an unkeyed `.map()` whose rows are components, in a reactive child: each
2703
+ // row component claims as the call creates it, before the array the rows
2704
+ // make is placed, so it would take the markers the server wrote around
2705
+ // that array for its own. _$members enters them first.
2706
+ function orderedRows(expr, state, bracketed) {
2707
+ if (!state.hydratable) return expr;
2708
+ if (t.isArrayExpression(expr) && expr.elements.some(isJsxValue) && expr.elements.every((m) => m !== null && !t.isSpreadElement(m))) {
2709
+ const body = [];
2710
+ const items = expr.elements.map((member, i) => {
2711
+ const id = t.identifier(uniqueName(state, '_m$'));
2712
+ // Its JSX is built where it stands (isInPlace).
2713
+ member._whatInPlace = true;
2714
+ placeFlat(member);
2715
+ const value = t.isJSXElement(member) && !lowersToRegion(member, state) ? member : t.callExpression(helper(state, '_$member'), [member, t.numericLiteral(i)]);
2716
+ body.push(t.variableDeclaration('const', [t.variableDeclarator(id, value)]));
2717
+ return t.cloneNode(id);
2718
+ });
2719
+ body.push(t.returnStatement(t.arrayExpression(items)));
2720
+ const args = [t.arrowFunctionExpression([], t.blockStatement(body))];
2721
+ if (!bracketed) args.push(t.numericLiteral(1));
2722
+ return t.callExpression(helper(state, '_$members'), args);
2723
+ }
2724
+ if (t.isConditionalExpression(expr)) {
2725
+ expr.consequent = orderedRows(expr.consequent, state, bracketed);
2726
+ expr.alternate = orderedRows(expr.alternate, state, bracketed);
2727
+ return expr;
2728
+ }
2729
+ if (t.isLogicalExpression(expr)) {
2730
+ expr.right = orderedRows(expr.right, state, bracketed);
2731
+ return expr;
2732
+ }
2733
+ if (!bracketed || !t.isCallExpression(expr) || !t.isMemberExpression(expr.callee) || expr.callee.computed
2734
+ || !t.isIdentifier(expr.callee.property, { name: 'map' })) return expr;
2735
+ const fn = expr.arguments[0];
2736
+ if (!t.isArrowFunctionExpression(fn) && !t.isFunctionExpression(fn)) return expr;
2737
+ let row = fn.body;
2738
+ if (t.isBlockStatement(row)) {
2739
+ const last = row.body[row.body.length - 1];
2740
+ row = t.isReturnStatement(last) ? last.argument : null;
2741
+ }
2742
+ if (!t.isJSXElement(row) || !isComponentElement(row)) return expr;
2743
+ return t.callExpression(helper(state, '_$members'), [t.arrowFunctionExpression([], expr)]);
2744
+ }
2745
+
2746
+ // Whether JSX lowers to what claims only where it is placed, not where it is
2747
+ // created: <For>, <Show> and <Switch> (transformElementFineGrained) are a list
2748
+ // or a reactive child.
2749
+ function lowersToRegion(node, state) {
2750
+ const flow = controlFlowTag(node, state);
2751
+ return flow === 'For' || flow === 'Show' || flow === 'Switch' || (flow === null && liveKey(node, state) !== null);
2752
+ }
2753
+
2754
+ function transformFragmentFineGrained(path, state) {
2755
+ const { node } = path;
2756
+ const children = node.children;
2757
+
2758
+ const members = [];
2759
+ for (const child of children) {
2760
+ if (t.isJSXText(child)) {
2761
+ const text = normalizeJsxText(child.value);
2762
+ if (text) members.push({ expr: t.stringLiteral(text), setup: [] });
2763
+ } else if (t.isJSXExpressionContainer(child)) {
2764
+ if (!t.isJSXEmptyExpression(child.expression)) {
2765
+ members.push(arrayMember(state, () => lowerFragmentExprChild(child.expression, state)));
2766
+ }
2767
+ } else if (t.isJSXElement(child)) {
2768
+ members.push(arrayMember(state, () => transformElementFineGrained({ node: child }, state)));
2769
+ } else if (t.isJSXFragment(child)) {
2770
+ members.push(arrayMember(state, () => transformFragmentFineGrained({ node: child }, state)));
2771
+ }
2772
+ }
2773
+
2774
+ if (members.length === 1) return members[0].expr;
2775
+ // The server renders a fragment as the array a Fragment returns, which it
2776
+ // brackets, unless it is a member of an array other code builds.
2777
+ const nested = path.parentPath ? followsOtherMarkers(path) : false;
2778
+ return membersArray(members, state, nested, !nested);
2779
+ }
2780
+
2781
+ // Whether the fragment at `path` is a member of an array other code builds:
2782
+ // a row a callback returns (`.map(x => <>…</>)`) or a member of an array
2783
+ // literal. The server brackets that array before the fragment.
2784
+ function followsOtherMarkers(path) {
2785
+ let p = path;
2786
+ for (;;) {
2787
+ const parent = p.parentPath;
2788
+ if (!parent || parent.isArrayExpression()) return parent !== null;
2789
+ if (parent.isReturnStatement() || (parent.isArrowFunctionExpression() && p.key === 'body')) {
2790
+ const fn = parent.isReturnStatement() ? parent.getFunctionParent() : parent;
2791
+ return fn !== null && fn.parentPath.isCallExpression() && fn.listKey === 'arguments';
2792
+ }
2793
+ const climbs = (parent.isConditionalExpression() && p.key !== 'test')
2794
+ || (parent.isLogicalExpression() && p.key === 'right')
2795
+ || parent.isParenthesizedExpression() || parent.isTSAsExpression() || parent.isTSNonNullExpression();
2796
+ if (!climbs) return false;
2797
+ p = parent;
2798
+ }
2799
+ }
2800
+
2801
+ // --- Arrays, hydrated in order ---
2802
+ // While hydrating, an element or a component claims the server's nodes when
2803
+ // it is created, and an array's other members (text, a reactive child, a
2804
+ // list, a value) are adopted when the array is placed, after all of them
2805
+ // were created. An array literal written after its members' setup therefore
2806
+ // claims out of document order where such a member stands before one that
2807
+ // claims when created, or where a member's setup claims before an earlier
2808
+ // member claims inline: the server's nodes go to the wrong members, and the
2809
+ // page shows them in the wrong order. A hydratable build builds that array
2810
+ // with _$members, which creates the members in order and adopts each one
2811
+ // that does not claim when created where it stands (_$member).
2812
+
2813
+ // A member of an array: its expression and the statements transforming it
2814
+ // added to _pendingSetup.
2815
+ function arrayMember(state, transform) {
2816
+ if (!state._pendingSetup) state._pendingSetup = [];
2817
+ const mark = state._pendingSetup.length;
2818
+ const expr = transform();
2819
+ return { expr, setup: state._pendingSetup.slice(mark) };
2820
+ }
2821
+
2822
+ // The array of `members`, whose setup is the end of _pendingSetup.
2823
+ // `nested`: it follows the markers of an array other code builds.
2824
+ // `bracketed`: the server writes its markers around it (a conditional's
2825
+ // content, the value of a reactive child), before those of a component in it.
2826
+ // `always`: built with _$members whatever the order its members claim in.
2827
+ function membersArray(members, state, nested = false, bracketed = false, always = false) {
2828
+ if (state.hydratable) for (const m of members) placeFlat(m.expr);
2829
+ if (!state.hydratable || !(always || claimsOutOfOrder(members, state, nested, bracketed))) return t.arrayExpression(members.map((m) => m.expr));
2830
+ const own = members.reduce((n, m) => n + m.setup.length, 0);
2831
+ state._pendingSetup.splice(state._pendingSetup.length - own, own);
2832
+ const body = [];
2833
+ const items = members.map((m, i) => {
2834
+ body.push(...m.setup);
2835
+ if (t.isIdentifier(m.expr) && createdClaims(m, state)) return m.expr;
2836
+ const id = t.identifier(uniqueName(state, '_m$'));
2837
+ // JSX inside the member is still built where it stands (isInPlace).
2838
+ m.expr._whatInPlace = true;
2839
+ const value = createdClaims(m, state) ? m.expr : t.callExpression(helper(state, '_$member'), [m.expr, t.numericLiteral(i)]);
2840
+ body.push(t.variableDeclaration('const', [t.variableDeclarator(id, value)]));
2841
+ return t.cloneNode(id);
2842
+ });
2843
+ body.push(t.returnStatement(t.arrayExpression(items)));
2844
+ const args = [t.arrowFunctionExpression([], t.blockStatement(body))];
2845
+ if (nested) args.push(t.numericLiteral(1));
2846
+ return t.callExpression(helper(state, '_$members'), args);
2847
+ }
2848
+
2849
+ function claimsOutOfOrder(members, state, nested, bracketed) {
2850
+ // An array _$members builds among the members takes its own markers, so
2851
+ // this one must have taken its own before; so does a component in an array
2852
+ // the server brackets, whose output may be such an array.
2853
+ if (members.some((m) => isMembersCall(m.expr, state))) return true;
2854
+ if (bracketed && members.length > 1 && members.some((m) => isComponentCall(m.expr, state))) return true;
2855
+ // The other code builds its next members before it places this one.
2856
+ if (nested && members.some((m) => !createdClaims(m, state))) return true;
2857
+ // An earlier member is adopted only when the array is placed; an earlier
2858
+ // member claims as the literal is evaluated.
2859
+ let placed = false;
2860
+ let inline = false;
2861
+ for (const m of members) {
2862
+ const setupClaims = m.setup.some((stmt) => containsClaim(stmt, state));
2863
+ const inlineClaims = claimsInline(m.expr);
2864
+ if ((placed && (setupClaims || inlineClaims)) || (inline && setupClaims)) return true;
2865
+ if (!createdClaims(m, state)) placed = true;
2866
+ if (inlineClaims) inline = true;
2867
+ }
2868
+ return false;
2869
+ }
2870
+
2871
+ // The placing reads (_$place) a value holds where it is placed: placed in an
2872
+ // element's hole, or as a member of a fragment or an array, they are placed
2873
+ // where the server writes their members in place, with no markers of their
2874
+ // own (dom.js _place).
2875
+ function placeFlat(expr) {
2876
+ if (t.isConditionalExpression(expr)) {
2877
+ placeFlat(expr.consequent);
2878
+ placeFlat(expr.alternate);
2879
+ } else if (t.isLogicalExpression(expr)) {
2880
+ placeFlat(expr.left);
2881
+ placeFlat(expr.right);
2882
+ } else if (t.isCallExpression(expr) && expr.callee._whatPlace === true && expr.arguments.length === 2) {
2883
+ expr.arguments.push(t.numericLiteral(1));
2884
+ }
2885
+ }
2886
+
2887
+ const CLAIMING = ['_$claim', '_$claimControl', '_$createComponent', '_$members'];
2888
+
2889
+ function isMembersCall(node, state) {
2890
+ return t.isCallExpression(node) && t.isIdentifier(node.callee) && helperLocals(state).get('_$members') === node.callee.name;
2891
+ }
2892
+
2893
+ // A call to one of the runtime helpers compiled output imports.
2894
+ function isHelperCall(node, state) {
2895
+ if (!t.isIdentifier(node.callee)) return false;
2896
+ for (const local of helperLocals(state).values()) if (local === node.callee.name) return true;
2897
+ return false;
2898
+ }
2899
+
2900
+ function isComponentCall(node, state) {
2901
+ node = placedCall(node, state);
2902
+ return t.isCallExpression(node) && t.isIdentifier(node.callee) && helperLocals(state).get('_$createComponent') === node.callee.name;
2903
+ }
2904
+
2905
+ function isClaimCall(node, state) {
2906
+ node = placedCall(node, state);
2907
+ return t.isCallExpression(node) && t.isIdentifier(node.callee)
2908
+ && CLAIMING.some((name) => helperLocals(state).get(name) === node.callee.name);
2909
+ }
2910
+
2911
+ function containsClaim(node, state) {
2912
+ let found = false;
2913
+ t.traverseFast(node, (n) => { if (!found && isClaimCall(n, state)) found = true; });
2914
+ return found;
2915
+ }
2916
+
2917
+ // Whether creating the member claims everything it renders: an element, a
2918
+ // component, or an array _$members builds.
2919
+ function createdClaims(m, state) {
2920
+ if (isClaimCall(m.expr, state)) return true;
2921
+ return t.isIdentifier(m.expr) && m.setup.some((stmt) => t.isVariableDeclaration(stmt)
2922
+ && stmt.declarations.some((d) => t.isIdentifier(d.id, { name: m.expr.name }) && isClaimCall(d.init, state)));
2923
+ }
2924
+
2925
+ // Whether evaluating `expr` can claim: anything but a literal, a function, a
2926
+ // name or a list's inserter.
2927
+ function claimsInline(expr) {
2928
+ return !(t.isLiteral(expr) || t.isFunction(expr) || t.isIdentifier(expr) || isListInserterCall(expr));
2929
+ }
2930
+
2931
+ // Closing tags at the very end of a template: end of input closes them.
2932
+ const TRAILING_CLOSE_TAGS = /(?:<\/[a-zA-Z][\w:.-]*>)+$/;
2933
+
2934
+ // Template deduplication: same markup → same module-level const.
2935
+ //
2936
+ // An SVG or MathML root other than <svg>/<math> itself only parses in its
2937
+ // namespace inside one, so the compiler wraps it and flags the template (2):
2938
+ // the runtime clones the wrapper's only child.
2939
+ // Flag credit: Solid 2.0's template flags (MIT, Ryan Carniato).
2940
+ function getOrCreateTemplate(state, html, ns, rootTag) {
2941
+ let flag = 0;
2942
+ if (ns === 'svg' && rootTag !== 'svg') {
2943
+ html = `<svg>${html}</svg>`;
2944
+ flag = 2;
2945
+ } else if (ns === 'math' && rootTag !== 'math') {
2946
+ html = `<math>${html}</math>`;
2947
+ flag = 2;
2948
+ }
2949
+ html = html.replace(TRAILING_CLOSE_TAGS, '');
2950
+ const dedupKey = `${flag}:${html}`;
2951
+ if (state.templateMap.has(dedupKey)) {
2952
+ return state.templateMap.get(dedupKey);
2953
+ }
2954
+ const id = uniqueName(state, '_tmpl$');
2955
+ state.templateMap.set(dedupKey, id);
2956
+ state.templates.push({ id, html, flag });
2957
+ return id;
2958
+ }
2959
+
2960
+ // Shared driver for top-level JSX roots (elements AND fragments).
2961
+ //
2962
+ // transformElementFineGrained does NOT emit IIFEs: it pushes setup
2963
+ // statements (`const _el$N = _tmpl$X(); _el$N.$$click = ...; _$insert(...)`)
2964
+ // into state._pendingSetup and returns the bare `_el$N` identifier. Whoever
2965
+ // visits the JSX root is responsible for draining _pendingSetup and placing
2966
+ // those statements somewhere the returned reference can see them.
2967
+ //
2968
+ // The JSXElement and JSXFragment visitors both use this driver, so a fragment
2969
+ // whose element children have dynamic parts (event handlers, dynamic
2970
+ // attrs/children) declares the _el$N variables those parts reference. Branch
2971
+ // memo and specialized-setter statements ride in _pendingSetup too.
2972
+ export function transformJsxRoot(path, state) {
2973
+ enterJsxRoot(path, state);
2974
+ state._pendingSetup = [];
2975
+ state._selectorIds = new Map();
2976
+ const outside = state.hydratable && !isInPlace(path, state);
2977
+ const transform = t.isJSXFragment(path.node) ? transformFragmentFineGrained : transformElementFineGrained;
2978
+ const transformed = transform(path, state);
2979
+ const pending = state._pendingSetup;
2980
+ state._pendingSetup = [];
2981
+ if (state._selectorDecls.length > 0) {
2982
+ pending.unshift(...state._selectorDecls);
2983
+ state._selectorDecls = [];
2984
+ }
2985
+
2986
+ // Hydratable output: JSX built before it is placed is built on the client
2987
+ // while hydrating, and replaces the server's copy where it lands.
2988
+ if (outside) {
2989
+ pending.push(t.returnStatement(transformed));
2990
+ path.replaceWith(t.callExpression(helper(state, '_$outside'), [t.arrowFunctionExpression([], t.blockStatement(pending))]));
2991
+ return;
2992
+ }
2993
+
2994
+ if (pending.length > 0) {
2995
+ // Find the enclosing statement to hoist setup before it,
2996
+ // but only if it's in the SAME function scope. Crossing into
2997
+ // an inner arrow/function (e.g., .map(item => <JSX/>)) would
2998
+ // hoist references to closure variables out of scope.
2999
+ let stmtPath = path;
3000
+ let crossedFunctionBoundary = false;
3001
+ // Setup hoisted out of a guard runs whether the guard opens or not.
3002
+ // `return user() && <p>{user().name}</p>` is the React shape everybody
3003
+ // writes, and hoisting built the <p> and ran `() => user().name` at
3004
+ // mount, so the very first render threw on a null user. Same for a
3005
+ // ternary arm and for a guarded arm sitting in a component prop.
3006
+ // A guarded arm has to be CONSTRUCTED INSIDE its guard, which is exactly
3007
+ // what the IIFE path below does.
3008
+ let crossedGuard = false;
3009
+ while (stmtPath && !stmtPath.isStatement()) {
3010
+ if (stmtPath.isArrowFunctionExpression() || stmtPath.isFunctionExpression()) {
3011
+ crossedFunctionBoundary = true;
3012
+ }
3013
+ if (isConditionallyEvaluated(stmtPath)) crossedGuard = true;
3014
+ stmtPath = stmtPath.parentPath;
3015
+ }
3016
+ // We can safely hoist setup as siblings of `stmtPath` ONLY if
3017
+ // `stmtPath` lives inside a statement list (BlockStatement.body or
3018
+ // Program.body). For single-statement positions like
3019
+ // `if (cond) return <jsx/>;` or `while (x) return <jsx/>;`,
3020
+ // Babel's `insertBefore` wraps the parent into a block lazily and
3021
+ // multi-statement inserts end up split across scopes, leaving the
3022
+ // `_$insert(_el$N, ...)` call outside the block that declares
3023
+ // `const _el$N`. This is a TDZ/ReferenceError at runtime.
3024
+ //
3025
+ // To guarantee that ALL setup statements and the returned reference
3026
+ // share one lexical block, require that `stmtPath.listKey` points
3027
+ // at a statement list. Otherwise fall through to the IIFE path,
3028
+ // which is always safe.
3029
+ const inStatementList =
3030
+ stmtPath
3031
+ && stmtPath.isStatement()
3032
+ && (stmtPath.listKey === 'body' || stmtPath.listKey === 'consequent')
3033
+ && Array.isArray(stmtPath.container);
3034
+ if (inStatementList && !crossedFunctionBoundary && !crossedGuard) {
3035
+ // Same function scope — safe to hoist setup before the enclosing
3036
+ // statement. Works for return statements too: `insertBefore`
3037
+ // places setup above `return <jsx/>` without wrapping in an IIFE.
3038
+ stmtPath.insertBefore(pending);
3039
+ path.replaceWith(transformed);
3040
+ } else if (path.parentPath.isArrowFunctionExpression() && path.key === 'body') {
3041
+ // The JSX is an arrow's whole body (`row => <tr>…</tr>`): the arrow
3042
+ // takes a block body, which is the same scope and placement an IIFE
3043
+ // would give, without a closure and a call per evaluation.
3044
+ pending.push(t.returnStatement(transformed));
3045
+ path.replaceWith(t.blockStatement(pending));
3046
+ } else {
3047
+ // Crossed a function boundary or a guard, or no enclosing statement
3048
+ // was found — fall back to IIFE, which keeps closure variables in
3049
+ // scope AND keeps the construction where the source put it.
3050
+ pending.push(t.returnStatement(transformed));
3051
+ path.replaceWith(
3052
+ t.callExpression(
3053
+ t.arrowFunctionExpression([], t.blockStatement(pending)),
3054
+ []
3055
+ )
3056
+ );
3057
+ }
3058
+ } else {
3059
+ path.replaceWith(transformed);
3060
+ }
3061
+ }
3062
+
3063
+
3064
+ // Whether a JSX root is evaluated where it renders, so that a hydratable
3065
+ // build can claim the server's nodes for it as it is built: returned (from a
3066
+ // function, or as an arrow's body, e.g. a component, a row or a region
3067
+ // thunk), or the value of a hole the compiler placed (_whatInPlace), through
3068
+ // conditionals, logical operators and array literals. What a callback a call
3069
+ // takes returns (`links.map((l) => <li />)`) is where that call is: in place
3070
+ // in a hole, built before it is placed in a variable. Anything else (a
3071
+ // variable, an attribute that is not a slot, an argument) is built before it
3072
+ // is placed.
3073
+ function isInPlace(path, state) {
3074
+ let p = path;
3075
+ for (;;) {
3076
+ const parent = p.parentPath;
3077
+ if (!parent) return false;
3078
+ if (p.node._whatInPlace) return true;
3079
+ /** @type {any} */
3080
+ let fn = null;
3081
+ if (parent.isReturnStatement()) fn = parent.getFunctionParent();
3082
+ else if (parent.isArrowFunctionExpression() && p.key === 'body') fn = parent;
3083
+ if (fn !== null) {
3084
+ // A function the runtime calls where it renders (a component, a row, a
3085
+ // region, a children factory, a slot) places what it returns.
3086
+ const call = fn.parentPath;
3087
+ if (fn.listKey !== 'arguments' || !(call.isCallExpression() || call.isOptionalCallExpression()) || isHelperCall(call.node, state)) return true;
3088
+ p = call;
3089
+ continue;
3090
+ }
3091
+ const climbs = (parent.isConditionalExpression() && p.key !== 'test')
3092
+ || (parent.isLogicalExpression() && p.key === 'right')
3093
+ || (parent.isSequenceExpression() && p.key === parent.node.expressions.length - 1)
3094
+ || parent.isArrayExpression()
3095
+ || parent.isParenthesizedExpression()
3096
+ || parent.isTSAsExpression() || parent.isTSNonNullExpression() || parent.isTypeCastExpression()
3097
+ || (parent.isJSXExpressionContainer() && parent.parentPath.isJSXElement());
3098
+ if (!climbs) return false;
3099
+ p = parent;
3100
+ }
3101
+ }
3102
+
3103
+ // --- Program setup and teardown ---
3104
+
3105
+ export function initDomState(state) {
3106
+ // A module whose every list is a keyed .map() imports the keyed-only list
3107
+ // entry; <For> and hand-written mapArray() need the general one.
3108
+ state.needsGeneralMapArray = false;
3109
+ // A module none of whose component calls hands over children or JSX in a
3110
+ // prop imports the component call that installs no lazy getter.
3111
+ state.needsLazyProps = false;
3112
+ // A module whose every insert is of a function written in the hole imports
3113
+ // the reactive region insert() would hand it to.
3114
+ state.needsGeneralInsert = false;
3115
+ // A module that calls a component which may be a class component (one
3116
+ // whose prototype has render(): anything but a plain function the module
3117
+ // can see, isPlainFunctionComponent) imports the call that runs one.
3118
+ state.classComponents = false;
3119
+ // A module whose JSX writes a prop of a select or an option installs the
3120
+ // selection code (_$selects()).
3121
+ state.makesSelects = false;
3122
+ // A module whose JSX has an SVG element with an XLink or XML attribute
3123
+ // (`xlinkHref`, `xmlLang`) or a spread installs their writer (_$xlink()).
3124
+ state.writesXlink = false;
3125
+ // A module whose JSX can build a form field installs the carrying of what
3126
+ // the user changed before hydration (_$carryFields(), buildsField).
3127
+ state.carriesFields = false;
3128
+ // A component reads a field of a prop in its run (common.js markPropFieldReads).
3129
+ state.marksPropFields = false;
3130
+ state._selectorDecls = [];
3131
+ state._selectorIds = new Map();
3132
+ state.delegatedEvents = new Set();
3133
+ state.templates = [];
3134
+ state.templateMap = new Map(); // html → template id (deduplication)
3135
+ // The readers of keyed rows' plain fields (`r => r.label`), hoisted to the
3136
+ // module so a row allocates none.
3137
+ state.rowFieldReaders = [];
3138
+ state._pendingSetup = [];
3139
+ state.nextVarId = () => uniqueName(state, '_el$');
3140
+ state.nextMemoId = () => uniqueName(state, '_c$');
3141
+ // Output a page that a server rendered can hydrate (render.js _$claim).
3142
+ state.hydratable = state.opts?.hydratable === true;
3143
+ }
3144
+
3145
+ // The runtime helpers compiled DOM output imports, in the order their import
3146
+ // specifiers are written. `null` takes the export name from the module state.
3147
+ const RENDER_IMPORTS = [
3148
+ // The compiler-internal `_$template`, never the public `template`, which
3149
+ // dev-warns for hand-written calls with dynamic strings.
3150
+ // Hydratable output takes `_$htemplate`, which also hands claims the root.
3151
+ ['_$template', null],
3152
+ ['_$insert', null],
3153
+ ['_$effect', 'effect'],
3154
+ ['_$mapArray', null],
3155
+ ['_$item', '_$item'],
3156
+ ['_$field', '_$field'],
3157
+ ['_$hfield', '_$hfield'],
3158
+ ['_$plain', '_$plain'],
3159
+ ['_$hplain', '_$hplain'],
3160
+ ['_$rowFields', '_$rowFields'],
3161
+ ['_$propField', '_$propField'],
3162
+ ['_$createSelector', 'createSelector'],
3163
+ ['_$spread', '_$spread'],
3164
+ ['_$spreads', '_$spreads'],
3165
+ ['_$xlink', '_$xlink'],
3166
+ ['_$controlled', '_$controlled'],
3167
+ ['_$setProp', '_$setProp'],
3168
+ ['_$retype', '_$retype'],
3169
+ ['_$memo', '_$memo'],
3170
+ ['_$lazyMemo', '_$lazyMemo'],
3171
+ ['_$untrack', 'untrack'],
3172
+ ['_$keyed', '_$keyed'],
3173
+ ['_$Island', '_$Island'],
3174
+ ['_$buildDiagnostics', '_$buildDiagnostics'],
3175
+ ['_$setClass', 'setClass'],
3176
+ ['_$className', 'className'],
3177
+ ['_$setClassList', 'setClassList'],
3178
+ ['_$applyRef', 'applyRef'],
3179
+ ['_$setStyle', 'setStyle'],
3180
+ ['_$setAttr', 'setAttr'],
3181
+ ['_$setValue', '_$setValue'],
3182
+ ['_$setChecked', 'setChecked'],
3183
+ ['_$createComponent', null],
3184
+ ['_$componentVNode', '_$componentVNode'],
3185
+ ['_$hcomponentVNode', '_$hcomponentVNode'],
3186
+ ['_$delegateEvents', 'delegateEvents'],
3187
+ ['_$changes', '_$changes'],
3188
+ ['_$own', '_$own'],
3189
+ ['_$on', 'on'],
3190
+ ['_$claim', '_$claim'],
3191
+ ['_$next', '_$next'],
3192
+ ['_$control', '_$control'],
3193
+ ['_$claimControl', '_$claimControl'],
3194
+ ['_$skip', '_$skip'],
3195
+ ['_$hole', '_$hole'],
3196
+ ['_$exit', '_$exit'],
3197
+ ['_$outside', '_$outside'],
3198
+ ['_$members', '_$members'],
3199
+ ['_$member', '_$member'],
3200
+ ['_$slots', '_$slots'],
3201
+ ['_$place', '_$place'],
3202
+ ['_$merge', '_$merge'],
3203
+ ['_$marked', '_$marked'],
3204
+ ['_$omit', '_$omit'],
3205
+ ['_$inNs', '_$inNs'],
3206
+ ['_$selects', '_$selects'],
3207
+ ['_$carryFields', '_$carryFields'],
3208
+ ];
3209
+
3210
+ // The export a helper whose RENDER_IMPORTS entry is null imports.
3211
+ function renderExport(name, state) {
3212
+ if (name === '_$mapArray') return state.needsGeneralMapArray ? 'mapArray' : '_$mapKeyed';
3213
+ if (name === '_$template') return state.hydratable ? '_$htemplate' : '_$template';
3214
+ if (name === '_$insert') return state.needsGeneralInsert ? 'insert' : '_$reactive';
3215
+ // A module whose every component is a plain function imports the call that
3216
+ // looks for neither a class component nor a tag held in a binding (render.js
3217
+ // asComponent).
3218
+ if (state.hydratable) return state.classComponents ? '_$hcreateComponent' : '_$hcreateFn';
3219
+ if (state.needsLazyProps) return state.classComponents ? '_$createComponent' : '_$createLazyFn';
3220
+ return state.classComponents ? '_$createLeaf' : '_$createFn';
3221
+ }
3222
+
3223
+ // The components of what-framework itself, which are functions: its root
3224
+ // entry's, and its router's.
3225
+ const FRAMEWORK_SOURCES = new Set(['what-framework', 'what-core', 'what-framework/router', 'what-router']);
3226
+
3227
+ // Whether the component a JSX tag names is a plain function, which a class
3228
+ // component (a prototype with render() or isReactComponent, render.js
3229
+ // _toFunctionComponent) can never be: an arrow function the module defines
3230
+ // (the bridge would construct it, which throws for an arrow, whatever its
3231
+ // prototype holds), a function the module defines, does not export and uses
3232
+ // only in JSX (so nothing can give its prototype a render()), and a component
3233
+ // imported from what-framework. In every case the binding is never
3234
+ // reassigned.
3235
+ function isPlainFunctionComponent(scope, name, marks) {
3236
+ if (!t.isJSXIdentifier(name) || scope == null) return false;
3237
+ const binding = scope.getBinding(name.name);
3238
+ if (!binding || !binding.constant) return false;
3239
+ const decl = binding.path;
3240
+ if (binding.kind === 'module') {
3241
+ return t.isImportSpecifier(decl.node) && FRAMEWORK_SOURCES.has(decl.parent.source.value);
3242
+ }
3243
+ // A call of what-react translate mode's marks (babel-plugin.js
3244
+ // TRANSLATED_MARKS) on the function: `_$translated(function Row() {…})`,
3245
+ // `_$translated(App)`, `_$inReact(App)`.
3246
+ const marked = (node) => t.isCallExpression(node) && t.isIdentifier(node.callee) && marks.has(node.callee.name);
3247
+ /** @type {any} */
3248
+ let fn = null;
3249
+ if (t.isFunctionDeclaration(decl.node)) fn = decl.node;
3250
+ else if (t.isVariableDeclarator(decl.node)) {
3251
+ const init = marked(decl.node.init) && decl.node.init.arguments.length === 1 ? decl.node.init.arguments[0] : decl.node.init;
3252
+ if (t.isArrowFunctionExpression(init) || t.isFunctionExpression(init)) fn = init;
3253
+ }
3254
+ if (fn === null || fn.async || fn.generator) return false;
3255
+ if (t.isArrowFunctionExpression(fn)) return true;
3256
+ // Another module could give an exported function a prototype with render().
3257
+ const statement = t.isVariableDeclarator(decl.node) ? decl.parentPath : decl;
3258
+ if (t.isExportNamedDeclaration(statement.parent) || t.isExportDefaultDeclaration(statement.parent)) return false;
3259
+ // A component call this compiler wrote is a tag too: Babel counts its
3260
+ // reference once the call stands in a function a later lowering made (the
3261
+ // element of a branch's arm, a key's build: render.js _$keyed).
3262
+ return binding.referencePaths.every((ref) => ref.node._whatTag === true || t.isJSXOpeningElement(ref.parent) || t.isJSXClosingElement(ref.parent)
3263
+ || (ref.listKey === 'arguments' && marked(ref.parent)));
3264
+ }
3265
+
3266
+ // Whether a component tag may hold a string at run time (a tag held in a
3267
+ // binding: a prop, a parameter, a variable), unlike a name, or a member of a
3268
+ // name, that the module imports.
3269
+ function mayHoldTag(scope, name) {
3270
+ let root = name;
3271
+ while (t.isJSXMemberExpression(root)) root = root.object;
3272
+ const binding = t.isJSXIdentifier(root) && scope != null ? scope.getBinding(root.name) : null;
3273
+ return binding?.kind !== 'module';
3274
+ }
3275
+
3276
+ function isEmptyArray(node) {
3277
+ return t.isArrayExpression(node) && node.elements.length === 0;
3278
+ }
3279
+ const CORE_IMPORTS = ['h'];
3280
+
3281
+ export function finishDomProgram(path, state) {
3282
+ // Emit LAZY event delegation setup if any delegated events were used.
3283
+ // A bare module-top-level `_$delegateEvents([...])` call would be a side
3284
+ // effect that (a) keeps bundlers from tree-shaking modules whose components
3285
+ // are never used, and (b) attaches document listeners at import time even
3286
+ // when no component ever mounts.
3287
+ // Instead we emit a once-guarded helper that each element setup calls
3288
+ // at construction time; unused modules carry only dead declarations
3289
+ // that DCE removes.
3290
+ /** @type {any[] | null} */
3291
+ let delegation = null;
3292
+ if (state.delegatedEvents.size > 0) {
3293
+ // onChange (`$$change`) is React's change event, which its own install
3294
+ // delegates (what-core render.js _$changes): a module without one carries
3295
+ // none of its code.
3296
+ const events = [...state.delegatedEvents].filter(e => e !== 'change');
3297
+ const install = [];
3298
+ if (events.length > 0) {
3299
+ install.push(t.expressionStatement(
3300
+ t.callExpression(helper(state, '_$delegateEvents'), [t.arrayExpression(events.map(e => t.stringLiteral(e)))])
3301
+ ));
3302
+ }
3303
+ if (state.delegatedEvents.has('change')) {
3304
+ install.push(t.expressionStatement(t.callExpression(helper(state, '_$changes'), [])));
3305
+ }
3306
+ // function _$delegate$(el) { _$own(el); if (_$delegated$) return; _$delegated$ = true; _$delegateEvents([...]); _$changes(); }
3307
+ const helperFn = t.functionDeclaration(
3308
+ helper(state, '_$delegate$'),
3309
+ [t.identifier('el')],
3310
+ t.blockStatement([
3311
+ t.expressionStatement(t.callExpression(helper(state, '_$own'), [t.identifier('el')])),
3312
+ t.ifStatement(
3313
+ helper(state, '_$delegated$'),
3314
+ t.returnStatement()
3315
+ ),
3316
+ t.expressionStatement(
3317
+ t.assignmentExpression('=', helper(state, '_$delegated$'), t.booleanLiteral(true))
3318
+ ),
3319
+ ...install,
3320
+ ])
3321
+ );
3322
+ delegation = [
3323
+ t.variableDeclaration('let', [
3324
+ t.variableDeclarator(helper(state, '_$delegated$'), t.booleanLiteral(false))
3325
+ ]),
3326
+ helperFn,
3327
+ ];
3328
+ }
3329
+
3330
+ // At module scope, so the code is installed before any of the module's
3331
+ // components builds a select.
3332
+ if (state.makesSelects) path.unshiftContainer('body', t.expressionStatement(t.callExpression(helper(state, '_$selects'), [])));
3333
+ if (state.writesXlink) path.unshiftContainer('body', t.expressionStatement(t.callExpression(helper(state, '_$xlink'), [])));
3334
+ if (state.carriesFields) path.unshiftContainer('body', t.expressionStatement(t.callExpression(helper(state, '_$carryFields'), [])));
3335
+
3336
+ for (const reader of state.rowFieldReaders.reverse()) {
3337
+ path.unshiftContainer('body', t.variableDeclaration('const', [t.variableDeclarator(t.identifier(reader.id), reader.fn)]));
3338
+ }
3339
+
3340
+ // Insert template declarations at top of program (hoisted to module scope)
3341
+ for (const tmpl of state.templates.reverse()) {
3342
+ // /* @__PURE__ */ marks the hoisted call as side-effect-free so
3343
+ // bundlers (esbuild/rollup/terser) can drop templates whose
3344
+ // components are tree-shaken away.
3345
+ const tmplCall = t.callExpression(helper(state, '_$template'), tmpl.flag
3346
+ ? [t.stringLiteral(tmpl.html), t.numericLiteral(tmpl.flag)]
3347
+ : [t.stringLiteral(tmpl.html)]);
3348
+ t.addComment(tmplCall, 'leading', ' @__PURE__ ');
3349
+ path.unshiftContainer('body',
3350
+ t.variableDeclaration('const', [
3351
+ t.variableDeclarator(t.identifier(tmpl.id), tmplCall)
3352
+ ])
3353
+ );
3354
+ }
3355
+
3356
+ if (state._buildDiagnostics?.length) {
3357
+ const records = state._buildDiagnostics.map(diagnosticRecord);
3358
+ path.pushContainer('body', t.expressionStatement(t.callExpression(helper(state, '_$buildDiagnostics'), [t.arrayExpression(records)])));
3359
+ }
3360
+
3361
+ const used = helperLocals(state);
3362
+ // Whether this module builds DOM (a template clone or a component call that
3363
+ // renders one), which a server bundle cannot run. The Vite plugin reads it.
3364
+ if (state.file?.metadata && (used.has('_$template') || used.has('_$createComponent'))) {
3365
+ state.file.metadata.whatBuildsDom = true;
3366
+ }
3367
+ const renderSpecifiers = [];
3368
+ for (const [name, exported] of RENDER_IMPORTS) {
3369
+ const local = used.get(name);
3370
+ if (local === undefined) continue;
3371
+ const imported = exported ?? renderExport(name, state);
3372
+ renderSpecifiers.push(t.importSpecifier(t.identifier(local), t.identifier(imported)));
3373
+ }
3374
+ addImports(path, renderSpecifiers, ['what-framework/render', 'what-core/render'], 'what-framework/render');
3375
+
3376
+ const coreSpecifiers = [];
3377
+ for (const name of CORE_IMPORTS) {
3378
+ const local = used.get(name);
3379
+ if (local !== undefined) coreSpecifiers.push(t.importSpecifier(t.identifier(local), t.identifier(name)));
3380
+ }
3381
+ addImports(path, coreSpecifiers, ['what-core', 'what-framework'], 'what-framework');
3382
+
3383
+ // First in the file, so `let _$delegated$ = false` executes before any
3384
+ // top-level component construction (e.g. a same-module mount()).
3385
+ if (delegation) path.unshiftContainer('body', delegation);
3386
+ }