@barefootjs/jsx 0.39.7 → 0.39.8

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 (146) hide show
  1. package/dist/adapters/callback-method.d.ts +17 -0
  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 +151 -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/parsed-expr-emitter.d.ts +27 -0
  12. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  13. package/dist/adapters/style-object.d.ts +33 -0
  14. package/dist/adapters/style-object.d.ts.map +1 -0
  15. package/dist/analyzer.d.ts.map +1 -1
  16. package/dist/children-nullish.d.ts +22 -0
  17. package/dist/children-nullish.d.ts.map +1 -0
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/expression-parser.d.ts +9 -19
  21. package/dist/expression-parser.d.ts.map +1 -1
  22. package/dist/free-refs.d.ts +6 -0
  23. package/dist/free-refs.d.ts.map +1 -1
  24. package/dist/index.d.ts +14 -11
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +14685 -14000
  27. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  29. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  31. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  34. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  37. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  39. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  42. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  44. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/imports.d.ts +23 -2
  46. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -2
  48. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  50. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  53. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  55. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/types.d.ts +3 -3
  57. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/utils.d.ts +2 -11
  59. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  60. package/dist/jsx-to-ir.d.ts.map +1 -1
  61. package/dist/nullable-signal-attr.d.ts +40 -10
  62. package/dist/nullable-signal-attr.d.ts.map +1 -1
  63. package/dist/prop-rewrite.d.ts +18 -0
  64. package/dist/prop-rewrite.d.ts.map +1 -1
  65. package/dist/props-binding.d.ts +9 -1
  66. package/dist/props-binding.d.ts.map +1 -1
  67. package/dist/scanner/js-scanner.d.ts.map +1 -1
  68. package/dist/scanner/js-scanner.js +30 -2
  69. package/dist/signal-prop-name-collision.d.ts +6 -5
  70. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  71. package/dist/ssr-defaults.d.ts +28 -0
  72. package/dist/ssr-defaults.d.ts.map +1 -1
  73. package/dist/ssr-seed-plan.d.ts +39 -14
  74. package/dist/ssr-seed-plan.d.ts.map +1 -1
  75. package/dist/types.d.ts +108 -18
  76. package/dist/types.d.ts.map +1 -1
  77. package/dist/value-references.d.ts +21 -0
  78. package/dist/value-references.d.ts.map +1 -1
  79. package/package.json +2 -2
  80. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  81. package/src/__tests__/adapter-output.test.ts +5 -3
  82. package/src/__tests__/analyzer.test.ts +33 -0
  83. package/src/__tests__/arithmetic-lowering.test.ts +44 -0
  84. package/src/__tests__/children-read.test.ts +226 -0
  85. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  86. package/src/__tests__/component-props.test.ts +68 -1
  87. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  88. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  89. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  90. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  91. package/src/__tests__/expression-parser.test.ts +1 -44
  92. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  93. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  94. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  95. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  96. package/src/__tests__/ssr-defaults.test.ts +19 -1
  97. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  98. package/src/__tests__/style-object-plan.test.ts +54 -0
  99. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  100. package/src/adapters/callback-method.ts +23 -0
  101. package/src/adapters/component-props.ts +130 -12
  102. package/src/adapters/dsl-template-adapter.ts +248 -0
  103. package/src/adapters/jsx-adapter.ts +12 -6
  104. package/src/adapters/literal-value.ts +2 -2
  105. package/src/adapters/parsed-expr-emitter.ts +34 -0
  106. package/src/adapters/style-object.ts +61 -0
  107. package/src/analyzer.ts +114 -15
  108. package/src/children-nullish.ts +33 -0
  109. package/src/debug.ts +2 -2
  110. package/src/errors.ts +12 -0
  111. package/src/expression-parser.ts +56 -53
  112. package/src/free-refs.ts +28 -17
  113. package/src/index.ts +18 -8
  114. package/src/ir-to-client-js/compute-inlinability.ts +29 -2
  115. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  116. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  117. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  118. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  119. package/src/ir-to-client-js/csr-substitute.ts +12 -2
  120. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  121. package/src/ir-to-client-js/emit-registration.ts +28 -57
  122. package/src/ir-to-client-js/generate-init.ts +17 -1
  123. package/src/ir-to-client-js/html-template.ts +30 -50
  124. package/src/ir-to-client-js/identifiers.ts +75 -24
  125. package/src/ir-to-client-js/imports.ts +56 -19
  126. package/src/ir-to-client-js/index.ts +2 -1
  127. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  128. package/src/ir-to-client-js/phases/props-extraction.ts +16 -15
  129. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  130. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  131. package/src/ir-to-client-js/reactivity.ts +2 -2
  132. package/src/ir-to-client-js/rewrite-destructured-props.ts +21 -4
  133. package/src/ir-to-client-js/safe-html.ts +29 -35
  134. package/src/ir-to-client-js/types.ts +3 -2
  135. package/src/ir-to-client-js/utils.ts +2 -26
  136. package/src/jsx-to-ir.ts +279 -78
  137. package/src/nullable-signal-attr.ts +149 -33
  138. package/src/prop-rewrite.ts +41 -0
  139. package/src/props-binding.ts +17 -2
  140. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  141. package/src/scanner/js-scanner.ts +64 -4
  142. package/src/signal-prop-name-collision.ts +50 -24
  143. package/src/ssr-defaults.ts +47 -20
  144. package/src/ssr-seed-plan.ts +103 -23
  145. package/src/types.ts +115 -19
  146. package/src/value-references.ts +132 -0
@@ -0,0 +1,44 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { parseExpression } from '../expression-parser'
3
+ import { arithmeticHelper, groupBinaryOperand, groupUnaryOperand } from '../adapters/parsed-expr-emitter'
4
+
5
+ describe('arithmeticHelper (#3474)', () => {
6
+ test('`%` lowers to the runtime\'s JS remainder', () => {
7
+ expect(arithmeticHelper('%')).toBe('mod')
8
+ })
9
+
10
+ test('the other operators are spelled by the adapter', () => {
11
+ for (const op of ['+', '-', '*', '/', '**', '===', '<']) expect(arithmeticHelper(op)).toBeNull()
12
+ })
13
+ })
14
+
15
+ describe('groupUnaryOperand (#3474)', () => {
16
+ const group = (src: string) => {
17
+ const parsed = parseExpression(src)
18
+ if (parsed.kind !== 'unary') throw new Error(`not a unary: ${src}`)
19
+ return groupUnaryOperand(parsed.argument, 'X')
20
+ }
21
+
22
+ test('a compound operand is grouped, as under a binary operator', () => {
23
+ expect(group('-(a + b)')).toBe('(X)')
24
+ expect(group('-(a || b)')).toBe('(X)')
25
+ expect(group('-(a ? b : c)')).toBe('(X)')
26
+ })
27
+
28
+ test('a nested unary operand is grouped, so `--x` never forms', () => {
29
+ expect(group('-(-a)')).toBe('(X)')
30
+ })
31
+
32
+ test('a leaf operand stays as it is', () => {
33
+ expect(group('-a')).toBe('X')
34
+ expect(group('-a.b')).toBe('X')
35
+ expect(group('-f()')).toBe('X')
36
+ })
37
+
38
+ test('agrees with groupBinaryOperand on everything but a unary operand', () => {
39
+ for (const src of ['a + b', 'a && b', 'a ? b : c', 'a', 'a.b', 'f()', '1']) {
40
+ const parsed = parseExpression(src)
41
+ expect(groupUnaryOperand(parsed, 'X')).toBe(groupBinaryOperand(parsed, 'X'))
42
+ }
43
+ })
44
+ })
@@ -0,0 +1,226 @@
1
+ /**
2
+ * `IRExpression.childrenRead` (#3539): which expression children read the
3
+ * component's own `children` prop, decided from the binding in Phase 1.
4
+ */
5
+ import { describe, test, expect } from 'bun:test'
6
+ import { compileJSX } from '../compiler'
7
+ import { fallbackChainParts, nullishChainParts } from '../children-nullish'
8
+ import { parseExpression, stringifyParsedExpr } from '../expression-parser'
9
+ import { TestAdapter } from '../adapters/test-adapter'
10
+
11
+ /** `childrenRead` of every expression child, in document order. */
12
+ function childrenReads(source: string): (string | undefined)[] {
13
+ const result = compileJSX(source.trimStart(), 'C.tsx', { adapter: new TestAdapter(), outputIR: true })
14
+ const ir = JSON.parse(result.files.find(f => f.type === 'ir')!.content)
15
+ const out: (string | undefined)[] = []
16
+ const walk = (node: unknown): void => {
17
+ if (!node || typeof node !== 'object') return
18
+ const n = node as Record<string, unknown>
19
+ if (n.type === 'expression') out.push(n.childrenRead as string | undefined)
20
+ for (const value of Object.values(n)) {
21
+ if (Array.isArray(value)) value.forEach(walk)
22
+ else if (value && typeof value === 'object') walk(value)
23
+ }
24
+ }
25
+ walk(ir.root)
26
+ return out
27
+ }
28
+
29
+ describe('nullishChainParts', () => {
30
+ test('a left-nested chain reads its head, else the remaining fallbacks', () => {
31
+ const parts = nullishChainParts(parseExpression("(c ?? '<b>x</b>') ?? ''"))!
32
+ expect(stringifyParsedExpr(parts.head)).toBe('c')
33
+ expect(stringifyParsedExpr(parts.fallback)).toBe('"<b>x</b>" ?? ""')
34
+ })
35
+
36
+ test('a non-nullish expression has no parts', () => {
37
+ expect(nullishChainParts(parseExpression('c || d'))).toBeNull()
38
+ })
39
+ })
40
+
41
+ describe('fallbackChainParts', () => {
42
+ test('a left-nested || chain reads its head, else the remaining fallbacks', () => {
43
+ const parts = fallbackChainParts(parseExpression("(c || '<b>x</b>') || ''"), '||')!
44
+ expect(stringifyParsedExpr(parts.head)).toBe('c')
45
+ expect(stringifyParsedExpr(parts.fallback)).toBe('"<b>x</b>" || ""')
46
+ })
47
+
48
+ test('a chain of the other operator has no parts', () => {
49
+ expect(fallbackChainParts(parseExpression('c ?? d'), '||')).toBeNull()
50
+ expect(fallbackChainParts(parseExpression('(c ?? d) || e'), '??')).toBeNull()
51
+ })
52
+ })
53
+
54
+ describe('childrenRead', () => {
55
+ test('a chained fallback stays a fallback, not an empty read', () => {
56
+ expect(childrenReads(`
57
+ export function Box(props: { children?: unknown }) {
58
+ return <div>{(props.children ?? '<b>fallback</b>') ?? ''}{(props.children ?? '') ?? ''}</div>
59
+ }
60
+ `)).toEqual(['nullish-fallback', 'nullish-empty'])
61
+ })
62
+
63
+ test('an || fallback over the children prop is an or-fallback read', () => {
64
+ expect(childrenReads(`
65
+ export function Box({ children, label }: { children?: unknown; label?: string }) {
66
+ return <div>{children || '<b>x</b>'}{(children || label) || ''}{label || children}{(children ?? label) || ''}</div>
67
+ }
68
+ `)).toEqual(['or-fallback', 'or-fallback', undefined, undefined])
69
+ })
70
+
71
+ test('a loop preamble local named children shadows the prop', () => {
72
+ expect(childrenReads(`
73
+ export function List({ children, rows }: { children?: unknown; rows: { label: string }[] }) {
74
+ return (
75
+ <div>
76
+ {children}
77
+ <ul>{rows.map(r => { const children = r.label; return <li key={r.label}>{children}</li> })}</ul>
78
+ </div>
79
+ )
80
+ }
81
+ `)).toEqual(['bare', undefined])
82
+ })
83
+ })
84
+
85
+ /** The client JS `compileJSX` emits for `source`. */
86
+ function clientJs(source: string): string {
87
+ const result = compileJSX(source.trimStart(), 'C.tsx', { adapter: new TestAdapter() })
88
+ return result.files.find(f => f.type === 'clientJs')?.content ?? ''
89
+ }
90
+
91
+ describe('children prop renamed in the parameter destructure (#3572)', () => {
92
+ test('is a children read, not a reactive prop slot', () => {
93
+ const source = `
94
+ 'use client'
95
+ export function Box({ children: kids }: { children?: unknown }) {
96
+ return <div><p>{kids}</p><p>{kids ?? '<b>x</b>'}</p><p>{kids || '<b>y</b>'}</p></div>
97
+ }
98
+ `
99
+ expect(childrenReads(source)).toEqual(['bare', 'nullish-fallback', 'or-fallback'])
100
+ const js = clientJs(source)
101
+ expect(js).not.toContain('createEffect')
102
+ expect(js).not.toContain('escapeTextOrMarkup(_p.children')
103
+ expect(js).toContain('markupOrEmpty(_p.children)')
104
+ })
105
+
106
+ test('compiles to the same client JS as the unrenamed binding', () => {
107
+ const body = `{label}{KIDS}{KIDS ?? '<b>x</b>'}{KIDS ? <i>{KIDS}</i> : null}`
108
+ const renamed = clientJs(`
109
+ 'use client'
110
+ export function Box({ children: kids, label }: { children?: unknown; label?: string }) {
111
+ return <div>${body.replaceAll('KIDS', 'kids')}</div>
112
+ }
113
+ `)
114
+ const plain = clientJs(`
115
+ 'use client'
116
+ export function Box({ children, label }: { children?: unknown; label?: string }) {
117
+ return <div>${body.replaceAll('KIDS', 'children')}</div>
118
+ }
119
+ `)
120
+ expect(renamed).toBe(plain)
121
+ })
122
+
123
+ test('a handler read binds the renamed local once from _p.children', () => {
124
+ const js = clientJs(`
125
+ 'use client'
126
+ export function Box({ children: kids }: { children?: unknown }) {
127
+ return <button onClick={() => console.log(kids)}>{kids}</button>
128
+ }
129
+ `)
130
+ expect(js).toContain('const kids = _p.children')
131
+ expect(js).toContain('console.log(kids)')
132
+ })
133
+
134
+ test('a template-only read leaves no eager _p.children read in init', () => {
135
+ const js = clientJs(`
136
+ 'use client'
137
+ import { createSignal } from '@barefootjs/client'
138
+ export function Box({ children: kids }: { children?: unknown }) {
139
+ const [n, setN] = createSignal(0)
140
+ return <button onClick={() => setN(n() + 1)}>{n()}{kids}</button>
141
+ }
142
+ `)
143
+ expect(js).toContain('function initBox')
144
+ expect(js).not.toContain('const kids')
145
+ })
146
+
147
+ test('a local named children that binds another prop is that prop', () => {
148
+ const js = clientJs(`
149
+ 'use client'
150
+ export function Box({ label: children }: { label?: string }) {
151
+ return <button onClick={() => console.log(children)}>{children}</button>
152
+ }
153
+ `)
154
+ expect(js).not.toContain('_p.children')
155
+ expect(js).toContain('console.log(_p.label)')
156
+ expect(js).toContain('createEffect')
157
+ })
158
+
159
+ test('a const alias hop of the children prop is a children read', () => {
160
+ expect(childrenReads(`
161
+ export function Box({ children, rows }: { children?: unknown; rows: string[] }) {
162
+ const c = children
163
+ const d = c
164
+ return <div>{c}{d ?? '<b>x</b>'}<ul>{rows.map(c => <li key={c}>{c}</li>)}</ul></div>
165
+ }
166
+ `)).toEqual(['bare', 'nullish-fallback', undefined])
167
+ expect(childrenReads(`
168
+ export function Box(props: { children?: unknown }) {
169
+ const p = props
170
+ const q = p
171
+ const c = q.children
172
+ return <div>{p.children}{q.children || '<b>x</b>'}{c}</div>
173
+ }
174
+ `)).toEqual(['bare', 'or-fallback', 'bare'])
175
+ })
176
+
177
+ test('a loop row shadowing a name an outer alias resolves through does not change the alias', () => {
178
+ // The initializer `props.children` and the hop through `a` resolve in
179
+ // the component scope; only the name read at the use site is checked
180
+ // against the loop rows.
181
+ expect(childrenReads(`
182
+ export function Box(props: { children?: unknown; rows: string[][] }) {
183
+ const { children: c } = props
184
+ return <ul>{props.rows.map((props, i) => <li key={i}>{c}{props.map((props, j) => <i key={j}>{c}</i>)}</li>)}</ul>
185
+ }
186
+ `)).toEqual(['bare', 'bare'])
187
+ expect(childrenReads(`
188
+ export function Box({ children, rows }: { children?: unknown; rows: string[] }) {
189
+ const a = children
190
+ const b = a
191
+ return <ul>{rows.map(a => <li key={a}>{b}{a}</li>)}{rows.map((children, i) => <li key={i}>{b}{children}</li>)}</ul>
192
+ }
193
+ `)).toEqual(['bare', undefined, 'bare', undefined])
194
+ })
195
+
196
+ test('a let alias of the children prop is not a children read', () => {
197
+ expect(childrenReads(`
198
+ export function Box({ children }: { children?: unknown }) {
199
+ let c = children
200
+ return <div>{c}</div>
201
+ }
202
+ `)).toEqual([undefined])
203
+ })
204
+
205
+ test('a read through a const alias of the props object is not a reactive slot', () => {
206
+ const js = clientJs(`
207
+ 'use client'
208
+ export function Box(props: { children?: unknown }) {
209
+ const p = props
210
+ return <div>{p.children}</div>
211
+ }
212
+ `)
213
+ expect(js).not.toContain('createEffect')
214
+ expect(js).toContain('markupOrEmpty((_p).children)')
215
+ })
216
+
217
+ test('a fragment root reading only the renamed binding is transparent', () => {
218
+ const js = clientJs(`
219
+ 'use client'
220
+ export function Pass({ children: kids }: { children?: unknown }) {
221
+ return <>{kids}</>
222
+ }
223
+ `)
224
+ expect(js).toContain('transparent: true')
225
+ })
226
+ })
@@ -180,12 +180,37 @@ export function Box(props: { children?: unknown }) {
180
180
  pin: (js) => expect(js).toContain('markupOrEmpty('),
181
181
  },
182
182
  {
183
+ // #3554 — present children stay markup; only the fallback is escaped.
183
184
  id: 'children-nullish-text-fallback',
184
185
  source: `
185
186
  export function Box(props: { children?: unknown }) {
186
187
  return <div>{props.children ?? '<b>text</b>'}</div>
187
188
  }`,
188
- pin: (js) => expect(js).toContain('escapeText('),
189
+ pin: (js) =>
190
+ expect(js).toContain(
191
+ "${_p.children == null ? escapeText(_p.children ?? '<b>text</b>') : markupOrEmpty(_p.children)}",
192
+ ),
193
+ },
194
+ {
195
+ // #3554 — a destructured children reads `_p.children` in the template.
196
+ id: 'children-nullish-text-fallback-destructured',
197
+ source: `
198
+ export function Box({ children }: { children?: unknown }) {
199
+ return <div>{(children ?? '<b>text</b>') ?? ''}</div>
200
+ }`,
201
+ pin: (js) =>
202
+ expect(js).toContain(
203
+ "${_p.children == null ? escapeText((_p.children ?? '<b>text</b>') ?? '') : markupOrEmpty(_p.children)}",
204
+ ),
205
+ },
206
+ {
207
+ id: 'children-or-text-fallback',
208
+ source: `
209
+ export function Box(props: { children?: unknown }) {
210
+ return <div>{props.children || '<b>text</b>'}</div>
211
+ }`,
212
+ pin: (js) =>
213
+ expect(js).toContain("${!_p.children ? escapeText(_p.children || '<b>text</b>') : markupOrEmpty(_p.children)}"),
189
214
  },
190
215
  {
191
216
  // The author-facing escape hatch, by name.
@@ -386,6 +411,11 @@ function classifyHole(expr: ts.Expression, nested: ts.TemplateExpression[]): str
386
411
  }
387
412
  return 'conditional-markup'
388
413
  }
414
+ // `absent ? escapeText(fallback) : markupOrEmpty(children)` —
415
+ // childrenMarkupOrEscapedFallback (#3554): each branch is an escaping or
416
+ // trusted call on its own.
417
+ const branchForms = [e.whenTrue, e.whenFalse].map(b => (ts.isCallExpression(strip(b)) ? classifyHole(b, nested) : null))
418
+ if (branchForms.every(f => f !== null && (f.startsWith('escape:') || f.startsWith('trusted:')))) return 'children-or-fallback'
389
419
  // `x ? 'attr' : ''` / `x != null ? 'attr="' + escapeAttr(x) + '"' : ''`.
390
420
  if (isAttrConcat(e.whenTrue) && (isEmptyString(e.whenFalse) || ts.isStringLiteral(strip(e.whenFalse)))) return 'attr'
391
421
  return null
@@ -8,6 +8,8 @@ import { describe, test, expect } from 'bun:test'
8
8
  import {
9
9
  isEmptyComponentProps,
10
10
  planComponentProps,
11
+ propsSpreadParam,
12
+ resolveComponentPropKeys,
11
13
  spellComponentProps,
12
14
  type ComponentPropEntry,
13
15
  type ComponentPropsOptions,
@@ -64,6 +66,7 @@ function spell(comp: IRComponent, options = noProps): string[] {
64
66
  return spellComponentProps(planComponentProps(comp, options), {
65
67
  entry: describe,
66
68
  spread: (value) => value.expr,
69
+ presentParam: (name) => `${name}?=$${name}`,
67
70
  }).map((segment) => (segment.kind === 'spread' ? `...${segment.expr}` : `{${segment.parts.join(', ')}}`))
68
71
  }
69
72
 
@@ -101,8 +104,30 @@ describe('planComponentProps', () => {
101
104
  test('a repeated key keeps its first position and takes the later value', () => {
102
105
  const later = component([prop('', spread('props')), prop('tone', literal('explicit'))])
103
106
  expect(spell(later, withProps)).toEqual([`{tone='explicit', size=$size, _bf_slot='s0'}`])
107
+ })
108
+
109
+ test('{...props} after an explicit prop carries that key only when the caller passed it', () => {
104
110
  const earlier = component([prop('tone', literal('first')), prop('', spread('props'))])
105
- expect(spell(earlier, withProps)).toEqual([`{tone=$tone, size=$size, _bf_slot='s0'}`])
111
+ expect(spell(earlier, withProps)).toEqual([`{tone='first'}`, '...tone?=$tone', `{size=$size, _bf_slot='s0'}`])
112
+ })
113
+
114
+ test('{...props} after a spread of unknown keys carries every key only when passed', () => {
115
+ const comp = component([prop('', spread('rest')), prop('', spread('props'))], { slotId: null })
116
+ expect(spell(comp, withProps)).toEqual(['{}', '...rest', '...tone?=$tone', '...size?=$size'])
117
+ })
118
+
119
+ test('a required param always wins: the caller always passes it', () => {
120
+ const required: ComponentPropsOptions = {
121
+ propsObjectName: 'props',
122
+ propsParams: [{ name: 'tone', optional: false }, { name: 'size', optional: true }],
123
+ }
124
+ const comp = component([prop('tone', literal('first')), prop('size', literal('s')), prop('', spread('props'))])
125
+ expect(spell(comp, required)).toEqual([`{tone=$tone, size='s'}`, '...size?=$size', `{_bf_slot='s0'}`])
126
+ })
127
+
128
+ test('an explicit prop after the spread replaces a passed-only key', () => {
129
+ const comp = component([prop('tone', literal('a')), prop('', spread('props')), prop('tone', literal('z'))])
130
+ expect(spell(comp, withProps)).toEqual([`{tone='a'}`, '...tone?=$tone', `{size=$size, tone='z', _bf_slot='s0'}`])
106
131
  })
107
132
 
108
133
  test('a key repeated across a spread stays twice: the spread may set it in between', () => {
@@ -124,6 +149,47 @@ describe('planComponentProps', () => {
124
149
  })
125
150
  })
126
151
 
152
+ describe('propsSpreadParam', () => {
153
+ const none = { keys: new Set<string>(), spread: false }
154
+ test('nothing earlier sets the key: an ordinary entry', () => {
155
+ expect(propsSpreadParam({ name: 'tone' }, none)).toBe('entry')
156
+ })
157
+ test('an earlier entry or an earlier spread may set the key: only when passed', () => {
158
+ expect(propsSpreadParam({ name: 'tone' }, { keys: new Set(['tone']), spread: false })).toBe('present')
159
+ expect(propsSpreadParam({ name: 'tone', optional: true }, { keys: new Set(), spread: true })).toBe('present')
160
+ })
161
+ test('a required param is always passed, so it always wins', () => {
162
+ expect(propsSpreadParam({ name: 'tone', optional: false }, { keys: new Set(['tone']), spread: true })).toBe('entry')
163
+ })
164
+ })
165
+
166
+ describe('resolveComponentPropKeys', () => {
167
+ test('per key, in first-set order: the passed param over the latest unconditional entry', () => {
168
+ const comp = component([prop('tone', literal('first')), prop('size', literal('s')), prop('', spread('props'))], {
169
+ slotId: null,
170
+ })
171
+ const resolved = resolveComponentPropKeys(planComponentProps(comp, withProps))!
172
+ expect(resolved.map((r) => [r.key, r.base?.kind, r.presentParams])).toEqual([
173
+ ['tone', 'value', ['tone']],
174
+ ['size', 'value', ['size']],
175
+ ])
176
+ })
177
+
178
+ test('a later entry clears the passed-only params before it', () => {
179
+ const comp = component([prop('tone', literal('a')), prop('', spread('props')), prop('tone', literal('z'))], {
180
+ slotId: null,
181
+ })
182
+ const tone = resolveComponentPropKeys(planComponentProps(comp, withProps))!.find((r) => r.key === 'tone')!
183
+ expect(tone.presentParams).toEqual([])
184
+ expect(tone.base).toEqual({ kind: 'value', name: 'tone', value: literal('z') })
185
+ })
186
+
187
+ test('a spread of unknown keys cannot be resolved at compile time', () => {
188
+ const comp = component([prop('', spread('rest')), prop('', spread('props'))])
189
+ expect(resolveComponentPropKeys(planComponentProps(comp, withProps))).toBeNull()
190
+ })
191
+ })
192
+
127
193
  describe('spellComponentProps', () => {
128
194
  test('spells entries in source order and drops an empty part', () => {
129
195
  const order: string[] = []
@@ -136,6 +202,7 @@ describe('spellComponentProps', () => {
136
202
  return entry.kind === 'value' ? '' : 'part'
137
203
  },
138
204
  spread: () => '',
205
+ presentParam: () => '',
139
206
  })
140
207
  expect(order).toEqual(['a', 'b', 'c', 'slot-id', 'children'])
141
208
  expect(segments).toEqual([{ kind: 'entries', parts: ['part', 'part', 'part', 'part'] }])
@@ -0,0 +1,136 @@
1
+ /**
2
+ * Constant inlining in the client JS runs on the expression tree (#3535).
3
+ *
4
+ * The component template used to inline a constant with
5
+ * ``text.replace(new RegExp(`(?<![-.])\\b${name}\\b`), `(${value})`)`` behind
6
+ * a quoted-string protector. The static segments of a template literal and an
7
+ * object-literal shorthand were exposed, so `` `btn size-${size}` `` rendered
8
+ * `btn ('lg')-lg` and `{ size }` became the SyntaxError `{ ('lg') }`.
9
+ */
10
+
11
+ import { describe, test, expect } from 'bun:test'
12
+ import { compileJSX } from '../compiler'
13
+ import { TestAdapter } from '../adapters/test-adapter'
14
+ import { resolveChainedRefs } from '../ir-to-client-js/emit-registration'
15
+
16
+ const adapter = new TestAdapter()
17
+ const transpiler = new Bun.Transpiler({ loader: 'js' })
18
+
19
+ function clientJs(locals: string, jsx: string): string {
20
+ const source = `
21
+ 'use client'
22
+ import { createSignal } from '@barefootjs/client'
23
+ export function T(props: { label: string; items: string[] }) {
24
+ const [on, setOn] = createSignal(false)
25
+ ${locals}
26
+ return ${jsx}
27
+ }
28
+ `
29
+ const result = compileJSX(source, 'T.tsx', { adapter })
30
+ expect(result.errors).toHaveLength(0)
31
+ const js = result.files.find(f => f.type === 'clientJs')!.content
32
+ expect(() => transpiler.transformSync(js)).not.toThrow()
33
+ return js
34
+ }
35
+
36
+ /** The `template: (_p) => …` lambda the client registers for CSR. */
37
+ function templateOf(js: string): string {
38
+ const line = js.split('\n').find(l => l.includes('template: (_p) =>'))
39
+ expect(line).toBeDefined()
40
+ return line!
41
+ }
42
+
43
+ const button = (attrs: string) => `<button ${attrs} onClick={() => setOn(!on())}>{props.label}</button>`
44
+
45
+ describe('constant inlining on the tree (#3535)', () => {
46
+ test('a template-literal static segment that spells the constant is kept', () => {
47
+ const tpl = templateOf(clientJs("const size = 'lg'", button('className={`btn size-${size}`}')))
48
+ expect(tpl).not.toContain("('lg')-")
49
+ expect(tpl).toContain("size-${('lg')}")
50
+ })
51
+
52
+ test('an object-literal shorthand expands to a key-value pair', () => {
53
+ const tpl = templateOf(clientJs("const size = 'lg'", button('data-o={JSON.stringify({ size })}')))
54
+ expect(tpl).toContain("size: ('lg')")
55
+ })
56
+
57
+ test('a member name and a string spelling the constant are kept', () => {
58
+ const tpl = templateOf(clientJs("const size = 'lg'", button("data-o={props.label.size + 'size'}")))
59
+ expect(tpl).toContain('.size')
60
+ expect(tpl).toContain("'size'")
61
+ })
62
+
63
+ test('a $-named constant is inlined', () => {
64
+ const tpl = templateOf(clientJs("const size$ = 'lg'", button('data-size={size$}')))
65
+ expect(tpl).not.toMatch(/\bsize\$/)
66
+ expect(tpl).toContain('lg')
67
+ })
68
+
69
+ test('a loop row binding that shadows the constant is not replaced', () => {
70
+ const js = clientJs(
71
+ "const item = 'outer'",
72
+ "<ul data-x={item}>{props.items.map(item => <li key={item}>{item}</li>)}</ul>",
73
+ )
74
+ expect(js).not.toContain("key={('outer')}")
75
+ })
76
+ })
77
+
78
+ /** Runs the registered template lambda against `props`, as a CSR mount would. */
79
+ function renderTemplate(js: string, props: Record<string, unknown>): string {
80
+ const line = templateOf(js)
81
+ const lambda = line.slice(line.indexOf('template: (_p) =>') + 'template: '.length).replace(/ \}\)\s*$/, '')
82
+ const escape = (v: unknown) => String(v ?? '')
83
+ const run = new Function('escapeAttr', 'escapeText', 'escapeTextOrMarkup', 'markupOrEmpty', `return (${lambda})`)
84
+ return run(escape, escape, escape, escape)(props)
85
+ }
86
+
87
+ describe('computed object keys (#3535 review)', () => {
88
+ test('a constant in a computed key is inlined, so the template runs', () => {
89
+ const js = clientJs("const size = 'lg'", button('data-o={JSON.stringify({ [size]: props.label })}'))
90
+ expect(templateOf(js)).toContain("[('lg')]")
91
+ expect(() => renderTemplate(js, { label: 'hello' })).not.toThrow()
92
+ })
93
+
94
+ test('a compound computed key is inlined too', () => {
95
+ const js = clientJs("const size = 'lg'", button("data-o={JSON.stringify({ [size + '!']: props.label })}"))
96
+ expect(() => renderTemplate(js, { label: 'hello' })).not.toThrow()
97
+ })
98
+ })
99
+
100
+ describe('resolveChainedRefs', () => {
101
+ test('resolves a chain on the tree, leaving strings and member names alone', () => {
102
+ const constants = new Map([
103
+ ['base', "'lg'"],
104
+ ['cls', '`btn base-${base}`'],
105
+ ['opts', '({ base, other: o.base })'],
106
+ ])
107
+ resolveChainedRefs(constants)
108
+ expect(constants.get('cls')).toBe("`btn base-${('lg')}`")
109
+ expect(constants.get('opts')).toBe("({ base: ('lg'), other: o.base })")
110
+ })
111
+
112
+ test('a computed key in a chained constant is resolved', () => {
113
+ const constants = new Map([
114
+ ['size', "'lg'"],
115
+ ['obj', '({ [size]: 1 })'],
116
+ ])
117
+ resolveChainedRefs(constants)
118
+ expect(constants.get('obj')).toBe("({ [('lg')]: 1 })")
119
+ })
120
+
121
+ test('a value brought in by a substitution is resolved too', () => {
122
+ const constants = new Map([
123
+ ['a', 'b + 1'],
124
+ ['b', 'c * 2'],
125
+ ['c', '3'],
126
+ ])
127
+ const freeIds = new Map([
128
+ ['a', new Set(['b'])],
129
+ ['b', new Set(['c'])],
130
+ ['c', new Set<string>()],
131
+ ])
132
+ resolveChainedRefs(constants, freeIds)
133
+ expect(constants.get('a')).toBe('((3) * 2) + 1')
134
+ expect([...freeIds.get('a')!]).toEqual([])
135
+ })
136
+ })