@barefootjs/jsx 0.39.8 → 0.40.0

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 (118) hide show
  1. package/dist/adapters/attr-plan.d.ts +1 -20
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +19 -7
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +79 -1
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-plan.d.ts +173 -9
  8. package/dist/adapters/loop-plan.d.ts.map +1 -1
  9. package/dist/adapters/parsed-expr-emitter.d.ts +20 -3
  10. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  11. package/dist/analyzer.d.ts.map +1 -1
  12. package/dist/assignment-target.d.ts +26 -0
  13. package/dist/assignment-target.d.ts.map +1 -0
  14. package/dist/augment-inherited-props.d.ts.map +1 -1
  15. package/dist/css-layer-prefixer.d.ts.map +1 -1
  16. package/dist/debug.d.ts.map +1 -1
  17. package/dist/errors.d.ts +1 -0
  18. package/dist/errors.d.ts.map +1 -1
  19. package/dist/index.d.ts +6 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +2566 -2007
  22. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  25. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  27. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  29. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  31. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/props-extraction.d.ts +5 -3
  35. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  37. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  40. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/utils.d.ts +1 -1
  42. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  43. package/dist/jsx-to-ir.d.ts.map +1 -1
  44. package/dist/module-exports.d.ts.map +1 -1
  45. package/dist/prop-rewrite.d.ts +17 -8
  46. package/dist/prop-rewrite.d.ts.map +1 -1
  47. package/dist/props-binding.d.ts +57 -0
  48. package/dist/props-binding.d.ts.map +1 -1
  49. package/dist/scope/binding-scope.d.ts +32 -2
  50. package/dist/scope/binding-scope.d.ts.map +1 -1
  51. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  52. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  53. package/dist/template-parts.d.ts +1 -1
  54. package/dist/template-parts.d.ts.map +1 -1
  55. package/dist/types.d.ts +30 -2
  56. package/dist/types.d.ts.map +1 -1
  57. package/package.json +2 -2
  58. package/src/__tests__/arithmetic-lowering.test.ts +5 -1
  59. package/src/__tests__/attr-plan.test.ts +1 -14
  60. package/src/__tests__/binding-scope.test.ts +29 -0
  61. package/src/__tests__/client-template-escape-soundness.test.ts +17 -4
  62. package/src/__tests__/client-template-static-delimiters.test.ts +57 -0
  63. package/src/__tests__/create-query.test.ts +1 -1
  64. package/src/__tests__/dsl-template-adapter.test.ts +70 -0
  65. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  66. package/src/__tests__/extract-function-params.test.ts +37 -0
  67. package/src/__tests__/issue-2960-multi-root-cond-same-tag.test.ts +18 -0
  68. package/src/__tests__/jsx-text-linebreak-whitespace.test.ts +11 -0
  69. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  70. package/src/__tests__/loop-plan.test.ts +196 -1
  71. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  72. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  73. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  74. package/src/__tests__/props-alias-const.test.ts +60 -1
  75. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  76. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  77. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  78. package/src/__tests__/template-parts-literal-boundary.test.ts +22 -0
  79. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  80. package/src/adapters/attr-plan.ts +2 -54
  81. package/src/adapters/callback-method.ts +25 -10
  82. package/src/adapters/dsl-template-adapter.ts +155 -2
  83. package/src/adapters/loop-plan.ts +267 -14
  84. package/src/adapters/parsed-expr-emitter.ts +37 -4
  85. package/src/analyzer.ts +283 -2
  86. package/src/assignment-target.ts +79 -0
  87. package/src/augment-inherited-props.ts +5 -9
  88. package/src/css-layer-prefixer.ts +4 -5
  89. package/src/debug.ts +1 -0
  90. package/src/errors.ts +11 -0
  91. package/src/index.ts +23 -4
  92. package/src/ir-to-client-js/compute-inlinability.ts +7 -4
  93. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  94. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  95. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  96. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  97. package/src/ir-to-client-js/csr-substitute.ts +70 -22
  98. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  99. package/src/ir-to-client-js/emit-registration.ts +6 -1
  100. package/src/ir-to-client-js/html-template.ts +70 -52
  101. package/src/ir-to-client-js/phases/props-extraction.ts +26 -5
  102. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  103. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  104. package/src/ir-to-client-js/rewrite-destructured-props.ts +2 -2
  105. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  106. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  107. package/src/ir-to-client-js/utils.ts +41 -97
  108. package/src/jsx-to-ir.ts +65 -32
  109. package/src/loop-destructure.ts +4 -1
  110. package/src/module-exports.ts +13 -21
  111. package/src/prop-rewrite.ts +31 -72
  112. package/src/props-binding.ts +73 -1
  113. package/src/rich-type-refusal.ts +3 -1
  114. package/src/scope/binding-scope.ts +39 -3
  115. package/src/scope/lexical-scope-walk.ts +167 -0
  116. package/src/template-parts.ts +4 -2
  117. package/src/template-position-walk.ts +3 -1
  118. package/src/types.ts +27 -2
@@ -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
+ })
@@ -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
+ })
@@ -0,0 +1,256 @@
1
+ /**
2
+ * Callback parameters spelled like the props object in the CSR client JS.
3
+ *
4
+ * The init body reads the component's props through `_p`, and a
5
+ * destructured prop read compiles to `_p.<prop>`. The props-object rename
6
+ * (`rewritePropsObjectRef`) used to rename EVERY `props` identifier in the
7
+ * init body, binders included, so a `.map((props) => …)` row, a handler
8
+ * `(props) => …` arrow, a `.filter((props) => …)` callback or a nested
9
+ * `function f(props)` became a `_p` binding that captured the outer
10
+ * `_p.<prop>` reads inside it: a client-created row lost its `suffix`, a
11
+ * forwarded child prop read the row accessor, and `props.by * step` became
12
+ * `NaN`. Fixture: `loop-param-named-props`.
13
+ */
14
+ import { describe, test, expect } from 'bun:test'
15
+ import { compileJSX } from '../compiler'
16
+ import { TestAdapter } from '../adapters/test-adapter'
17
+ import { rewriteScopedValueRefs } from '../prop-rewrite'
18
+
19
+ const adapter = new TestAdapter()
20
+
21
+ function clientJs(source: string): string {
22
+ const result = compileJSX(source, 'Repro.tsx', { adapter })
23
+ expect(result.errors.filter(e => e.severity === 'error')).toHaveLength(0)
24
+ return result.files.find(f => f.type === 'clientJs')!.content
25
+ }
26
+
27
+ /** An `init<Name>` function body (excludes the module-level template lambda). */
28
+ function initBody(content: string, name = ''): string {
29
+ const start = content.indexOf(`export function init${name}`)
30
+ const end = content.indexOf('\nhydrate(', start)
31
+ return content.slice(start, end)
32
+ }
33
+
34
+ describe('a callback param named `props` keeps its binding in the client JS', () => {
35
+ test('destructured props: a reactive loop row reads the outer prop through `_p`', () => {
36
+ const body = initBody(clientJs(`
37
+ "use client";
38
+ import { createSignal } from '@barefootjs/client'
39
+ export function Rows({ suffix }: { suffix: string }) {
40
+ const [items, setItems] = createSignal([{ id: 1, label: 'a' }])
41
+ return (
42
+ <div>
43
+ <ul>{items().map((props) => <li key={props.id}>{props.label}{suffix}</li>)}</ul>
44
+ <button onClick={() => setItems([...items(), { id: 2, label: 'b' }])}>add</button>
45
+ </div>
46
+ )
47
+ }
48
+ `))
49
+ expect(body).toContain('const props = () => __e.item')
50
+ expect(body).toContain('props().label')
51
+ expect(body).toContain('_p.suffix')
52
+ expect(body).not.toMatch(/const _p = /)
53
+ expect(body).not.toContain('_p().')
54
+ })
55
+
56
+ test('a child component forwarded inside the row reads the outer prop, not the row', () => {
57
+ const body = initBody(clientJs(`
58
+ "use client";
59
+ import { createSignal } from '@barefootjs/client'
60
+ function Item(props: { label: string; mark: string }) { return <li>{props.label}{props.mark}</li> }
61
+ export function List({ mark }: { mark: string }) {
62
+ const [items, setItems] = createSignal([{ label: 'a' }])
63
+ return (
64
+ <div>
65
+ <ul>{items().map((props) => <Item key={props.label} label={props.label} mark={mark} />)}</ul>
66
+ <button onClick={() => setItems([...items(), { label: 'b' }])}>add</button>
67
+ </div>
68
+ )
69
+ }
70
+ `), 'List')
71
+ expect(body).toContain('get mark() { return _p.mark }')
72
+ expect(body).toContain('get label() { return props().label }')
73
+ })
74
+
75
+ test('props object: an inlined outer read inside a `props` row stays on `_p`', () => {
76
+ const body = initBody(clientJs(`
77
+ "use client";
78
+ import { createSignal } from '@barefootjs/client'
79
+ export function Rows(props: { title: string }) {
80
+ const t = props.title
81
+ const [items, setItems] = createSignal([{ id: 1 }])
82
+ return (
83
+ <div>
84
+ <ul>{items().map((props) => <li key={props.id}>{props.id}{t}</li>)}</ul>
85
+ <button onClick={() => setItems([...items(), { id: 2 }])}>add</button>
86
+ </div>
87
+ )
88
+ }
89
+ `))
90
+ expect(body).toContain('const props = () => __e.item')
91
+ expect(body).toContain('_p.title')
92
+ expect(body).not.toMatch(/const _p = /)
93
+ })
94
+
95
+ test('a handler arrow param and a filter callback param keep their names', () => {
96
+ const body = initBody(clientJs(`
97
+ "use client";
98
+ import { createSignal } from '@barefootjs/client'
99
+ export function Counter({ step }: { step: number }) {
100
+ const [n, setN] = createSignal(0)
101
+ const [items, setItems] = createSignal([{ id: 1 }, { id: 2 }])
102
+ const bump = (props: { by: number }) => setN(n() + props.by * step)
103
+ return (
104
+ <div>
105
+ <button onClick={() => bump({ by: 2 })}>{n()}</button>
106
+ <button onClick={() => setItems(items().filter((props) => props.id !== step))}>{items().length}</button>
107
+ </div>
108
+ )
109
+ }
110
+ `))
111
+ expect(body).toContain('const bump = (props) => setN(n() + props.by * _p.step)')
112
+ expect(body).toContain('.filter((props) => props.id !== _p.step)')
113
+ })
114
+
115
+ test('a nested function param keeps its name', () => {
116
+ const body = initBody(clientJs(`
117
+ "use client";
118
+ import { createSignal } from '@barefootjs/client'
119
+ export function Say({ suffix }: { suffix: string }) {
120
+ const [last, setLast] = createSignal('')
121
+ function describe(props: { label: string }) { return props.label + suffix }
122
+ return <button onClick={() => setLast(describe({ label: 'x' }))}>{last()}</button>
123
+ }
124
+ `))
125
+ expect(body).toContain('props.label + _p.suffix')
126
+ })
127
+
128
+ test('a free `props` read in a destructured component is still renamed', () => {
129
+ const body = initBody(clientJs(`
130
+ "use client";
131
+ import { createSignal } from '@barefootjs/client'
132
+ export function Free({ id }: { id: string }) {
133
+ const [n, setN] = createSignal(0)
134
+ return <button data-id={id} onClick={() => setN(n() + (props as any).delta)}>{n()}</button>
135
+ }
136
+ `))
137
+ expect(body).toContain('(_p).delta')
138
+ })
139
+ })
140
+
141
+ describe('a `var` binds in its whole function, not just its block', () => {
142
+ test('a `var props` in a nested block shadows the props rename for the whole handler', () => {
143
+ const body = initBody(clientJs(`
144
+ "use client";
145
+ import { createSignal } from '@barefootjs/client'
146
+ export function A({ step }: { step: number }) {
147
+ const [n, setN] = createSignal(0)
148
+ return <button onClick={() => { if (step > 0) { var props = { by: 2 } } setN(n() + props.by * step) }}>{n()}</button>
149
+ }
150
+ `))
151
+ expect(body).toContain('{ var props = { by: 2 } } setN(n() + props.by * _p.step)')
152
+ })
153
+
154
+ test('a `for (var props …)` head shadows the props rename after the loop', () => {
155
+ const body = initBody(clientJs(`
156
+ "use client";
157
+ import { createSignal } from '@barefootjs/client'
158
+ export function B({ step }: { step: number }) {
159
+ const [n, setN] = createSignal(0)
160
+ return <button onClick={() => { for (var props = 0; props < step; props++) {} setN(n() + props) }}>{n()}</button>
161
+ }
162
+ `))
163
+ expect(body).toContain('for (var props = 0; props < _p.step; props++) {} setN(n() + props)')
164
+ })
165
+
166
+ test('a block-nested `var` named like a destructured prop is not rewritten to the prop', () => {
167
+ const body = initBody(clientJs(`
168
+ "use client";
169
+ import { createSignal } from '@barefootjs/client'
170
+ export function C({ step }: { step: number }) {
171
+ const [n, setN] = createSignal(0)
172
+ return <button data-step={step} onClick={() => { if (n() >= 0) { var step = 5 } setN(n() + step) }}>{n()}</button>
173
+ }
174
+ `))
175
+ expect(body).toContain('{ var step = 5 } setN(n() + step)')
176
+ })
177
+
178
+ test('a `let` in a nested block still binds only inside that block', () => {
179
+ const body = initBody(clientJs(`
180
+ "use client";
181
+ import { createSignal } from '@barefootjs/client'
182
+ export function D({ step }: { step: number }) {
183
+ const [n, setN] = createSignal(0)
184
+ return <button onClick={() => { if (n() >= 0) { let step = 5; setN(step) } setN(n() + step) }}>{n()}</button>
185
+ }
186
+ `))
187
+ expect(body).toContain('{ let step = 5; setN(step) } setN(n() + _p.step)')
188
+ })
189
+ })
190
+
191
+ describe('the Phase-1 prop rewrite shares the same `var` scoping', () => {
192
+ const toProp = (name: string) => `_p.${name}`
193
+ test('a block-nested `var` binds for the whole arrow', () => {
194
+ const out = rewriteScopedValueRefs('() => { if (c) { var step = 5 } return step }', new Set(['step']), toProp)
195
+ expect(out).toBe('() => { if (c) { var step = 5 } return step }')
196
+ })
197
+
198
+ test('a `for (var …)` head binds after the loop', () => {
199
+ const out = rewriteScopedValueRefs('() => { for (var step = 0; step < 3; step++) {} return step }', new Set(['step']), toProp)
200
+ expect(out).toBe('() => { for (var step = 0; step < 3; step++) {} return step }')
201
+ })
202
+
203
+ test('a `let` stays block-scoped', () => {
204
+ const out = rewriteScopedValueRefs('() => { if (c) { let step = 5 } return step }', new Set(['step']), toProp)
205
+ expect(out).toBe('() => { if (c) { let step = 5 } return _p.step }')
206
+ })
207
+ })
208
+
209
+ describe('a parameter default does not see the body\'s declarations', () => {
210
+ const toProp = (name: string) => `_p.${name}`
211
+ test('Phase-1 rewrite: a default reads the prop despite a same-named body `var`', () => {
212
+ const out = rewriteScopedValueRefs('(value = step) => { var step = 0; return value }', new Set(['step']), toProp)
213
+ expect(out).toBe('(value = _p.step) => { var step = 0; return value }')
214
+ })
215
+
216
+ test('Phase-1 rewrite: a default reads the prop despite a same-named body `let`', () => {
217
+ const out = rewriteScopedValueRefs('(value = step) => { let step = 0; return value + step }', new Set(['step']), toProp)
218
+ expect(out).toBe('(value = _p.step) => { let step = 0; return value + step }')
219
+ })
220
+
221
+ test('a handler-local arrow whose default reads a destructured prop shadowed in its body', () => {
222
+ const body = initBody(clientJs(`
223
+ "use client";
224
+ import { createSignal } from '@barefootjs/client'
225
+ export function E({ step }: { step: number }) {
226
+ const [n, setN] = createSignal(0)
227
+ return <button onClick={() => { const f = (value = step) => { var step = 0; return value + step }; setN(f()) }}>{n()}</button>
228
+ }
229
+ `))
230
+ expect(body).toContain('const f = (value = _p.step) => { var step = 0; return value + step }')
231
+ })
232
+ })
233
+
234
+ describe('a class static block owns its `var`s', () => {
235
+ const toProp = (name: string) => `_p.${name}`
236
+ test('Phase-1 rewrite: a read inside the static block is local, a read after the class is the prop', () => {
237
+ const out = rewriteScopedValueRefs(
238
+ '() => { class C { static { var step = 0; C.s = step } }; return step }',
239
+ new Set(['step']),
240
+ toProp,
241
+ )
242
+ expect(out).toBe('() => { class C { static { var step = 0; C.s = step } }; return _p.step }')
243
+ })
244
+
245
+ test('a handler whose class static block declares a `var` named like a destructured prop', () => {
246
+ const body = initBody(clientJs(`
247
+ "use client";
248
+ import { createSignal } from '@barefootjs/client'
249
+ export function F({ step }: { step: number }) {
250
+ const [n, setN] = createSignal(0)
251
+ return <button onClick={() => { class C { static { var step = 0; C.s = step } }; setN(n() + step) }}>{n()}</button>
252
+ }
253
+ `))
254
+ expect(body).toContain('class C { static { var step = 0; C.s = step } }; setN(n() + _p.step)')
255
+ })
256
+ })
@@ -0,0 +1,86 @@
1
+ /**
2
+ * The client template reads a renamed body destructure binding that holds
3
+ * its prop (`const { b: local = d } = props`) as that prop with its default,
4
+ * like the parameter form (#3579). A binding that no longer holds the prop
5
+ * (a `let` reassigned before the return, a folded reassignment, a value
6
+ * mutated in place) stays a local: the template leaves its slot empty and
7
+ * defers a child that receives it, instead of reading `_p.b ?? d`.
8
+ *
9
+ * The reassigned shapes have no conformance fixture: the reference adapter
10
+ * itself drops the reassignment of a destructured binding, so these pin the
11
+ * client template only.
12
+ */
13
+
14
+ import { describe, test, expect } from 'bun:test'
15
+ import { compileJSX } from '../compiler'
16
+ import { TestAdapter } from '../adapters/test-adapter'
17
+
18
+ const adapter = new TestAdapter()
19
+ const transpiler = new Bun.Transpiler({ loader: 'js' })
20
+
21
+ const CHILD = 'function Child(props: { xs: string[] }) { return <i>{props.xs.length}</i> }'
22
+
23
+ /** The `template: (_p) => …` lambda the client registers for `C`. */
24
+ function templateOf(body: string, jsx: string, propsType = '{ b?: string[] | null }'): string {
25
+ const source = `
26
+ 'use client'
27
+ ${CHILD}
28
+ export function C(props: ${propsType}) {
29
+ ${body}
30
+ return ${jsx}
31
+ }
32
+ `
33
+ const result = compileJSX(source, 'C.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
+ expect(() => transpiler.transformSync(js)).not.toThrow()
37
+ const line = js.split('\n').find(l => l.includes("hydrate('C'") && l.includes('template: (_p) =>'))
38
+ expect(line).toBeDefined()
39
+ return line!
40
+ }
41
+
42
+ describe('renamed body destructure binding in the client template (#3579)', () => {
43
+ test('a default holding a callback reads the prop with its default', () => {
44
+ const t = templateOf("const { b: local = ['y', ''].filter((x) => x !== '') } = props", '<p>{local.length}</p>')
45
+ expect(t).toContain("_p.b ?? (['y', ''].filter((x) => x !== ''))")
46
+ expect(t).not.toContain("${''}")
47
+ })
48
+
49
+ test('a child prop holding it renders the child in place', () => {
50
+ const t = templateOf("const { b: local = ['y', ''].filter((x) => x !== '') } = props", '<p><Child xs={local} /></p>')
51
+ expect(t).toContain("renderChild('Child")
52
+ expect(t).not.toContain('data-bf-ph')
53
+ })
54
+
55
+ test('a let reassigned before the return keeps the child deferred', () => {
56
+ const t = templateOf("let { b: local = null } = props\n local = ['changed']", '<p><Child xs={local} /></p>')
57
+ expect(t).toContain('data-bf-ph')
58
+ expect(t).not.toContain('_p.b ?? null')
59
+ })
60
+
61
+ test('a let reassigned before the return is not read as the prop in text or an attribute', () => {
62
+ const t = templateOf("let { b: local = 'x' } = props\n local = local + '!'", '<p data-v={local}>{local}</p>', '{ b?: string }')
63
+ expect(t).not.toContain("_p.b ?? 'x'")
64
+ })
65
+
66
+ test('a folded conditional reassignment is not read as the prop', () => {
67
+ const t = templateOf("let { b: local = 'x' } = props\n if (!local) local = 'y'", '<p>{local}</p>', '{ b?: string }')
68
+ expect(t).not.toContain("_p.b ?? 'x'")
69
+ })
70
+
71
+ test('an un-renamed let reassigned before the return keeps the child deferred too', () => {
72
+ const t = templateOf("let { b = null } = props\n b = ['changed']", '<p><Child xs={b} /></p>')
73
+ expect(t).toContain('data-bf-ph')
74
+ expect(t).not.toContain('_p.b ?? null')
75
+ })
76
+
77
+ test('an un-renamed binding with a callback default renders the child in place', () => {
78
+ const t = templateOf("const { b = ['y', ''].filter((x) => x !== '') } = props", '<p><Child xs={b} /></p>')
79
+ expect(t).toContain("renderChild('Child")
80
+ })
81
+
82
+ test('a value mutated in place is not read as the prop', () => {
83
+ const t = templateOf("const { b: local = ['x'] } = props\n local.push('y')", '<p>{local.length}</p>', '{ b?: string[] }')
84
+ expect(t).not.toContain("_p.b ?? ['x']")
85
+ })
86
+ })