@barefootjs/jsx 0.39.2 → 0.39.4

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 (98) hide show
  1. package/dist/adapters/boolean-result.d.ts +32 -0
  2. package/dist/adapters/boolean-result.d.ts.map +1 -0
  3. package/dist/adapters/line-statement-text.d.ts +17 -0
  4. package/dist/adapters/line-statement-text.d.ts.map +1 -0
  5. package/dist/analyzer.d.ts +1 -0
  6. package/dist/analyzer.d.ts.map +1 -1
  7. package/dist/augment-inherited-props.d.ts +20 -0
  8. package/dist/augment-inherited-props.d.ts.map +1 -1
  9. package/dist/errors.d.ts +1 -0
  10. package/dist/errors.d.ts.map +1 -1
  11. package/dist/html-types.d.ts +15 -0
  12. package/dist/html-types.d.ts.map +1 -1
  13. package/dist/index.d.ts +6 -2
  14. package/dist/index.d.ts.map +1 -1
  15. package/dist/index.js +595 -140
  16. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  17. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +5 -0
  20. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  21. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +7 -0
  22. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  24. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +2 -0
  26. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/composite-loop.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts +14 -0
  31. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/imports.d.ts +2 -2
  34. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts +3 -1
  36. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/safe-html.d.ts +6 -0
  39. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/types.d.ts +12 -0
  41. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/nullable-signal-attr.d.ts +94 -0
  44. package/dist/nullable-signal-attr.d.ts.map +1 -0
  45. package/dist/profiler.d.ts +9 -1
  46. package/dist/profiler.d.ts.map +1 -1
  47. package/dist/scope/root-prop-alias.d.ts +43 -0
  48. package/dist/scope/root-prop-alias.d.ts.map +1 -0
  49. package/package.json +2 -2
  50. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
  51. package/src/__tests__/attribute-fallback-wrap.test.ts +24 -0
  52. package/src/__tests__/boolean-result.test.ts +27 -0
  53. package/src/__tests__/compiler-stress-1244.test.ts +10 -13
  54. package/src/__tests__/conditional-fallback-wrap.test.ts +20 -0
  55. package/src/__tests__/csr-template-loop-shadow.test.ts +83 -0
  56. package/src/__tests__/html-event-handler-names.test.ts +107 -0
  57. package/src/__tests__/line-statement-text.test.ts +25 -0
  58. package/src/__tests__/lookup-literal-const.test.ts +46 -0
  59. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +66 -19
  60. package/src/__tests__/nullable-signal-attr.test.ts +124 -0
  61. package/src/__tests__/profile-binding-ids.test.ts +102 -0
  62. package/src/__tests__/profile-turn-markers.test.ts +22 -0
  63. package/src/__tests__/profiler.test.ts +10 -9
  64. package/src/__tests__/root-prop-alias.test.ts +62 -0
  65. package/src/__tests__/ssr-portal-ref-callback.test.ts +88 -13
  66. package/src/adapters/boolean-result.ts +89 -0
  67. package/src/adapters/line-statement-text.ts +24 -0
  68. package/src/analyzer.ts +50 -26
  69. package/src/augment-inherited-props.ts +49 -0
  70. package/src/errors.ts +11 -0
  71. package/src/html-types.ts +15 -0
  72. package/src/index.ts +16 -2
  73. package/src/ir-to-client-js/collect-elements.ts +18 -4
  74. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +2 -2
  75. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +2 -0
  76. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +13 -0
  77. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +7 -2
  78. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +7 -0
  79. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  80. package/src/ir-to-client-js/control-flow/plan/loop.ts +2 -0
  81. package/src/ir-to-client-js/control-flow/shared.ts +2 -0
  82. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +6 -3
  83. package/src/ir-to-client-js/control-flow/stringify/composite-loop.ts +7 -4
  84. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +21 -6
  85. package/src/ir-to-client-js/control-flow/stringify/insert.ts +6 -1
  86. package/src/ir-to-client-js/control-flow/stringify/loop.ts +55 -8
  87. package/src/ir-to-client-js/html-template.ts +59 -8
  88. package/src/ir-to-client-js/imports.ts +3 -1
  89. package/src/ir-to-client-js/phases/rest-attr-applications.ts +8 -2
  90. package/src/ir-to-client-js/reactivity.ts +1 -0
  91. package/src/ir-to-client-js/safe-html.ts +10 -0
  92. package/src/ir-to-client-js/stringify/declaration-emit.ts +5 -5
  93. package/src/ir-to-client-js/types.ts +12 -0
  94. package/src/ir-to-client-js/utils.ts +88 -117
  95. package/src/jsx-to-ir.ts +145 -32
  96. package/src/nullable-signal-attr.ts +202 -0
  97. package/src/profiler.ts +79 -10
  98. package/src/scope/root-prop-alias.ts +81 -0
package/dist/index.js CHANGED
@@ -2432,24 +2432,6 @@ function templatePartsToJsExpr(parts, opts) {
2432
2432
  return result;
2433
2433
  }
2434
2434
 
2435
- // src/identifier-pattern.ts
2436
- function withUnicodeFlag(flags) {
2437
- return flags.includes("u") ? flags : `${flags}u`;
2438
- }
2439
- function escapeIdentifierForRegex(name) {
2440
- return name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2441
- }
2442
- var ID_BOUNDARY_BEFORE = "(?<![\\p{ID_Continue}$])";
2443
- var ID_BOUNDARY_AFTER = "(?![\\p{ID_Continue}$])";
2444
- function identifierPattern(name, flags = "") {
2445
- const esc = escapeIdentifierForRegex(name);
2446
- return new RegExp(`${ID_BOUNDARY_BEFORE}${esc}${ID_BOUNDARY_AFTER}`, withUnicodeFlag(flags));
2447
- }
2448
- function identifierCallPattern(name, flags = "") {
2449
- const esc = escapeIdentifierForRegex(name);
2450
- return new RegExp(`${ID_BOUNDARY_BEFORE}${esc}\\s*\\(`, withUnicodeFlag(flags));
2451
- }
2452
-
2453
2435
  // src/ir-to-client-js/utils.ts
2454
2436
  import {
2455
2437
  BF_KEY as DATA_KEY,
@@ -2556,6 +2538,24 @@ function collectValueReferencedNames(code) {
2556
2538
  return names;
2557
2539
  }
2558
2540
 
2541
+ // src/identifier-pattern.ts
2542
+ function withUnicodeFlag(flags) {
2543
+ return flags.includes("u") ? flags : `${flags}u`;
2544
+ }
2545
+ function escapeIdentifierForRegex(name) {
2546
+ return name.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2547
+ }
2548
+ var ID_BOUNDARY_BEFORE = "(?<![\\p{ID_Continue}$])";
2549
+ var ID_BOUNDARY_AFTER = "(?![\\p{ID_Continue}$])";
2550
+ function identifierPattern(name, flags = "") {
2551
+ const esc = escapeIdentifierForRegex(name);
2552
+ return new RegExp(`${ID_BOUNDARY_BEFORE}${esc}${ID_BOUNDARY_AFTER}`, withUnicodeFlag(flags));
2553
+ }
2554
+ function identifierCallPattern(name, flags = "") {
2555
+ const esc = escapeIdentifierForRegex(name);
2556
+ return new RegExp(`${ID_BOUNDARY_BEFORE}${esc}\\s*\\(`, withUnicodeFlag(flags));
2557
+ }
2558
+
2559
2559
  // src/ir-to-client-js/imports.ts
2560
2560
  var RUNTIME_IMPORT_CANDIDATES = [
2561
2561
  "createSignal",
@@ -2600,6 +2600,10 @@ var RUNTIME_IMPORT_CANDIDATES = [
2600
2600
  "markupOrEmpty",
2601
2601
  "qsa",
2602
2602
  "qsaItem",
2603
+ "adoptRowPortal",
2604
+ "claimRowPortals",
2605
+ "relayRowPortalEvents",
2606
+ "isRowPortalOf",
2603
2607
  "qsaChildScope",
2604
2608
  "qsaChildScopes",
2605
2609
  "upsertChildItem",
@@ -3093,33 +3097,54 @@ function wrapIndexParamAsAccessor(expr, indexParam) {
3093
3097
  return rewriteIdentifierAsAccessor(expr, indexParam);
3094
3098
  }
3095
3099
  function rewriteIdentifierAsAccessor(expr, name) {
3096
- if (!expr.includes(name))
3100
+ return rewriteIdentifierReferences(expr, new Map([[name, `${name}()`]]), { skipCallee: true });
3101
+ }
3102
+ function rewriteIdentifierReferences(expr, replacements, opts) {
3103
+ let any = false;
3104
+ for (const name of replacements.keys()) {
3105
+ if (expr.includes(name)) {
3106
+ any = true;
3107
+ break;
3108
+ }
3109
+ }
3110
+ if (!any)
3097
3111
  return expr;
3098
3112
  const wrapped = `(${expr})`;
3099
3113
  const sf = ts5.createSourceFile("__bf_expr.ts", wrapped, ts5.ScriptTarget.Latest, true);
3100
3114
  const edits = [];
3101
- const visit = (node) => {
3102
- if (ts5.isFunctionExpression(node) && node.name?.text === name)
3115
+ const visit = (node, active) => {
3116
+ if (ts5.isFunctionExpression(node) && node.name && active.has(node.name.text)) {
3117
+ const inner = new Map(active);
3118
+ inner.delete(node.name.text);
3119
+ if (inner.size === 0)
3120
+ return;
3121
+ ts5.forEachChild(node, (child) => visit(child, inner));
3103
3122
  return;
3104
- if (ts5.isIdentifier(node) && node.text === name) {
3123
+ }
3124
+ if (ts5.isIdentifier(node)) {
3125
+ const replacement = active.get(node.text);
3126
+ if (replacement === undefined)
3127
+ return;
3105
3128
  const p = node.parent;
3106
3129
  if (isNonReferenceIdentifierPosition(node))
3107
3130
  return;
3108
- if (ts5.isFunctionDeclaration(p) && p.name === node)
3109
- return;
3110
- if (ts5.isCallExpression(p) && p.expression === node)
3111
- return;
3112
- if (ts5.isNewExpression(p) && p.expression === node)
3113
- return;
3131
+ if (opts.skipCallee) {
3132
+ if (ts5.isFunctionDeclaration(p) && p.name === node)
3133
+ return;
3134
+ if (ts5.isCallExpression(p) && p.expression === node)
3135
+ return;
3136
+ if (ts5.isNewExpression(p) && p.expression === node)
3137
+ return;
3138
+ }
3114
3139
  const isShorthand = ts5.isShorthandPropertyAssignment(p) && p.name === node;
3115
3140
  const start = node.getStart(sf) - 1;
3116
3141
  const end = node.getEnd() - 1;
3117
- edits.push({ start, end, replacement: isShorthand ? `${name}: ${name}()` : `${name}()` });
3142
+ edits.push({ start, end, replacement: isShorthand ? `${node.text}: ${replacement}` : replacement });
3118
3143
  return;
3119
3144
  }
3120
- ts5.forEachChild(node, visit);
3145
+ ts5.forEachChild(node, (child) => visit(child, active));
3121
3146
  };
3122
- visit(sf);
3147
+ visit(sf, replacements);
3123
3148
  if (edits.length === 0)
3124
3149
  return expr;
3125
3150
  edits.sort((a, b) => b.start - a.start);
@@ -3130,38 +3155,10 @@ function rewriteIdentifierAsAccessor(expr, name) {
3130
3155
  return out;
3131
3156
  }
3132
3157
  function rewriteLoopBindingRefs(expr, bindings, accessor) {
3133
- const byName = new Map;
3158
+ const replacements = new Map;
3134
3159
  for (const b of bindings)
3135
- byName.set(b.name, b);
3136
- const preprocessed = expandShorthandBindings(expr, new Set(byName.keys()));
3137
- const alt = bindings.map((b) => escapeIdentifierForRegex(b.name)).join("|");
3138
- const re = new RegExp(`${ID_BOUNDARY_BEFORE}(${alt})${ID_BOUNDARY_AFTER}`, "gu");
3139
- return replaceInExprContexts(preprocessed, re, (_m, name) => renderLoopBindingAccess(byName.get(name), accessor));
3140
- }
3141
- function expandShorthandBindings(expr, bindingNames) {
3142
- if (!expr.includes("{"))
3143
- return expr;
3144
- const wrapped = `(${expr})`;
3145
- const sf = ts5.createSourceFile("__bf_expr.ts", wrapped, ts5.ScriptTarget.Latest, true);
3146
- const edits = [];
3147
- const visit = (node) => {
3148
- if (ts5.isShorthandPropertyAssignment(node) && ts5.isIdentifier(node.name) && bindingNames.has(node.name.text)) {
3149
- const start = node.getStart(sf) - 1;
3150
- const end = node.getEnd() - 1;
3151
- const name = node.name.text;
3152
- edits.push({ start, end, replacement: `${JSON.stringify(name)}: ${name}` });
3153
- }
3154
- ts5.forEachChild(node, visit);
3155
- };
3156
- visit(sf);
3157
- if (edits.length === 0)
3158
- return expr;
3159
- edits.sort((a, b) => b.start - a.start);
3160
- let out = expr;
3161
- for (const e of edits) {
3162
- out = out.slice(0, e.start) + e.replacement + out.slice(e.end);
3163
- }
3164
- return out;
3160
+ replacements.set(b.name, renderLoopBindingAccess(b, accessor));
3161
+ return rewriteIdentifierReferences(expr, replacements, { skipCallee: false });
3165
3162
  }
3166
3163
  function substituteLoopBindings(expr, bindings, accessor) {
3167
3164
  if (!bindings || bindings.length === 0)
@@ -4300,6 +4297,11 @@ function conditionalMarkup(condition, whenTrue, whenFalse) {
4300
4297
  function mappedRowsMarkup(arrayExpr, method, params, body) {
4301
4298
  return safeHtml(`${arrayExpr}.${method}(${params} => ${body}).join('')`);
4302
4299
  }
4300
+ function withOuterBindings(params, values, markup) {
4301
+ if (params.length === 0)
4302
+ return markup;
4303
+ return safeHtml(`((${params.join(", ")}) => ${markup})(${values.join(", ")})`);
4304
+ }
4303
4305
  var EMPTY_MARKUP = safeHtml("''");
4304
4306
  function isChildrenPassthroughExpr(expr) {
4305
4307
  return isChildrenPassthrough(parseExpression(expr));
@@ -5488,6 +5490,23 @@ function mergeCsrNullUnsafe(ctx, unsafeLocalNames) {
5488
5490
  }
5489
5491
  return merged ?? unsafeLocalNames;
5490
5492
  }
5493
+ function closeOverLoopBindings(env, boundHere) {
5494
+ const substitutions = new Map;
5495
+ const hoisted = [];
5496
+ for (const [name, sub] of env.substitutions) {
5497
+ if (boundHere.has(name))
5498
+ continue;
5499
+ if (!setIntersects(extractFreeIdentifiersFromText(sub.replacement), boundHere)) {
5500
+ substitutions.set(name, sub);
5501
+ continue;
5502
+ }
5503
+ const closed = csrSubstitute(sub.replacement, env);
5504
+ if (setIntersects(closed.freeIdentifiers, boundHere))
5505
+ hoisted.push(name);
5506
+ substitutions.set(name, { ...sub, replacement: closed.rewritten, freeIdentifiers: closed.freeIdentifiers });
5507
+ }
5508
+ return { substitutions, hoisted };
5509
+ }
5491
5510
  function buildCsrEnvForCtx(ctx, inlinableConstants, propsObjectName) {
5492
5511
  const base = buildSignalMemoEnv(ctx.signals, ctx.memos, propsObjectName ?? null, ctx.localConstants);
5493
5512
  const csrEnv = { substitutions: new Map(base.substitutions), propsObjectName: base.propsObjectName };
@@ -5734,10 +5753,20 @@ function generateCsrTemplateWithOpts(node, opts) {
5734
5753
  case "loop": {
5735
5754
  const childScope = (opts.scope ?? BindingScope.EMPTY).enterLoopRow(node);
5736
5755
  const boundHere = childScope.boundNames();
5737
- const childEnv = {
5738
- ...env,
5739
- substitutions: new Map([...env.substitutions].filter(([name]) => !boundHere.has(name)))
5740
- };
5756
+ const { substitutions: childSubstitutions, hoisted } = closeOverLoopBindings(env, boundHere);
5757
+ const hoistParams = [];
5758
+ const hoistValues = [];
5759
+ for (const name of hoisted) {
5760
+ const sub = env.substitutions.get(name);
5761
+ const value = transformExpr(sub.kind === "call" ? `${name}()` : name);
5762
+ if (value === UNSAFE_TEMPLATE_EXPR)
5763
+ continue;
5764
+ const param = `__bf_outer_${name}`;
5765
+ hoistParams.push(param);
5766
+ hoistValues.push(value);
5767
+ childSubstitutions.set(name, { kind: sub.kind, replacement: param, freeIdentifiers: new Set([param]) });
5768
+ }
5769
+ const childEnv = { ...env, substitutions: childSubstitutions };
5741
5770
  const recurseInLoopBody = (n) => generateCsrTemplateWithOpts(n, {
5742
5771
  ...opts,
5743
5772
  loopDepth: loopDepth + 1,
@@ -5762,12 +5791,12 @@ function generateCsrTemplateWithOpts(node, opts) {
5762
5791
  transformJs: (t) => rewritePropsObjectRef(t, propsObjectName ?? null, restPropsName ?? null, { enclosingScope: childScope }),
5763
5792
  renderLeaf: (ir) => recurseInLoopBody(leafKeyAsDataKeyAttr(ir))
5764
5793
  });
5765
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, "flatMap", node.flatMapCallback.params, body));
5794
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, "flatMap", node.flatMapCallback.params, body)));
5766
5795
  } else if (node.preamble) {
5767
5796
  const preamble = renderPreamble(node.preamble, { textVariant: "template", transformJs: (t) => rewritePropsObjectRef(t, propsObjectName ?? null, restPropsName ?? null, { enclosingScope: childScope }), renderLeaf: (ir) => recurseInLoopBody(ir) });
5768
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`));
5797
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `{ ${preamble} return \`${childTemplate}\` }`)));
5769
5798
  } else {
5770
- mapExpr = interp(mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `\`${childTemplate}\``));
5799
+ mapExpr = interp(withOuterBindings(hoistParams, hoistValues, mappedRowsMarkup(iterArrayExpr, iterMethod, callbackParam, `\`${childTemplate}\``)));
5771
5800
  }
5772
5801
  return `<!--${loopStartMarker(node.markerId)}-->${mapExpr}<!--${loopEndMarker(node.markerId)}-->`;
5773
5802
  }
@@ -6916,6 +6945,7 @@ var ErrorCodes = {
6916
6945
  STAGE_INIT_LOCAL_IN_TEMPLATE: "BF061",
6917
6946
  STAGE_AWAIT_IN_TEMPLATE: "BF062",
6918
6947
  REF_ATTR_ABSENT_AT_SSR: "BF063",
6948
+ ROW_PORTAL_UNPAIRABLE: "BF064",
6919
6949
  INLINE_JSX_CALLBACK_CAPTURE: "BF080",
6920
6950
  UNRECOGNIZED_REACTIVE_FACTORY: "BF110",
6921
6951
  REACTIVE_FACTORY_RENAME_UNSUPPORTED: "BF111",
@@ -6955,6 +6985,7 @@ var errorMessages = {
6955
6985
  [ErrorCodes.STAGE_INIT_LOCAL_IN_TEMPLATE]: "Init-scope local referenced from template scope. The template lambda runs at module scope (via render() / renderChild()) and cannot reach init-body locals. Wrap the JSX expression in /* @client */, or lift the value to a prop or module-scope const.",
6956
6986
  [ErrorCodes.STAGE_AWAIT_IN_TEMPLATE]: "AwaitExpression in template scope. The generated template and init functions are synchronous — a bare `await` produces a SyntaxError at parse time. Move the await into the component body (before the return) or into an onMount/effect callback, and pass the resolved value to JSX.",
6957
6987
  [ErrorCodes.REF_ATTR_ABSENT_AT_SSR]: "A ref callback writes an attribute on mount that the element's JSX never renders. A ref callback never runs at SSR, so the server HTML lacks the attribute and hydration adds it — the DOM visibly changes at the hydrate boundary.",
6988
+ [ErrorCodes.ROW_PORTAL_UNPAIRABLE]: "A ref callback portals an element out of a .map() row that hydration cannot pair with the element (the row root itself, a nested or unkeyed loop, an element inside a reactive conditional in the row, or an element inside a child component's children), so its event handlers would stop running after hydration.",
6958
6989
  [ErrorCodes.INLINE_JSX_CALLBACK_CAPTURE]: "Inline JSX-returning arrow function captures a non-module identifier. Extract the callback into a top-level 'use client' component (e.g. `function MyNode(n) { return <div/> }` then `renderNode={MyNode}`) or pass captured values via component props.",
6959
6990
  [ErrorCodes.UNRECOGNIZED_REACTIVE_FACTORY]: "Tuple destructuring of a non-reactive factory call. The compiler only recognizes createSignal / createMemo calls and same-file helpers that wrap them with a single `return [a, b]` exit.",
6960
6991
  [ErrorCodes.REACTIVE_FACTORY_RENAME_UNSUPPORTED]: "Reactive factory object return/destructure must use shorthand properties only. " + "Property renames (`{ lists: myLists }`), defaults, and rest elements are not " + "supported — destructure with the factory's own property names.",
@@ -8039,14 +8070,9 @@ function collectSignal(node, ctx) {
8039
8070
  if (getterElided && !setter)
8040
8071
  return;
8041
8072
  const getter = getterElided ? `__bfGet_${setter}` : elements[0].name.text;
8042
- const initialValue = callExpr.arguments[0] ? ctx.getJS(callExpr.arguments[0]) : "";
8073
+ const initialValue = signalInitialValueText(callExpr, ctx);
8043
8074
  const typedInitialValue = callExpr.arguments[0] ? callExpr.arguments[0].getText(ctx.sourceFile) : undefined;
8044
- let type = { kind: "unknown", raw: "unknown" };
8045
- if (callExpr.typeArguments && callExpr.typeArguments.length > 0) {
8046
- type = typeNodeToTypeInfo(callExpr.typeArguments[0], ctx.sourceFile) ?? type;
8047
- } else {
8048
- type = inferTypeFromValue(initialValue);
8049
- }
8075
+ const type = signalTypeInfo(callExpr, initialValue, ctx);
8050
8076
  const envReader = resolveEnvSignalKey(callExpr, ctx) ?? undefined;
8051
8077
  const envFactory = envReader ? callExpr.expression.getText(ctx.sourceFile) : undefined;
8052
8078
  let templateInitialValue;
@@ -8189,17 +8215,34 @@ function isSignalIndexAccess(node, ctx) {
8189
8215
  }
8190
8216
  return null;
8191
8217
  }
8218
+ function signalInitialValueText(callExpr, ctx) {
8219
+ return callExpr.arguments[0] ? ctx.getJS(callExpr.arguments[0]) : "undefined";
8220
+ }
8221
+ function signalTypeInfo(callExpr, initialValue, ctx) {
8222
+ const typeArg = callExpr.typeArguments?.[0];
8223
+ if (!typeArg)
8224
+ return inferTypeFromValue(initialValue);
8225
+ const type = typeNodeToTypeInfo(typeArg, ctx.sourceFile) ?? { kind: "unknown", raw: "unknown" };
8226
+ return callExpr.arguments[0] ? type : withUndefined(type);
8227
+ }
8228
+ function withUndefined(type) {
8229
+ const members = type.kind === "union" && type.unionTypes ? type.unionTypes : [type];
8230
+ if (members.some((t) => t.kind === "primitive" && t.primitive === "undefined"))
8231
+ return type;
8232
+ if (type.kind === "unknown")
8233
+ return type;
8234
+ return {
8235
+ kind: "union",
8236
+ raw: `${type.raw} | undefined`,
8237
+ unionTypes: [...members, { kind: "primitive", raw: "undefined", primitive: "undefined" }]
8238
+ };
8239
+ }
8192
8240
  function collectSignalTupleRef(node, ctx) {
8193
8241
  const name = node.name.text;
8194
8242
  const callExpr = node.initializer;
8195
- const initialValue = callExpr.arguments[0] ? ctx.getJS(callExpr.arguments[0]) : "";
8243
+ const initialValue = signalInitialValueText(callExpr, ctx);
8196
8244
  const typedInitialValue = callExpr.arguments[0] ? callExpr.arguments[0].getText(ctx.sourceFile) : undefined;
8197
- let type = { kind: "unknown", raw: "unknown" };
8198
- if (callExpr.typeArguments && callExpr.typeArguments.length > 0) {
8199
- type = typeNodeToTypeInfo(callExpr.typeArguments[0], ctx.sourceFile) ?? type;
8200
- } else {
8201
- type = inferTypeFromValue(initialValue);
8202
- }
8245
+ const type = signalTypeInfo(callExpr, initialValue, ctx);
8203
8246
  ctx.signalTupleRefs.set(name, {
8204
8247
  initialValue,
8205
8248
  typedInitialValue: typedInitialValue !== initialValue ? typedInitialValue : undefined,
@@ -8214,14 +8257,9 @@ function collectSignalFromIndexAccess(node, match, ctx) {
8214
8257
  const varName = node.name.text;
8215
8258
  if (match.kind === "direct") {
8216
8259
  const callExpr = match.callExpr;
8217
- const initialValue = callExpr.arguments[0] ? ctx.getJS(callExpr.arguments[0]) : "";
8260
+ const initialValue = signalInitialValueText(callExpr, ctx);
8218
8261
  const typedInitialValue = callExpr.arguments[0] ? callExpr.arguments[0].getText(ctx.sourceFile) : undefined;
8219
- let type = { kind: "unknown", raw: "unknown" };
8220
- if (callExpr.typeArguments && callExpr.typeArguments.length > 0) {
8221
- type = typeNodeToTypeInfo(callExpr.typeArguments[0], ctx.sourceFile) ?? type;
8222
- } else {
8223
- type = inferTypeFromValue(initialValue);
8224
- }
8262
+ const type = signalTypeInfo(callExpr, initialValue, ctx);
8225
8263
  const loc = getSourceLocation(node, ctx.sourceFile, ctx.filePath);
8226
8264
  const initialFreeIdentifiers = callExpr.arguments[0] ? extractFreeIdentifiersFromNode(callExpr.arguments[0]) : new Set;
8227
8265
  if (match.index === 0) {
@@ -14542,6 +14580,88 @@ function applyLoopKeyAttr(node, name, value) {
14542
14580
  applyLoopKeyAttr(first, name, value);
14543
14581
  }
14544
14582
  }
14583
+ function applyRowPortalKeyAttrs(children, key, depth, ctx) {
14584
+ const refuse = (el, reason) => {
14585
+ ctx.analyzer.errors.push(createError(ErrorCodes.ROW_PORTAL_UNPAIRABLE, el.loc, {
14586
+ message: `A ref callback portals <${el.tag}> out of a .map() row, but ${reason}, so hydration cannot pair the ` + "portaled element with its row and its event handlers would stop running after hydration.",
14587
+ suggestion: {
14588
+ message: "Portal an element inside the root of a keyed top-level .map() row (`key={…}` on the row root), " + "outside reactive conditionals and child components' children, or move the portal outside the loop.",
14589
+ escape: [{ kind: "rewrite" }]
14590
+ }
14591
+ }));
14592
+ };
14593
+ const visit3 = (node, blocked) => {
14594
+ switch (node.type) {
14595
+ case "element":
14596
+ if (node.ssrPortalOwnerScope) {
14597
+ if (node.keyAttr)
14598
+ refuse(node, "it is the root element of the row");
14599
+ else if (blocked)
14600
+ refuse(node, blocked);
14601
+ else if (key === null)
14602
+ refuse(node, "the loop has no `key`");
14603
+ else if (depth > 0)
14604
+ refuse(node, "the loop is nested inside another loop");
14605
+ else {
14606
+ node.keyAttr = { name: keyAttrName2(depth), value: key };
14607
+ if (!node.attrs.some((a) => a.name === "key")) {
14608
+ node.attrs.push(rowKeyAttribute(children) ?? { name: "key", value: { kind: "expression", expr: key }, loc: node.loc });
14609
+ }
14610
+ }
14611
+ }
14612
+ for (const c of node.children)
14613
+ visit3(c, blocked);
14614
+ return;
14615
+ case "fragment":
14616
+ for (const c of node.children)
14617
+ visit3(c, blocked);
14618
+ return;
14619
+ case "conditional": {
14620
+ const inner = blocked ?? (node.slotId ? "it is rendered inside a reactive conditional in the row" : null);
14621
+ visit3(node.whenTrue, inner);
14622
+ visit3(node.whenFalse, inner);
14623
+ return;
14624
+ }
14625
+ case "if-statement":
14626
+ visit3(node.consequent, blocked);
14627
+ if (node.alternate)
14628
+ visit3(node.alternate, blocked);
14629
+ return;
14630
+ case "component":
14631
+ case "provider":
14632
+ for (const c of node.children)
14633
+ visit3(c, blocked ?? "it is rendered inside another component's children");
14634
+ return;
14635
+ case "async":
14636
+ visit3(node.fallback, blocked ?? "it is rendered inside another component's children");
14637
+ for (const c of node.children)
14638
+ visit3(c, blocked ?? "it is rendered inside another component's children");
14639
+ return;
14640
+ default:
14641
+ return;
14642
+ }
14643
+ };
14644
+ for (const c of children)
14645
+ visit3(c, null);
14646
+ }
14647
+ function rowKeyAttribute(children) {
14648
+ const find = (node) => {
14649
+ switch (node.type) {
14650
+ case "element":
14651
+ return node.attrs.find((a) => a.name === "key") ?? null;
14652
+ case "conditional":
14653
+ return find(node.whenTrue);
14654
+ case "fragment": {
14655
+ const first2 = node.children.find((c) => !(c.type === "text" && typeof c.value === "string" && !c.value.trim()));
14656
+ return first2 ? find(first2) : null;
14657
+ }
14658
+ default:
14659
+ return null;
14660
+ }
14661
+ };
14662
+ const first = children.find((c) => !(c.type === "text" && typeof c.value === "string" && !c.value.trim()));
14663
+ return first ? find(first) : null;
14664
+ }
14545
14665
  function loopBodyItemConditional(children) {
14546
14666
  const real = children.filter((c) => !(c.type === "text" && typeof c.value === "string" && !c.value.trim()));
14547
14667
  if (real.length !== 1)
@@ -14935,6 +15055,7 @@ function transformMapCall(node, ctx, isClientOnly = false, method = "map") {
14935
15055
  applyLoopKeyAttr(children[0], resolvedKeyAttrName2, key);
14936
15056
  }
14937
15057
  }
15058
+ applyRowPortalKeyAttrs(children, key, depth, ctx);
14938
15059
  const declaredNameSet = preamble && preamble.declaredNames.length > 0 ? new Set(preamble.declaredNames) : undefined;
14939
15060
  if (key && declaredNameSet) {
14940
15061
  const keyRefs = extractFreeIdentifiersFromText(key);
@@ -15826,12 +15947,12 @@ function datasetKeyToAttrName(key) {
15826
15947
  function resolveRefCallback(refExpr) {
15827
15948
  const expr = unwrapTransparentTsWrappers(refExpr);
15828
15949
  if (ts19.isArrowFunction(expr) || ts19.isFunctionExpression(expr)) {
15829
- return { param: firstSimpleParamName(expr), body: expr.body, named: false, innermostScope: false };
15950
+ return { param: firstSimpleParamName(expr), body: expr.body, named: false };
15830
15951
  }
15831
15952
  if (!ts19.isIdentifier(expr))
15832
15953
  return;
15833
- const resolved = findNamedCallback(expr);
15834
- return resolved && { ...resolved.callback, named: true, innermostScope: resolved.innermostScope };
15954
+ const callback = findNamedCallback(expr);
15955
+ return callback && { ...callback, named: true };
15835
15956
  }
15836
15957
  function isFunctionLike(node) {
15837
15958
  return ts19.isArrowFunction(node) || ts19.isFunctionExpression(node) || ts19.isFunctionDeclaration(node);
@@ -15846,15 +15967,13 @@ function findEnclosingFunctionLike(node) {
15846
15967
  return;
15847
15968
  }
15848
15969
  function findNamedCallback(ident) {
15849
- const innermost = findEnclosingFunctionLike(ident);
15850
- for (let fn = innermost;fn; fn = findEnclosingFunctionLike(fn)) {
15970
+ for (let fn = findEnclosingFunctionLike(ident);fn; fn = findEnclosingFunctionLike(fn)) {
15851
15971
  if (fn.parameters.some((p) => bindingDeclares(p.name, ident.text)))
15852
15972
  return;
15853
15973
  const decl = fn.body && findScopeDeclaration(ident.text, fn.body);
15854
15974
  if (!decl)
15855
15975
  continue;
15856
- const callback = localCallbackOf(decl);
15857
- return callback && { callback, innermostScope: fn === innermost };
15976
+ return localCallbackOf(decl);
15858
15977
  }
15859
15978
  return;
15860
15979
  }
@@ -15890,7 +16009,7 @@ function bindingDeclares(binding, name) {
15890
16009
  return names.has(name);
15891
16010
  }
15892
16011
  function isSsrPortalRefCallback(callback) {
15893
- return !!callback?.named && callback.innermostScope && !!callback.param && containsSsrPortalPlacementCall(callback.body, callback.param);
16012
+ return !!callback?.named && !!callback.param && containsSsrPortalPlacementCall(callback.body, callback.param);
15894
16013
  }
15895
16014
  function firstSimpleParamName(fn) {
15896
16015
  const first = fn.parameters[0];
@@ -16786,6 +16905,8 @@ function hasReactiveAttributes(attrs, ctx) {
16786
16905
  if (isSignalOrMemoReference(valueToCheck, ctx) || isPropsReference(valueToCheck, ctx)) {
16787
16906
  return true;
16788
16907
  }
16908
+ if (attr.callsReactiveGetters || attr.hasFunctionCalls)
16909
+ return true;
16789
16910
  const scopeValueNames = ctx.scope.valueBoundNames();
16790
16911
  if (scopeValueNames.size > 0) {
16791
16912
  for (const p of scopeValueNames) {
@@ -17263,7 +17384,8 @@ function collectLoopChildRefs(node) {
17263
17384
  if (el.slotId && el.ref) {
17264
17385
  refs.push({
17265
17386
  childSlotId: el.slotId,
17266
- callback: el.ref
17387
+ callback: el.ref,
17388
+ ...el.ssrPortalOwnerScope && { ssrPortalOwner: true }
17267
17389
  });
17268
17390
  }
17269
17391
  }, true);
@@ -18208,9 +18330,12 @@ function collectFromElement(element, ctx, insideConditional = false) {
18208
18330
  }
18209
18331
  function collectBranchReactiveAttrs(node, ctx) {
18210
18332
  const attrs = [];
18211
- walkIR(node, null, {
18333
+ walkIR(node, [], {
18212
18334
  ...stopAt("conditional", "ifStatement", "loop"),
18213
- element: ({ node: el, descend }) => {
18335
+ component: ({ node: c, scope, descend }) => {
18336
+ descend(c.slotId ? [...scope, c.slotId] : scope);
18337
+ },
18338
+ element: ({ node: el, scope, descend }) => {
18214
18339
  if (!el.slotId) {
18215
18340
  descend();
18216
18341
  return;
@@ -18228,6 +18353,7 @@ function collectBranchReactiveAttrs(node, ctx) {
18228
18353
  continue;
18229
18354
  attrs.push({
18230
18355
  slotId: el.slotId,
18356
+ ...el.slotId.startsWith("^") && { receiverSlotIds: scope },
18231
18357
  attrName: attr.name,
18232
18358
  expression: expanded.expr,
18233
18359
  ...pickAttrMetaFromIR(attr),
@@ -18244,7 +18370,7 @@ function collectBranchTextEffects(node) {
18244
18370
  walkIR(node, null, {
18245
18371
  ...stopAt("conditional", "ifStatement", "loop"),
18246
18372
  expression: ({ node: n }) => {
18247
- if (n.reactive && n.slotId && !n.clientOnly) {
18373
+ if (decideWrapFromAstFlags(n).wrap && n.slotId && !n.clientOnly) {
18248
18374
  effects.push({ slotId: n.slotId, expression: n.expr });
18249
18375
  }
18250
18376
  }
@@ -20032,25 +20158,25 @@ function emitSignal(lines, plan) {
20032
20158
  lines.push(` const [${bindings}] = ${plan.initializerOverride}`);
20033
20159
  return;
20034
20160
  }
20035
- const id = bfIdArg(plan.bfId);
20161
+ const args = `${plan.initialValueExpr}${bfIdArg(plan.bfId)}`;
20036
20162
  if (plan.branchCondition) {
20037
20163
  if (plan.setter) {
20038
20164
  lines.push(plan.getterElided ? ` let ${plan.setter}` : ` let ${plan.getter}, ${plan.setter}`);
20039
20165
  lines.push(` if (${plan.branchCondition}) {`);
20040
- lines.push(` ;[${getterSlot}, ${plan.setter}] = createSignal(${plan.initialValueExpr}${id})`);
20166
+ lines.push(` ;[${getterSlot}, ${plan.setter}] = createSignal(${args})`);
20041
20167
  lines.push(` }`);
20042
20168
  } else {
20043
20169
  lines.push(` let ${plan.getter}`);
20044
20170
  lines.push(` if (${plan.branchCondition}) {`);
20045
- lines.push(` ;[${plan.getter}] = createSignal(${plan.initialValueExpr}${id})`);
20171
+ lines.push(` ;[${plan.getter}] = createSignal(${args})`);
20046
20172
  lines.push(` }`);
20047
20173
  }
20048
20174
  return;
20049
20175
  }
20050
20176
  if (plan.setter) {
20051
- lines.push(` const [${getterSlot}, ${plan.setter}] = createSignal(${plan.initialValueExpr}${id})`);
20177
+ lines.push(` const [${getterSlot}, ${plan.setter}] = createSignal(${args})`);
20052
20178
  } else {
20053
- lines.push(` const [${plan.getter}] = createSignal(${plan.initialValueExpr}${id})`);
20179
+ lines.push(` const [${plan.getter}] = createSignal(${args})`);
20054
20180
  }
20055
20181
  if (plan.controlledEffect) {
20056
20182
  emitControlledEffect(lines, plan.controlledEffect);
@@ -20356,7 +20482,8 @@ function buildChildRefBindings(refs, loopParam, loopParamBindings, loopIndex) {
20356
20482
  return [];
20357
20483
  return refs.map((r) => ({
20358
20484
  childSlotId: r.childSlotId,
20359
- callback: wrapLoopParamAsAccessor(r.callback, loopParam, loopParamBindings, loopIndex)
20485
+ callback: wrapLoopParamAsAccessor(r.callback, loopParam, loopParamBindings, loopIndex),
20486
+ ...r.ssrPortalOwner && { ssrPortalOwner: true }
20360
20487
  }));
20361
20488
  }
20362
20489
  function buildStaticChildRefBindings(refs) {
@@ -20364,7 +20491,8 @@ function buildStaticChildRefBindings(refs) {
20364
20491
  return [];
20365
20492
  return refs.map((r) => ({
20366
20493
  childSlotId: r.childSlotId,
20367
- callback: r.callback
20494
+ callback: r.callback,
20495
+ ...r.ssrPortalOwner && { ssrPortalOwner: true }
20368
20496
  }));
20369
20497
  }
20370
20498
  function exprRefsLoopBinding(freeIds, loop) {
@@ -21519,7 +21647,7 @@ function collectTextOnlySlotIds(nodes, into) {
21519
21647
  }
21520
21648
  function buildComponentLoopPlan(elem, profileComponentName) {
21521
21649
  const { name } = elem.childComponent;
21522
- const propsExpr = buildComponentPropsExpr2(elem.childComponent, elem.param, undefined, elem.index);
21650
+ const propsExpr = buildComponentPropsExpr2(elem.childComponent, elem.param, elem.paramBindings, elem.index);
21523
21651
  const keyExpr = wrapLoopParamAsAccessor(elem.key || "__idx", elem.param, elem.paramBindings, elem.index);
21524
21652
  const { head: paramHead, unwrap: paramUnwrap } = destructureLoopParam(elem.param, elem.paramBindings);
21525
21653
  const mapPreambleWrapped = elem.preamble ? renderPreamble(elem.preamble, {
@@ -21542,7 +21670,7 @@ function buildComponentLoopPlan(elem, profileComponentName) {
21542
21670
  return {
21543
21671
  componentName: comp.name,
21544
21672
  selector: buildCompSelector(comp),
21545
- propsExpr: buildComponentPropsExpr2(comp, elem.param, undefined, elem.index),
21673
+ propsExpr: buildComponentPropsExpr2(comp, elem.param, elem.paramBindings, elem.index),
21546
21674
  childrenTextEffect: childrenRefsLoop ? buildChildrenTextEffect(comp.children, rawChildrenExpr, wrap) : null
21547
21675
  };
21548
21676
  });
@@ -21599,7 +21727,7 @@ function wrapAttrValueExpression2(value, wrap) {
21599
21727
  }
21600
21728
  }
21601
21729
  function buildInnerLoopsPlan(args) {
21602
- const { levels, parentElVar, outerLoopParam, outerLoopParamBindings, outerLoopIndex } = args;
21730
+ const { levels, parentElVar, outerLoopParam, outerLoopParamBindings, outerLoopIndex, rowHasPortal } = args;
21603
21731
  const wrapOuter = outerLoopParam ? (expr) => wrapLoopParamAsAccessor(expr, outerLoopParam, outerLoopParamBindings, outerLoopIndex) : (expr) => expr;
21604
21732
  const plan = [];
21605
21733
  let i = 0;
@@ -21621,7 +21749,7 @@ function buildInnerLoopsPlan(args) {
21621
21749
  j++;
21622
21750
  }
21623
21751
  const uidSuffix = `${inner.depth}_${i}`;
21624
- const containerExpr = inner.containerSlotId ? `qsa(${parentElVar}, '[bf="${inner.containerSlotId}"]')` : parentElVar;
21752
+ const containerExpr = inner.containerSlotId ? `${rowHasPortal ? "qsaItem" : "qsa"}(${parentElVar}, '[bf="${inner.containerSlotId}"]')` : parentElVar;
21625
21753
  const emit = buildReactiveEmit(inner, level, wrapOuter, uidSuffix, outerLoopParam, outerLoopParamBindings, outerLoopIndex);
21626
21754
  const arrayExpr = wrapOuter(inner.array);
21627
21755
  const childLevelsPlan = childLevels.length > 0 ? buildInnerLoopsPlan({
@@ -21769,7 +21897,8 @@ function buildTopLevelCompositePlan(elem, profileComponentName) {
21769
21897
  parentElVar: "__el",
21770
21898
  outerLoopParam: elem.param,
21771
21899
  outerLoopParamBindings: elem.paramBindings,
21772
- outerLoopIndex: elem.index
21900
+ outerLoopIndex: elem.index,
21901
+ rowHasPortal: elem.bindings.refs.some((r) => r.ssrPortalOwner)
21773
21902
  }),
21774
21903
  loopParam: elem.param,
21775
21904
  loopParamBindings: elem.paramBindings,
@@ -21822,7 +21951,8 @@ function buildBranchCompositePlan(loop, cv, profileComponentName) {
21822
21951
  parentElVar: "__el",
21823
21952
  outerLoopParam: loop.param,
21824
21953
  outerLoopParamBindings: loop.paramBindings,
21825
- outerLoopIndex: loop.index
21954
+ outerLoopIndex: loop.index,
21955
+ rowHasPortal: loop.bindings.refs.some((r) => r.ssrPortalOwner)
21826
21956
  }),
21827
21957
  loopParam: loop.param,
21828
21958
  loopParamBindings: loop.paramBindings,
@@ -22157,7 +22287,8 @@ function emitRestAttrApplications(lines, ctx) {
22157
22287
  for (const elem of ctx.restAttrElements) {
22158
22288
  const v = varSlotId(elem.slotId);
22159
22289
  const excludeKeys = JSON.stringify(elem.excludeKeys);
22160
- lines.push(` if (_${v}) applyRestAttrs(_${v}, ${elem.source}, ${excludeKeys})`);
22290
+ const turnSite = ctx.profile ? `, ${JSON.stringify(`${ctx.componentName}#handler:${elem.slotId}`)}` : "";
22291
+ lines.push(` if (_${v}) applyRestAttrs(_${v}, ${elem.source}, ${excludeKeys}${turnSite})`);
22161
22292
  }
22162
22293
  lines.push("");
22163
22294
  }
@@ -23227,14 +23358,16 @@ function stringifyCompositeLoop(lines, plan) {
23227
23358
  singleRootLayout: "multiline",
23228
23359
  mountRow: true
23229
23360
  });
23230
- emitComponentAndEventSetup(lines, bodyIndent, "__el", compsArr, eventsArr, loopParam, loopParamBindings, bodyIsMultiRoot, loopIndex);
23361
+ emitRowPortalClaim(lines, childRefs, { indent: bodyIndent, containerVar });
23362
+ const itemLookup = bodyIsMultiRoot || rowPortalSlotIds(childRefs).length > 0;
23363
+ emitComponentAndEventSetup(lines, bodyIndent, "__el", compsArr, eventsArr, loopParam, loopParamBindings, itemLookup, loopIndex);
23231
23364
  if (innerLoops.length > 0) {
23232
23365
  stringifyInnerLoops(lines, innerLoops, bodyIndent, pc);
23233
23366
  }
23234
23367
  if (reactiveEffects) {
23235
- stringifyReactiveEffects(lines, reactiveEffects, { indent: bodyIndent, elVar: "__el", bodyIsMultiRoot });
23368
+ stringifyReactiveEffects(lines, reactiveEffects, { indent: bodyIndent, elVar: "__el", bodyIsMultiRoot: itemLookup });
23236
23369
  }
23237
- emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: "__el", bodyIsMultiRoot });
23370
+ emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: "__el", bodyIsMultiRoot: itemLookup, containerVar });
23238
23371
  lines.push(`${bodyIndent}return __el`);
23239
23372
  const loopBfId = profileLoopId ? `, ${JSON.stringify(profileLoopId)}` : "";
23240
23373
  if (branchClearChildren) {
@@ -23465,16 +23598,30 @@ function seedDiffersExpr(target, a) {
23465
23598
  function emitLoopChildRefs(lines, refs, opts) {
23466
23599
  if (refs.length === 0)
23467
23600
  return;
23468
- const { indent, elVar, bodyIsMultiRoot, elementIndexBySlot } = opts;
23469
- const lookup = bodyIsMultiRoot ? "qsaItem" : "qsa";
23601
+ const { indent, elVar, bodyIsMultiRoot, elementIndexBySlot, containerVar } = opts;
23470
23602
  for (const ref of refs) {
23603
+ const lookup = bodyIsMultiRoot || ref.ssrPortalOwner ? "qsaItem" : "qsa";
23471
23604
  const varName = `__rf_${varSlotId(ref.childSlotId)}`;
23472
23605
  const pIdx = elementIndexBySlot?.get(ref.childSlotId);
23473
23606
  const lookupExpr = pIdx !== undefined ? `__p ? __p[${pIdx}] : ${lookup}(${elVar}, '[bf="${ref.childSlotId}"]')` : `${lookup}(${elVar}, '[bf="${ref.childSlotId}"]')`;
23474
23607
  lines.push(`${indent}{ const ${varName} = ${lookupExpr}`);
23475
- lines.push(`${indent}if (${varName}) ${emitRefCall(ref.callback, varName)} }`);
23608
+ if (ref.ssrPortalOwner && containerVar) {
23609
+ lines.push(`${indent}if (${varName}) { ${emitRefCall(ref.callback, varName, true)}; adoptRowPortal(${elVar}, ${varName}, ${containerVar}) } }`);
23610
+ } else {
23611
+ lines.push(`${indent}if (${varName}) ${emitRefCall(ref.callback, varName)} }`);
23612
+ }
23476
23613
  }
23477
23614
  }
23615
+ function rowPortalSlotIds(refs) {
23616
+ return refs.filter((r) => r.ssrPortalOwner).map((r) => r.childSlotId);
23617
+ }
23618
+ function emitRowPortalClaim(lines, refs, opts) {
23619
+ const slots = rowPortalSlotIds(refs);
23620
+ if (slots.length === 0)
23621
+ return;
23622
+ const claim = `claimRowPortals(${opts.rowVar ?? "__existing"}, __scopeId, ${JSON.stringify(slots)}, ${opts.containerVar})`;
23623
+ lines.push(opts.rowVar ? `${opts.indent}${claim}` : `${opts.indent}if (__existing) ${claim}`);
23624
+ }
23478
23625
  function stringifyLoop(lines, plan) {
23479
23626
  switch (plan.kind) {
23480
23627
  case "static":
@@ -23584,6 +23731,8 @@ function stringifyPlainLoop(lines, plan, topIndent = " ") {
23584
23731
  singleRootLayout: "inline"
23585
23732
  });
23586
23733
  }
23734
+ emitRowPortalClaim(lines, childRefs, { indent: bodyIndent, containerVar });
23735
+ const itemLookup = bodyIsMultiRoot || rowPortalSlotIds(childRefs).length > 0;
23587
23736
  let pathPlan = null;
23588
23737
  if (hoistedTpl && plan.skeletonPaths) {
23589
23738
  const elementSlotIds = [
@@ -23610,14 +23759,14 @@ function stringifyPlainLoop(lines, plan, topIndent = " ") {
23610
23759
  stringifyReactiveEffects(lines, reactiveEffects, {
23611
23760
  indent: bodyIndent,
23612
23761
  elVar: "__el",
23613
- bodyIsMultiRoot,
23762
+ bodyIsMultiRoot: itemLookup,
23614
23763
  elementIndexBySlot: pathPlan?.elementIndexBySlot,
23615
23764
  textClaimPathExprs,
23616
23765
  preambleRegions,
23617
23766
  mapPreambleWrapped
23618
23767
  });
23619
23768
  }
23620
- emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: "__el", bodyIsMultiRoot, elementIndexBySlot: pathPlan?.elementIndexBySlot });
23769
+ emitLoopChildRefs(lines, childRefs, { indent: bodyIndent, elVar: "__el", bodyIsMultiRoot: itemLookup, elementIndexBySlot: pathPlan?.elementIndexBySlot, containerVar });
23621
23770
  lines.push(`${bodyIndent}return __el`);
23622
23771
  lines.push(`${topIndent}}, '${markerId}'${loopBfId})`);
23623
23772
  }
@@ -23713,12 +23862,14 @@ function stringifyStaticLoop(lines, plan) {
23713
23862
  lines.push(` }`);
23714
23863
  }
23715
23864
  lines.push(` if (__iterEl) {`);
23865
+ emitRowPortalClaim(lines, childRefs, { indent: " ", containerVar, rowVar: "__iterEl" });
23866
+ const rowHasPortal = rowPortalSlotIds(childRefs).length > 0;
23716
23867
  if (attrsBySlot.length > 0)
23717
23868
  lines.push(` ${DEDUP_STORE_DECL}`);
23718
23869
  let ordinal = 0;
23719
23870
  for (const [slotId, attrs] of attrsBySlot) {
23720
23871
  const varName = `__t_${varSlotId(slotId)}`;
23721
- lines.push(` const ${varName} = qsa(__iterEl, '[bf="${slotId}"]')`);
23872
+ lines.push(` const ${varName} = ${rowHasPortal ? "qsaItem" : "qsa"}(__iterEl, '[bf="${slotId}"]')`);
23722
23873
  lines.push(` if (${varName}) {`);
23723
23874
  for (const attr of attrs) {
23724
23875
  lines.push(` createEffect(() => {`);
@@ -23737,7 +23888,7 @@ function stringifyStaticLoop(lines, plan) {
23737
23888
  lines.push(` createEffect(() => { ${writer}('${text.slotId}', String(${text.expression})) }${profileBindingId(pc, text.slotId)})`);
23738
23889
  }
23739
23890
  }
23740
- emitLoopChildRefs(lines, childRefs, { indent: " ", elVar: "__iterEl", bodyIsMultiRoot: false });
23891
+ emitLoopChildRefs(lines, childRefs, { indent: " ", elVar: "__iterEl", bodyIsMultiRoot: rowHasPortal, containerVar });
23741
23892
  lines.push(` }`);
23742
23893
  lines.push(` })`);
23743
23894
  lines.push(` }`);
@@ -23927,6 +24078,7 @@ function buildDynamicLoopDelegationPlan(elem, profileComponentName, ownHandlers)
23927
24078
  events: elem.bindings.events,
23928
24079
  profileComponentName,
23929
24080
  ownHandlers,
24081
+ ...hasRowPortalRef(elem) && { relayRowPortals: true },
23930
24082
  itemLookup: buildKeyedOrIndexLookup({
23931
24083
  array: buildChainedArrayExpr(elem),
23932
24084
  param: elem.param,
@@ -23946,6 +24098,7 @@ function buildBranchLoopDelegationPlan(loop, cv, profileComponentName) {
23946
24098
  containerVar: `__loop_${cv}`,
23947
24099
  events: loop.bindings.events,
23948
24100
  profileComponentName,
24101
+ ...hasRowPortalRef(loop) && { relayRowPortals: true },
23949
24102
  itemLookup: buildKeyedOrIndexLookup({
23950
24103
  array: buildChainedArrayExpr(loop),
23951
24104
  param: loop.param,
@@ -23960,6 +24113,9 @@ function buildBranchLoopDelegationPlan(loop, cv, profileComponentName) {
23960
24113
  };
23961
24114
  }
23962
24115
  function buildStaticArrayDelegationPlan(elem, profileComponentName, ownHandlers) {
24116
+ if (hasRowPortalRef(elem) && elem.key !== null) {
24117
+ return buildDynamicLoopDelegationPlan(elem, profileComponentName, ownHandlers);
24118
+ }
23963
24119
  return {
23964
24120
  kind: "event-delegation",
23965
24121
  containerVar: `_${varSlotId(elem.slotId)}`,
@@ -23979,6 +24135,9 @@ function buildStaticArrayDelegationPlan(elem, profileComponentName, ownHandlers)
23979
24135
  }
23980
24136
  };
23981
24137
  }
24138
+ function hasRowPortalRef(loop) {
24139
+ return loop.bindings.refs.some((r) => r.ssrPortalOwner);
24140
+ }
23982
24141
  function buildKeyedOrIndexLookup(args) {
23983
24142
  const hasBindings = (args.paramBindings?.length ?? 0) > 0;
23984
24143
  if (args.key !== null) {
@@ -24136,7 +24295,7 @@ function preambleLineForHandler(mapPreamble, declaredNames, handler) {
24136
24295
  return declaredNames.some((name) => free.has(name)) ? mapPreamble : null;
24137
24296
  }
24138
24297
  function stringifyEventDelegation(lines, plan) {
24139
- const { containerVar, events, itemLookup, profileComponentName, ownHandlers } = plan;
24298
+ const { containerVar, events, itemLookup, profileComponentName, ownHandlers, relayRowPortals } = plan;
24140
24299
  const eventsByName = new Map;
24141
24300
  for (const ev of events) {
24142
24301
  if (!eventsByName.has(ev.eventName))
@@ -24149,16 +24308,19 @@ function stringifyEventDelegation(lines, plan) {
24149
24308
  const domEventName = toDomEventName(eventName);
24150
24309
  const ownHandler = ownHandlers?.get(domEventName);
24151
24310
  const ownHandlerCall = ownHandler ? withTurn(`(${ownHandler.handler.trim()})(__bfEvt)`, profileComponentName, ownHandler.slotId, ownHandler.eventName) : null;
24152
- if (useCapture) {
24153
- lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${eventName}', (__bfEvt) => {`);
24311
+ const listenedName = useCapture ? eventName : domEventName;
24312
+ if (relayRowPortals) {
24313
+ lines.push(` if (${containerVar}) {`);
24314
+ lines.push(` const __bfDl = (__bfEvt) => {`);
24154
24315
  } else {
24155
- lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${domEventName}', (__bfEvt) => {`);
24316
+ lines.push(` if (${containerVar}) ${containerVar}.addEventListener('${listenedName}', (__bfEvt) => {`);
24156
24317
  }
24157
24318
  lines.push(` const target = __bfEvt.target`);
24158
24319
  for (const ev of evs) {
24159
24320
  const childVar = varSlotId(ev.childSlotId);
24160
24321
  lines.push(` const ${childVar}El = target.closest('[bf="${ev.childSlotId}"]')`);
24161
- lines.push(` if (${childVar}El && ${containerVar}.contains(${childVar}El)) {`);
24322
+ const inContainer = relayRowPortals ? `(${containerVar}.contains(${childVar}El) || isRowPortalOf(${childVar}El, ${containerVar}))` : `${containerVar}.contains(${childVar}El)`;
24323
+ lines.push(` if (${childVar}El && ${inContainer}) {`);
24162
24324
  const handlerCall = withTurn(`(${ev.handler.trim()})(__bfEvt)`, profileComponentName, ev.childSlotId, ev.eventName);
24163
24325
  switch (itemLookup.kind) {
24164
24326
  case "keyed":
@@ -24180,7 +24342,13 @@ function stringifyEventDelegation(lines, plan) {
24180
24342
  if (ownHandlerCall) {
24181
24343
  lines.push(` if (!__bfEvt.cancelBubble) { ${ownHandlerCall} }`);
24182
24344
  }
24183
- if (useCapture) {
24345
+ if (relayRowPortals) {
24346
+ const captureArg = useCapture ? ", true" : "";
24347
+ lines.push(` }`);
24348
+ lines.push(` ${containerVar}.addEventListener('${listenedName}', __bfDl${captureArg})`);
24349
+ lines.push(` relayRowPortalEvents(${containerVar}, '${listenedName}', __bfDl${captureArg})`);
24350
+ lines.push(` }`);
24351
+ } else if (useCapture) {
24184
24352
  lines.push(` }, true)`);
24185
24353
  } else {
24186
24354
  lines.push(` })`);
@@ -24418,16 +24586,18 @@ function emitPlain(lines, plan) {
24418
24586
  indent: " ",
24419
24587
  singleRootLayout: "inline"
24420
24588
  });
24589
+ emitRowPortalClaim(lines, childRefs, { indent: " ", containerVar });
24590
+ const itemLookup = bodyIsMultiRoot || rowPortalSlotIds(childRefs).length > 0;
24421
24591
  if (reactiveEffects !== null || preambleRegions.length > 0) {
24422
24592
  stringifyReactiveEffects(lines, reactiveEffects, {
24423
24593
  indent: " ",
24424
24594
  elVar: "__el",
24425
- bodyIsMultiRoot,
24595
+ bodyIsMultiRoot: itemLookup,
24426
24596
  preambleRegions,
24427
24597
  mapPreambleWrapped
24428
24598
  });
24429
24599
  }
24430
- emitLoopChildRefs(lines, childRefs, { indent: " ", elVar: "__el", bodyIsMultiRoot });
24600
+ emitLoopChildRefs(lines, childRefs, { indent: " ", elVar: "__el", bodyIsMultiRoot: itemLookup, containerVar });
24431
24601
  lines.push(` return __el`);
24432
24602
  lines.push(` }, '${markerId}'${loopBfId})`);
24433
24603
  }
@@ -24502,7 +24672,9 @@ function emitArmBody(lines, body, mode, indent, profileComponentName) {
24502
24672
  for (const [slotId, attrs] of attrsBySlot) {
24503
24673
  const v = varSlotId(slotId);
24504
24674
  const elVar = `__ra_${v}`;
24505
- lines.push(`${indent}{ const ${elVar} = qsa(__branchScope, '[bf="${slotId}"]')`);
24675
+ const receivers = attrs[0].receiverSlotIds;
24676
+ const receiverArg = receivers && receivers.length > 0 ? `, ${JSON.stringify(receivers)}` : "";
24677
+ lines.push(`${indent}{ const ${elVar} = qsa(__branchScope, '[bf="${slotId}"]'${receiverArg})`);
24506
24678
  lines.push(`${indent}${DEDUP_STORE_DECL}`);
24507
24679
  lines.push(`${indent}if (${elVar}) {`);
24508
24680
  let ordinal = 0;
@@ -26699,6 +26871,39 @@ function lookupStaticRecordLiteral(objectName, key, constants, isShadowed) {
26699
26871
  }
26700
26872
  return null;
26701
26873
  }
26874
+ function lookupLiteralConst(name, constants, isShadowed) {
26875
+ if (isShadowed(name))
26876
+ return null;
26877
+ const c = (constants ?? []).find((lc) => lc.name === name);
26878
+ if (c?.value === undefined)
26879
+ return null;
26880
+ const p = c.parsed;
26881
+ if (p?.kind === "literal") {
26882
+ if (p.literalType === "string" && typeof p.value === "string")
26883
+ return { kind: "string", text: p.value };
26884
+ if (p.literalType === "boolean" && typeof p.value === "boolean")
26885
+ return { kind: "boolean", text: String(p.value) };
26886
+ if (p.literalType === "null")
26887
+ return { kind: "null", text: "null" };
26888
+ if (p.literalType === "number" && typeof p.value === "number" && Number.isFinite(p.value)) {
26889
+ return { kind: "number", text: String(p.value) };
26890
+ }
26891
+ }
26892
+ if (p?.kind === "unary" && p.op === "-" && p.argument.kind === "literal" && p.argument.literalType === "number" && typeof p.argument.value === "number" && Number.isFinite(p.argument.value)) {
26893
+ return { kind: "number", text: String(-p.argument.value) };
26894
+ }
26895
+ if (p)
26896
+ return null;
26897
+ const v = c.value.trim();
26898
+ if (/^-?\d+(\.\d+)?$/.test(v))
26899
+ return { kind: "number", text: v };
26900
+ if (v === "true" || v === "false")
26901
+ return { kind: "boolean", text: v };
26902
+ if (v === "null")
26903
+ return { kind: "null", text: "null" };
26904
+ const strLit2 = /^'([^'\\]*)'$/.exec(v) ?? /^"([^"\\]*)"$/.exec(v);
26905
+ return strLit2 ? { kind: "string", text: strLit2[1] } : null;
26906
+ }
26702
26907
  function evalStringArrayJoin(source) {
26703
26908
  const sf = ts26.createSourceFile("__join.ts", `const __x = (${source});`, ts26.ScriptTarget.Latest, false);
26704
26909
  const stmt = sf.statements[0];
@@ -28797,6 +29002,55 @@ function collectLoopBoundNames(ir) {
28797
29002
  visit3(ir.root);
28798
29003
  return names;
28799
29004
  }
29005
+ // src/adapters/boolean-result.ts
29006
+ var COMPARISON_OPS = new Set([
29007
+ "<",
29008
+ ">",
29009
+ "<=",
29010
+ ">=",
29011
+ "==",
29012
+ "===",
29013
+ "!=",
29014
+ "!=="
29015
+ ]);
29016
+ function isBooleanResultParsed(node) {
29017
+ switch (node.kind) {
29018
+ case "literal":
29019
+ return node.literalType === "boolean";
29020
+ case "binary":
29021
+ return COMPARISON_OPS.has(node.op);
29022
+ case "unary":
29023
+ return node.op === "!";
29024
+ case "logical":
29025
+ return isBooleanResultParsed(node.left) && isBooleanResultParsed(node.right);
29026
+ case "conditional":
29027
+ return isBooleanResultParsed(node.consequent) && isBooleanResultParsed(node.alternate);
29028
+ default:
29029
+ return false;
29030
+ }
29031
+ }
29032
+ function stringifyBooleanTernaryBranches(node) {
29033
+ if (node.kind !== "conditional" || isBooleanResultParsed(node))
29034
+ return node;
29035
+ return {
29036
+ ...node,
29037
+ consequent: stringifyBooleanBranch(node.consequent),
29038
+ alternate: stringifyBooleanBranch(node.alternate)
29039
+ };
29040
+ }
29041
+ function stringifyBooleanBranch(branch) {
29042
+ if (!isBooleanResultParsed(branch))
29043
+ return stringifyBooleanTernaryBranches(branch);
29044
+ if (branch.kind === "literal") {
29045
+ return { kind: "literal", value: String(branch.value), literalType: "string" };
29046
+ }
29047
+ return {
29048
+ kind: "conditional",
29049
+ test: branch,
29050
+ consequent: { kind: "literal", value: "true", literalType: "string" },
29051
+ alternate: { kind: "literal", value: "false", literalType: "string" }
29052
+ };
29053
+ }
28800
29054
  // src/static-literal.ts
28801
29055
  function evaluateStaticLiteral(expr, bindings) {
28802
29056
  switch (expr.kind) {
@@ -28898,6 +29152,106 @@ function resolveStaticLoopSource(arrayParsed, localConstants, opts) {
28898
29152
  return null;
28899
29153
  return resolved.value;
28900
29154
  }
29155
+ // src/nullable-signal-attr.ts
29156
+ function isNullishType(type) {
29157
+ return type.kind === "primitive" && (type.primitive === "undefined" || type.primitive === "null");
29158
+ }
29159
+ function admitsNullish(type) {
29160
+ if (isNullishType(type))
29161
+ return true;
29162
+ return type.kind === "union" && (type.unionTypes ?? []).some(isNullishType);
29163
+ }
29164
+ function isNullishLiteral(expr) {
29165
+ if (!expr)
29166
+ return false;
29167
+ if (expr.kind === "identifier")
29168
+ return expr.name === "undefined";
29169
+ return expr.kind === "literal" && expr.literalType === "null";
29170
+ }
29171
+ function isNullableSignal(signal) {
29172
+ if (admitsNullish(signal.type))
29173
+ return true;
29174
+ return signal.type.kind === "unknown" && isNullishLiteral(signal.parsed);
29175
+ }
29176
+ function collectNullableSignalGetters(ir) {
29177
+ return new Set((ir.metadata.signals ?? []).filter(isNullableSignal).map((s) => s.getter));
29178
+ }
29179
+ function bareGetterCallName(parsed) {
29180
+ if (!parsed || parsed.kind !== "call" || parsed.args.length !== 0)
29181
+ return null;
29182
+ return parsed.callee.kind === "identifier" ? parsed.callee.name : null;
29183
+ }
29184
+ function nullableSignalAttrGetter(parsed, nullable) {
29185
+ const getter = bareGetterCallName(parsed);
29186
+ return getter !== null && nullable.has(getter) ? getter : null;
29187
+ }
29188
+ function collectNullishAttrContext(ir) {
29189
+ const signals = ir.metadata.signals ?? [];
29190
+ return {
29191
+ nullableSignals: collectNullableSignalGetters(ir),
29192
+ nullSeededSignals: new Set(signals.filter((s) => s.parsed?.kind === "literal" && s.parsed.literalType === "null").map((s) => s.getter)),
29193
+ memos: new Map((ir.metadata.memos ?? []).map((m) => [m.name, m]))
29194
+ };
29195
+ }
29196
+ function attrValueMayBeNullish(parsed, ctx, isShadowed = () => false) {
29197
+ const visiting = new Set;
29198
+ const walk = (expr, shadowed) => {
29199
+ switch (expr.kind) {
29200
+ case "identifier":
29201
+ return expr.name === "undefined";
29202
+ case "literal":
29203
+ return expr.literalType === "null";
29204
+ case "call": {
29205
+ const getter = bareGetterCallName(expr);
29206
+ if (getter === null || shadowed(getter))
29207
+ return false;
29208
+ if (ctx.nullableSignals.has(getter))
29209
+ return true;
29210
+ const memo = ctx.memos.get(getter);
29211
+ if (!memo || visiting.has(getter))
29212
+ return false;
29213
+ if (admitsNullish(memo.type))
29214
+ return true;
29215
+ visiting.add(getter);
29216
+ const result = memo.parsed !== undefined && walk(memo.parsed, () => false);
29217
+ visiting.delete(getter);
29218
+ return result;
29219
+ }
29220
+ case "member":
29221
+ return expr.optional || walk(expr.object, shadowed);
29222
+ case "index-access":
29223
+ return walk(expr.object, shadowed);
29224
+ case "conditional":
29225
+ return walk(expr.consequent, shadowed) || walk(expr.alternate, shadowed);
29226
+ case "logical":
29227
+ return expr.op === "&&" ? walk(expr.left, shadowed) || walk(expr.right, shadowed) : walk(expr.right, shadowed);
29228
+ default:
29229
+ return false;
29230
+ }
29231
+ };
29232
+ return parsed !== undefined && walk(parsed, isShadowed);
29233
+ }
29234
+ function arithmeticOperandIsNull(parsed, ctx, isShadowed = () => false) {
29235
+ const visiting = new Set;
29236
+ const walk = (expr, shadowed) => {
29237
+ if (expr.kind === "literal")
29238
+ return expr.literalType === "null";
29239
+ const getter = expr.kind === "identifier" ? expr.name : bareGetterCallName(expr);
29240
+ if (getter === null || shadowed(getter))
29241
+ return false;
29242
+ if (ctx.nullSeededSignals?.has(getter))
29243
+ return true;
29244
+ const memo = ctx.memos.get(getter);
29245
+ if (!memo?.parsed || visiting.has(getter))
29246
+ return false;
29247
+ visiting.add(getter);
29248
+ const result = walk(memo.parsed, () => false);
29249
+ visiting.delete(getter);
29250
+ return result;
29251
+ };
29252
+ return parsed !== undefined && walk(parsed, isShadowed);
29253
+ }
29254
+ var NULL_COERCING_ARITHMETIC_OPS = new Set(["-", "*", "/", "%", "**"]);
28901
29255
  // src/query-href-lowering.ts
28902
29256
  function matchQueryHrefCall(callee, args, localNames) {
28903
29257
  if (callee.kind !== "identifier" || !localNames.has(callee.name))
@@ -29039,6 +29393,15 @@ function emitAttrValue(value, emitter, name) {
29039
29393
  }
29040
29394
  }
29041
29395
  }
29396
+ // src/adapters/line-statement-text.ts
29397
+ function escapeLineStatementSigil(text, sigil, literal) {
29398
+ return text.split(`
29399
+ `).map((line) => {
29400
+ const indent = line.length - line.trimStart().length;
29401
+ return line.startsWith(sigil, indent) ? line.slice(0, indent) + literal + line.slice(indent + sigil.length) : line;
29402
+ }).join(`
29403
+ `);
29404
+ }
29042
29405
  // src/adapters/dangerous-inner-html.ts
29043
29406
  var DANGEROUS_INNER_HTML_ATTR = "dangerouslySetInnerHTML";
29044
29407
  function isDangerousInnerHtmlAttr(attr) {
@@ -29357,6 +29720,42 @@ function restNamesMisused(loop, names) {
29357
29720
  function escapeRe(s) {
29358
29721
  return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
29359
29722
  }
29723
+ // src/scope/root-prop-alias.ts
29724
+ function rootPropAliasNames(ir, propNames) {
29725
+ const { metadata } = ir;
29726
+ const props = [...propNames];
29727
+ const taken = new Set([
29728
+ ...props,
29729
+ ...metadata.localConstants.map((c) => c.name),
29730
+ ...metadata.localFunctions.map((f) => f.name),
29731
+ ...metadata.signals.flatMap((s) => s.setter ? [s.getter, s.setter] : [s.getter]),
29732
+ ...metadata.memos.map((m) => m.name),
29733
+ ...collectLoopBoundNames(ir)
29734
+ ]);
29735
+ const aliases = new Map;
29736
+ for (const name of props) {
29737
+ let alias = `__bf_root_${name}`;
29738
+ while (taken.has(alias))
29739
+ alias += "_";
29740
+ taken.add(alias);
29741
+ aliases.set(name, alias);
29742
+ }
29743
+ return aliases;
29744
+ }
29745
+ function rootPropAliasesForLoop(outer, row, aliases) {
29746
+ const shadowed = [];
29747
+ for (const name of row.boundNames()) {
29748
+ const alias = aliases.get(name);
29749
+ if (alias !== undefined && !outer.isBound(name))
29750
+ shadowed.push({ name, alias });
29751
+ }
29752
+ return shadowed;
29753
+ }
29754
+ function rootPropReadName(name, scope, aliases) {
29755
+ if (!scope.isBound(name))
29756
+ return name;
29757
+ return aliases.get(name) ?? name;
29758
+ }
29360
29759
  // src/debug.ts
29361
29760
  import ts31 from "typescript";
29362
29761
  function buildComponentGraph(source, filePath, componentName) {
@@ -31156,6 +31555,32 @@ function buildIdIndex(graph) {
31156
31555
  }
31157
31556
  return index;
31158
31557
  }
31558
+ function buildRestHandlerSites(componentName, ir) {
31559
+ const sites = new Map;
31560
+ walkIR(ir.root, undefined, {
31561
+ element({ node, descend }) {
31562
+ const spread = node.slotId ? node.attrs.find((a) => a.name === "...") : undefined;
31563
+ if (spread && node.slotId) {
31564
+ const loc = spread.loc ?? node.loc;
31565
+ sites.set(`${componentName}#handler:${node.slotId}`, {
31566
+ kind: "handler",
31567
+ name: `@${node.slotId} {...}`,
31568
+ loc: { file: loc.file, line: loc.start.line }
31569
+ });
31570
+ }
31571
+ descend();
31572
+ },
31573
+ component({ descend, descendJsxChildren }) {
31574
+ descend();
31575
+ descendJsxChildren();
31576
+ }
31577
+ });
31578
+ return sites;
31579
+ }
31580
+ function restSiteOf(handlerId, sites) {
31581
+ const colon = handlerId.lastIndexOf(":");
31582
+ return colon < 0 ? undefined : sites.get(handlerId.slice(0, colon));
31583
+ }
31159
31584
  function isRuntimeBookkeepingId(id) {
31160
31585
  return /^[serm]\d+$/.test(id);
31161
31586
  }
@@ -31627,7 +32052,8 @@ function buildProfileReport(input) {
31627
32052
  const allSources = [{ source, filePath }, ...input.extraSources ?? []];
31628
32053
  const index = new Map;
31629
32054
  const turnBindings = new Map;
31630
- let handlersTotal = 0;
32055
+ const staticHandlerIds = new Set;
32056
+ const restSites = new Map;
31631
32057
  const instrumentedEffectLines = new Map;
31632
32058
  for (const s of allSources) {
31633
32059
  const program = createProgramForFile(s.source, s.filePath)?.program;
@@ -31641,13 +32067,19 @@ function buildProfileReport(input) {
31641
32067
  componentNames = [undefined];
31642
32068
  for (const name of componentNames) {
31643
32069
  let graph;
32070
+ let ir;
31644
32071
  try {
31645
- graph = buildComponentAnalysis(s.source, s.filePath, name, program).graph;
32072
+ ({ graph, ir } = buildComponentAnalysis(s.source, s.filePath, name, program));
31646
32073
  } catch {
31647
32074
  continue;
31648
32075
  }
31649
- for (const [k, v] of buildIdIndex(graph))
32076
+ for (const [k, v] of buildIdIndex(graph)) {
31650
32077
  index.set(k, v);
32078
+ if (v.kind === "handler")
32079
+ staticHandlerIds.add(k);
32080
+ }
32081
+ for (const [k, v] of buildRestHandlerSites(graph.componentName, ir))
32082
+ restSites.set(k, v);
31651
32083
  for (const e of graph.effects) {
31652
32084
  const set = instrumentedEffectLines.get(e.loc.file) ?? new Set;
31653
32085
  set.add(e.loc.line);
@@ -31655,13 +32087,19 @@ function buildProfileReport(input) {
31655
32087
  }
31656
32088
  try {
31657
32089
  const summary = buildEventSummary(s.source, s.filePath, name, program);
31658
- handlersTotal += summary.events.length;
31659
32090
  for (const [turn, binding] of turnToEventBinding(graph, summary.events)) {
31660
32091
  turnBindings.set(turn, { binding, graph });
31661
32092
  }
31662
32093
  } catch {}
31663
32094
  }
31664
32095
  }
32096
+ for (const e of events) {
32097
+ if (e.turn === null || index.has(e.turn))
32098
+ continue;
32099
+ const site = restSiteOf(e.turn, restSites);
32100
+ if (site)
32101
+ index.set(e.turn, { ...site, name: `${e.turn.slice(e.turn.lastIndexOf(":") + 1)}${site.name}` });
32102
+ }
31665
32103
  const hasFallbackEffectId = events.some((e) => e.subscriber !== undefined && isFallbackEffectId(e.subscriber));
31666
32104
  const uninstrumentedCandidates = [];
31667
32105
  if (hasFallbackEffectId) {
@@ -31697,9 +32135,10 @@ function buildProfileReport(input) {
31697
32135
  handlerIds.add(e.turn);
31698
32136
  }
31699
32137
  }
32138
+ const handlersTotal = new Set([...staticHandlerIds, ...handlerIds]).size;
31700
32139
  const findings = buildAgentFindings(primary.componentName, hotSubscribers, wastedReReruns, batchAdvisor, unattributed);
31701
32140
  const status = findings.some((f) => f.severity === "warning" || f.severity === "error") ? "warning" : "ok";
31702
- const ratio = handlersTotal > 0 ? Math.min(1, handlerIds.size / handlersTotal) : 1;
32141
+ const ratio = handlersTotal > 0 ? handlerIds.size / handlersTotal : 1;
31703
32142
  let guidance;
31704
32143
  if (turnSeqs.size === 0) {
31705
32144
  guidance = handlersTotal === 0 ? {
@@ -32164,10 +32603,14 @@ export {
32164
32603
  traceUpdatePath,
32165
32604
  testAdapter,
32166
32605
  stringifyParsedExpr,
32606
+ stringifyBooleanTernaryBranches,
32167
32607
  sortComparatorFromArrow,
32168
32608
  serializeParsedExpr,
32169
32609
  searchParamsLocalNames,
32170
32610
  scanComponentFile,
32611
+ rootPropReadName,
32612
+ rootPropAliasesForLoop,
32613
+ rootPropAliasNames,
32171
32614
  rewriteImportsForTemplate,
32172
32615
  rewriteDynamicImportsInSource,
32173
32616
  resolveStaticLoopSource,
@@ -32193,6 +32636,7 @@ export {
32193
32636
  parseExpression,
32194
32637
  parseBlockBodyTolerant,
32195
32638
  parseBlockBody,
32639
+ nullableSignalAttrGetter,
32196
32640
  needsTypeBasedDetection,
32197
32641
  materializeGetterCalls,
32198
32642
  matchSearchParamsMethodCall,
@@ -32201,6 +32645,7 @@ export {
32201
32645
  makeIdCallRegex,
32202
32646
  loweringNodeChildren,
32203
32647
  lookupStaticRecordLiteral,
32648
+ lookupLiteralConst,
32204
32649
  literalMemberIndex,
32205
32650
  listComponentFunctions as listExportedComponents,
32206
32651
  listComponentFunctions,
@@ -32213,6 +32658,8 @@ export {
32213
32658
  isStringTypedOperand,
32214
32659
  isStringConcatBinary,
32215
32660
  isOpaqueLocalAccessorName,
32661
+ isNullishLiteral,
32662
+ isNullableSignal,
32216
32663
  isLowerableObjectRestDestructure,
32217
32664
  isLowerableLoopDestructure,
32218
32665
  isIdentifierName,
@@ -32221,6 +32668,7 @@ export {
32221
32668
  isEventHandlerName,
32222
32669
  isElidedFactoryGetter,
32223
32670
  isDangerousInnerHtmlAttr,
32671
+ isBooleanResultParsed,
32224
32672
  isBooleanAttr,
32225
32673
  importsSearchParams,
32226
32674
  identifierPath,
@@ -32266,6 +32714,7 @@ export {
32266
32714
  evaluateStaticLiteral,
32267
32715
  evaluateProfileGates,
32268
32716
  evalStringArrayJoin,
32717
+ escapeLineStatementSigil,
32269
32718
  envSignalReaderFor,
32270
32719
  envSignalLocalNames,
32271
32720
  enableCompilerInstrumentation,
@@ -32290,6 +32739,8 @@ export {
32290
32739
  compileJSX,
32291
32740
  combineParentChildClientJs,
32292
32741
  collectValueReferencedNames,
32742
+ collectNullishAttrContext,
32743
+ collectNullableSignalGetters,
32293
32744
  collectModuleStringConsts,
32294
32745
  collectLoopBoundNames,
32295
32746
  collectContextConsumers,
@@ -32313,7 +32764,9 @@ export {
32313
32764
  buildComponentGraph,
32314
32765
  buildComponentAnalysis,
32315
32766
  augmentInheritedPropAccesses,
32767
+ attrValueMayBeNullish,
32316
32768
  asCallbackMethodCall,
32769
+ arithmeticOperandIsNull,
32317
32770
  applyCssLayerPrefix,
32318
32771
  analyzeWastedReReruns,
32319
32772
  analyzeHotSubscribers,
@@ -32330,11 +32783,13 @@ export {
32330
32783
  REACTIVE_PRIMITIVES,
32331
32784
  PROFILE_SCHEMA_VERSION,
32332
32785
  PARSED_EXPR_KINDS,
32786
+ NULL_COERCING_ARITHMETIC_OPS,
32333
32787
  JsxAdapter,
32334
32788
  ErrorCodes,
32335
32789
  ESCAPE_SSR_COST,
32336
32790
  ENV_SIGNAL_READERS,
32337
32791
  CLIENT_EXPRESSION_DIRECTIVE,
32792
+ CLIENT_EXPORTS,
32338
32793
  CALLBACK_METHODS,
32339
32794
  BindingScope,
32340
32795
  BaseAdapter,