@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
@@ -46,9 +46,95 @@ export function isNullableSignal(signal: SignalInfo): boolean {
46
46
  return signal.type.kind === 'unknown' && isNullishLiteral(signal.parsed)
47
47
  }
48
48
 
49
- /** Getter names of the component's signals whose SSR value can be nullish. */
49
+ /**
50
+ * Getter names of the component's signals whose SSR value can be nullish:
51
+ * a nullable signal (`isNullableSignal`), or one whose seed can evaluate to
52
+ * an absent optional prop (`createSignal(props.label)`,
53
+ * `createSignal(wide ? props.label : 'narrow')`, #3567). The seed is read in
54
+ * the form the SSR seed plan resolved it to, so a hop through a
55
+ * component-scope const counts too.
56
+ */
50
57
  export function collectNullableSignalGetters(ir: ComponentIR): Set<string> {
51
- return new Set((ir.metadata.signals ?? []).filter(isNullableSignal).map(s => s.getter))
58
+ const absentReads = collectAbsentPropSeedReads(ir)
59
+ return new Set(
60
+ (ir.metadata.signals ?? []).filter(s => isNullableSignal(s) || absentReads.has(s.getter)).map(s => s.getter),
61
+ )
62
+ }
63
+
64
+ /**
65
+ * For each signal whose seed can evaluate to an absent optional prop, the
66
+ * props (by param name) it can read whole (#3567). The seed is read in the
67
+ * form the SSR seed plan resolved it to. A backend that types a prop by
68
+ * value (Go) flips each of these props to a nillable field so the absence
69
+ * survives into the signal.
70
+ */
71
+ export function collectAbsentPropSeedReads(ir: ComponentIR): Map<string, Set<string>> {
72
+ const nullableProps = collectNullablePropReads(ir)
73
+ const out = new Map<string, Set<string>>()
74
+ if (nullableProps.size === 0) return out
75
+ const resolved = new Map<string, ParsedExpr>()
76
+ for (const step of ir.metadata.ssrSeedPlan?.steps ?? []) {
77
+ if (step.kind === 'derived' && step.origin === 'signal') resolved.set(step.name, step.parsed)
78
+ }
79
+ for (const s of ir.metadata.signals ?? []) {
80
+ const reads = new Set<string>()
81
+ collectSeedPropReads(resolved.get(s.getter) ?? s.parsed, nullableProps, reads)
82
+ if (reads.size > 0) out.set(s.getter, reads)
83
+ }
84
+ return out
85
+ }
86
+
87
+ /**
88
+ * Reads of a prop that can be absent at SSR time (optional or typed with
89
+ * `undefined` / `null`, no default, not a rest param): the name a read
90
+ * uses (the binding name, or `<propsObjectName>.<key>` for a member read)
91
+ * mapped to the param name.
92
+ */
93
+ function collectNullablePropReads(ir: ComponentIR): ReadonlyMap<string, string> {
94
+ const names = new Map<string, string>()
95
+ const objectName = ir.metadata.propsObjectName
96
+ for (const p of ir.metadata.propsParams) {
97
+ if (p.isRest || p.defaultValue !== undefined) continue
98
+ if (!p.optional && !(p.type && admitsNullish(p.type))) continue
99
+ names.set(objectName ? `${objectName}.${p.sourceName ?? p.name}` : p.name, p.name)
100
+ }
101
+ return names
102
+ }
103
+
104
+ /**
105
+ * Add to `out` the params of `nullableProps` a seed's value can be read
106
+ * whole from: a bare read, a ternary branch, the right operand of `??` /
107
+ * `||`, or either operand of `&&`. A call, a member read past the prop, or
108
+ * any other shape produces its own value, so it does not count.
109
+ */
110
+ function collectSeedPropReads(
111
+ expr: ParsedExpr | undefined,
112
+ nullableProps: ReadonlyMap<string, string>,
113
+ out: Set<string>,
114
+ ): void {
115
+ if (!expr) return
116
+ const add = (key: string): void => {
117
+ const param = nullableProps.get(key)
118
+ if (param !== undefined) out.add(param)
119
+ }
120
+ switch (expr.kind) {
121
+ case 'identifier':
122
+ add(expr.name)
123
+ return
124
+ case 'member':
125
+ if (!expr.computed && expr.object.kind === 'identifier') add(`${expr.object.name}.${expr.property}`)
126
+ return
127
+ case 'conditional':
128
+ collectSeedPropReads(expr.consequent, nullableProps, out)
129
+ collectSeedPropReads(expr.alternate, nullableProps, out)
130
+ return
131
+ case 'logical':
132
+ if (expr.op === '&&') collectSeedPropReads(expr.left, nullableProps, out)
133
+ collectSeedPropReads(expr.right, nullableProps, out)
134
+ return
135
+ default:
136
+ return
137
+ }
52
138
  }
53
139
 
54
140
  /**
@@ -91,10 +177,23 @@ export interface NullishAttrContext {
91
177
  readonly memos: ReadonlyMap<string, MemoInfo>
92
178
  /** Props declared as a number that may be `null` or absent (`n: number |
93
179
  * null`, `n?: number`), by the name a read uses: the binding name, and
94
- * `<propsObjectName>.<key>` for a member read (#3474). */
95
- readonly nullableNumberProps?: ReadonlySet<string>
180
+ * `<propsObjectName>.<key>` for a member read (#3474), mapped to what the
181
+ * engine's nil stands for there (`NullableNumberPropNil`, #3533). */
182
+ readonly nullableNumberProps?: ReadonlyMap<string, NullableNumberPropNil>
96
183
  }
97
184
 
185
+ /**
186
+ * What a nullable number prop's nil stands for at SSR (#3533). JS reads an
187
+ * absent prop as `undefined` (`NaN` in arithmetic) and a `null` one as `0`,
188
+ * while a template engine holds both as the same nil, so the declared type
189
+ * decides. A prop whose type admits `null` (`n: number | null`) reads its
190
+ * nil as `null`. A prop that can only be absent (`n?: number`,
191
+ * `n: number | undefined`) reads it as `undefined`; a present value, `0`
192
+ * included, is unaffected. A prop that admits both (`n?: number | null`)
193
+ * keeps the `null` reading: its nil can be either.
194
+ */
195
+ export type NullableNumberPropNil = 'null' | 'undefined'
196
+
98
197
  export function collectNullishAttrContext(ir: ComponentIR): NullishAttrContext {
99
198
  const signals = ir.metadata.signals ?? []
100
199
  return {
@@ -110,23 +209,29 @@ export function collectNullishAttrContext(ir: ComponentIR): NullishAttrContext {
110
209
  }
111
210
  }
112
211
 
113
- /** Whether `type` is a number that admits `null` / `undefined` and no other family. */
114
- function isNullableNumberType(type: TypeInfo | undefined, optional: boolean): boolean {
115
- if (!type) return false
212
+ /**
213
+ * What the nil of a number prop that admits `null` / `undefined` and no other
214
+ * family stands for (`NullableNumberPropNil`); `null` for any other type.
215
+ */
216
+ function nullableNumberPropNil(type: TypeInfo | undefined, optional: boolean): NullableNumberPropNil | null {
217
+ if (!type) return null
116
218
  const members = type.kind === 'union' ? (type.unionTypes ?? []) : [type]
117
219
  const families = new Set(members.map(m => (m.kind === 'primitive' ? m.primitive : m.kind)))
118
- const nullable = optional || families.has('null') || families.has('undefined')
220
+ const admitsNull = families.has('null')
221
+ const nullable = optional || admitsNull || families.has('undefined')
119
222
  families.delete('null')
120
223
  families.delete('undefined')
121
- return nullable && families.size === 1 && families.has('number')
224
+ if (!nullable || families.size !== 1 || !families.has('number')) return null
225
+ return admitsNull ? 'null' : 'undefined'
122
226
  }
123
227
 
124
- function collectNullableNumberProps(ir: ComponentIR): ReadonlySet<string> {
125
- const names = new Set<string>()
228
+ function collectNullableNumberProps(ir: ComponentIR): ReadonlyMap<string, NullableNumberPropNil> {
229
+ const names = new Map<string, NullableNumberPropNil>()
126
230
  const objectName = ir.metadata.propsObjectName
127
231
  for (const p of ir.metadata.propsParams) {
128
- if (p.isRest || p.defaultValue !== undefined || !isNullableNumberType(p.type, p.optional)) continue
129
- names.add(objectName ? `${objectName}.${p.sourceName ?? p.name}` : p.name)
232
+ if (p.isRest || p.defaultValue !== undefined) continue
233
+ const nil = nullableNumberPropNil(p.type, p.optional)
234
+ if (nil !== null) names.set(objectName ? `${objectName}.${p.sourceName ?? p.name}` : p.name, nil)
130
235
  }
131
236
  return names
132
237
  }
@@ -230,17 +335,25 @@ export function arithmeticOperandIsUndefined(
230
335
  return arithmeticOperandSeed(parsed, ctx, isShadowed) === 'undefined'
231
336
  }
232
337
 
338
+ /**
339
+ * What an arithmetic operand's SSR nil stands for: `'null'` / `'undefined'`
340
+ * when the operand is that value (a nullable number prop's `null` reading
341
+ * included), `'absent'` when it is a number prop that may be absent
342
+ * (`n?: number`), whose nil is `undefined` but which may hold a number.
343
+ */
344
+ type OperandSeed = 'null' | 'undefined' | 'absent' | null
345
+
233
346
  function arithmeticOperandSeed(
234
347
  parsed: ParsedExpr | undefined,
235
348
  ctx: NullishAttrContext,
236
349
  isShadowed: (name: string) => boolean,
237
- ): 'null' | 'undefined' | null {
350
+ ): OperandSeed {
238
351
  const visiting = new Set<string>()
239
- const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): 'null' | 'undefined' | null => {
352
+ const walk = (expr: ParsedExpr, shadowed: (name: string) => boolean): OperandSeed => {
240
353
  if (expr.kind === 'literal') return expr.literalType === 'null' ? 'null' : null
241
354
  if (expr.kind === 'identifier' && expr.name === 'undefined' && !shadowed('undefined')) return 'undefined'
242
355
  const prop = nullableNumberPropRead(expr, ctx, shadowed)
243
- if (prop) return 'null'
356
+ if (prop !== null) return prop === 'undefined' ? 'absent' : 'null'
244
357
  const getter = expr.kind === 'identifier' ? expr.name : bareGetterCallName(expr)
245
358
  if (getter === null || shadowed(getter)) return null
246
359
  if (ctx.nullSeededSignals?.has(getter)) return 'null'
@@ -256,22 +369,20 @@ function arithmeticOperandSeed(
256
369
  }
257
370
 
258
371
  /**
259
- * A read of a prop declared as a nullable number. Its SSR value may be
260
- * `null` or absent; it is coerced like a `null` operand. JS reads an absent
261
- * prop as `undefined` (`NaN` in arithmetic), which a template engine cannot
262
- * tell from `null` (the `omitted-optional-number-arithmetic` limitation).
372
+ * What the nil of a read of a prop declared as a nullable number stands for
373
+ * (`NullableNumberPropNil`), or `null` when the read is not such a prop.
263
374
  */
264
375
  function nullableNumberPropRead(
265
376
  expr: ParsedExpr,
266
377
  ctx: NullishAttrContext,
267
378
  shadowed: (name: string) => boolean,
268
- ): boolean {
269
- if (!ctx.nullableNumberProps?.size) return false
270
- if (expr.kind === 'identifier') return !shadowed(expr.name) && ctx.nullableNumberProps.has(expr.name)
379
+ ): NullableNumberPropNil | null {
380
+ if (!ctx.nullableNumberProps?.size) return null
381
+ if (expr.kind === 'identifier') return shadowed(expr.name) ? null : (ctx.nullableNumberProps.get(expr.name) ?? null)
271
382
  if (expr.kind === 'member' && !expr.computed && expr.object.kind === 'identifier' && !shadowed(expr.object.name)) {
272
- return ctx.nullableNumberProps.has(`${expr.object.name}.${expr.property}`)
383
+ return ctx.nullableNumberProps.get(`${expr.object.name}.${expr.property}`) ?? null
273
384
  }
274
- return false
385
+ return null
275
386
  }
276
387
 
277
388
  /**
@@ -285,18 +396,21 @@ export const NULL_COERCING_ARITHMETIC_OPS: ReadonlySet<string> = new Set(['-', '
285
396
 
286
397
  /** How a DSL adapter coerces an arithmetic operand (#3474): `'null'` reads a
287
398
  * nil as `0` (JS `ToNumber(null)`), `'undefined'` reads it as `NaN`
288
- * (`ToNumber(undefined)`), `null` leaves the operand as is. */
399
+ * (`ToNumber(undefined)`), `null` leaves the operand as is. Either coercion
400
+ * leaves a non-nil operand's value as it is. */
289
401
  export type ArithmeticCoercion = 'null' | 'undefined' | null
290
402
 
291
403
  /**
292
404
  * The one decision behind every DSL adapter's arithmetic over a nullish
293
405
  * operand (#3474). An operand known to be `null` / `undefined`
294
- * (`arithmeticOperandIsNull` / `arithmeticOperandIsUndefined`, or a nullable
295
- * number prop) is coerced under the operators JS applies `ToNumber` to
296
- * ({@link NULL_COERCING_ARITHMETIC_OPS}), and under `+` when the other
297
- * operand is a number literal, where `+` cannot concatenate. Each adapter
298
- * only spells the coercion; one whose engine already reads nil as `0`
299
- * spells `'null'` as the operand itself.
406
+ * (`arithmeticOperandIsNull` / `arithmeticOperandIsUndefined`), or a
407
+ * nullable number prop, whose nil reads as its type says
408
+ * (`NullableNumberPropNil`, #3533), is coerced under the operators JS
409
+ * applies `ToNumber` to ({@link NULL_COERCING_ARITHMETIC_OPS}), and under
410
+ * `+` when the other operand is a number literal, where `+` cannot
411
+ * concatenate. Unary minus applies `ToNumber` too: it passes `'-'` with no
412
+ * `other`. Each adapter only spells the coercion; one whose engine already
413
+ * reads nil as `0` spells `'null'` as the operand itself.
300
414
  */
301
415
  export function arithmeticOperandCoercion(
302
416
  op: string,
@@ -306,7 +420,9 @@ export function arithmeticOperandCoercion(
306
420
  isShadowed: (name: string) => boolean = () => false,
307
421
  ): ArithmeticCoercion {
308
422
  const numeric = NULL_COERCING_ARITHMETIC_OPS.has(op) || (op === '+' && isNumberLiteral(other))
309
- return numeric ? arithmeticOperandSeed(operand, ctx, isShadowed) : null
423
+ if (!numeric) return null
424
+ const seed = arithmeticOperandSeed(operand, ctx, isShadowed)
425
+ return seed === 'absent' ? 'undefined' : seed
310
426
  }
311
427
 
312
428
  function isNumberLiteral(expr: ParsedExpr | undefined): boolean {
@@ -7,84 +7,23 @@
7
7
  * references in the emitted text via a second scope-aware walk over
8
8
  * the text's own AST.
9
9
  *
10
- * Scope model: a name bound INSIDE the expression — a nested arrow /
11
- * function parameter, a block-scoped declaration, a catch variable —
12
- * refers to that binding, not the prop, for the whole binding's scope.
13
- * Both the discovery walk and the rewrite walk carry the same binding
14
- * stack, so `items.map((title) => title.a)` never turns into the
15
- * syntactically invalid `.map((_p.title) => _p.title.a)` when `title`
16
- * is also a prop. (Names bound by loop callbacks that ENCLOSE the
17
- * expression are the caller's job — see the `ctx.scope` filter in
10
+ * Scope model (`walkWithScope`, `scope/lexical-scope-walk.ts`): a name
11
+ * bound INSIDE the expression — a nested arrow / function parameter, a
12
+ * block-scoped declaration, a catch variable — refers to that binding,
13
+ * not the prop, for the whole binding's scope. Both the discovery walk
14
+ * and the rewrite walk carry the same binding stack, so
15
+ * `items.map((title) => title.a)` never turns into the syntactically
16
+ * invalid `.map((_p.title) => _p.title.a)` when `title` is also a prop.
17
+ * (Names bound by loop callbacks that ENCLOSE the expression are the
18
+ * caller's job — see the `ctx.scope` filter in
18
19
  * `jsx-to-ir.ts`'s `rewriteBarePropRefs` wrapper, #2222.)
19
20
  */
20
21
 
21
22
  import ts from 'typescript'
22
23
  import { PROPS_PARAM } from './ir-to-client-js/utils.ts'
23
24
  import { createTemplateAwareStringProtector } from './ir-to-client-js/html-template.ts'
24
-
25
- /** Collect every name introduced by a binding name (identifier or pattern). */
26
- function collectBindingNames(name: ts.BindingName, out: Set<string>): void {
27
- if (ts.isIdentifier(name)) {
28
- out.add(name.text)
29
- return
30
- }
31
- for (const el of name.elements) {
32
- if (ts.isBindingElement(el)) collectBindingNames(el.name, out)
33
- }
34
- }
35
-
36
- /**
37
- * Names bound by `n` for its subtree, or null when `n` introduces no
38
- * scope. Function-likes bind their parameters (and a function
39
- * expression its own name); blocks bind their statement-level
40
- * variable/function declarations; catch clauses bind their variable.
41
- */
42
- function scopeFrameOf(n: ts.Node): Set<string> | null {
43
- if (ts.isFunctionLike(n)) {
44
- const frame = new Set<string>()
45
- for (const p of n.parameters) collectBindingNames(p.name, frame)
46
- if ((ts.isFunctionExpression(n) || ts.isFunctionDeclaration(n)) && n.name) frame.add(n.name.text)
47
- return frame.size > 0 ? frame : null
48
- }
49
- if (ts.isBlock(n)) {
50
- const frame = new Set<string>()
51
- for (const st of n.statements) {
52
- if (ts.isVariableStatement(st)) {
53
- for (const d of st.declarationList.declarations) collectBindingNames(d.name, frame)
54
- } else if (ts.isFunctionDeclaration(st) && st.name) {
55
- frame.add(st.name.text)
56
- }
57
- }
58
- return frame.size > 0 ? frame : null
59
- }
60
- if (ts.isCatchClause(n) && n.variableDeclaration) {
61
- const frame = new Set<string>()
62
- collectBindingNames(n.variableDeclaration.name, frame)
63
- return frame.size > 0 ? frame : null
64
- }
65
- return null
66
- }
67
-
68
- /**
69
- * Depth-first walk that maintains the binding stack described above and
70
- * reports every identifier along with whether a binding within `root`
71
- * currently shadows it.
72
- */
73
- function walkWithScope(
74
- root: ts.Node,
75
- visit: (ident: ts.Identifier, parent: ts.Node | undefined, shadowed: boolean) => void,
76
- ): void {
77
- const scopeStack: Set<string>[] = []
78
- const isShadowed = (name: string) => scopeStack.some(frame => frame.has(name))
79
- function rec(n: ts.Node, parent?: ts.Node) {
80
- const frame = scopeFrameOf(n)
81
- if (frame) scopeStack.push(frame)
82
- if (ts.isIdentifier(n)) visit(n, parent, isShadowed(n.text))
83
- ts.forEachChild(n, child => rec(child, n))
84
- if (frame) scopeStack.pop()
85
- }
86
- rec(root)
87
- }
25
+ import { isAssignmentTargetIdentifier } from './assignment-target.ts'
26
+ import { walkWithScope } from './scope/lexical-scope-walk.ts'
88
27
 
89
28
  /**
90
29
  * True when `n` sits in a non-value position where a prop rewrite must
@@ -148,6 +87,22 @@ export function collectAstPropRefs(
148
87
  })
149
88
  }
150
89
 
90
+ /**
91
+ * The identifiers below `node` that write a name in `names`
92
+ * (`isAssignmentTargetIdentifier`: an assignment, an update, a destructuring
93
+ * assignment or a `for … of/in` head), nested functions included. A write to
94
+ * a name an inner binding shadows (a handler's own `let start`, a
95
+ * `for (let i …)`) is that binding's, not the outer one's, and is left out.
96
+ */
97
+ export function collectAssignmentTargets(node: ts.Node, names: ReadonlySet<string>): ts.Identifier[] {
98
+ const targets: ts.Identifier[] = []
99
+ walkWithScope(node, (n, _parent, shadowed) => {
100
+ if (shadowed || !names.has(n.text)) return
101
+ if (isAssignmentTargetIdentifier(n)) targets.push(n)
102
+ })
103
+ return targets
104
+ }
105
+
151
106
  /**
152
107
  * Scope-aware rewrite: parse `text` as an expression, walk it with the
153
108
  * binding stack, and splice `replacementFor(name)` onto exactly the
@@ -194,6 +149,9 @@ export function rewriteScopedValueRefs(
194
149
  walkWithScope(sf, (n, parent, shadowed) => {
195
150
  if (shadowed || !names.has(n.text)) return
196
151
  if (isNonValuePosition(n, parent)) return
152
+ // A written name (`++title`, `title = x`) keeps its binding: a
153
+ // replacement value is not an assignment target.
154
+ if (isAssignmentTargetIdentifier(n)) return
197
155
  const start = n.getStart(sf) - usedPrefix.length
198
156
  const end = n.getEnd() - usedPrefix.length
199
157
  if (start < 0 || end > text.length) return
@@ -213,6 +171,48 @@ export function rewriteScopedValueRefs(
213
171
  return result
214
172
  }
215
173
 
174
+ /** A piece of `splitScopedValueRefs`'s result: text between references, or one reference. */
175
+ export type ScopedValueRefPiece = { kind: 'text'; text: string } | { kind: 'ref'; name: string }
176
+
177
+ /**
178
+ * The structured twin of `rewriteScopedValueRefs`: the same scope-aware walk,
179
+ * but instead of splicing a replacement it splits `text` at each value
180
+ * reference to a name in `names`, so a later stage renders each reference by
181
+ * its own rule without touching the text again (#3531). A shorthand property
182
+ * (`{ off }`) keeps its key as text (`off: `) before the reference. Returns
183
+ * null when `text` doesn't parse as an expression, and an empty reference set
184
+ * leaves one `text` piece.
185
+ */
186
+ export function splitScopedValueRefs(text: string, names: ReadonlySet<string>): ScopedValueRefPiece[] | null {
187
+ const prefix = '('
188
+ const sf = ts.createSourceFile('__bf_scoped_split.ts', `${prefix}${text}\n)`, ts.ScriptTarget.Latest, true)
189
+ const parseDiagnostics = (sf as unknown as { parseDiagnostics?: unknown[] }).parseDiagnostics
190
+ if (parseDiagnostics && parseDiagnostics.length > 0) return null
191
+
192
+ const refs: Array<{ start: number; end: number; name: string; key?: string }> = []
193
+ walkWithScope(sf, (n, parent, shadowed) => {
194
+ if (shadowed || !names.has(n.text)) return
195
+ if (isNonValuePosition(n, parent)) return
196
+ if (isAssignmentTargetIdentifier(n)) return
197
+ const start = n.getStart(sf) - prefix.length
198
+ const end = n.getEnd() - prefix.length
199
+ if (start < 0 || end > text.length) return
200
+ const shorthand = parent !== undefined && ts.isShorthandPropertyAssignment(parent) && parent.name === n
201
+ refs.push({ start, end, name: n.text, ...(shorthand && { key: n.text }) })
202
+ })
203
+
204
+ const pieces: ScopedValueRefPiece[] = []
205
+ let cursor = 0
206
+ for (const ref of refs.sort((a, b) => a.start - b.start)) {
207
+ const before = text.slice(cursor, ref.start) + (ref.key !== undefined ? `${ref.key}: ` : '')
208
+ if (before !== '') pieces.push({ kind: 'text', text: before })
209
+ pieces.push({ kind: 'ref', name: ref.name })
210
+ cursor = ref.end
211
+ }
212
+ if (cursor < text.length) pieces.push({ kind: 'text', text: text.slice(cursor) })
213
+ return pieces
214
+ }
215
+
216
216
  /**
217
217
  * `applyScopedPropRefRewrite` specializes `rewriteScopedValueRefs` for
218
218
  * the destructured-prop case: the substitution defaults to
@@ -96,6 +96,77 @@ export function isPropsAliasConst(
96
96
  return read !== null && read.key === c.name && (!read.hasDefault || c.mutatedAfterDeclaration === true)
97
97
  }
98
98
 
99
+ /**
100
+ * Whether a component-scope binding keeps the value its declaration gives
101
+ * it, so it may be read as the prop it was destructured from (a live
102
+ * `_p.<key> ?? <default>` read).
103
+ *
104
+ * - A body binding (`ConstantInfo`) must be a `const` nothing mutates
105
+ * after the declaration. A `let` may be reassigned (`local =
106
+ * ['changed']`, or a folded `if (!local) local = 'y'`) and a mutated
107
+ * value (`items.push(x)`, `markMutatedConstants`) has changed.
108
+ * - A destructured prop parameter (`ParamInfo`, no declaration kind)
109
+ * keeps the value the caller passed unless the component writes it.
110
+ *
111
+ * Either way a binding the component writes anywhere (`reassigned`, set on
112
+ * both by `markWrittenBindings`, analyzer.ts) does not: a write needs a
113
+ * local, so the init body declares one (`emitPropsExtraction`) and keeps
114
+ * every reference to it. The one rule for every site that turns a props
115
+ * binding into a live prop read: the init body's alias rewrite
116
+ * (`resolveBodyPropAliases`) and parameter rewrite
117
+ * (`rewriteDestructuredPropReads`), the reactive attribute rewrite
118
+ * (`rewriteDestructuredPropsInExpr`), and the template's prop shadow guard
119
+ * (`propShadowingNames`, `jsx-to-ir.ts`, #3579).
120
+ */
121
+ export function keepsDeclaredValue(
122
+ b: { declarationKind?: ConstantInfo['declarationKind']; mutatedAfterDeclaration?: boolean; reassigned?: boolean },
123
+ ): boolean {
124
+ if (b.reassigned === true || b.mutatedAfterDeclaration === true) return false
125
+ return b.declarationKind === undefined || b.declarationKind === 'const'
126
+ }
127
+
128
+ /**
129
+ * Whether the component writes any of its bindings (`reassigned`, set by
130
+ * `markWrittenBindings`): a prop parameter or a component-scope `let`. Such
131
+ * a component's client template has to check each expression for a write
132
+ * (`csrSubstitute`'s `writes`), which only the CSR template emitter does, so
133
+ * it never takes the static template fast path (`emit-registration.ts`),
134
+ * and a child whose prop writes a binding is deferred to init
135
+ * (`computeDeferredChildSlots`).
136
+ */
137
+ export function writesAnyBinding(b: {
138
+ propsParams: readonly Pick<ParamInfo, 'reassigned'>[]
139
+ localConstants: readonly Pick<ConstantInfo, 'reassigned'>[]
140
+ }): boolean {
141
+ return b.propsParams.some(p => p.reassigned === true) || b.localConstants.some(c => c.reassigned === true)
142
+ }
143
+
144
+ /**
145
+ * Whether a renamed binding of a body destructure (`const { b: local = d } =
146
+ * props`) is a prop under its local name: the analyzer gives such a binding
147
+ * with a default its own `ParamInfo` (`name: local`, `sourceName: b`, the
148
+ * default's fields), the same entry the parameter form `function C({ b:
149
+ * local = d })` has. A template then reads the prop through that entry
150
+ * (`livePropReadExpr`), default included, instead of inlining the const.
151
+ *
152
+ * Only a binding that keeps its declared value (`keepsDeclaredValue`): a
153
+ * reassigned or mutated one stays a local and keeps the unsafe-local path
154
+ * (an empty slot, a deferred child).
155
+ *
156
+ * Kept apart from `isPropsAliasConst`: that one also decides relocate's
157
+ * binding kind, whose `prop` lift reads `_p.<key>` without a default, so a
158
+ * renamed binding classified there would lose its default.
159
+ */
160
+ export function isRenamedBodyPropParam(
161
+ c: Pick<ConstantInfo, 'name' | 'propsDestructure' | 'declarationKind' | 'mutatedAfterDeclaration' | 'reassigned'>,
162
+ propsParams: readonly ParamInfo[],
163
+ ): boolean {
164
+ const key = c.propsDestructure?.sourceKey
165
+ if (key === undefined || key === c.name) return false
166
+ if (!keepsDeclaredValue(c)) return false
167
+ return propsParams.some(p => !p.isRest && p.name === c.name && p.sourceName === key)
168
+ }
169
+
99
170
  /**
100
171
  * How a parsed signal initializer reads a prop: a member chain rooted at the
101
172
  * props object (`props.<name>`, `props.row.count`, `props.items[0]`) or a
@@ -276,7 +347,7 @@ export function resolveBodyPropAliases(
276
347
  if (propsObjectName === null) return aliases
277
348
  for (const c of localConstants) {
278
349
  if (c.isModule || !c.value) continue
279
- if (requireLiveRewriteSafe && (c.declarationKind !== 'const' || c.mutatedAfterDeclaration)) continue
350
+ if (requireLiveRewriteSafe && !keepsDeclaredValue(c)) continue
280
351
  // Re-parse `value` (rather than walking `c.parsed`) so the default's
281
352
  // SOURCE TEXT is available verbatim — `ParsedExpr` structures the
282
353
  // default but doesn't retain its original formatting, and this reuses
@@ -326,13 +397,14 @@ export function boundPropLocalNames(b: PropsParamBindings): ReadonlySet<string>
326
397
 
327
398
  const EMPTY_SET: ReadonlySet<string> = new Set()
328
399
 
400
+
329
401
  /**
330
402
  * The subset of `ParamInfo` a live prop read actually needs. A body-level
331
403
  * pure-alias local (`resolveBodyPropAliases`) has no real `ParamInfo` — it
332
404
  * never bound a parameter — so callers synthesize one of these instead of a
333
405
  * full `ParamInfo` (which would need a fabricated `type`/`optional`).
334
406
  */
335
- export type LivePropReadInfo = Pick<ParamInfo, 'name' | 'sourceName' | 'defaultValue' | 'defaultContainsArrow'>
407
+ export type LivePropReadInfo = Pick<ParamInfo, 'name' | 'sourceName' | 'defaultValue' | 'defaultContainsArrow' | 'defaultParts'>
336
408
 
337
409
  /** `_p.<callerKey>` — `_p` is always keyed by the caller-facing name (#2524 CSR half). */
338
410
  export function propReadBase(p: LivePropReadInfo): string {
@@ -372,12 +444,27 @@ export function propReadFallback(
372
444
  usage: PropUsage | undefined,
373
445
  usedAsCondition: boolean,
374
446
  ): string | null {
375
- if (p.defaultValue) return coalesceDefaultText(p.defaultValue, p.defaultContainsArrow)
447
+ const defaultText = propDefaultText(p)
448
+ if (defaultText) return coalesceDefaultText(defaultText, p.defaultContainsArrow)
376
449
  if (usage?.usedAsLoopArray) return '[]'
377
450
  if (propHasPropertyAccess(usage) && !usedAsCondition) return '{}'
378
451
  return null
379
452
  }
380
453
 
454
+ /**
455
+ * A prop's destructure default as client JS. A default that reads an earlier
456
+ * binding of its own pattern (`{ off = false, on = off }`, #3531) renders each
457
+ * read as that prop's own live read (`_p.off ?? false`), since the emitted
458
+ * scope binds no `off`; any other default is its source text. Undefined when
459
+ * the prop has no default.
460
+ */
461
+ export function propDefaultText(p: LivePropReadInfo): string | undefined {
462
+ if (!p.defaultParts) return p.defaultValue
463
+ return p.defaultParts
464
+ .map(part => (part.kind === 'text' ? part.text : livePropReadExpr(part.param, undefined, false)))
465
+ .join('')
466
+ }
467
+
381
468
  /**
382
469
  * The live read of a destructured prop inside init scope, in the same shape
383
470
  * props-object mode emits for `props.X`. The one formula every live-read
@@ -1,8 +1,11 @@
1
1
  import { describe, test, expect } from 'bun:test'
2
+ import ts from 'typescript'
2
3
  import {
3
4
  replaceInExprContexts,
4
5
  findInterpolationEnd,
5
6
  findTopLevelTemplateLiterals,
7
+ isTriviaKind,
8
+ iterateJsTokens,
6
9
  } from '../js-scanner'
7
10
 
8
11
  // ---------------------------------------------------------------------------
@@ -243,3 +246,37 @@ describe('findTopLevelTemplateLiterals', () => {
243
246
  expect(r).toEqual(['<a/>', '<b/>'])
244
247
  })
245
248
  })
249
+
250
+ describe('iterateJsTokens: division after a keyword used as a name (#3536)', () => {
251
+ const kinds = (text: string) =>
252
+ [...iterateJsTokens(text)].filter(t => !isTriviaKind(t.kind)).map(t => ts.SyntaxKind[t.kind])
253
+
254
+ test('a contextual-keyword binding is followed by division', () => {
255
+ expect(kinds('type / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
256
+ })
257
+
258
+ test('a keyword-named member is followed by division', () => {
259
+ expect(kinds('obj.default / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
260
+ expect(kinds('obj?.new / 2')).not.toContain('RegularExpressionLiteral')
261
+ })
262
+
263
+ test('`of` as a binding is followed by division; as the for-of separator, by a regex literal', () => {
264
+ expect(kinds('of / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
265
+ expect(kinds('for (const hit of /"/.exec(x) || []) {}')).toContain('RegularExpressionLiteral')
266
+ expect(kinds('for (const [a, b] of /x/.exec(s)) {}')).toContain('RegularExpressionLiteral')
267
+ expect(kinds('for await (const hit of /x/.exec(s)) {}')).toContain('RegularExpressionLiteral')
268
+ expect(kinds('for (const type of /"/.exec(x) || []) {}')).toContain('RegularExpressionLiteral')
269
+ expect(kinds('for (const of of /x/.exec(s)) {}')).toContain('RegularExpressionLiteral')
270
+ })
271
+
272
+ test('`of` after a binding outside a for header is a name (ASI)', () => {
273
+ expect(kinds('let of = x\nof /= step\nreturn of')).not.toContain('RegularExpressionLiteral')
274
+ expect(kinds('f(x)\nof / 2 + step / 3')).not.toContain('RegularExpressionLiteral')
275
+ })
276
+
277
+ test('an operator keyword still starts a regex literal', () => {
278
+ expect(kinds('return /a/.test(x)')).toContain('RegularExpressionLiteral')
279
+ expect(kinds('typeof /a/')).toContain('RegularExpressionLiteral')
280
+ expect(kinds('await /a/.test(x)')).toContain('RegularExpressionLiteral')
281
+ })
282
+ })