@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
@@ -6,7 +6,7 @@
6
6
  import { describe, test, expect } from 'bun:test'
7
7
  import { analyzeComponent } from '../analyzer'
8
8
  import { jsxToIR } from '../jsx-to-ir'
9
- import { planLoop, type LoopPlanContext } from '../adapters/loop-plan'
9
+ import { planLoop, spellDestructureLocals, spellFilteredRow, spellSortedSource, type LoopPlanContext, type LoopSortSpelling } from '../adapters/loop-plan'
10
10
  import { BindingScope } from '../scope/binding-scope'
11
11
  import type { IRLoop, IRNode } from '../types'
12
12
 
@@ -46,6 +46,10 @@ describe('planLoop', () => {
46
46
  unresolvableConst: null,
47
47
  sort: null,
48
48
  captureAliases: [],
49
+ filter: null,
50
+ itemVar: 'x',
51
+ indexLocal: null,
52
+ destructureLocals: [],
49
53
  })
50
54
  })
51
55
 
@@ -94,6 +98,33 @@ describe('planLoop', () => {
94
98
  expect(sorted.sort).toMatchObject({ kind: 'eval', helper: 'sort_eval' })
95
99
  })
96
100
 
101
+ test('a comparator outside the evaluator falls back to the structured descriptor', () => {
102
+ const sorted = plan(`export function Test(props: { items: { name: string }[] }) { return <ul>{props.items.toSorted((a, b) => a.name.localeCompare(b.name)).map(x => <li key={x.name}>{x.name}</li>)}</ul> }`)
103
+ expect(sorted.sort).toMatchObject({ kind: 'structured-sort', comparator: { keys: [{ key: { kind: 'field', field: 'name' }, type: 'string', direction: 'asc' }] } })
104
+ })
105
+
106
+ test('the sorted source spells each arm of the sort plan', () => {
107
+ const refusals: string[] = []
108
+ const spelling: LoopSortSpelling = {
109
+ emit: (e) => (e.kind === 'identifier' ? `v.${e.name}` : '?'),
110
+ eval: {
111
+ call: (helper, operands) => `${helper}(${operands.join(', ')})`,
112
+ string: (value) => `'${value}'`,
113
+ boolean: (value) => String(value),
114
+ env: (entries) => `{${entries.map(([name, value]) => `${name}: ${value}`).join(', ')}}`,
115
+ },
116
+ structured: (recv, comparator) => `sort(${recv}, ${comparator.keys.map((k) => (k.key.kind === 'field' ? k.key.field : 'self')).join(',')})`,
117
+ refuse: (message) => refusals.push(message),
118
+ }
119
+ expect(spellSortedSource(null, 'xs', spelling)).toBe('xs')
120
+ const evaluated = spellSortedSource({ kind: 'eval', helper: 'sort_eval', operands: [{ kind: 'string', value: 'body' }], captured: ['k'] }, 'xs', spelling)
121
+ expect(evaluated).toBe(`sort_eval(xs, 'body', {k: v.k})`)
122
+ const structured = plan(`export function Test(props: { items: { name: string }[] }) { return <ul>{props.items.toSorted((a, b) => a.name.localeCompare(b.name)).map(x => <li key={x.name}>{x.name}</li>)}</ul> }`)
123
+ expect(spellSortedSource(structured.sort, 'xs', spelling)).toBe('sort(xs, name)')
124
+ expect(spellSortedSource({ kind: 'refuse', message: 'no form', suggestion: '' }, 'xs', spelling)).toBe('xs')
125
+ expect(refusals).toEqual(['no form'])
126
+ })
127
+
97
128
  test('a filter capture a row binding would shadow gets a per-loop alias', () => {
98
129
  const captured = plan(`export function Test(props: { items: { id: string }[]; id: string }) {
99
130
  const id = props.id
@@ -101,4 +132,103 @@ describe('planLoop', () => {
101
132
  }`)
102
133
  expect(captured.captureAliases).toEqual([{ name: 'id', alias: expect.stringMatching(/^__bf_cap_\w+_id$/) }])
103
134
  })
135
+
136
+ test('a filter predicate is renamed for the row: captures to their aliases, the filter param to the loop param', () => {
137
+ const filtered = plan(`export function Test(props: { items: { id: string; label: string }[]; id: string }) {
138
+ const id = props.id
139
+ return <ul>{props.items.filter(x => x.id !== id && x.label !== 'x').map(id => <li key={id.id}>{id.id}</li>)}</ul>
140
+ }`)
141
+ const alias = filtered.captureAliases[0]!.alias
142
+ expect(filtered.filter).toMatchObject({ kind: 'predicate', param: 'x', aliases: new Map([[alias, 'id']]) })
143
+ if (filtered.filter?.kind !== 'predicate') throw new Error('expected a predicate')
144
+ const names = (e: unknown): string[] => {
145
+ if (Array.isArray(e)) return e.flatMap(names)
146
+ if (e === null || typeof e !== 'object') return []
147
+ const node = e as Record<string, unknown>
148
+ if (node.kind === 'identifier') return [node.name as string]
149
+ return Object.values(node).flatMap(names)
150
+ }
151
+ expect(names(filtered.filter.predicate)).toEqual(['x', 'id', 'x'])
152
+ expect(names(filtered.filter.captured)).toEqual(['x', alias, 'x'])
153
+ expect(names(filtered.filter.onRow)).toEqual(['id', alias, 'id'])
154
+ })
155
+
156
+ test('a filter without a predicate is refused, and a loop without a filter plans none', () => {
157
+ const loop = (filterPredicate: IRLoop['filterPredicate']): IRLoop => {
158
+ const ctx = analyzeComponent(`export function Test(props: { items: string[] }) { return <ul>{props.items.map(x => <li key={x}>{x}</li>)}</ul> }`, 'Test.tsx')
159
+ return { ...firstLoop(jsxToIR(ctx)), filterPredicate }
160
+ }
161
+ const ctx: LoopPlanContext<unknown[]> = {
162
+ scope: BindingScope.EMPTY,
163
+ localConstants: [],
164
+ resolveLiteralConst: () => null,
165
+ callbackLowering: { adapterName: 'Test' },
166
+ spellStatic: (items) => items,
167
+ }
168
+ expect(planLoop(loop(undefined), ctx).filter).toBeNull()
169
+ expect(planLoop(loop({ param: 'x', raw: 'x => { return x }' }), ctx).filter).toMatchObject({
170
+ kind: 'refuse',
171
+ message: expect.stringContaining('no Test loop-filter form'),
172
+ })
173
+ })
174
+
175
+ test('a filtered row spells inside its guard, a refused one under the stand-in condition', () => {
176
+ const refusals: string[] = []
177
+ const spelling = {
178
+ condition: (f: { param: string }) => `ok(${f.param})`,
179
+ refuse: (message: string) => refusals.push(message),
180
+ refused: 'true',
181
+ open: (condition: string) => `if ${condition}`,
182
+ close: 'end',
183
+ }
184
+ expect(spellFilteredRow(null, ['a', 'b'], spelling)).toEqual(['a', 'b'])
185
+ expect(spellFilteredRow({ kind: 'refuse', message: 'no form', suggestion: '' }, ['a'], spelling)).toEqual(['if true', 'a', 'end'])
186
+ expect(refusals).toEqual(['no form'])
187
+ })
188
+
189
+ test('the row binds its index through a local, except in an object iteration', () => {
190
+ expect(plan(`export function Test(props: { items: string[] }) { return <ul>{props.items.map((x, i) => <li key={x}>{i}</li>)}</ul> }`)).toMatchObject({
191
+ itemVar: 'x',
192
+ indexLocal: 'i',
193
+ })
194
+ expect(plan(`export function Test(props: { items: string[] }) { return <ul>{props.items.keys().map(k => <li key={k}>{k}</li>)}</ul> }`)).toMatchObject({
195
+ itemVar: '__bf_item',
196
+ indexLocal: 'k',
197
+ })
198
+ expect(plan(`export function Test(props: { m: Record<string, string> }) { return <ul>{Object.entries(props.m).map(([k, v]) => <li key={k}>{v}</li>)}</ul> }`)).toMatchObject({
199
+ indexLocal: null,
200
+ destructureLocals: [],
201
+ })
202
+ })
203
+
204
+ test('a lowered destructure binds one local per binding off the item', () => {
205
+ const lowered = plan(`export function Test(props: { rows: { id: string; user: { name: string }; tags: string[]; on: boolean }[] }) {
206
+ return <ul>{props.rows.map(({ id, user: { name }, ...rest }) => <li key={id} data-on={rest.on}>{name}</li>)}</ul>
207
+ }`)
208
+ expect(lowered.itemVar).toBe('__bf_item')
209
+ expect(lowered.destructureLocals).toEqual([
210
+ { name: 'id', value: { kind: 'path', segments: [{ kind: 'field', key: 'id', isIdent: true }] } },
211
+ { name: 'name', value: { kind: 'path', segments: [{ kind: 'field', key: 'user', isIdent: true }, { kind: 'field', key: 'name', isIdent: true }] } },
212
+ { name: 'rest', value: { kind: 'omit', segments: [], exclude: ['id', 'user'] } },
213
+ ])
214
+ const tuple = plan(`export function Test(props: { rows: string[][] }) { return <ul>{props.rows.map(([head, ...tail]) => <li key={head}>{tail.length}</li>)}</ul> }`)
215
+ expect(tuple.destructureLocals).toEqual([
216
+ { name: 'head', value: { kind: 'path', segments: [{ kind: 'index', index: 0 }] } },
217
+ { name: 'tail', value: { kind: 'slice', segments: [], from: 1 } },
218
+ ])
219
+ const spelled = spellDestructureLocals(tuple, 'it', {
220
+ accessor: (item, segments) => item + segments.map((s) => (s.kind === 'index' ? `[${s.index}]` : `.${s.key}`)).join(''),
221
+ slice: (parent, from) => `slice(${parent}, ${from})`,
222
+ omit: (parent, keys) => `omit(${parent}, ${keys.join('|')})`,
223
+ })
224
+ expect(spelled).toEqual([
225
+ { name: 'head', value: 'it[0]' },
226
+ { name: 'tail', value: 'slice(it, 1)' },
227
+ ])
228
+ })
229
+
230
+ test('an unlowerable destructure binds no locals', () => {
231
+ const refused = plan(`export function Test(props: { rows: { a: string; b: string }[] }) { return <ul>{props.rows.map(({ a, ...rest }) => <li key={a}>{String(rest)}</li>)}</ul> }`)
232
+ expect(refused).toMatchObject({ destructure: 'unlowerable', destructureLocals: [] })
233
+ })
104
234
  })
@@ -0,0 +1,129 @@
1
+ /**
2
+ * #3607: an event handler on an element forwarded as a loop-row child
3
+ * component's own `children` (`<Chip key={o.id}><button onClick={…}/></Chip>`).
4
+ * `collectLoopChildBindings` collects the event into the loop's
5
+ * `bindings.events`, but the component-root loop builder never read it, and
6
+ * a component-root loop has no delegation pass — so the handler reached no
7
+ * part of the client JS. The builder now resolves those events into
8
+ * `rowEvents`, and each row (hydrated and client-built) attaches them
9
+ * directly, the same per-row listener the composite row uses. The static
10
+ * array twin (`single-comp` child init) attaches them to each hydrated row.
11
+ *
12
+ * Conformance coverage: `loop-row-child-children-handler`.
13
+ */
14
+
15
+ import { describe, test, expect } from 'bun:test'
16
+ import ts from 'typescript'
17
+ import { compileJSX } from '../compiler'
18
+ import { TestAdapter } from '../adapters/test-adapter'
19
+
20
+ const adapter = new TestAdapter()
21
+
22
+ function clientJsOf(body: string): string {
23
+ const source = `
24
+ 'use client'
25
+ import { createSignal } from '@barefootjs/client'
26
+ function Chip({ children }: { children?: any }) {
27
+ return <span class="chip">{children}</span>
28
+ }
29
+ export function Picker() {
30
+ const [rows, setRows] = createSignal([{ id: 'a', label: 'A' }])
31
+ const [picked, setPicked] = createSignal('')
32
+ const pick = (id: string) => setPicked(id)
33
+ return <div><p>{picked()}</p>${body}</div>
34
+ }
35
+ `
36
+ const result = compileJSX(source, 'Picker.tsx', { adapter })
37
+ expect(result.errors.filter(e => e.severity === 'error')).toHaveLength(0)
38
+ const js = result.files.find(f => f.type === 'clientJs')!.content
39
+ const diagnostics = ts.transpileModule(js, {
40
+ reportDiagnostics: true,
41
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.Latest },
42
+ }).diagnostics ?? []
43
+ expect(diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error)).toHaveLength(0)
44
+ return js
45
+ }
46
+
47
+ /** The per-row listener block, as attached to the hydrated and the client-built row. */
48
+ function rowListener(elVar: '__existing' | '__csrEl', handler: string): string {
49
+ return `{ const __e = qsa(${elVar}, '[bf="^s3"]'); if (__e) __e.addEventListener('click', ${handler}) }`
50
+ }
51
+
52
+ describe('event handler in forwarded loop-row child children (#3607)', () => {
53
+ test('a handler reading the row item is attached to the hydrated and the client-built row', () => {
54
+ const js = clientJsOf(
55
+ '{rows().map(o => (<Chip key={o.id}><button onClick={() => pick(o.id)}>{o.label}</button></Chip>))}',
56
+ )
57
+ expect(js).toContain(rowListener('__existing', '() => pick(o().id)'))
58
+ expect(js).toContain(rowListener('__csrEl', '() => pick(o().id)'))
59
+ // Attached after the row component is initialised / created.
60
+ expect(js.indexOf(rowListener('__existing', '() => pick(o().id)')))
61
+ .toBeGreaterThan(js.indexOf(`initChild('Chip`))
62
+ expect(js.indexOf(rowListener('__csrEl', '() => pick(o().id)')))
63
+ .toBeGreaterThan(js.indexOf('const __csrEl = createComponent('))
64
+ })
65
+
66
+ test('a handler reading the row index reads it through the accessor', () => {
67
+ const js = clientJsOf(
68
+ '{rows().map((o, i) => (<Chip key={o.id}><button onClick={() => pick(o.id + i)}>{o.label}</button></Chip>))}',
69
+ )
70
+ expect(js).toContain(rowListener('__existing', '() => pick(o().id + i())'))
71
+ expect(js).toContain(rowListener('__csrEl', '() => pick(o().id + i())'))
72
+ })
73
+
74
+ test('a handler reading destructured row bindings reads the row item accessor', () => {
75
+ const js = clientJsOf(
76
+ '{rows().map(({ id, label }, i) => (<Chip key={id}><button onClick={() => pick(id + i)}>{label}</button></Chip>))}',
77
+ )
78
+ expect(js).toContain(rowListener('__existing', '() => pick(__bfItem().id + i())'))
79
+ expect(js).toContain(rowListener('__csrEl', '() => pick(__bfItem().id + i())'))
80
+ })
81
+
82
+ test('a row with only a forwarded handler leaves the simple renderItem shape', () => {
83
+ // No reactive text: the handler alone must force the SSR/CSR split, since
84
+ // the simple shape returns straight from initChild/createComponent.
85
+ const js = clientJsOf(
86
+ `{rows().map(o => (<Chip key={o.id}><button onClick={() => pick(o.id)}>pick</button></Chip>))}`,
87
+ )
88
+ expect(js).not.toContain('if (__existing) { initChild(')
89
+ expect(js).toContain(`{ const __e = qsa(__existing, '[bf="^s2"]'); if (__e) __e.addEventListener('click', () => pick(o().id)) }`)
90
+ expect(js).toContain(`{ const __e = qsa(__csrEl, '[bf="^s2"]'); if (__e) __e.addEventListener('click', () => pick(o().id)) }`)
91
+ })
92
+
93
+ test('a module-const array attaches the handler to each hydrated row, unwrapped', () => {
94
+ // A static array has no delegation pass for a component row either; the
95
+ // forEach binds the plain item and index, so the handler is not
96
+ // accessor-wrapped.
97
+ const source = `
98
+ 'use client'
99
+ import { createSignal } from '@barefootjs/client'
100
+ function Chip({ children }: { children?: any }) {
101
+ return <span class="chip">{children}</span>
102
+ }
103
+ const OPTS = [{ id: 'a', label: 'A' }]
104
+ export function Picker() {
105
+ const [picked, setPicked] = createSignal('')
106
+ return <div><p>{picked()}</p>{OPTS.map(({ id, label }, i) => (<Chip key={id}><button onClick={() => setPicked(id + i)}>{label}</button></Chip>))}</div>
107
+ }
108
+ `
109
+ const result = compileJSX(source, 'Picker.tsx', { adapter })
110
+ expect(result.errors.filter(e => e.severity === 'error')).toHaveLength(0)
111
+ const js = result.files.find(f => f.type === 'clientJs')!.content
112
+ expect(ts.transpileModule(js, {
113
+ reportDiagnostics: true,
114
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.Latest },
115
+ }).diagnostics?.filter(d => d.category === ts.DiagnosticCategory.Error) ?? []).toHaveLength(0)
116
+ expect(js).toContain(`__childScopes.forEach((childScope, i) => {
117
+ const { id, label } = OPTS[i]
118
+ initChild('Chip__`)
119
+ expect(js).toContain(`{ const __e = qsa(childScope, '[bf="^s3"]'); if (__e) __e.addEventListener('click', () => setPicked(id + i)) }`)
120
+ })
121
+
122
+ test('the direct-child row keeps its delegated dispatcher (control)', () => {
123
+ const js = clientJsOf(
124
+ '{rows().map(o => (<div key={o.id}><button onClick={() => pick(o.id)}>{o.label}</button></div>))}',
125
+ )
126
+ expect(js).toContain(`const s3El = target.closest('[bf="s3"]')`)
127
+ expect(js).toContain(';(() => pick(o.id))(__bfEvt)')
128
+ })
129
+ })
@@ -0,0 +1,74 @@
1
+ /**
2
+ * #3595: an inner `.map()` in a loop-row child component's forwarded
3
+ * children rebinds a name the outer row binds. The forwarded children are
4
+ * rewritten with the outer row's accessor (`wrapLoopParamAsAccessor`), and
5
+ * that rewrite once turned the inner callback's PARAMETER into the outer
6
+ * accessor: `o().tags.map((tag, i()) => …)`, a SyntaxError ("Invalid binding
7
+ * pattern") in the emitted client JS. The rewrite now follows the shared
8
+ * lexical-scope walk (`walkWithScope`): the binder is never rewritten and
9
+ * the references it shadows read the inner binding, while references
10
+ * outside the inner callback still read the outer row's accessor.
11
+ *
12
+ * Conformance coverage: `loop-row-child-children-inner-loop-shadow`.
13
+ */
14
+
15
+ import { describe, test, expect } from 'bun:test'
16
+ import ts from 'typescript'
17
+ import { compileJSX } from '../compiler'
18
+ import { TestAdapter } from '../adapters/test-adapter'
19
+
20
+ const adapter = new TestAdapter()
21
+
22
+ function clientJsOf(row: string, mapParams: string): string {
23
+ const source = `
24
+ 'use client'
25
+ function Chip({ children }: { children?: any }) {
26
+ return <span class="chip">{children}</span>
27
+ }
28
+ type Row = { id: string; tags: string[] }
29
+ export function Shadow(props: { rows: Row[] }) {
30
+ return <p>{props.rows.map((${mapParams}) => (${row}))}</p>
31
+ }
32
+ `
33
+ const result = compileJSX(source, 'Shadow.tsx', { adapter })
34
+ expect(result.errors.filter(e => e.severity === 'error')).toHaveLength(0)
35
+ const js = result.files.find(f => f.type === 'clientJs')!.content
36
+ const diagnostics = ts.transpileModule(js, {
37
+ reportDiagnostics: true,
38
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.Latest },
39
+ }).diagnostics ?? []
40
+ expect(diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error)).toHaveLength(0)
41
+ return js
42
+ }
43
+
44
+ describe('inner loop in forwarded loop-row children shadows the outer row (#3595)', () => {
45
+ test('an inner index named like the outer index keeps its binder and is read plain', () => {
46
+ const js = clientJsOf(
47
+ '<Chip key={o.id}><em>{i}</em><ul>{o.tags.map((tag, i) => <li key={tag}>{tag}-{i}</li>)}</ul></Chip>',
48
+ 'o, i',
49
+ )
50
+ expect(js).toContain('o().tags.map((tag, i) => `<li data-key-1="${escapeAttr(tag)}">')
51
+ expect(js).toContain('-<!--bf:^s2-->${escapeText(i)}<!--/--></li>')
52
+ // Outside the inner callback the name is still the outer row's index.
53
+ expect(js).toContain('<em><!--bf:^s0-->${escapeText(i())}<!--/--></em>')
54
+ expect(js).not.toContain('i()) =>')
55
+ })
56
+
57
+ test('an inner item named like the outer item reads the inner item', () => {
58
+ const js = clientJsOf(
59
+ '<Chip key={o.id}><ul>{o.tags.map((o) => <li key={o}>{o}</li>)}</ul></Chip>',
60
+ 'o',
61
+ )
62
+ expect(js).toContain('o().tags.map((o) => `<li data-key-1="${escapeAttr(o)}"><!--bf:^s0-->${escapeText(o)}<!--/--></li>`)')
63
+ expect(js).not.toContain('(o()) =>')
64
+ })
65
+
66
+ test('an inner param named like an outer destructured binding reads the inner param', () => {
67
+ const js = clientJsOf(
68
+ '<Chip key={id}><ul>{tags.map((id, i) => <li key={id}>{id}-{i}</li>)}</ul></Chip>',
69
+ '{ id, tags }, i',
70
+ )
71
+ expect(js).toContain('__bfItem().tags.map((id, i) => `<li data-key-1="${escapeAttr(id)}"><!--bf:^s0-->${escapeText(id)}<!--/-->-<!--bf:^s1-->${escapeText(i)}<!--/--></li>`)')
72
+ expect(js).not.toContain('__bfItem().id, i')
73
+ })
74
+ })
@@ -0,0 +1,117 @@
1
+ /**
2
+ * #3612: a `ref` callback on an element forwarded as a loop-row child
3
+ * component's own `children` (`<Chip key={o.id}><input ref={…}/></Chip>`).
4
+ * `collectLoopChildBindings` collects the ref into the loop's
5
+ * `bindings.refs` and the component-root loop builder resolves it into the
6
+ * plan's `childRefs`, but `stringifyComponentLoop` never emitted them — so
7
+ * the callback never ran. Each row (hydrated and client-built) now invokes
8
+ * them against its own element, the same per-row ref call the composite row
9
+ * uses. The static-array twin already invoked them through the static
10
+ * loop's own ref pass.
11
+ *
12
+ * Conformance coverage: `loop-row-child-children-ref`.
13
+ */
14
+
15
+ import { describe, test, expect } from 'bun:test'
16
+ import ts from 'typescript'
17
+ import { compileJSX } from '../compiler'
18
+ import { TestAdapter } from '../adapters/test-adapter'
19
+
20
+ const adapter = new TestAdapter()
21
+
22
+ function compileClientJs(source: string): string {
23
+ const result = compileJSX(source, 'Picker.tsx', { adapter })
24
+ expect(result.errors.filter(e => e.severity === 'error')).toHaveLength(0)
25
+ const js = result.files.find(f => f.type === 'clientJs')!.content
26
+ const diagnostics = ts.transpileModule(js, {
27
+ reportDiagnostics: true,
28
+ compilerOptions: { module: ts.ModuleKind.ESNext, target: ts.ScriptTarget.Latest },
29
+ }).diagnostics ?? []
30
+ expect(diagnostics.filter(d => d.category === ts.DiagnosticCategory.Error)).toHaveLength(0)
31
+ return js
32
+ }
33
+
34
+ function clientJsOf(body: string): string {
35
+ return compileClientJs(`
36
+ 'use client'
37
+ import { createSignal } from '@barefootjs/client'
38
+ function Chip({ children }: { children?: any }) {
39
+ return <span class="chip">{children}</span>
40
+ }
41
+ export function Picker() {
42
+ const [rows, setRows] = createSignal([{ id: 'a', label: 'A' }])
43
+ const register = (id: string, el: HTMLElement) => { el.addEventListener('click', () => console.log(id)) }
44
+ return <div>${body}</div>
45
+ }
46
+ `)
47
+ }
48
+
49
+ /** The per-row ref call, as made on the hydrated and the client-built row. */
50
+ function rowRef(elVar: '__existing' | '__csrEl', slot: string, callback: string): string {
51
+ return `{ const __rf_${slot} = qsa(${elVar}, '[bf="^${slot}"]')\n${elVar === '__existing' ? ' ' : ' '}if (__rf_${slot}) (${callback})?.(__rf_${slot}) }`
52
+ }
53
+
54
+ describe('ref callback in forwarded loop-row child children (#3612)', () => {
55
+ test('a ref reading the row item runs on the hydrated and the client-built row', () => {
56
+ const js = clientJsOf('{rows().map(o => (<Chip key={o.id}><input ref={el => register(o.id, el)} /></Chip>))}')
57
+ const hydrated = rowRef('__existing', 's0', 'el => register(o().id, el)')
58
+ const created = rowRef('__csrEl', 's0', 'el => register(o().id, el)')
59
+ expect(js).toContain(hydrated)
60
+ expect(js).toContain(created)
61
+ // A ref-only row leaves the simple renderItem shape, and the call comes
62
+ // after the row component is initialised / created.
63
+ expect(js).not.toContain('if (__existing) { initChild(')
64
+ expect(js.indexOf(hydrated)).toBeGreaterThan(js.indexOf(`initChild('Chip`))
65
+ expect(js.indexOf(created)).toBeGreaterThan(js.indexOf('const __csrEl = createComponent('))
66
+ })
67
+
68
+ test('a ref reading the row index reads it through the accessor', () => {
69
+ const js = clientJsOf('{rows().map((o, i) => (<Chip key={o.id}><input ref={el => register(o.id + i, el)} /></Chip>))}')
70
+ expect(js).toContain(rowRef('__existing', 's0', 'el => register(o().id + i(), el)'))
71
+ expect(js).toContain(rowRef('__csrEl', 's0', 'el => register(o().id + i(), el)'))
72
+ })
73
+
74
+ test('a ref on a nested element reading destructured row bindings reads the row item accessor', () => {
75
+ const js = clientJsOf(
76
+ '{rows().map(({ id, label }, i) => (<Chip key={id}><label>{label}<input ref={el => register(id + i, el)} /></label></Chip>))}',
77
+ )
78
+ expect(js).toContain(rowRef('__existing', 's1', 'el => register(__bfItem().id + i(), el)'))
79
+ expect(js).toContain(rowRef('__csrEl', 's1', 'el => register(__bfItem().id + i(), el)'))
80
+ })
81
+
82
+ test('a ref beside a forwarded handler runs after the handler is attached', () => {
83
+ const js = clientJsOf(
84
+ '{rows().map(o => (<Chip key={o.id}><button onClick={() => register(o.id, document.body)}>x</button><input ref={el => register(o.id, el)} /></Chip>))}',
85
+ )
86
+ const hydratedRef = rowRef('__existing', 's1', 'el => register(o().id, el)')
87
+ expect(js).toContain(hydratedRef)
88
+ expect(js.indexOf(hydratedRef)).toBeGreaterThan(js.indexOf(`{ const __e = qsa(__existing, '[bf="^s0"]')`))
89
+ })
90
+
91
+ test('a module-const array invokes the ref on each row, unwrapped (control)', () => {
92
+ const js = compileClientJs(`
93
+ 'use client'
94
+ function Chip({ children }: { children?: any }) {
95
+ return <span class="chip">{children}</span>
96
+ }
97
+ const OPTS = [{ id: 'a' }]
98
+ export function Picker() {
99
+ const register = (id: string, el: HTMLElement) => { el.addEventListener('click', () => console.log(id)) }
100
+ return <div>{OPTS.map((o, i) => (<Chip key={o.id}><input ref={el => register(o.id + i, el)} /></Chip>))}</div>
101
+ }
102
+ `)
103
+ expect(js).toContain(`if (__rf_s0) (el => register(o.id + i, el))?.(__rf_s0) }`)
104
+ expect(js).not.toContain('o().id')
105
+ })
106
+
107
+ test("a ref inside a non-loop child component's children runs once (control)", () => {
108
+ const js = clientJsOf('<Chip><input ref={el => register("x", el)} /></Chip>')
109
+ expect(js).toContain(`if (_s0) (el => register("x", el))?.(_s0)`)
110
+ })
111
+
112
+ test('a ref on the row component element itself is passed as a prop (control)', () => {
113
+ const js = clientJsOf('{rows().map(o => (<Chip key={o.id} ref={el => register(o.id, el)}><b>x</b></Chip>))}')
114
+ expect(js).toContain('get ref() { return el => register(o().id, el) }')
115
+ expect(js).not.toContain('__rf_')
116
+ })
117
+ })
@@ -3,7 +3,9 @@ import { analyzeComponent } from '../analyzer'
3
3
  import { parseExpression } from '../expression-parser'
4
4
  import {
5
5
  arithmeticOperandCoercion,
6
+ arithmeticOperandIsUndefined,
6
7
  attrValueMayBeNullish,
8
+ collectAbsentPropSeedReads,
7
9
  collectNullableSignalGetters,
8
10
  collectNullishAttrContext,
9
11
  nullableSignalAttrGetter,
@@ -50,6 +52,47 @@ describe('collectNullableSignalGetters (#3304)', () => {
50
52
  })
51
53
  })
52
54
 
55
+ function componentIR(params: string, decls: string): ComponentIR {
56
+ const source = `
57
+ 'use client'
58
+ import { createSignal } from '@barefootjs/client'
59
+ export function C(${params}) {
60
+ ${decls}
61
+ return <p>x</p>
62
+ }
63
+ `
64
+ return { metadata: analyzeComponent(source, 'C.tsx') } as unknown as ComponentIR
65
+ }
66
+
67
+ describe('signals seeded from an absent optional prop (#3567)', () => {
68
+ test('a bare read, a ternary branch and a `??` right operand are nullable', () => {
69
+ const ir = componentIR('props: { a?: string; b?: string; c?: string }', `
70
+ const [bare] = createSignal(props.a)
71
+ const [branch] = createSignal(props.a === 'x' ? props.b : 'y')
72
+ const [fallback] = createSignal(props.a ?? props.c)
73
+ `)
74
+ expect([...collectNullableSignalGetters(ir)].sort()).toEqual(['bare', 'branch', 'fallback'])
75
+ expect(collectAbsentPropSeedReads(ir).get('branch')).toEqual(new Set(['b']))
76
+ expect(collectAbsentPropSeedReads(ir).get('fallback')).toEqual(new Set(['c']))
77
+ })
78
+
79
+ test('destructured params are read by their binding name', () => {
80
+ const ir = componentIR('{ label }: { label?: string }', 'const [shown] = createSignal(label)')
81
+ expect([...collectNullableSignalGetters(ir)]).toEqual(['shown'])
82
+ })
83
+
84
+ test('a required prop, a defaulted prop, a `??` left operand or a value built from the prop is not', () => {
85
+ const ir = componentIR("{ req, def = 'd', opt }: { req: string; def?: string; opt?: string }", `
86
+ const [a] = createSignal(req)
87
+ const [b] = createSignal(def)
88
+ const [c] = createSignal(opt ?? 'x')
89
+ const [d] = createSignal(opt === 'x')
90
+ const [e] = createSignal(\`\${opt}\`)
91
+ `)
92
+ expect([...collectNullableSignalGetters(ir)]).toEqual([])
93
+ })
94
+ })
95
+
53
96
  describe('nullableSignalAttrGetter (#3304)', () => {
54
97
  const nullable = new Set(['s'])
55
98
 
@@ -141,14 +184,35 @@ describe('arithmeticOperandCoercion (#3474)', () => {
141
184
  arithmeticOperandCoercion(op, parseExpression(operand), parseExpression(other), ctx)
142
185
 
143
186
  test('a nullable number prop reads as null under every arithmetic operator, + with a number included', () => {
144
- const ctx = ctxOf('props: { a: number | null; b?: number; c: number; d: string | null }')
187
+ const ctx = ctxOf('props: { a: number | null; c: number; d: string | null }')
145
188
  for (const op of ['-', '*', '/', '%', '**']) expect(coercion(ctx, op, 'props.a', 'x')).toBe('null')
146
189
  expect(coercion(ctx, '+', 'props.a', '1')).toBe('null')
147
- expect(coercion(ctx, '+', 'props.b', '-2')).toBe('null')
148
190
  expect(coercion(ctx, '*', 'props.c', '2')).toBeNull()
149
191
  expect(coercion(ctx, '*', 'props.d', '2')).toBeNull()
150
192
  })
151
193
 
194
+ test('a number prop that can only be absent reads its nil as undefined (#3533)', () => {
195
+ const ctx = ctxOf('props: { b?: number; u: number | undefined; both?: number | null }')
196
+ for (const op of ['-', '*', '/', '%', '**']) expect(coercion(ctx, op, 'props.b', 'x')).toBe('undefined')
197
+ expect(coercion(ctx, '+', 'props.b', '-2')).toBe('undefined')
198
+ expect(coercion(ctx, '*', 'props.u', '2')).toBe('undefined')
199
+ // A type that admits both keeps the null reading: its nil can be either.
200
+ expect(coercion(ctx, '*', 'props.both', '2')).toBe('null')
201
+ })
202
+
203
+ test('unary minus passes no other operand and coerces like binary minus (#3533)', () => {
204
+ const ctx = ctxOf('props: { a: number | null; b?: number; c: number }')
205
+ const unary = (operand: string) => arithmeticOperandCoercion('-', parseExpression(operand), undefined, ctx)
206
+ expect(unary('props.a')).toBe('null')
207
+ expect(unary('props.b')).toBe('undefined')
208
+ expect(unary('props.c')).toBeNull()
209
+ })
210
+
211
+ test('an absent-only prop is not certainly undefined: arithmeticOperandIsUndefined stays false', () => {
212
+ const ctx = ctxOf('props: { b?: number }')
213
+ expect(arithmeticOperandIsUndefined(parseExpression('props.b'), ctx)).toBe(false)
214
+ })
215
+
152
216
  test('+ is left alone unless the other operand is a number: it may concatenate', () => {
153
217
  const ctx = ctxOf('props: { a: number | null }', 'const [n] = createSignal<number | null>(null)')
154
218
  expect(coercion(ctx, '+', 'props.a', 'label')).toBeNull()
@@ -158,7 +222,7 @@ describe('arithmeticOperandCoercion (#3474)', () => {
158
222
 
159
223
  test('a destructured nullable number prop, and a shadowed one', () => {
160
224
  const ctx = ctxOf('{ a }: { a?: number }')
161
- expect(coercion(ctx, '*', 'a', '2')).toBe('null')
225
+ expect(coercion(ctx, '*', 'a', '2')).toBe('undefined')
162
226
  expect(arithmeticOperandCoercion('*', parseExpression('a'), parseExpression('2'), ctx, n => n === 'a')).toBeNull()
163
227
  })
164
228
 
@@ -1,6 +1,7 @@
1
1
  import { describe, expect, test } from 'bun:test'
2
2
  import { analyzeComponent } from '../analyzer.ts'
3
- import { isPropsAliasConst } from '../props-binding.ts'
3
+ import { isPropsAliasConst, isRenamedBodyPropParam } from '../props-binding.ts'
4
+ import { isChildrenPropParam } from '../types.ts'
4
5
 
5
6
  /**
6
7
  * Whether a const reads as its own prop (#3501): a bare `props.X` read, or
@@ -63,3 +64,61 @@ describe('isPropsAliasConst', () => {
63
64
  expect(isPropsAliasConst(constOf('const label = props.label').c, null)).toBe(false)
64
65
  })
65
66
  })
67
+
68
+ /**
69
+ * Whether a renamed body destructure binding reads as a prop under its local
70
+ * name (#3579): only one with a default, which the analyzer gives its own
71
+ * `ParamInfo` (`name: other`, `sourceName: label`).
72
+ */
73
+ describe('isRenamedBodyPropParam', () => {
74
+ function renamedOf(body: string, name: string): boolean {
75
+ const ctx = analyzeComponent(
76
+ `'use client'\nexport function S(props: { label?: string; text?: string }) {\n ${body}\n return <p>{${name}}</p>\n}`,
77
+ 'S.tsx',
78
+ )
79
+ return isRenamedBodyPropParam(ctx.localConstants.find(x => x.name === name)!, ctx.propsParams)
80
+ }
81
+
82
+ test('a renamed binding with a default is the prop under its local name', () => {
83
+ expect(renamedOf("const { label: other = 'Default' } = props", 'other')).toBe(true)
84
+ expect(renamedOf("const { label: other = ['y', ''].filter((x) => x !== '').join() } = props", 'other')).toBe(true)
85
+ })
86
+
87
+ test('a renamed let binding is not, reassigned or not', () => {
88
+ expect(renamedOf("let { label: other = 'Default' } = props", 'other')).toBe(false)
89
+ expect(renamedOf("let { label: other = 'Default' } = props\n other = other + '!'", 'other')).toBe(false)
90
+ })
91
+
92
+ test('a renamed binding mutated in place is not', () => {
93
+ expect(renamedOf("const { label: other = ['x'] } = props\n other.push('y')", 'other')).toBe(false)
94
+ })
95
+
96
+ test('a renamed binding without a default is not', () => {
97
+ expect(renamedOf('const { label: other } = props', 'other')).toBe(false)
98
+ })
99
+
100
+ test('an un-renamed binding is left to isPropsAliasConst', () => {
101
+ expect(renamedOf("const { label = 'Default' } = props", 'label')).toBe(false)
102
+ })
103
+
104
+ test('a renamed binding named like another prop does not take that prop entry', () => {
105
+ // `text` is also a type member, so the analyzer adds no entry for the
106
+ // renamed binding, and `text`'s own entry reads `props.text`.
107
+ expect(renamedOf("const { label: text = 'Default' } = props", 'text')).toBe(false)
108
+ })
109
+
110
+ test('a hand-written `?? default` const is not', () => {
111
+ expect(renamedOf("const other = props.label ?? 'Default'", 'other')).toBe(false)
112
+ })
113
+
114
+ test('a renamed binding of the children prop reads as the children prop', () => {
115
+ const ctx = analyzeComponent(
116
+ "'use client'\nexport function S(props: { children?: unknown }) {\n const { children: kids = 'none' } = props\n return <p>{kids}</p>\n}",
117
+ 'S.tsx',
118
+ )
119
+ const kids = ctx.localConstants.find(x => x.name === 'kids')!
120
+ expect(isRenamedBodyPropParam(kids, ctx.propsParams)).toBe(true)
121
+ const entry = ctx.propsParams.find(p => p.name === 'kids')!
122
+ expect(isChildrenPropParam(entry)).toBe(true)
123
+ })
124
+ })