@barefootjs/jsx 0.39.7 → 0.39.9

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 (192) hide show
  1. package/dist/adapters/callback-method.d.ts +36 -7
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +80 -13
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +153 -0
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
  7. package/dist/adapters/jsx-adapter.d.ts +4 -0
  8. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  9. package/dist/adapters/literal-value.d.ts +2 -2
  10. package/dist/adapters/literal-value.d.ts.map +1 -1
  11. package/dist/adapters/loop-plan.d.ts +133 -9
  12. package/dist/adapters/loop-plan.d.ts.map +1 -1
  13. package/dist/adapters/parsed-expr-emitter.d.ts +44 -0
  14. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  15. package/dist/adapters/style-object.d.ts +33 -0
  16. package/dist/adapters/style-object.d.ts.map +1 -0
  17. package/dist/analyzer.d.ts.map +1 -1
  18. package/dist/assignment-target.d.ts +26 -0
  19. package/dist/assignment-target.d.ts.map +1 -0
  20. package/dist/children-nullish.d.ts +22 -0
  21. package/dist/children-nullish.d.ts.map +1 -0
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/expression-parser.d.ts +9 -19
  25. package/dist/expression-parser.d.ts.map +1 -1
  26. package/dist/free-refs.d.ts +6 -0
  27. package/dist/free-refs.d.ts.map +1 -1
  28. package/dist/index.d.ts +17 -14
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +15040 -13899
  31. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  34. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  36. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  38. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  40. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  42. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  45. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  47. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  49. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  51. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  54. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  56. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/imports.d.ts +23 -2
  58. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  59. package/dist/ir-to-client-js/phases/props-extraction.d.ts +6 -3
  60. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  62. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  64. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  65. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  66. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  67. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  68. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  69. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  70. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  71. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  72. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  73. package/dist/ir-to-client-js/types.d.ts +3 -3
  74. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  75. package/dist/ir-to-client-js/utils.d.ts +2 -11
  76. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  77. package/dist/jsx-to-ir.d.ts.map +1 -1
  78. package/dist/nullable-signal-attr.d.ts +40 -10
  79. package/dist/nullable-signal-attr.d.ts.map +1 -1
  80. package/dist/prop-rewrite.d.ts +35 -8
  81. package/dist/prop-rewrite.d.ts.map +1 -1
  82. package/dist/props-binding.d.ts +66 -1
  83. package/dist/props-binding.d.ts.map +1 -1
  84. package/dist/scanner/js-scanner.d.ts.map +1 -1
  85. package/dist/scanner/js-scanner.js +30 -2
  86. package/dist/scope/binding-scope.d.ts +30 -2
  87. package/dist/scope/binding-scope.d.ts.map +1 -1
  88. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  89. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  90. package/dist/signal-prop-name-collision.d.ts +6 -5
  91. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  92. package/dist/ssr-defaults.d.ts +28 -0
  93. package/dist/ssr-defaults.d.ts.map +1 -1
  94. package/dist/ssr-seed-plan.d.ts +39 -14
  95. package/dist/ssr-seed-plan.d.ts.map +1 -1
  96. package/dist/types.d.ts +133 -19
  97. package/dist/types.d.ts.map +1 -1
  98. package/dist/value-references.d.ts +21 -0
  99. package/dist/value-references.d.ts.map +1 -1
  100. package/package.json +2 -2
  101. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  102. package/src/__tests__/adapter-output.test.ts +5 -3
  103. package/src/__tests__/analyzer.test.ts +33 -0
  104. package/src/__tests__/arithmetic-lowering.test.ts +48 -0
  105. package/src/__tests__/binding-scope.test.ts +29 -0
  106. package/src/__tests__/children-read.test.ts +226 -0
  107. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  108. package/src/__tests__/component-props.test.ts +68 -1
  109. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  110. package/src/__tests__/create-query.test.ts +1 -1
  111. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  112. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  113. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  114. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  115. package/src/__tests__/expression-parser.test.ts +1 -44
  116. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  117. package/src/__tests__/loop-plan.test.ts +131 -1
  118. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  119. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  120. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  121. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  122. package/src/__tests__/props-alias-const.test.ts +60 -1
  123. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  124. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  125. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  126. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  127. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  128. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  129. package/src/__tests__/ssr-defaults.test.ts +19 -1
  130. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  131. package/src/__tests__/style-object-plan.test.ts +54 -0
  132. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  133. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  134. package/src/adapters/callback-method.ts +48 -10
  135. package/src/adapters/component-props.ts +130 -12
  136. package/src/adapters/dsl-template-adapter.ts +259 -0
  137. package/src/adapters/jsx-adapter.ts +12 -6
  138. package/src/adapters/literal-value.ts +2 -2
  139. package/src/adapters/loop-plan.ts +201 -13
  140. package/src/adapters/parsed-expr-emitter.ts +67 -0
  141. package/src/adapters/style-object.ts +61 -0
  142. package/src/analyzer.ts +396 -16
  143. package/src/assignment-target.ts +79 -0
  144. package/src/children-nullish.ts +33 -0
  145. package/src/debug.ts +2 -2
  146. package/src/errors.ts +23 -0
  147. package/src/expression-parser.ts +56 -53
  148. package/src/free-refs.ts +28 -17
  149. package/src/index.ts +31 -10
  150. package/src/ir-to-client-js/compute-inlinability.ts +35 -5
  151. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  152. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  153. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  154. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  155. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  156. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  157. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  158. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  159. package/src/ir-to-client-js/csr-substitute.ts +82 -24
  160. package/src/ir-to-client-js/emit-reactive.ts +3 -3
  161. package/src/ir-to-client-js/emit-registration.ts +34 -58
  162. package/src/ir-to-client-js/generate-init.ts +17 -1
  163. package/src/ir-to-client-js/html-template.ts +48 -57
  164. package/src/ir-to-client-js/identifiers.ts +75 -24
  165. package/src/ir-to-client-js/imports.ts +56 -19
  166. package/src/ir-to-client-js/index.ts +2 -1
  167. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  168. package/src/ir-to-client-js/phases/props-extraction.ts +39 -17
  169. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  170. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  171. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  172. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  173. package/src/ir-to-client-js/reactivity.ts +2 -2
  174. package/src/ir-to-client-js/rewrite-destructured-props.ts +22 -5
  175. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  176. package/src/ir-to-client-js/safe-html.ts +29 -35
  177. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  178. package/src/ir-to-client-js/types.ts +3 -2
  179. package/src/ir-to-client-js/utils.ts +42 -122
  180. package/src/jsx-to-ir.ts +310 -90
  181. package/src/nullable-signal-attr.ts +149 -33
  182. package/src/prop-rewrite.ts +72 -72
  183. package/src/props-binding.ts +90 -3
  184. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  185. package/src/scanner/js-scanner.ts +64 -4
  186. package/src/scope/binding-scope.ts +34 -3
  187. package/src/scope/lexical-scope-walk.ts +167 -0
  188. package/src/signal-prop-name-collision.ts +50 -24
  189. package/src/ssr-defaults.ts +47 -20
  190. package/src/ssr-seed-plan.ts +103 -23
  191. package/src/types.ts +140 -20
  192. package/src/value-references.ts +132 -0
@@ -40,7 +40,7 @@ import { PROPS_PARAM } from './utils.ts'
40
40
  * Does `init` read `<objectName>.<key>` or `<objectName>.<key> ?? <fallback>`?
41
41
  * The one recognizer for "a prop read initializer", shared by
42
42
  * `propExtractionName` below (which additionally requires the bound name to
43
- * equal `key`, and always reads off `_p`), `rewriteBodyAliasReads`
43
+ * equal `key` unless `key` is `children`, and always reads off `_p`), `rewriteBodyAliasReads`
44
44
  * (`rewrite-destructured-props.ts`, which does not require the name match —
45
45
  * a renamed alias's bound name differs from `key` by definition, but also
46
46
  * always reads off `_p`), and `resolveBodyPropAliases` (`props-binding.ts`,
@@ -66,8 +66,11 @@ export function parsePropReadInitializer(
66
66
  }
67
67
 
68
68
  /** Is `stmt` a single-declarator `const X = _p.X…` prop extraction whose
69
- * initializer is `_p.X` or `_p.X ?? <default>`? Returns the bound name, or
70
- * null when the statement is anything else. */
69
+ * initializer is `_p.X` or `_p.X ?? <default>`? The children prop's
70
+ * extraction may bind another name (`const kids = _p.children`, a renamed
71
+ * `{ children: kids }`, #3572): its eager read is the hazard this pass
72
+ * removes, so it matches under any name. Returns the bound name, or null
73
+ * when the statement is anything else. */
71
74
  function propExtractionName(stmt: ts.Statement): string | null {
72
75
  if (!ts.isVariableStatement(stmt)) return null
73
76
  const decls = stmt.declarationList.declarations
@@ -76,7 +79,7 @@ function propExtractionName(stmt: ts.Statement): string | null {
76
79
  if (!ts.isIdentifier(decl.name) || !decl.initializer) return null
77
80
 
78
81
  const parsed = parsePropReadInitializer(decl.initializer)
79
- if (parsed === null || parsed.key !== decl.name.text) return null
82
+ if (parsed === null || (parsed.key !== decl.name.text && parsed.key !== 'children')) return null
80
83
  return decl.name.text
81
84
  }
82
85
 
@@ -2,7 +2,7 @@
2
2
  * Reactivity detection: reactive expression checking, event/ref collection.
3
3
  */
4
4
 
5
- import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin } from '../types.ts'
5
+ import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin, isChildrenPropParam } from '../types.ts'
6
6
  import type {
7
7
  ClientJsContext,
8
8
  ConditionalBranchEvent,
@@ -237,7 +237,7 @@ function needsEffectWrapperCore(
237
237
  // Check individual prop names (excluding children which is server-rendered
238
238
  // and should not trigger effect wrapping on the client)
239
239
  for (const prop of ctx.propsParams) {
240
- if (prop.name === 'children') continue
240
+ if (isChildrenPropParam(prop)) continue
241
241
  if (freeIdentifiers ? freeIdentifiers.has(prop.name) : tokenContainsIdent(expr, prop.name)) {
242
242
  return true
243
243
  }
@@ -25,9 +25,9 @@
25
25
  */
26
26
 
27
27
  import ts from 'typescript'
28
- import type { PropUsage } from '../types.ts'
28
+ import { type PropUsage, isChildrenPropParam } from '../types.ts'
29
29
  import { computePropsUsedAsConditions } from './compute-prop-usage.ts'
30
- import { boundPropLocalNames, livePropReadExpr, resolveBodyPropAliases, type LivePropReadInfo } from '../props-binding.ts'
30
+ import { boundPropLocalNames, livePropReadExpr, keepsDeclaredValue, resolveBodyPropAliases, type LivePropReadInfo } from '../props-binding.ts'
31
31
  import { parsePropReadInitializer } from './prune-unused-prop-extractions.ts'
32
32
  import { rewriteScopedValueRefs } from '../prop-rewrite.ts'
33
33
  import { identifierPattern } from '../identifier-pattern.ts'
@@ -54,7 +54,8 @@ export function rewriteDestructuredPropReads(
54
54
  * handler-local `const title = 'local'` keep their own binding even when
55
55
  * `title` is also a prop name.
56
56
  *
57
- * Excluding `children`: reading `_p.children` live re-invokes a getter that
57
+ * Excluding the children prop (`isChildrenPropParam`, renamed or not):
58
+ * reading `_p.children` live re-invokes a getter that
58
59
  * instantiates child components (see `emitPropsExtraction`) — `children`
59
60
  * must stay a captured-once read, by design.
60
61
  *
@@ -74,7 +75,7 @@ function rewriteParamDestructuredReads(
74
75
  propUsage: ReadonlyMap<string, PropUsage>,
75
76
  ): string {
76
77
  const names = new Set(boundPropLocalNames(ctx))
77
- names.delete('children')
78
+ for (const p of ctx.propsParams) if (isChildrenPropParam(p) || !keepsDeclaredValue(p)) names.delete(p.name)
78
79
  if (names.size === 0) return code
79
80
 
80
81
  const propsUsedAsConditions = computePropsUsedAsConditions(ctx, names)
@@ -102,6 +103,16 @@ function rewriteParamDestructuredReads(
102
103
  return result
103
104
  }
104
105
 
106
+ /**
107
+ * The `defaultParts` the analyzer recorded on a body-destructured local's
108
+ * props param (`ParamInfo.defaultParts`), when its default reads an earlier
109
+ * binding of the same pattern.
110
+ */
111
+ function bodyAliasDefaultParts(ctx: ClientJsContext, local: string, key: string): Pick<LivePropReadInfo, 'defaultParts'> {
112
+ const param = ctx.propsParams.find(p => !p.isRest && p.name === local && (p.sourceName ?? p.name) === key)
113
+ return param?.defaultParts ? { defaultParts: param.defaultParts } : {}
114
+ }
115
+
105
116
  /**
106
117
  * Rewrite every bare value-position read of a BODY-destructured (or
107
118
  * bare-member-alias) prop local in `code` to a live `_p.<key>` read, for a
@@ -150,7 +161,7 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
150
161
  const sourceFile = ts.createSourceFile('init-body.ts', code, ts.ScriptTarget.Latest, /*setParentNodes*/ true, ts.ScriptKind.TS)
151
162
 
152
163
  const spans: Array<readonly [number, number]> = []
153
- const located = new Map<string, { key: string; defaultValue?: string; defaultContainsArrow?: boolean }>()
164
+ const located = new Map<string, Pick<LivePropReadInfo, 'defaultValue' | 'defaultContainsArrow' | 'defaultParts'> & { key: string }>()
154
165
  for (const stmt of sourceFile.statements) {
155
166
  if (!ts.isFunctionDeclaration(stmt) || !stmt.name?.text.startsWith('init') || !stmt.body) continue
156
167
  for (const inner of stmt.body.statements) {
@@ -181,6 +192,11 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
181
192
  defaultContainsArrow: alias.defaultContainsArrow && !(
182
193
  parsedInit.fallback && ts.isParenthesizedExpression(parsedInit.fallback)
183
194
  ),
195
+ // A default reading an earlier binding of the same destructure
196
+ // (`const { off = false, on = off } = props`, #3531): the analyzer
197
+ // split it on the binding's props param, and the earlier binding's
198
+ // declaration is gone from this body, so the read renders live.
199
+ ...bodyAliasDefaultParts(ctx, decl.name.text, alias.key),
184
200
  })
185
201
  spans.push([inner.getFullStart(), inner.getEnd()])
186
202
  }
@@ -205,6 +221,7 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
205
221
  sourceName: info.key,
206
222
  defaultValue: info.defaultValue,
207
223
  defaultContainsArrow: info.defaultContainsArrow,
224
+ ...(info.defaultParts && { defaultParts: info.defaultParts }),
208
225
  }
209
226
  return livePropReadExpr(prop, undefined, false)
210
227
  }
@@ -27,6 +27,7 @@ import ts from 'typescript'
27
27
  import { PROPS_PARAM } from './utils.ts'
28
28
  import { identifierPattern } from '../identifier-pattern.ts'
29
29
  import type { BindingScope } from '../scope/binding-scope.ts'
30
+ import { walkWithScope } from '../scope/lexical-scope-walk.ts'
30
31
 
31
32
  export interface PropsObjectRewriteOptions {
32
33
  /**
@@ -105,15 +106,20 @@ function rewriteOneName(code: string, srcPropsName: string): string {
105
106
  // Spans are sorted by `start` ascending in the order TS visits them
106
107
  // (depth-first, source order), so we can apply replacements right-to-
107
108
  // left without re-sorting.
109
+ //
110
+ // Only references that resolve to the component's props binding are
111
+ // renamed. An identifier an inner binding of the same spelling shadows
112
+ // (`.map((props) => …)` row callbacks and their `const props = () =>
113
+ // __e.item` accessors, a handler's own `(props) => …` parameter, a nested
114
+ // `function f(props)`) belongs to that binding: renaming it — binder and
115
+ // references alike — to `_p` would capture every compiler-emitted
116
+ // `_p.<prop>` read of the OUTER props object inside that scope (a
117
+ // destructured prop referenced in the row, a forwarded child prop).
108
118
  const spans: Array<readonly [number, number]> = []
109
-
110
- function visit(node: ts.Node): void {
111
- if (ts.isIdentifier(node) && node.text === srcPropsName && shouldRewrite(node)) {
112
- spans.push([node.getStart(sourceFile), node.getEnd()])
113
- }
114
- ts.forEachChild(node, visit)
115
- }
116
- visit(sourceFile)
119
+ walkWithScope(sourceFile, (node, _parent, shadowed) => {
120
+ if (shadowed || node.text !== srcPropsName || !shouldRewrite(node)) return
121
+ spans.push([node.getStart(sourceFile), node.getEnd()])
122
+ })
117
123
 
118
124
  if (spans.length === 0) return code
119
125
 
@@ -37,7 +37,7 @@
37
37
  */
38
38
 
39
39
  import type { IRExpression } from '../types.ts'
40
- import { parseExpression, type ParsedExpr } from '../expression-parser.ts'
40
+ import { PROPS_PARAM } from './utils.ts'
41
41
 
42
42
  /**
43
43
  * A JS expression string that evaluates, in the client template, to HTML
@@ -110,6 +110,27 @@ export function childrenMarkup(expr: string): SafeHtml {
110
110
  return safeHtml(`markupOrEmpty(${expr})`)
111
111
  }
112
112
 
113
+ /**
114
+ * `_p.children == null ? escapeText(expr) : markupOrEmpty(_p.children)` — a
115
+ * read of the children prop with a text fallback: `children ?? 'x'`,
116
+ * `(children ?? '<b>x</b>') ?? ''` (`absentWhen: 'nullish'`), or
117
+ * `children || 'x'` (`absentWhen: 'falsy'`, tested as `!_p.children`); #3554.
118
+ * Phase 1 decided from the binding that the chain's head is the component's
119
+ * own `children` prop (`IRExpression.childrenRead`), so the head is read where
120
+ * every client template finds that prop, `_p.children` (the same place the
121
+ * Phase 1 `templateExpr` rewrite and the alias inlining resolve a destructured
122
+ * or aliased `children` to). Present children are the HTML string
123
+ * `materializeComponent` joined, spliced as `childrenMarkup` does; otherwise
124
+ * `expr` (the whole lowered chain) evaluates to its fallback, which is text
125
+ * and escaped. `expr` is not split: when the head is absent,
126
+ * `(c ?? x) ?? y` and `c ?? (x ?? y)` both evaluate to `x ?? y`.
127
+ */
128
+ export function childrenMarkupOrEscapedFallback(expr: string, absentWhen: 'nullish' | 'falsy'): SafeHtml {
129
+ const children = `${PROPS_PARAM}.children`
130
+ const absent = absentWhen === 'nullish' ? `${children} == null` : `!${children}`
131
+ return safeHtml(`${absent} ? escapeText(${expr}) : markupOrEmpty(${children})`)
132
+ }
133
+
113
134
  /**
114
135
  * Stage 3 / D4 — an element-array child (`{out}`) built by an arbitrary
115
136
  * `.map()` preamble is an array of compiled-leaf HTML strings; join it
@@ -179,37 +200,6 @@ export const EMPTY_MARKUP: SafeHtml = safeHtml("''")
179
200
  // The door for a child-position expression node.
180
201
  // ---------------------------------------------------------------------------
181
202
 
182
- /**
183
- * Recognizes a JSX child-position expression that is exactly a reference to
184
- * the reserved `children` prop, optionally with `?? ''`: bare `children` (destructured) or
185
- * `<receiver>.children` for any single-identifier receiver (`props.children`,
186
- * a custom props-param name, a loop-scoped alias closing over props, ...).
187
- *
188
- * Deliberately LOOSER than `isTransparentFragment` (`jsx-to-ir.ts`), which
189
- * runs on the TS AST with the analyzer-resolved props name in hand. This
190
- * layer parses IR expressions without analyzer context, so any single-identifier receiver
191
- * is the available approximation. The looseness costs nothing measurable: an
192
- * unrelated `.children` member (a tree node's own `children` array, say) is a
193
- * reactive member expression that gets a `slotId` and takes the slotted arm
194
- * of `spliceChildValue` before this predicate is consulted.
195
- */
196
- function isChildrenPassthroughExpr(expr: string): boolean {
197
- return isChildrenPassthrough(parseExpression(expr))
198
- }
199
-
200
- function isChildrenPassthrough(expr: ParsedExpr): boolean {
201
- if (expr.kind === 'identifier') return expr.name === 'children'
202
- if (expr.kind === 'member') {
203
- return expr.object.kind === 'identifier' && expr.property === 'children'
204
- && !expr.computed && !expr.optional
205
- }
206
- // An empty fallback adds no untrusted text to the compiler-built markup.
207
- // Other fallbacks still take the escape-by-default path.
208
- return expr.kind === 'logical' && expr.op === '??'
209
- && expr.right.kind === 'literal' && expr.right.value === ''
210
- && isChildrenPassthrough(expr.left)
211
- }
212
-
213
203
  export interface ChildSpliceContext {
214
204
  /**
215
205
  * Set while emitting inside a conditional-branch `template()` arrow
@@ -241,7 +231,9 @@ export interface ChildSpliceContext {
241
231
  * 3. `slotId` ∈ markupSlotIds → `escapedTextOrMarkup`
242
232
  * 4. `slotId` → `escapedText`
243
233
  * 5. `{children}` passthrough → `childrenMarkup` (bare splice only, #2775/#2786)
244
- * 6. otherwise → `escapedText`
234
+ * 6. `children ?? fallback`, → `childrenMarkupOrEscapedFallback` (#3554)
235
+ * `children || fallback`
236
+ * 7. otherwise → `escapedText`
245
237
  *
246
238
  * Arm 5 tests BOTH `node.expr` (the original source text, stable across
247
239
  * builders) and the caller's resolved form (with parentheses handled structurally): a
@@ -250,7 +242,7 @@ export interface ChildSpliceContext {
250
242
  * either alone misses one of the two shapes (#2786).
251
243
  */
252
244
  export function spliceChildValue(
253
- node: Pick<IRExpression, 'expr' | 'slotId' | 'joinArrayChild'>,
245
+ node: Pick<IRExpression, 'expr' | 'slotId' | 'joinArrayChild' | 'childrenRead'>,
254
246
  valueExpr: string,
255
247
  cx: ChildSpliceContext,
256
248
  ): SafeHtml {
@@ -259,8 +251,10 @@ export function spliceChildValue(
259
251
  if (node.slotId) {
260
252
  return cx.markupSlotIds?.has(node.slotId) ? escapedTextOrMarkup(valueExpr) : escapedText(valueExpr)
261
253
  }
262
- if (isChildrenPassthroughExpr(node.expr) || isChildrenPassthroughExpr(valueExpr)) {
254
+ if (node.childrenRead === 'bare' || node.childrenRead === 'nullish-empty') {
263
255
  return childrenMarkup(valueExpr)
264
256
  }
257
+ if (node.childrenRead === 'nullish-fallback') return childrenMarkupOrEscapedFallback(valueExpr, 'nullish')
258
+ if (node.childrenRead === 'or-fallback') return childrenMarkupOrEscapedFallback(valueExpr, 'falsy')
265
259
  return escapedText(valueExpr)
266
260
  }
@@ -12,6 +12,7 @@
12
12
  * <i> const <param> = <array>[<idx>]
13
13
  * <i> <outerPreludeStatements*> // raw outer preamble (#1064)
14
14
  * <i> initChild('<name>', childScope, <props>)
15
+ * <i> {<each row event: qsa(childScope, …) + addEventListener>}
15
16
  * <i> })
16
17
  * <i>}
17
18
  *
@@ -62,6 +63,7 @@ import { varSlotId } from '../utils.ts'
62
63
  import { emitDedupedAttrUpdate, DEDUP_STORE_DECL } from '../emit-reactive.ts'
63
64
  import { claimPlanLiteral, claimWriterVarName, type ClaimSlotSpec } from '../control-flow/stringify/claim-plan.ts'
64
65
  import { emitLoopChildRefs } from '../control-flow/stringify/loop.ts'
66
+ import { emitRowEventListener } from '../control-flow/shared.ts'
65
67
 
66
68
  export function stringifyStaticArrayChildInits(
67
69
  lines: string[],
@@ -90,7 +92,7 @@ function stringifyOne(lines: string[], plan: StaticArrayChildInitPlan): void {
90
92
  }
91
93
 
92
94
  function emitSingleComp(lines: string[], plan: SingleCompInitPlan): void {
93
- const { containerVar, componentName, childSelector, arrayExpr, param, indexParam, outerPreludeStatements, propsExpr } = plan
95
+ const { containerVar, componentName, childSelector, arrayExpr, param, indexParam, outerPreludeStatements, propsExpr, rowEvents } = plan
94
96
  lines.push(` // Initialize static array children (hydrate skips nested instances)`)
95
97
  lines.push(` if (${containerVar}) {`)
96
98
  lines.push(` const __childScopes = qsaChildScopes(${containerVar}, ${childSelector})`)
@@ -103,6 +105,7 @@ function emitSingleComp(lines: string[], plan: SingleCompInitPlan): void {
103
105
  lines.push(` ${stmt}`)
104
106
  }
105
107
  lines.push(` initChild('${nameForRegistryRef(componentName)}', childScope, ${propsExpr})`)
108
+ for (const ev of rowEvents) emitRowEventListener(lines, ' ', 'childScope', ev)
106
109
  lines.push(` })`)
107
110
  lines.push(` }`)
108
111
  lines.push('')
@@ -24,6 +24,7 @@ import type {
24
24
  TypeDefinition,
25
25
  MapCallbackPreamble,
26
26
  PreambleRegionSource,
27
+ JsSourceText,
27
28
  } from '../types.ts'
28
29
  import type { CsrInlinabilityMap } from './csr-substitute.ts'
29
30
  import type { SkeletonSlotPaths } from './html-template.ts'
@@ -197,7 +198,7 @@ export interface DynamicElement {
197
198
  export interface ConditionalBranchEvent {
198
199
  slotId: string
199
200
  eventName: string
200
- handler: string
201
+ handler: JsSourceText
201
202
  }
202
203
 
203
204
  export interface ConditionalBranchRef {
@@ -528,7 +529,7 @@ export interface NestedLoop extends LoopCore {
528
529
  export interface LoopChildEvent {
529
530
  eventName: string // 'click', 'submit', etc.
530
531
  childSlotId: string // bf slot ID of the element with the event
531
- handler: string // Handler expression (may reference loop param)
532
+ handler: JsSourceText // Handler expression (may reference loop param)
532
533
  /** Nesting info for events inside nested inner loops. Empty = direct child. */
533
534
  nestedLoops: NestedLoop[]
534
535
  /** DOM nesting depth (0 = loop body root). Deepest-first sorting for event delegation (#774). */
@@ -4,9 +4,10 @@
4
4
  */
5
5
 
6
6
  import ts from 'typescript'
7
- import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR } from '../types.ts'
7
+ import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR, JsSourceText } from '../types.ts'
8
8
  import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
9
9
  import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
10
+ import { walkWithScope } from '../scope/lexical-scope-walk.ts'
10
11
  import { BindingScope, type LoopBindingSource } from '../scope/binding-scope.ts'
11
12
  import { buildLoopChainExpr } from '../loop-chain.ts'
12
13
  import { templatePartsToJsExpr } from '../template-parts.ts'
@@ -387,30 +388,6 @@ export function quotePropName(name: string): string {
387
388
  // toHtmlAttrName is now re-exported from @barefootjs/shared (classifyDOMProp's
388
389
  // toHTMLAttrName), keeping the same public name for downstream consumers.
389
390
 
390
- /**
391
- * Wrap arrow function handler in block to prevent accidental return false.
392
- * Returning false from a DOM event handler prevents default behavior.
393
- *
394
- * Example:
395
- * Input: (e) => e.key === 'Enter' && handleAdd()
396
- * Output: (e) => { e.key === 'Enter' && handleAdd() }
397
- */
398
- export function wrapHandlerInBlock(handler: string): string {
399
- const trimmed = handler.trim()
400
-
401
- if (trimmed.startsWith('(') && trimmed.includes('=>')) {
402
- const arrowIndex = trimmed.indexOf('=>')
403
- const params = trimmed.substring(0, arrowIndex + 2)
404
- const body = trimmed.substring(arrowIndex + 2).trim()
405
-
406
- if (!body.startsWith('{')) {
407
- return `${params} { ${body} }`
408
- }
409
- }
410
-
411
- return trimmed
412
- }
413
-
414
391
  /**
415
392
  * Profile mode (#1690, SR3): wrap an event handler so a profiling run can
416
393
  * attribute the reactive work it triggers to one turn. The original handler
@@ -424,7 +401,7 @@ export function wrapHandlerInBlock(handler: string): string {
424
401
  * emitted while it runs. Used at every handler emit site in profile mode so
425
402
  * no path is left unattributed.
426
403
  */
427
- export function wrapHandlerForTurn(handler: string, handlerId: string, loc?: string): string {
404
+ export function wrapHandlerForTurn(handler: JsSourceText, handlerId: string, loc?: string): string {
428
405
  const idArg = loc ? `${JSON.stringify(handlerId)}, ${JSON.stringify(loc)}` : JSON.stringify(handlerId)
429
406
  return `(...__bfa) => { beginTurn(${idArg}); try { return (${handler.trim()})(...__bfa) } finally { endTurn() } }`
430
407
  }
@@ -819,34 +796,15 @@ export function wrapIndexParamAsAccessor(expr: string, indexParam: string): stri
819
796
  * of those positions a type of AST node this function can name and skip,
820
797
  * instead of a regex guessing from surrounding characters.
821
798
  *
822
- * A nested declaration that re-binds `name` (a parameter, a `const`/`let`,
823
- * or a destructured local) is deliberately NOT skipped, unlike
824
- * `analyzer.ts`'s rename `classify()`: this rewrite has no scope tracking,
825
- * so it cannot tell a reference to the shadowing local from a reference to
826
- * the outer loop param past that point, and silently wrapping only the
827
- * OUTER-scope references while leaving the shadowed ones alone (or vice
828
- * versa) would just move the #3239 bug rather than fix it. Wrapping the
829
- * shadowing declaration's own name is always a syntax break at the
830
- * declaration site itself (`const name = 1` → `const name() = 1`, `(name)
831
- * => …` → `(name()) => …` — a call can't legally appear where a binding
832
- * name is expected), so the module fails to parse instead of silently
833
- * running with the wrong value — the same loud, build-time failure the old
834
- * regex produced for this shape (it had no shadow-awareness either).
835
- *
836
- * A NAMED function expression is the one shadowing shape this function
837
- * skips wholesale rather than leaving loud: `(function name() { ... })`'s
838
- * own name is scoped to exactly that expression's body and nowhere else, so
839
- * `visit` never descends into it at all once it sees the self-shadowing
840
- * name — no reference inside can possibly mean the outer `name`. A
841
- * `function`/`class` DECLARATION's name is different: its binding reaches
842
- * into the surrounding scope too (a function declaration's name is hoisted
843
- * above it; a class declaration's own static/instance members can
844
- * self-reference it), so the same whole-subtree skip isn't sound here —
845
- * a self-reference to a `function`/`class` declaration whose name happens
846
- * to match `name` is still silently misrewritten, an accepted
847
- * pre-existing-shaped gap the old regex had too (the "followed by `(`"
848
- * exclusion below only protects the declaration's OWN name token, not
849
- * references reachable from within or after it).
799
+ * A name an inner binding re-binds — a nested callback's parameter (an inner
800
+ * `.map((tag, i) => …)` reusing the outer index name, #3595), a
801
+ * `const`/`let`, a destructured local, a `function`/`class` declaration, a
802
+ * named function expression's own name — is that binding's, not the outer
803
+ * loop param's, for the binding's whole scope. The walk follows the shared
804
+ * lexical-scope model (`walkWithScope`, `scope/lexical-scope-walk.ts`, the
805
+ * same frames the props rewrites use), so it never rewrites the binder
806
+ * itself (`(tag, i()) =>` is not a binding pattern) and leaves every
807
+ * reference the binder shadows alone.
850
808
  */
851
809
  function rewriteIdentifierAsAccessor(expr: string, name: string): string {
852
810
  return rewriteIdentifierReferences(expr, new Map([[name, `${name}()`]]), { skipCallee: true })
@@ -861,14 +819,13 @@ function rewriteIdentifierAsAccessor(expr: string, name: string): string {
861
819
  * reference and why; both callers answer that question here, so they cannot
862
820
  * drift apart (#3260).
863
821
  *
864
- * `skipCallee` leaves `name()` / `new name()` and a `function name()`
865
- * declaration's own name alone. It is the accessor rewrite's no-double-wrap
866
- * rule (#2592): there `name()` already IS the accessor call, and the old
867
- * regex's "followed by (" lookahead skipped all three. A destructured
868
- * binding has no such shape — `handler()` with `({ handler })` calls the
869
- * item's field, so it must become `__bfItem().handler()` — and its caller
870
- * passes `false`, which also leaves a shadowing function declaration to
871
- * fail loudly, as it did under the old destructured regex.
822
+ * `skipCallee` leaves `name()` / `new name()` alone. It is the accessor
823
+ * rewrite's no-double-wrap rule (#2592): there `name()` already IS the
824
+ * accessor call. A destructured binding has no such shape — `handler()` with
825
+ * `({ handler })` calls the item's field, so it must become
826
+ * `__bfItem().handler()` — and its caller passes `false`. A nested
827
+ * `function name() {}` declaration needs neither rule: it binds `name` for
828
+ * its block, so the scope walk leaves its name and its calls alone.
872
829
  *
873
830
  * One pass over the AST, so a replacement is never re-scanned: a binding
874
831
  * `a` with path `.a` cannot cascade into `__bfItem().__bfItem().a`.
@@ -892,66 +849,29 @@ function rewriteIdentifierReferences(
892
849
  const sf = ts.createSourceFile('__bf_expr.ts', wrapped, ts.ScriptTarget.Latest, /* setParentNodes */ true)
893
850
  const edits: Array<{ start: number; end: number; replacement: string }> = []
894
851
 
895
- const visit = (node: ts.Node, active: ReadonlyMap<string, string>): void => {
896
- // A named function expression's own name is scoped to exactly its own
897
- // body, so nothing reachable inside it can refer to the outer binding of
898
- // that name — drop it for the whole subtree instead of only its
899
- // declaration-name identifier (see `rewriteIdentifierAsAccessor`'s
900
- // docstring for why a `function`/`class` DECLARATION can't get the same
901
- // treatment this cheaply). Other names stay active inside.
902
- if (ts.isFunctionExpression(node) && node.name && active.has(node.name.text)) {
903
- const inner = new Map(active)
904
- inner.delete(node.name.text)
905
- if (inner.size === 0) return
906
- ts.forEachChild(node, child => visit(child, inner))
907
- return
908
- }
909
-
910
- if (ts.isIdentifier(node)) {
911
- const replacement = active.get(node.text)
912
- if (replacement === undefined) return
913
- const p = node.parent
914
- // Pure-key / non-reference positions — never rewrite. Shared with
915
- // `analyzer.ts`'s factory-rename `classify()`, which answers the same
916
- // "is this identifier actually a value reference" question.
917
- if (isNonReferenceIdentifierPosition(node)) return
918
- // A function declaration's own name is always followed by `(` in
919
- // valid source, which is exactly the shape the old
920
- // `\bname\b(?!\s*\()`-style regex used to recognize and skip. Leaving
921
- // it unwrapped (rather than declining loudly, as the shadowing
922
- // declarations below do) matches the old behavior instead of
923
- // regressing code that used to compile. A `class name {}`
924
- // declaration's name is followed by `{`/`extends`, not `(`, so the
925
- // old regex did NOT protect it either — wrapping it is a pre-existing
926
- // syntax break, not a regression, so it's left to the shadowing-decl
927
- // path below like any other declaration name.
928
- //
929
- // Accessor mode only: the old destructured-binding regex had no such
930
- // exemption, so there a shadowing `function color() {}` broke the
931
- // declaration loudly. Skipping its name here would keep the local
932
- // function while rewriting its calls to `__bfItem().color()` — valid
933
- // JS that calls the wrong value (#3260 review).
934
- if (opts.skipCallee) {
935
- if (ts.isFunctionDeclaration(p) && p.name === node) return
936
- if (ts.isCallExpression(p) && p.expression === node) return // already `name()` — no double-wrap (#2592)
937
- if (ts.isNewExpression(p) && p.expression === node) return // `new name()` — same "followed by (" shape as a call
938
- }
939
-
940
- // Shorthand property (`{ name }`) expands key + rewrites value in one
941
- // edit (#1244). Every other reachable position here is a genuine
942
- // value reference — OR a shadowing declaration name (nested
943
- // parameter/`const`/`let`/destructured local): both get rewritten,
944
- // per `rewriteIdentifierAsAccessor`'s docstring on why a shadow is
945
- // left to fail loudly rather than silently misrewritten.
946
- const isShorthand = ts.isShorthandPropertyAssignment(p) && p.name === node
947
- const start = node.getStart(sf) - 1
948
- const end = node.getEnd() - 1
949
- edits.push({ start, end, replacement: isShorthand ? `${node.text}: ${replacement}` : replacement })
950
- return
951
- }
952
- ts.forEachChild(node, child => visit(child, active))
953
- }
954
- visit(sf, replacements)
852
+ walkWithScope(sf, (node, p, shadowed) => {
853
+ // An inner binding of the name — the binder itself and every reference
854
+ // it shadows — is not the outer loop param (#3595).
855
+ if (shadowed) return
856
+ const replacement = replacements.get(node.text)
857
+ if (replacement === undefined || !p) return
858
+ // Pure-key / non-reference positions — never rewrite. Shared with
859
+ // `analyzer.ts`'s factory-rename `classify()`, which answers the same
860
+ // "is this identifier actually a value reference" question.
861
+ if (isNonReferenceIdentifierPosition(node)) return
862
+ // Accessor mode only: `name()` already IS the accessor call (#2592), and
863
+ // `new name()` has the same "followed by (" shape. A destructured binding
864
+ // called as a function (`handler()` with `({ handler })`) calls the
865
+ // item's field, so it must become `__bfItem().handler()`.
866
+ if (opts.skipCallee && (ts.isCallExpression(p) || ts.isNewExpression(p)) && p.expression === node) return
867
+
868
+ // Shorthand property (`{ name }`) expands key + rewrites value in one
869
+ // edit (#1244).
870
+ const isShorthand = ts.isShorthandPropertyAssignment(p) && p.name === node
871
+ const start = node.getStart(sf) - 1
872
+ const end = node.getEnd() - 1
873
+ edits.push({ start, end, replacement: isShorthand ? `${node.text}: ${replacement}` : replacement })
874
+ })
955
875
 
956
876
  if (edits.length === 0) return expr
957
877
  // Apply right-to-left so earlier offsets stay valid as later ones grow.