@barefootjs/jsx 0.40.1 → 0.40.2

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 (176) hide show
  1. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +4 -3
  2. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +1 -1
  3. package/dist/adapters/boolean-result.d.ts +32 -10
  4. package/dist/adapters/boolean-result.d.ts.map +1 -1
  5. package/dist/adapters/brace-delimiter-text.d.ts +18 -0
  6. package/dist/adapters/brace-delimiter-text.d.ts.map +1 -0
  7. package/dist/adapters/callback-method.d.ts +38 -5
  8. package/dist/adapters/callback-method.d.ts.map +1 -1
  9. package/dist/adapters/computed-const.d.ts +11 -1
  10. package/dist/adapters/computed-const.d.ts.map +1 -1
  11. package/dist/adapters/dsl-template-adapter.d.ts +21 -0
  12. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  13. package/dist/adapters/loop-bound-names.d.ts +9 -1
  14. package/dist/adapters/loop-bound-names.d.ts.map +1 -1
  15. package/dist/adapters/loop-row-type.d.ts +52 -0
  16. package/dist/adapters/loop-row-type.d.ts.map +1 -0
  17. package/dist/adapters/nil-reading.d.ts +68 -0
  18. package/dist/adapters/nil-reading.d.ts.map +1 -0
  19. package/dist/adapters/non-primitive-equality.d.ts +33 -0
  20. package/dist/adapters/non-primitive-equality.d.ts.map +1 -0
  21. package/dist/adapters/number-value.d.ts +5 -3
  22. package/dist/adapters/number-value.d.ts.map +1 -1
  23. package/dist/adapters/operand-typing.d.ts +126 -0
  24. package/dist/adapters/operand-typing.d.ts.map +1 -0
  25. package/dist/adapters/parsed-expr-emitter.d.ts +70 -12
  26. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  27. package/dist/adapters/primitive-plan.d.ts +291 -0
  28. package/dist/adapters/primitive-plan.d.ts.map +1 -0
  29. package/dist/analyzer-context.d.ts +4 -0
  30. package/dist/analyzer-context.d.ts.map +1 -1
  31. package/dist/analyzer.d.ts.map +1 -1
  32. package/dist/augment-inherited-props.d.ts +63 -8
  33. package/dist/augment-inherited-props.d.ts.map +1 -1
  34. package/dist/compiler.d.ts.map +1 -1
  35. package/dist/event-handler-name.d.ts +12 -0
  36. package/dist/event-handler-name.d.ts.map +1 -1
  37. package/dist/expression-parser.d.ts +8 -0
  38. package/dist/expression-parser.d.ts.map +1 -1
  39. package/dist/index.d.ts +19 -9
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +4628 -2198
  42. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/child-props-object.d.ts +64 -0
  44. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -0
  45. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +4 -2
  50. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/imports.d.ts +2 -2
  53. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/index.d.ts +2 -6
  55. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/plan/build-static-array-child-init.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +30 -18
  58. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  59. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  60. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +3 -2
  61. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  62. package/dist/jsx-to-ir.d.ts +1 -0
  63. package/dist/jsx-to-ir.d.ts.map +1 -1
  64. package/dist/nullable-signal-attr.d.ts +68 -9
  65. package/dist/nullable-signal-attr.d.ts.map +1 -1
  66. package/dist/prop-rewrite.d.ts +7 -0
  67. package/dist/prop-rewrite.d.ts.map +1 -1
  68. package/dist/props-object-whole-read.d.ts +15 -0
  69. package/dist/props-object-whole-read.d.ts.map +1 -0
  70. package/dist/rich-type-refusal.d.ts.map +1 -1
  71. package/dist/scope/binding-scope.d.ts +85 -10
  72. package/dist/scope/binding-scope.d.ts.map +1 -1
  73. package/dist/scope/lexical-scope-walk.d.ts +3 -2
  74. package/dist/scope/lexical-scope-walk.d.ts.map +1 -1
  75. package/dist/scope/root-prop-alias.d.ts +10 -7
  76. package/dist/scope/root-prop-alias.d.ts.map +1 -1
  77. package/dist/strip-types.d.ts +13 -0
  78. package/dist/strip-types.d.ts.map +1 -1
  79. package/dist/template-position-walk.d.ts +21 -3
  80. package/dist/template-position-walk.d.ts.map +1 -1
  81. package/dist/types.d.ts +90 -0
  82. package/dist/types.d.ts.map +1 -1
  83. package/package.json +2 -2
  84. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
  85. package/src/__tests__/binding-scope.test.ts +89 -1
  86. package/src/__tests__/body-destructure-props-object-alias.test.ts +123 -0
  87. package/src/__tests__/boolean-result.test.ts +22 -5
  88. package/src/__tests__/brace-delimiter-text.test.ts +26 -0
  89. package/src/__tests__/callback-method.test.ts +62 -2
  90. package/src/__tests__/child-components-in-map.test.ts +1 -1
  91. package/src/__tests__/computed-const.test.ts +103 -0
  92. package/src/__tests__/emit-to-string-call.test.ts +2 -1
  93. package/src/__tests__/hydration-payload-analysis.test.ts +166 -0
  94. package/src/__tests__/issue-2724-prop-alias-loop-not-static.test.ts +7 -7
  95. package/src/__tests__/issue-2754-rest-spread-needs-slot.test.ts +5 -2
  96. package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +1 -1
  97. package/src/__tests__/issue-2835-props-type-member-name-collision.test.ts +4 -4
  98. package/src/__tests__/issue-3044-nested-prop-object-array-not-static.test.ts +1 -1
  99. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +2 -1
  100. package/src/__tests__/issue-3713-props-spread-loop-row.test.ts +65 -0
  101. package/src/__tests__/lookup-literal-const.test.ts +9 -3
  102. package/src/__tests__/loop-index-reactivity.test.ts +2 -2
  103. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +1 -1
  104. package/src/__tests__/loop-plan.test.ts +1 -1
  105. package/src/__tests__/loop-row-const-initializer-shadow.test.ts +146 -0
  106. package/src/__tests__/loop-row-type.test.ts +64 -0
  107. package/src/__tests__/lowering-value-position.test.ts +4 -0
  108. package/src/__tests__/module-const-destructure-default.test.ts +156 -0
  109. package/src/__tests__/nested-loop-index-param.test.ts +1 -1
  110. package/src/__tests__/nested-loop-reactive-attrs.test.ts +2 -2
  111. package/src/__tests__/nested-row-shadowing.test.ts +2 -2
  112. package/src/__tests__/nil-reading.test.ts +77 -0
  113. package/src/__tests__/nullable-signal-attr.test.ts +134 -0
  114. package/src/__tests__/primitive-plan.test.ts +416 -0
  115. package/src/__tests__/profile-loop-binding-ids.test.ts +2 -2
  116. package/src/__tests__/profile-nested-binding-ids.test.ts +2 -2
  117. package/src/__tests__/props-object-whole-read.test.ts +40 -0
  118. package/src/__tests__/reactive-attrs-in-map.test.ts +1 -1
  119. package/src/__tests__/reactive-factory-inlining.test.ts +4 -1
  120. package/src/__tests__/rest-binding-gaps.test.ts +192 -0
  121. package/src/__tests__/root-prop-alias.test.ts +53 -8
  122. package/src/__tests__/static-loop-csr-materialize.test.ts +2 -2
  123. package/src/__tests__/static-record-literal-array.test.ts +171 -0
  124. package/src/__tests__/string-concat-identifier.test.ts +40 -1
  125. package/src/adapters/ambiguous-nil-arithmetic.ts +22 -13
  126. package/src/adapters/boolean-result.ts +72 -66
  127. package/src/adapters/brace-delimiter-text.ts +25 -0
  128. package/src/adapters/callback-method.ts +151 -27
  129. package/src/adapters/computed-const.ts +238 -4
  130. package/src/adapters/dsl-template-adapter.ts +40 -2
  131. package/src/adapters/loop-bound-names.ts +9 -1
  132. package/src/adapters/loop-plan.ts +1 -1
  133. package/src/adapters/loop-row-type.ts +139 -0
  134. package/src/adapters/nil-reading.ts +297 -0
  135. package/src/adapters/non-primitive-equality.ts +92 -0
  136. package/src/adapters/number-value.ts +17 -4
  137. package/src/adapters/operand-typing.ts +522 -0
  138. package/src/adapters/parsed-expr-emitter.ts +154 -19
  139. package/src/adapters/primitive-plan.ts +696 -0
  140. package/src/analyzer-context.ts +6 -0
  141. package/src/analyzer.ts +505 -19
  142. package/src/augment-inherited-props.ts +108 -10
  143. package/src/compiler.ts +17 -0
  144. package/src/event-handler-name.ts +15 -0
  145. package/src/expression-parser.ts +70 -1
  146. package/src/index.ts +33 -7
  147. package/src/ir-to-client-js/build-references.ts +69 -0
  148. package/src/ir-to-client-js/child-props-object.ts +106 -0
  149. package/src/ir-to-client-js/collect-elements.ts +30 -55
  150. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +6 -1
  151. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +29 -28
  152. package/src/ir-to-client-js/control-flow/shared.ts +20 -22
  153. package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +5 -3
  154. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +2 -2
  155. package/src/ir-to-client-js/control-flow/stringify/lazy-row.ts +1 -1
  156. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +2 -2
  157. package/src/ir-to-client-js/control-flow/stringify/loop.ts +1 -1
  158. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +3 -3
  159. package/src/ir-to-client-js/html-template.ts +25 -8
  160. package/src/ir-to-client-js/imports.ts +1 -1
  161. package/src/ir-to-client-js/index.ts +53 -11
  162. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +31 -14
  163. package/src/ir-to-client-js/plan/static-array-child-init.ts +27 -18
  164. package/src/ir-to-client-js/prop-handling.ts +22 -3
  165. package/src/ir-to-client-js/stringify/static-array-child-init.ts +26 -10
  166. package/src/jsx-to-ir.ts +446 -37
  167. package/src/nullable-signal-attr.ts +246 -29
  168. package/src/prop-rewrite.ts +30 -6
  169. package/src/props-object-whole-read.ts +87 -0
  170. package/src/rich-type-refusal.ts +2 -1
  171. package/src/scope/binding-scope.ts +182 -18
  172. package/src/scope/lexical-scope-walk.ts +4 -3
  173. package/src/scope/root-prop-alias.ts +15 -8
  174. package/src/strip-types.ts +31 -3
  175. package/src/template-position-walk.ts +57 -28
  176. package/src/types.ts +87 -0
@@ -2,15 +2,16 @@
2
2
  * IR tree traversal → collect elements into ClientJsContext.
3
3
  */
4
4
 
5
- import { type IRNode, type IRElement, type IRComponent, type IRConditional, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
5
+ import { type AttrValue, type IRNode, type IRElement, type IRComponent, type IRConditional, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
6
6
  import type { ClientJsContext, ConditionalBranchChildComponent, ConditionalBranchReactiveAttr, BranchLoop, ConditionalBranchTextEffect, ConditionalElement, LoopChildBindings, LoopChildBranchSummary, LoopChildConditional, LoopOffset, NestedLoop } from './types.ts'
7
- import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, toHtmlAttrName, rowBoundNames, withRowAccessor, type LoopParamSpec } from './utils.ts'
7
+ import { attrValueToString, freeIdsFromRefs, PROPS_PARAM, toHtmlAttrName, rowBoundNames, withRowAccessor, type LoopParamSpec } from './utils.ts'
8
8
  import { classifyReactivity, needsEffectWrapper, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectConditionalBranchComponentNodes, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
9
9
  import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, jsxChildrenPropGetterExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, renderFlatMapClientBody, renderFlatMapProjectionClientBody, flatMapCallbackHasKeyedLeaf, type SkeletonSlotPaths } from './html-template.ts'
10
10
  import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-parse.ts'
11
11
  import { expandDynamicPropValue, expandConstantForReactivity, resolveRestSpreadOrigin, resolveRestSpreadNames } from './prop-handling.ts'
12
12
  import { extractFreeIdentifiersFromText } from './csr-substitute.ts'
13
13
  import { walkIR, stopAt } from './walker.ts'
14
+ import { callerFirstPropExpr, childPropsObjectExpr, isSpreadPropName, lastPropsObjectSpreadIndex } from './child-props-object.ts'
14
15
  import { buildLoopChainExpr } from '../loop-chain.ts'
15
16
  import { classifyDOMProp } from '@barefootjs/shared'
16
17
  import type { BindingScope } from '../scope/binding-scope.ts'
@@ -568,75 +569,52 @@ function componentInitPropValue(prop: IRProp, ctx: ClientJsContext): { expr: str
568
569
  }
569
570
 
570
571
  /**
571
- * Index of the last spread of the component's own props object in a child
572
- * component call (`<Tag tone="first" {...props} />`), or -1. An explicit
573
- * prop written before it is only a default: the spread overrides it when
574
- * the caller passed that key, as in JS (#3688). This is the one source-order
575
- * decision `initChild`'s props and both reactive DOM mirrors
576
- * (`ctx.reactiveProps`, `ctx.reactiveChildProps`) read, so an overridden
577
- * explicit expression can't overwrite the spread-selected value on update.
572
+ * The merged value of the explicit prop at `index` for a reactive DOM
573
+ * mirror: caller-first when a later props-object spread (at `spreadAt`, see
574
+ * `lastPropsObjectSpreadIndex`) overrides it, `expr` as written otherwise.
578
575
  */
579
- function lastPropsObjectSpreadIndex(props: IRProp[]): number {
580
- let at = -1
581
- props.forEach((p, index) => {
582
- if (p.value.kind === 'spread' && p.value.propsObject === true) at = index
583
- })
584
- return at
576
+ function mergedMirrorExpr(name: string, expr: string, index: number, spreadAt: number): string {
577
+ return index < spreadAt ? callerFirstPropExpr(name, expr) : expr
585
578
  }
586
579
 
587
580
  /**
588
- * The value of an explicit prop a later props-object spread overrides (see
589
- * `lastPropsObjectSpreadIndex`): the caller's own value when it passed the
590
- * key, `expr` otherwise. `forwardProps` lets every override win, so the
591
- * merge is spelled into the value itself.
581
+ * Which caller bag an element's spread attribute forwards, for
582
+ * `applyRestAttrs`: its text resolved through any `const x__alias = x` hop
583
+ * onto the rest/props binding (#2723, `resolveRestSpreadOrigin`). Null
584
+ * when Phase 1 did not resolve the spread to the bag
585
+ * (`SpreadAttr.callerBag`): a loop row or callback parameter spelled like
586
+ * the rest binding is that binding (#3851).
592
587
  */
593
- function callerFirstPropExpr(name: string, expr: string): string {
594
- const key = JSON.stringify(name)
595
- return `(${key} in ${PROPS_PARAM} ? ${PROPS_PARAM}[${key}] : ${expr})`
588
+ function callerBagSpreadOrigin(value: AttrValue, ctx: ClientJsContext): 'rest' | 'props' | null {
589
+ if (value.kind !== 'spread' || value.callerBag === undefined) return null
590
+ const spreadVal = attrValueToString(value) ?? ''
591
+ return spreadVal ? resolveRestSpreadOrigin(ctx, spreadVal) : null
596
592
  }
597
593
 
598
594
  /**
599
- * The merged value of the explicit prop at `index` for a reactive DOM
600
- * mirror: caller-first when a later props-object spread (at `spreadAt`, see
601
- * `lastPropsObjectSpreadIndex`) overrides it, `expr` as written otherwise.
595
+ * The live `_p.<key>` read a closed-rest-expanded attribute binds to
596
+ * (`IRAttribute.restExpandedKey`, #3057), with the value an earlier
597
+ * attribute gave the key when the caller omits it, as SSR rendered it
598
+ * (`IRAttribute.restFallback`, #3851).
602
599
  */
603
- function mergedMirrorExpr(name: string, expr: string, index: number, spreadAt: number): string {
604
- return index < spreadAt ? callerFirstPropExpr(name, expr) : expr
600
+ function restKeyLiveRead(attr: IRElement['attrs'][number]): string {
601
+ const read = `${PROPS_PARAM}.${attr.name}`
602
+ return attr.restFallback === undefined ? read : `${read} ?? (${attr.restFallback})`
605
603
  }
606
604
 
607
605
  /** Build propsExpr for a child component from its IR props. */
608
606
  function buildComponentPropsExpr(props: IRProp[], ctx: ClientJsContext): string {
609
607
  const knownSpreadProp = props.find(p => {
610
- if (p.name !== '...' && !p.name.startsWith('...')) return false
608
+ if (!isSpreadPropName(p.name)) return false
611
609
  if (p.value.kind !== 'spread' && p.value.kind !== 'expression') return false
612
610
  const expr = p.value.kind === 'spread' ? p.value.expr : p.value.expr
613
611
  // #2723: resolve through any `const x__alias = x` hop onto the
614
612
  // rest/props binding — see `resolveRestSpreadOrigin`'s docstring.
615
613
  return resolveRestSpreadOrigin(ctx, expr) !== null
616
614
  })
617
- const spreadSource = knownSpreadProp ? PROPS_PARAM : null
618
- const spreadAt = lastPropsObjectSpreadIndex(props)
619
-
620
- const propsForInit: string[] = []
621
- const explicitPropNames: string[] = []
622
- props.forEach((prop, index) => {
623
- if (prop.name === '...' || prop.name.startsWith('...')) return
624
- explicitPropNames.push(prop.name)
625
- const key = quotePropName(prop.name)
626
- const { expr, getter } = componentInitPropValue(prop, ctx)
627
- if (index < spreadAt) {
628
- propsForInit.push(`get ${key}() { return ${callerFirstPropExpr(prop.name, expr)} }`)
629
- } else {
630
- propsForInit.push(getter ? `get ${key}() { return ${expr} }` : `${key}: ${expr}`)
631
- }
615
+ return childPropsObjectExpr(props, prop => componentInitPropValue(prop, ctx), {
616
+ forwardCaller: knownSpreadProp !== undefined,
632
617
  })
633
-
634
- if (spreadSource) {
635
- const overrides = propsForInit.length > 0 ? `{ ${propsForInit.join(', ')} }` : '{}'
636
- const excludeKeys = JSON.stringify(explicitPropNames)
637
- return `forwardProps(${spreadSource}, ${overrides}, ${excludeKeys})`
638
- }
639
- return propsForInit.length > 0 ? `{ ${propsForInit.join(', ')} }` : '{}'
640
618
  }
641
619
 
642
620
  /**
@@ -1157,10 +1135,7 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
1157
1135
  // Other identifiers or complex expressions may not exist in the compiled init scope.
1158
1136
  // Always use PROPS_PARAM as the source since the init function parameter is PROPS_PARAM.
1159
1137
  if (attr.name === '...' && attr.value) {
1160
- const spreadVal = attrValueToString(attr.value) ?? ''
1161
- // #2723: resolve through any `const x__alias = x` hop onto the
1162
- // rest/props binding — see `resolveRestSpreadOrigin`'s docstring.
1163
- const spreadOrigin = spreadVal ? resolveRestSpreadOrigin(ctx, spreadVal) : null
1138
+ const spreadOrigin = callerBagSpreadOrigin(attr.value, ctx)
1164
1139
  if (spreadOrigin !== null) {
1165
1140
  // `applyRestAttrs(_el, _p, exclude)` is handed the FULL props
1166
1141
  // object (`PROPS_PARAM`), not a computed JS rest binding, and the
@@ -1249,7 +1224,7 @@ function collectFromElement(element: IRElement, ctx: ClientJsContext, insideCond
1249
1224
  ctx.reactiveAttrs.push({
1250
1225
  slotId: element.slotId,
1251
1226
  attrName: attr.name,
1252
- expression: `${PROPS_PARAM}.${attr.name}`,
1227
+ expression: restKeyLiveRead(attr),
1253
1228
  ...pickAttrMetaFromIR(attr),
1254
1229
  })
1255
1230
  continue
@@ -69,7 +69,12 @@ function wrapAttrValueExpression(value: AttrValue, wrap: (s: string) => string):
69
69
  return AttrValueOf.expression(wrap(flat ?? 'undefined'))
70
70
  }
71
71
  case 'spread':
72
- return AttrValueOf.spread(wrap(value.expr), value.templateExpr ? wrap(value.templateExpr) : undefined)
72
+ // Keep the Phase-1 props-object marker: the props object merges this
73
+ // spread in source order (#3713).
74
+ return {
75
+ ...AttrValueOf.spread(wrap(value.expr), value.templateExpr ? wrap(value.templateExpr) : undefined),
76
+ ...(value.propsObject && { propsObject: true as const }),
77
+ }
73
78
  }
74
79
  }
75
80
  import type { DepthLevel } from '../shared.ts'
@@ -24,7 +24,7 @@ import type {
24
24
  LoopParamBinding,
25
25
  } from '../../../types.ts'
26
26
  import { AttrValueOf, pickAttrMeta } from '../../../types.ts'
27
- import { quotePropName, wrapLoopParamAsAccessor, attrValueToString, rowBoundNames, unionNames, type ShadowableWrap } from '../../utils.ts'
27
+ import { wrapLoopParamAsAccessor, attrValueToString, rowBoundNames, unionNames, type ShadowableWrap } from '../../utils.ts'
28
28
  import { addCondAttrToTemplate, irChildrenToJsExpr } from '../../html-template.ts'
29
29
  import type { ReactiveAttrSlot } from './reactive-effects.ts'
30
30
 
@@ -58,12 +58,18 @@ function wrapAttrValueExpression(value: AttrValue, wrap: (s: string) => string):
58
58
  return AttrValueOf.expression(wrap(flat ?? 'undefined'))
59
59
  }
60
60
  case 'spread':
61
- return AttrValueOf.spread(wrap(value.expr), value.templateExpr ? wrap(value.templateExpr) : undefined)
61
+ // Keep the Phase-1 props-object marker: the props object merges this
62
+ // spread in source order (#3713).
63
+ return {
64
+ ...AttrValueOf.spread(wrap(value.expr), value.templateExpr ? wrap(value.templateExpr) : undefined),
65
+ ...(value.propsObject && { propsObject: true as const }),
66
+ }
62
67
  }
63
68
  }
64
69
  import { destructureLoopParam, loopKeyFn, buildCompSelector, nestedLoopIndexAlias } from '../shared.ts'
65
70
  import { BF_HOST, BF_AT } from '@barefootjs/shared'
66
71
  import { isEventHandlerName } from '../../../event-handler-name.ts'
72
+ import { childPropsObjectExpr, type ChildPropValue } from '../../child-props-object.ts'
67
73
  import type {
68
74
  BranchChildComponentInit,
69
75
  BranchChildComponentInitsPlan,
@@ -172,35 +178,30 @@ export function buildBranchChildComponentInitsPlan(
172
178
  for (const comp of components) {
173
179
  const selector = buildCompSelector(comp)
174
180
 
175
- const propsEntries = comp.props
176
- .filter(p => p.name !== 'key')
177
- .map(p => {
178
- if (isEventHandlerName(p.name)) {
179
- return `${quotePropName(p.name)}: ${wrap(attrValueToString(p.value) ?? 'undefined')}`
180
- }
181
- switch (p.value.kind) {
182
- case 'literal':
183
- return `get ${quotePropName(p.name)}() { return ${JSON.stringify(p.value.value)} }`
184
- case 'boolean-shorthand':
185
- case 'boolean-attr':
186
- return `get ${quotePropName(p.name)}() { return true }`
187
- case 'jsx-children':
188
- case 'expression':
189
- case 'template':
190
- case 'spread': {
191
- const expr = attrValueToString(p.value) ?? 'undefined'
192
- return `get ${quotePropName(p.name)}() { return ${wrap(expr)} }`
193
- }
194
- }
195
- })
196
-
197
181
  // Children are needed for CSR createComponent; SSR initChild ignores them
198
182
  // (text already lives in the rendered HTML).
199
183
  const childrenExpr = comp.children?.length ? irChildrenToJsExpr(comp.children) : null
200
- if (childrenExpr) {
201
- propsEntries.push(`get children() { return ${wrap(childrenExpr)} }`)
202
- }
203
- const propsExpr = propsEntries.length > 0 ? `{ ${propsEntries.join(', ')} }` : '{}'
184
+ const trailing = childrenExpr ? [`get children() { return ${wrap(childrenExpr)} }`] : []
185
+ // A props-object spread merges in source order through the shared door
186
+ // (#3713) instead of becoming a getter named `...`.
187
+ const propsExpr = childPropsObjectExpr(comp.props, (p): ChildPropValue | null => {
188
+ if (p.name === 'key') return null
189
+ if (isEventHandlerName(p.name)) {
190
+ return { expr: wrap(attrValueToString(p.value) ?? 'undefined'), getter: false }
191
+ }
192
+ switch (p.value.kind) {
193
+ case 'literal':
194
+ return { expr: JSON.stringify(p.value.value), getter: true }
195
+ case 'boolean-shorthand':
196
+ case 'boolean-attr':
197
+ return { expr: 'true', getter: true }
198
+ case 'jsx-children':
199
+ case 'expression':
200
+ case 'template':
201
+ case 'spread':
202
+ return { expr: wrap(attrValueToString(p.value) ?? 'undefined'), getter: true }
203
+ }
204
+ }, { trailing })
204
205
 
205
206
  inits.push({
206
207
  name: comp.name,
@@ -15,9 +15,10 @@
15
15
  import type { LoopChildBindings, LoopChildEvent, LoopChildRef, TopLevelLoop, NestedLoop, CollectedLoop } from '../types.ts'
16
16
  import type { IRLoopChildComponent, IRExpression, IRNode, LoopParamBinding } from '../../types.ts'
17
17
  import { preambleAnalysisText } from '../../types.ts'
18
- import { quotePropName, wrapLoopParamAsAccessor, irChildrenFreeIds, attrValueToString } from '../utils.ts'
18
+ import { wrapLoopParamAsAccessor, irChildrenFreeIds, attrValueToString } from '../utils.ts'
19
19
  import { irChildrenToJsExpr, jsxChildrenPropGetterExpr } from '../html-template.ts'
20
20
  import { spliceChildValue } from '../safe-html.ts'
21
+ import { childPropsObjectExpr, type ChildPropValue } from '../child-props-object.ts'
21
22
  import { emitListenerBlock } from './stringify/event-listener.ts'
22
23
  import { nameForRegistryRef } from '../component-scope.ts'
23
24
  import { BF_SCOPE, BF_HOST, BF_AT } from '@barefootjs/shared'
@@ -284,43 +285,40 @@ export function buildComponentPropsExpr(
284
285
  loopIndex?: string | null,
285
286
  ): string {
286
287
  const wrap = loopParam ? (expr: string) => wrapLoopParamAsAccessor(expr, loopParam, loopParamBindings, loopIndex) : (expr: string) => expr
287
- const entries = comp.props.map((p) => {
288
+ // A props-object spread merges in source order through the shared door
289
+ // (#3713) instead of becoming a getter named `...`.
290
+ const trailing: string[] = []
291
+ if ('children' in comp && Array.isArray(comp.children) && comp.children.length > 0) {
292
+ const childrenExpr = irChildrenToJsExpr(comp.children)
293
+ if (childrenExpr && childrenExpr !== "''") {
294
+ trailing.push(`get children() { return ${wrap(childrenExpr)} }`)
295
+ }
296
+ }
297
+ return childPropsObjectExpr(comp.props, (p): ChildPropValue => {
288
298
  if (p.isEventHandler) {
289
- const handlerExpr = attrValueToString(p.value) ?? 'undefined'
290
- return `${quotePropName(p.name)}: ${wrap(handlerExpr)}`
299
+ return { expr: wrap(attrValueToString(p.value) ?? 'undefined'), getter: false }
291
300
  }
292
301
  switch (p.value.kind) {
293
302
  case 'literal':
294
303
  // Literal string values must NOT be wrapped — they don't reference loop params
295
- return `get ${quotePropName(p.name)}() { return ${JSON.stringify(p.value.value)} }`
304
+ return { expr: JSON.stringify(p.value.value), getter: true }
296
305
  case 'boolean-shorthand':
297
306
  case 'boolean-attr':
298
- return `get ${quotePropName(p.name)}() { return true }`
299
- case 'jsx-children': {
307
+ return { expr: 'true', getter: true }
308
+ case 'jsx-children':
300
309
  // Brand via the shared door (#2651/#2702) — see
301
310
  // `jsxChildrenPropGetterExpr`'s docstring. This builder is shared
302
311
  // by loop and conditional-branch component reconciliation, so a
303
312
  // named jsx-children prop on a component instantiated in either
304
313
  // context used to reach its getter unbranded (pullfrog review, PR
305
314
  // #2820).
306
- const childExpr = jsxChildrenPropGetterExpr(p.value.children, p.name)
307
- return `get ${quotePropName(p.name)}() { return ${wrap(childExpr)} }`
308
- }
315
+ return { expr: wrap(jsxChildrenPropGetterExpr(p.value.children, p.name)), getter: true }
309
316
  case 'expression':
310
317
  case 'template':
311
- case 'spread': {
312
- const valueExpr = attrValueToString(p.value)!
313
- return `get ${quotePropName(p.name)}() { return ${wrap(valueExpr)} }`
314
- }
318
+ case 'spread':
319
+ return { expr: wrap(attrValueToString(p.value)!), getter: true }
315
320
  }
316
- })
317
- if ('children' in comp && Array.isArray(comp.children) && comp.children.length > 0) {
318
- const childrenExpr = irChildrenToJsExpr(comp.children)
319
- if (childrenExpr && childrenExpr !== "''") {
320
- entries.push(`get children() { return ${wrap(childrenExpr)} }`)
321
- }
322
- }
323
- return entries.length > 0 ? `{ ${entries.join(', ')} }` : '{}'
321
+ }, { trailing })
324
322
  }
325
323
 
326
324
  /** Per-inner-loop data for composite loop emission. */
@@ -65,10 +65,12 @@ export function rowTextSlotKind(text: RowTextSlot): 'text' | 'markup' {
65
65
  * The value a loop-row content slot's writer receives: `escapeTextOrNode`
66
66
  * for a markup slot (unwraps a `bfMarkup()` value, passes a Node or a
67
67
  * `__slot()` marker through, escapes a string before the markup writer's
68
- * `innerHTML`), `coerce(expr)` for a 'text' slot.
68
+ * `innerHTML`), `textOrNode(expr)` for a 'text' slot (passes a Node through
69
+ * for the claim to promote, and renders a boolean as no text, as JSX does,
70
+ * #3824 step 5).
69
71
  */
70
- export function rowTextSlotValue(text: RowTextSlot, expr: string, coerce: 'String' | 'textOrNode'): string {
71
- return text.markup ? `escapeTextOrNode(${expr})` : `${coerce}(${expr})`
72
+ export function rowTextSlotValue(text: RowTextSlot, expr: string): string {
73
+ return text.markup ? `escapeTextOrNode(${expr})` : `textOrNode(${expr})`
72
74
  }
73
75
 
74
76
  /** Render one `SlotSpec` as a source-text object literal. */
@@ -112,14 +112,14 @@ function emitReactive(lines: string[], inner: InnerLoopPlan, indent: string, pc:
112
112
  // writes are a plain, idempotent `nodeValue` assignment with no
113
113
  // dedup/trust-first-run state to go stale — so re-claiming here is exactly
114
114
  // as safe as, and replaces, the old re-query-$t-on-every-run discipline.
115
- lines.push(`${indent} createEffect(() => { claimSlots(__innerEl${uid}, [{ id: '${text.slotId}', kind: '${rowTextSlotKind(text)}', path: [] }]).write('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression, 'String')}) }${bf})`)
115
+ lines.push(`${indent} createEffect(() => { claimSlots(__innerEl${uid}, [{ id: '${text.slotId}', kind: '${rowTextSlotKind(text)}', path: [] }]).write('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression)}) }${bf})`)
116
116
  }
117
117
  if (plainTexts.length > 0) {
118
118
  const slots: ClaimSlotSpec[] = plainTexts.map(t => ({ id: t.slotId, kind: rowTextSlotKind(t), path: [] }))
119
119
  const writer = claimWriterVarName(slots, varSlotId)
120
120
  lines.push(`${indent} const ${writer} = lazySlots(__innerEl${uid}, ${claimPlanLiteral(slots)})`)
121
121
  for (const text of plainTexts) {
122
- lines.push(`${indent} createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression, 'String')}) }${profileBindingId(pc, text.slotId)})`)
122
+ lines.push(`${indent} createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression)}) }${profileBindingId(pc, text.slotId)})`)
123
123
  }
124
124
  }
125
125
  if (emit.reactiveAttrs.length > 0) lines.push(`${indent} ${DEDUP_STORE_DECL}`)
@@ -535,7 +535,7 @@ function emitTextBinding(
535
535
  ? `${doorExpr}.write('${t.slotId}', ${valueExpr})`
536
536
  : `${doorExpr}('${t.slotId}', ${valueExpr})`
537
537
 
538
- const value = rowTextSlotValue(t, '__x', 'textOrNode')
538
+ const value = rowTextSlotValue(t, '__x')
539
539
  if (mode === 'outer') {
540
540
  lines.push(`${ind}if (__seed) {`)
541
541
  lines.push(`${ind} const __s = ${value}`)
@@ -198,14 +198,14 @@ export function stringifyBranchInnerLoops(
198
198
  // insert() may swap the branch's DOM between runs, and a 'text' write
199
199
  // is a plain, idempotent `nodeValue` assignment with no dedup state to
200
200
  // go stale — replaces the old re-query-$t-on-every-run discipline.
201
- lines.push(`${indent} createEffect(() => { claimSlots(__bel${uid}, [{ id: '${text.slotId}', kind: '${rowTextSlotKind(text)}', path: [] }]).write('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression, 'String')}) }${bf})`)
201
+ lines.push(`${indent} createEffect(() => { claimSlots(__bel${uid}, [{ id: '${text.slotId}', kind: '${rowTextSlotKind(text)}', path: [] }]).write('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression)}) }${bf})`)
202
202
  }
203
203
  if (plainTexts.length > 0) {
204
204
  const slots: ClaimSlotSpec[] = plainTexts.map(t => ({ id: t.slotId, kind: rowTextSlotKind(t), path: [] }))
205
205
  const writer = claimWriterVarName(slots, varSlotId)
206
206
  lines.push(`${indent} const ${writer} = lazySlots(__bel${uid}, ${claimPlanLiteral(slots)})`)
207
207
  for (const text of plainTexts) {
208
- lines.push(`${indent} createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression, 'String')}) }${profileBindingId(pc, text.slotId)})`)
208
+ lines.push(`${indent} createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression)}) }${profileBindingId(pc, text.slotId)})`)
209
209
  }
210
210
  }
211
211
  if (inner.nestedConditionals.length > 0) {
@@ -519,7 +519,7 @@ export function stringifyStaticLoop(lines: string[], plan: StaticLoopPlan): void
519
519
  const writer = claimWriterVarName(slots, varSlotId)
520
520
  lines.push(` const ${writer} = lazySlots(__iterEl, ${claimPlanLiteral(slots)})`)
521
521
  for (const text of texts) {
522
- lines.push(` createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.expression, 'String')}) }${profileBindingId(pc, text.slotId)})`)
522
+ lines.push(` createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.expression)}) }${profileBindingId(pc, text.slotId)})`)
523
523
  }
524
524
  }
525
525
  // Ref callbacks fire on every forEach iteration — initial mount and any
@@ -294,7 +294,7 @@ function emitConsolidatedRowEffect(
294
294
  // preamble region) uses the multi-line block.
295
295
  if (attrSlots.length === 0 && preambleRegions.length === 0 && outerTexts.length === 1) {
296
296
  const text = outerTexts[0]
297
- lines.push(`${indent}createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression, 'String')}) })`)
297
+ lines.push(`${indent}createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression)}) })`)
298
298
  return
299
299
  }
300
300
  lines.push(`${indent}createEffect(() => {`)
@@ -319,7 +319,7 @@ function emitConsolidatedRowEffect(
319
319
  lines.push(`${indent} }`)
320
320
  }
321
321
  for (const text of outerTexts) {
322
- lines.push(`${indent} ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression, 'String')})`)
322
+ lines.push(`${indent} ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression)})`)
323
323
  }
324
324
  for (const region of preambleRegions) {
325
325
  lines.push(`${indent} ${writer}('${region.slotId}', ${region.valueExpr})`)
@@ -345,7 +345,7 @@ function emitOuterTexts(
345
345
  const writer = claimWriterVarName(slots, varSlotId)
346
346
  lines.push(`${indent}const ${writer} = lazySlots(${elVar}, ${claimPlanLiteral(slots)})`)
347
347
  for (const text of texts) {
348
- lines.push(`${indent}createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression, 'String')}) }${bindingBfId(text.slotId)})`)
348
+ lines.push(`${indent}createEffect(() => { ${writer}('${text.slotId}', ${rowTextSlotValue(text, text.wrappedExpression)}) }${bindingBfId(text.slotId)})`)
349
349
  }
350
350
  }
351
351
 
@@ -2,7 +2,7 @@
2
2
  * IR → HTML template string generation and validation.
3
3
  */
4
4
 
5
- import type { AttrValue, FlatMapCallback, IRAttribute, IRElement, IRExpression, IRNode, IRProp, MapCallbackPreamble, JsSourceText } from '../types.ts'
5
+ import type { AttrValue, FlatMapCallback, IRAttribute, IRElement, IRExpression, IRNode, IRProp, MapCallbackPreamble, JsSourceText, SpreadAttr } from '../types.ts'
6
6
  import { isBooleanAttr } from '../html-constants.ts'
7
7
  import { toHtmlAttrName, attrValueToString, quotePropName, PROPS_PARAM, DATA_BF_PH, keyAttrName, loopStartMarker, loopEndMarker, loopItemMarker, freeIdsFromRefs, setIntersects, wrapExprWithLoopParams, specsInsideRow } from './utils.ts'
8
8
  import type { LoopParamSpec } from './utils.ts'
@@ -144,11 +144,16 @@ export const VOID_ELEMENTS = new Set([
144
144
  * The `base` override lets the CSR-template path pre-substitute
145
145
  * props (`_p.items.toSorted(...)`) before the chain rides on top.
146
146
  */
147
- function applyLoopChain(loop: import('../types.ts').IRLoop, base: string = loop.array): string {
147
+ function applyLoopChain(loop: import('../types.ts').IRLoop, base: string = loop.array, moduleScope = false): string {
148
+ const filter = loop.filterPredicate
148
149
  return buildLoopChainExpr({
149
150
  base,
150
151
  sortComparator: loop.sortComparator,
151
- filterPredicate: loop.filterPredicate,
152
+ // The module-scope template reads the predicate's `_p.`-rewritten twin
153
+ // (Phase 1's `templateRaw`, #3845), as it reads `templateArray`.
154
+ filterPredicate: filter && moduleScope && filter.templateRaw !== undefined
155
+ ? { param: filter.param, raw: filter.templateRaw }
156
+ : filter,
152
157
  chainOrder: loop.chainOrder,
153
158
  })
154
159
  }
@@ -346,6 +351,18 @@ function transformKeyValue(value: AttrValue, transformExpr: (expr: JsSourceText,
346
351
  }
347
352
  }
348
353
 
354
+ /**
355
+ * Whether the spread `v` forwards the component's own caller bag (the rest
356
+ * props or the props object, through any alias), which the init's
357
+ * `applyRestAttrs` applies instead of the template. `name` must be one of
358
+ * `restSpreadNames`, and Phase 1 must have resolved the spread to the bag
359
+ * (`SpreadAttr.callerBag`): a loop row or callback parameter spelled like
360
+ * the rest binding is that binding, spread like any other object (#3851).
361
+ */
362
+ function isCallerBagSpread(v: SpreadAttr, restSpreadNames: ReadonlySet<string> | undefined, name: string = v.expr): boolean {
363
+ return !!restSpreadNames?.has(name) && v.callerBag !== undefined
364
+ }
365
+
349
366
  /**
350
367
  * Render one element attribute into its template-literal substring for the
351
368
  * SSR template path. Switches on `AttrValue.kind` exhaustively so a new
@@ -379,7 +396,7 @@ function renderTemplateAttrPart(
379
396
  return templateAttrExpr(attrName, wrap(tmplStr))
380
397
  }
381
398
  case 'spread': {
382
- if (restSpreadNames?.has(v.expr)) return ''
399
+ if (isCallerBagSpread(v, restSpreadNames)) return ''
383
400
  // `wrap` lowers loop-param references — including destructured rest
384
401
  // bindings (`...rest` lifted via `paramBindings`) — into their item
385
402
  // accessor. Skipping it here meant `{...rest}` inside a `.map()`
@@ -765,7 +782,7 @@ export function irToHtmlTemplate(node: IRNode, restSpreadNames?: ReadonlySet<str
765
782
  // SSR-reused row never has — visible the moment a row-count change
766
783
  // makes reused and rebuilt rows coexist in one list (#2756).
767
784
  const mergeCtx: MergeContext = {
768
- isFilteredSpread: (v) => !!restSpreadNames?.has(v.expr),
785
+ isFilteredSpread: (v) => isCallerBagSpread(v, restSpreadNames),
769
786
  honorClientOnly: true,
770
787
  }
771
788
  const useMerge = shouldUseSpreadAttrsMerge(node.attrs, mergeCtx)
@@ -1928,7 +1945,7 @@ function irToComponentTemplateWithOpts(node: IRNode, opts: TemplateOptions): str
1928
1945
  // loops emit `data-key-N` unconditionally per the reconciliation
1929
1946
  // contract).
1930
1947
  const mergeCtx: MergeContext = {
1931
- isFilteredSpread: (v) => !!restSpreadNames?.has(v.templateExpr ?? v.expr),
1948
+ isFilteredSpread: (v) => isCallerBagSpread(v, restSpreadNames, v.templateExpr ?? v.expr),
1932
1949
  honorClientOnly: true,
1933
1950
  }
1934
1951
  const useMerge = shouldUseSpreadAttrsMerge(node.attrs, mergeCtx)
@@ -2572,7 +2589,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2572
2589
  // `buildSpreadAttrsMergeCall`) keep the contract aligned with
2573
2590
  // the other two CSR-side emit paths.
2574
2591
  const mergeCtx: MergeContext = {
2575
- isFilteredSpread: (v) => !!restSpreadNames?.has(v.templateExpr ?? v.expr),
2592
+ isFilteredSpread: (v) => isCallerBagSpread(v, restSpreadNames, v.templateExpr ?? v.expr),
2576
2593
  honorClientOnly: true,
2577
2594
  }
2578
2595
  const useMerge = shouldUseSpreadAttrsMerge(node.attrs, mergeCtx)
@@ -2873,7 +2890,7 @@ function generateCsrTemplateWithOpts(node: IRNode, opts: TemplateOptions): strin
2873
2890
  // (already prop-substituted) so the chain inherits the same
2874
2891
  // `_p.X` rewrites the pre-Tier-B path used.
2875
2892
  const chainedTemplateArray = node.sortComparator || node.filterPredicate
2876
- ? applyLoopChain(node, node.templateArray)
2893
+ ? applyLoopChain(node, node.templateArray, true)
2877
2894
  : node.templateArray
2878
2895
  const safeRawArrayExpr = transformExprOrUnsafe(node.array, chainedTemplateArray) ?? '[]'
2879
2896
  const { array: iterArrayExpr, callbackParam } = applyIterationShape(node, safeRawArrayExpr, indexParam)
@@ -48,7 +48,7 @@ export const RUNTIME_IMPORT_CANDIDATES = [
48
48
  'markupOrEmpty',
49
49
  'qsa', 'qsaItem',
50
50
  // Loop-row elements a `ref` callback portals out of their row (#3318).
51
- 'adoptRowPortal', 'claimRowPortals', 'relayRowPortalEvents', 'isRowPortalOf', 'qsaChildScope', 'qsaChildScopes', 'upsertChildItem', '__slot', '__bfSlot', '__bfText',
51
+ 'adoptRowPortal', 'claimRowPortals', 'relayRowPortalEvents', 'isRowPortalOf', 'qsaChildScope', 'qsaChildScopes', 'childScopesBySlot', 'childScopeBySlot', 'upsertChildItem', '__slot', '__bfSlot', '__bfText',
52
52
  // Claim-plan interpreter (slot unification A2/A3, spec/slot-unification.md)
53
53
  // — the "one claim mechanism" that replaced `patchSlotRange` and
54
54
  // `updateClientMarker` (both deleted) as the content-slot update door.
@@ -4,7 +4,8 @@
4
4
  * Generates client-side JavaScript from Pure IR for hydration.
5
5
  */
6
6
 
7
- import type { ComponentIR } from '../types.ts'
7
+ import type { AttrValue, ClientAnalysis, ComponentIR, IRNode } from '../types.ts'
8
+ import { walkIR } from './walker.ts'
8
9
  import type { ClientJsContext } from './types.ts'
9
10
  import type {
10
11
  TemplatePrimitiveRegistry,
@@ -26,6 +27,7 @@ import { IMPORT_PLACEHOLDER, RUNTIME_MODULE, detectUsedImports, collectExternalI
26
27
  import { isInlinableInTemplate } from '../relocate.ts'
27
28
  import { buildSourceMapFromIR, type SourceMapV3 } from './source-map.ts'
28
29
  import { resolvePropDeclaredType, baseTypeName } from '../rich-type-evidence.ts'
30
+ import { isHydrationPayloadPropName } from '../event-handler-name.ts'
29
31
 
30
32
  export interface ClientJsResult {
31
33
  code: string
@@ -149,11 +151,11 @@ export function generateClientJsWithSourceMap(
149
151
  function computeLiveOnlyProps(ir: ComponentIR, neededProps: ReadonlySet<string>): Record<string, string> {
150
152
  const liveOnlyProps: Record<string, string> = {}
151
153
  for (const param of ir.metadata.propsParams) {
152
- // Same exclusions `propsToSerialize` (hono-adapter.ts) applies: `on*` is
153
- // the event-handler convention, wired through the listener path rather
154
- // than prop serialization, and `__*` is hydration plumbing that never
155
- // round-trips through `bf-p`.
156
- if (param.isRest || param.name.startsWith('on') || param.name.startsWith('__')) continue
154
+ // Same exclusions `propsToSerialize` (hono-adapter.ts) applies
155
+ // (`isHydrationPayloadPropName`): an `on[A-Z]` handler is wired through
156
+ // the listener path rather than prop serialization, and `__*` is
157
+ // hydration plumbing that never round-trips through `bf-p`.
158
+ if (param.isRest || !isHydrationPayloadPropName(param.name)) continue
157
159
  if (!neededProps.has(param.name)) continue
158
160
  const declared = resolvePropDeclaredType(param.sourceName ?? param.name, ir.metadata)
159
161
  const isFunctionTyped =
@@ -171,15 +173,13 @@ function computeLiveOnlyProps(ir: ComponentIR, neededProps: ReadonlySet<string>)
171
173
  * and which props the init function actually reads. This runs BEFORE the adapter
172
174
  * so the adapter can use the results to optimize bf-p serialization.
173
175
  */
174
- export function analyzeClientNeeds(
175
- ir: ComponentIR,
176
- ): { needsInit: boolean; usedProps: string[]; liveOnlyProps: Record<string, string> } {
176
+ export function analyzeClientNeeds(ir: ComponentIR): ClientAnalysis {
177
177
  const ctx = createContext(ir, undefined)
178
178
  const siblingOffsets = computeLoopSiblingOffsets(ir.root)
179
179
  collectElements(ir.root, ctx, siblingOffsets)
180
180
 
181
181
  if (!needsClientJs(ctx)) {
182
- return { needsInit: false, usedProps: [], liveOnlyProps: {} }
182
+ return { needsInit: false, usedProps: [], usedRestKeys: [], readsCallerBag: false, liveOnlyProps: {} }
183
183
  }
184
184
 
185
185
  // Use the shared reference graph instead of replicating the extraction
@@ -205,7 +205,49 @@ export function analyzeClientNeeds(
205
205
  }
206
206
  }
207
207
 
208
- return { needsInit: true, usedProps: [...neededProps], liveOnlyProps: computeLiveOnlyProps(ir, neededProps) }
208
+ return {
209
+ needsInit: true,
210
+ usedProps: [...neededProps],
211
+ usedRestKeys: usedRestKeys(ir, usedIdentifiers),
212
+ readsCallerBag: spreadsCallerBag(ir.root),
213
+ liveOnlyProps: computeLiveOnlyProps(ir, neededProps),
214
+ }
215
+ }
216
+
217
+ /**
218
+ * The closed-type rest keys (`restPropsExpandedKeys`) the client reads (#3845).
219
+ * A `{...rest}` spread of a closed rest type unrolls into one `rest.<key>`
220
+ * read per key, which the client reads live as `_p.<key>`. Matched the way
221
+ * `usedProps` matches a prop: by name among the identifiers the client code
222
+ * references (member names included), alongside the rest binding itself.
223
+ */
224
+ function usedRestKeys(ir: ComponentIR, usedIdentifiers: ReadonlySet<string>): string[] {
225
+ const restName = ir.metadata.restPropsName
226
+ if (!restName || !usedIdentifiers.has(restName)) return []
227
+ return ir.metadata.restPropsExpandedKeys.filter(key => usedIdentifiers.has(key) && isHydrationPayloadPropName(key))
228
+ }
229
+
230
+ /**
231
+ * Whether the component spreads one of the caller's prop bags whole
232
+ * (`SpreadAttr.callerBag`, decided in Phase 1) onto an element or a child
233
+ * component. The client reads every key of that bag off `_p`
234
+ * (`applyRestAttrs` / `forwardProps`), keys the component never names.
235
+ */
236
+ function spreadsCallerBag(root: IRNode): boolean {
237
+ let found = false
238
+ const isBagSpread = (value: AttrValue): boolean => value.kind === 'spread' && value.callerBag !== undefined
239
+ walkIR<null>(root, null, {
240
+ element: ({ node, descend }) => {
241
+ if (node.attrs.some(attr => isBagSpread(attr.value))) found = true
242
+ descend()
243
+ },
244
+ component: ({ node, descend, descendJsxChildren }) => {
245
+ if (node.props.some(prop => isBagSpread(prop.value))) found = true
246
+ descend()
247
+ descendJsxChildren()
248
+ },
249
+ })
250
+ return found
209
251
  }
210
252
 
211
253
  /** Initialize an empty ClientJsContext from component IR metadata. */