@barefootjs/jsx 0.39.3 → 0.39.5

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 (103) hide show
  1. package/dist/adapters/boolean-result.d.ts +32 -0
  2. package/dist/adapters/boolean-result.d.ts.map +1 -0
  3. package/dist/adapters/filter-capture-collisions.d.ts +17 -0
  4. package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
  5. package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
  6. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  7. package/dist/adapters/template-name-collisions.d.ts +21 -0
  8. package/dist/adapters/template-name-collisions.d.ts.map +1 -0
  9. package/dist/analyzer-context.d.ts.map +1 -1
  10. package/dist/errors.d.ts +1 -0
  11. package/dist/errors.d.ts.map +1 -1
  12. package/dist/expression-parser.d.ts +10 -0
  13. package/dist/expression-parser.d.ts.map +1 -1
  14. package/dist/index.d.ts +6 -3
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +688 -176
  17. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/plan/build-composite-loop.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +13 -0
  21. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  22. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
  23. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +7 -0
  25. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -0
  27. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +2 -0
  29. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/control-flow/stringify/composite-loop.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/loop.d.ts +14 -0
  34. package/dist/ir-to-client-js/control-flow/stringify/loop.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/imports.d.ts +2 -2
  37. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts +3 -1
  39. package/dist/ir-to-client-js/phases/rest-attr-applications.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/safe-html.d.ts +6 -0
  42. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/types.d.ts +12 -0
  44. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/utils.d.ts +39 -1
  46. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  47. package/dist/nullable-signal-attr.d.ts +33 -0
  48. package/dist/nullable-signal-attr.d.ts.map +1 -1
  49. package/dist/profiler.d.ts +9 -1
  50. package/dist/profiler.d.ts.map +1 -1
  51. package/dist/scope/binding-scope.d.ts +10 -0
  52. package/dist/scope/binding-scope.d.ts.map +1 -1
  53. package/dist/types.d.ts +7 -0
  54. package/dist/types.d.ts.map +1 -1
  55. package/package.json +2 -2
  56. package/src/__tests__/binding-scope-ratchet.test.ts +1 -1
  57. package/src/__tests__/binding-scope.test.ts +11 -0
  58. package/src/__tests__/boolean-result.test.ts +27 -0
  59. package/src/__tests__/compile-without-node-process.test.ts +78 -0
  60. package/src/__tests__/csr-template-loop-shadow.test.ts +83 -0
  61. package/src/__tests__/doc-examples.test.ts +1 -0
  62. package/src/__tests__/nested-row-shadowing.test.ts +57 -0
  63. package/src/__tests__/profile-turn-markers.test.ts +22 -0
  64. package/src/__tests__/profiler.test.ts +10 -9
  65. package/src/__tests__/rename-free-identifiers.test.ts +26 -0
  66. package/src/__tests__/ssr-portal-ref-callback.test.ts +88 -13
  67. package/src/__tests__/template-name-collisions.test.ts +81 -0
  68. package/src/adapters/boolean-result.ts +89 -0
  69. package/src/adapters/filter-capture-collisions.ts +29 -0
  70. package/src/adapters/parsed-expr-emitter.ts +18 -0
  71. package/src/adapters/template-name-collisions.ts +120 -0
  72. package/src/analyzer-context.ts +15 -1
  73. package/src/errors.ts +11 -0
  74. package/src/expression-parser.ts +32 -0
  75. package/src/index.ts +9 -2
  76. package/src/ir-to-client-js/collect-elements.ts +22 -10
  77. package/src/ir-to-client-js/control-flow/plan/build-composite-loop.ts +2 -0
  78. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +13 -0
  79. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +38 -12
  80. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
  81. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
  82. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +7 -0
  83. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -0
  84. package/src/ir-to-client-js/control-flow/plan/loop.ts +2 -0
  85. package/src/ir-to-client-js/control-flow/shared.ts +6 -1
  86. package/src/ir-to-client-js/control-flow/stringify/branch-loop.ts +6 -3
  87. package/src/ir-to-client-js/control-flow/stringify/composite-loop.ts +7 -4
  88. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +21 -6
  89. package/src/ir-to-client-js/control-flow/stringify/insert.ts +6 -1
  90. package/src/ir-to-client-js/control-flow/stringify/loop.ts +55 -8
  91. package/src/ir-to-client-js/html-template.ts +72 -15
  92. package/src/ir-to-client-js/imports.ts +3 -1
  93. package/src/ir-to-client-js/index.ts +7 -2
  94. package/src/ir-to-client-js/phases/rest-attr-applications.ts +8 -2
  95. package/src/ir-to-client-js/reactivity.ts +1 -0
  96. package/src/ir-to-client-js/safe-html.ts +10 -0
  97. package/src/ir-to-client-js/types.ts +12 -0
  98. package/src/ir-to-client-js/utils.ts +81 -7
  99. package/src/jsx-to-ir.ts +138 -32
  100. package/src/nullable-signal-attr.ts +78 -0
  101. package/src/profiler.ts +79 -10
  102. package/src/scope/binding-scope.ts +19 -0
  103. package/src/types.ts +7 -0
@@ -28,6 +28,25 @@ function rootFor(src: string, componentName: string): IRNode {
28
28
  return node
29
29
  }
30
30
 
31
+ /** `keyAttr` of every flagged element, in document order. */
32
+ function portalKeyAttrs(node: IRNode): Array<IRElement['keyAttr']> {
33
+ const out: Array<IRElement['keyAttr']> = []
34
+ const visit = (n: IRNode): void => {
35
+ if (n.type === 'element' && (n as IRElement).ssrPortalOwnerScope) out.push((n as IRElement).keyAttr)
36
+ if ('children' in n && Array.isArray((n as { children?: IRNode[] }).children)) {
37
+ for (const c of (n as { children: IRNode[] }).children) visit(c)
38
+ }
39
+ }
40
+ visit(node)
41
+ return out
42
+ }
43
+
44
+ /** Error codes `compileJSX` reports for `src`. */
45
+ function errorCodes(src: string): string[] {
46
+ const result = compileJSX(src.trimStart(), 'T.tsx', { adapter: new TestAdapter() })
47
+ return result.errors.map(e => e.code)
48
+ }
49
+
31
50
  function flaggedRefs(node: IRNode): string[] {
32
51
  const out: string[] = []
33
52
  const visit = (n: IRNode): void => {
@@ -176,18 +195,12 @@ export function Overlay() {
176
195
  expect(flaggedRefs(rootFor(src, 'Overlay'))).toEqual(['handleMount'])
177
196
  })
178
197
 
179
- // BF063 resolves a `ref` name outward through every enclosing function
180
- // scope; the portal recognition keeps the pre-BF063 limit (the callback
181
- // must be declared in the ref's innermost function scope) so sharing the
182
- // resolution does not widen what is recognized. These two tests pin that
183
- // scope limit only. A portal element inside a `.map()` row is broken
184
- // either way — the second test's row-declared callback is still
185
- // recognized and still breaks the row's hydration — which is the
186
- // registered known limitation `loop-row-ref-portal`
187
- // (`packages/adapter-tests/limitations/loop-row-ref-portal.ts`, fixture
188
- // `row-portal-ref`): the control pins today's behaviour as a known gap,
189
- // not as intended behaviour.
190
- test('does not flag a .map() row ref naming a portal callback declared in the component body', () => {
198
+ // The portal recognition shares BF063's resolution, which walks outward
199
+ // through every enclosing function scope (#3318): a `.map()` row ref
200
+ // naming a component-body portal callback is recognized like a
201
+ // row-declared one, and the flagged element carries the row key so
202
+ // hydration can pair it with its row.
203
+ test('flags a .map() row ref naming a portal callback declared in the component body', () => {
191
204
  const ir = root(`
192
205
  'use client'
193
206
  import { createPortal } from '@barefootjs/client'
@@ -196,7 +209,8 @@ export function List(props: { rows: string[] }) {
196
209
  return <ul>{props.rows.map(r => (<li key={r}><div ref={mountContent}>{r}</div></li>))}</ul>
197
210
  }
198
211
  `)
199
- expect(flaggedRefs(ir)).toEqual([])
212
+ expect(flaggedRefs(ir)).toEqual(['mountContent'])
213
+ expect(portalKeyAttrs(ir)).toEqual([{ name: 'data-key', value: 'r' }])
200
214
  })
201
215
 
202
216
  test('still flags a .map() row ref naming a portal callback declared in the row callback itself', () => {
@@ -216,4 +230,65 @@ export function List(props: { rows: string[] }) {
216
230
  `)
217
231
  expect(flaggedRefs(ir)).toEqual(['mountContent'])
218
232
  })
233
+
234
+ describe('row portals (#3318)', () => {
235
+ const portalRow = (loop: string) => `
236
+ 'use client'
237
+ import { createPortal, createSignal } from '@barefootjs/client'
238
+ export function List(props: { rows: string[]; groups: string[][] }) {
239
+ const [open] = createSignal(true)
240
+ const mountContent = (el: HTMLElement) => { createPortal(el, document.body, { ownerScope: 'x' }) }
241
+ return <ul>{${loop}}</ul>
242
+ }
243
+ `
244
+
245
+ test('keys the portaled element of a keyed top-level row without an error', () => {
246
+ expect(errorCodes(portalRow(`props.rows.map(r => <li key={r}><button ref={mountContent}>{r}</button></li>)`))).toEqual([])
247
+ })
248
+
249
+ test('refuses an unkeyed row (BF064)', () => {
250
+ expect(errorCodes(portalRow(`props.rows.map(r => <li><button ref={mountContent}>{r}</button></li>)`))).toContain('BF064')
251
+ })
252
+
253
+ test('refuses a nested row (BF064)', () => {
254
+ expect(
255
+ errorCodes(portalRow(
256
+ `props.groups.map((g, i) => <li key={i}><ol>{g.map(r => <li key={r}><button ref={mountContent}>{r}</button></li>)}</ol></li>)`,
257
+ )),
258
+ ).toContain('BF064')
259
+ })
260
+
261
+ test('refuses a portaled row root (BF064)', () => {
262
+ expect(errorCodes(portalRow(`props.rows.map(r => <button key={r} ref={mountContent}>{r}</button>)`))).toContain('BF064')
263
+ })
264
+
265
+ test('refuses a portaled row root of a nested loop (BF064)', () => {
266
+ expect(
267
+ errorCodes(portalRow(
268
+ `props.groups.map((g, i) => <li key={i}>{g.map(r => <button key={r} ref={mountContent}>{r}</button>)}</li>)`,
269
+ )),
270
+ ).toContain('BF064')
271
+ })
272
+
273
+ test('refuses a portal inside a reactive conditional in the row (BF064)', () => {
274
+ expect(
275
+ errorCodes(portalRow(
276
+ `props.rows.map(r => <li key={r}>{open() ? <button ref={mountContent}>{r}</button> : null}</li>)`,
277
+ )),
278
+ ).toContain('BF064')
279
+ })
280
+
281
+ test('does not touch a portal element outside any loop', () => {
282
+ const ir = root(`
283
+ 'use client'
284
+ import { createPortal } from '@barefootjs/client'
285
+ export function P() {
286
+ const mountContent = (el: HTMLElement) => { createPortal(el, document.body, { ownerScope: 'x' }) }
287
+ return <div><div ref={mountContent} /></div>
288
+ }
289
+ `)
290
+ expect(flaggedRefs(ir)).toEqual(['mountContent'])
291
+ expect(portalKeyAttrs(ir)).toEqual([undefined])
292
+ })
293
+ })
219
294
  })
@@ -0,0 +1,81 @@
1
+ import { describe, test, expect } from 'bun:test'
2
+ import { analyzeComponent } from '../analyzer'
3
+ import { jsxToIR } from '../jsx-to-ir'
4
+ import { templateNameCollisionErrors } from '../adapters/template-name-collisions'
5
+ import type { ComponentIR } from '../types'
6
+
7
+ // #3404: BF105 fires only for names visible at the same point — the
8
+ // component's own names and the bindings of the enclosing loop rows.
9
+ describe('templateNameCollisionErrors (#3404)', () => {
10
+ function ir(source: string): ComponentIR {
11
+ const ctx = analyzeComponent(source, 'Test.tsx')
12
+ const root = jsxToIR(ctx)
13
+ if (!root) throw new Error('expected IR')
14
+ const metadata = { localConstants: [], localFunctions: [], signals: [], memos: [] } as unknown as ComponentIR['metadata']
15
+ return { version: '0.1', metadata, root, errors: [] }
16
+ }
17
+ const ident = (name: string) => (name === 'loop' ? '__bf_loop' : name)
18
+ const codes = (component: ComponentIR, props: string[]) =>
19
+ templateNameCollisionErrors(component, props, ident, 'Jinja', 'Test').map(e => e.code)
20
+
21
+ test('two props that share a template variable collide', () => {
22
+ const component = ir(`
23
+ function Test(props: { loop: string; __bf_loop: string }) { return <div>{props.loop}{props.__bf_loop}</div> }
24
+ export { Test }
25
+ `)
26
+ expect(codes(component, ['loop', '__bf_loop'])).toEqual(['BF105'])
27
+ })
28
+
29
+ test('bindings of sibling loops do not collide', () => {
30
+ const component = ir(`
31
+ function Test(props: { a: string[]; b: string[] }) {
32
+ return <div>
33
+ <ul>{props.a.map(loop => <li key={loop}>{loop}</li>)}</ul>
34
+ <ul>{props.b.map(__bf_loop => <li key={__bf_loop}>{__bf_loop}</li>)}</ul>
35
+ </div>
36
+ }
37
+ export { Test }
38
+ `)
39
+ expect(codes(component, ['a', 'b'])).toEqual([])
40
+ })
41
+
42
+ test('a nested row binding collides with an enclosing row binding', () => {
43
+ const component = ir(`
44
+ function Test(props: { groups: string[][] }) {
45
+ return <div>{props.groups.map(loop => <ul key={loop[0]}>{loop.map(__bf_loop => <li key={__bf_loop}>{__bf_loop}</li>)}</ul>)}</div>
46
+ }
47
+ export { Test }
48
+ `)
49
+ expect(codes(component, ['groups'])).toEqual(['BF105'])
50
+ })
51
+
52
+ test('a row binding collides with a prop', () => {
53
+ const component = ir(`
54
+ function Test(props: { loop: string; items: string[] }) {
55
+ return <ul>{props.items.map(__bf_loop => <li key={__bf_loop}>{props.loop}</li>)}</ul>
56
+ }
57
+ export { Test }
58
+ `)
59
+ expect(codes(component, ['loop', 'items'])).toEqual(['BF105'])
60
+ })
61
+
62
+ test('a filter param collides with a prop', () => {
63
+ const component = ir(`
64
+ function Test(props: { items: { visible: boolean; label: string }[]; __bf_loop: { visible: boolean } }) {
65
+ return <div>{props.items.filter(loop => loop.visible).map(item => <span key={item.label}>{item.label}</span>)}</div>
66
+ }
67
+ export { Test }
68
+ `)
69
+ expect(codes(component, ['items', '__bf_loop'])).toEqual(['BF105'])
70
+ })
71
+
72
+ test('a filter param does not collide with the map param it feeds', () => {
73
+ const component = ir(`
74
+ function Test(props: { items: string[] }) {
75
+ return <ul>{props.items.filter(loop => loop !== '').map(__bf_loop => <li key={__bf_loop}>{__bf_loop}</li>)}</ul>
76
+ }
77
+ export { Test }
78
+ `)
79
+ expect(codes(component, ['items'])).toEqual([])
80
+ })
81
+ })
@@ -0,0 +1,89 @@
1
+ /**
2
+ * Backend-neutral boolean-result classification shared by the adapters whose
3
+ * host language has no boolean type (Mojolicious, Xslate: Perl renders a
4
+ * comparison as `''` / `1` and the literal `false` as `0`). Both adapters
5
+ * route a boolean-shaped attribute value through their `bool_str` runtime
6
+ * helper; this module decides which `ParsedExpr` shapes are boolean-shaped
7
+ * and rewrites a ternary that only PARTLY is (#3349).
8
+ *
9
+ * Detected boolean-result shapes:
10
+ * - `binary` with a comparison operator (`<`, `>`, `<=`, `>=`, `==`,
11
+ * `===`, `!=`, `!==`)
12
+ * - `unary` with logical `!`
13
+ * - `literal` with `literalType: 'boolean'`
14
+ * - `logical` (`&&` / `||` / `??`) when both sides are boolean-result
15
+ * - `conditional` (`?:`) when both branches are boolean-result
16
+ */
17
+
18
+ import type { ParsedExpr } from '../expression-parser.ts'
19
+
20
+ const COMPARISON_OPS = new Set([
21
+ '<',
22
+ '>',
23
+ '<=',
24
+ '>=',
25
+ '==',
26
+ '===',
27
+ '!=',
28
+ '!==',
29
+ ])
30
+
31
+ /** Whether `node` structurally evaluates to a JS boolean. */
32
+ export function isBooleanResultParsed(node: ParsedExpr): boolean {
33
+ switch (node.kind) {
34
+ case 'literal':
35
+ return node.literalType === 'boolean'
36
+ case 'binary':
37
+ return COMPARISON_OPS.has(node.op)
38
+ case 'unary':
39
+ return node.op === '!'
40
+ case 'logical':
41
+ // `x > 0 && y < 10` is boolean; `x() || 'fallback'` is not.
42
+ // Only both-sides-boolean qualifies.
43
+ return (
44
+ isBooleanResultParsed(node.left) && isBooleanResultParsed(node.right)
45
+ )
46
+ case 'conditional':
47
+ // `cond ? bool : bool` is boolean; `cond ? 'a' : 'b'` is not.
48
+ return (
49
+ isBooleanResultParsed(node.consequent) &&
50
+ isBooleanResultParsed(node.alternate)
51
+ )
52
+ default:
53
+ return false
54
+ }
55
+ }
56
+
57
+ /**
58
+ * Rewrites the boolean-result branches of a ternary whose OTHER branch is
59
+ * not boolean (`yes() ? false : s()`), so a taken boolean branch carries
60
+ * JS `String(boolean)` instead of Perl's `0` / `''` / `1` (#3349). The whole
61
+ * value isn't boolean-shaped, so `bool_str` can't wrap it; instead a literal
62
+ * `true` / `false` branch becomes the string literal `'true'` / `'false'`,
63
+ * and any other boolean-result branch `b` becomes `b ? 'true' : 'false'`.
64
+ * The existing ternary lowering then renders the rewritten tree unchanged.
65
+ * Nested ternary branches are rewritten recursively; anything that is not
66
+ * a mixed ternary is returned as is.
67
+ */
68
+ export function stringifyBooleanTernaryBranches(node: ParsedExpr): ParsedExpr {
69
+ if (node.kind !== 'conditional' || isBooleanResultParsed(node)) return node
70
+ return {
71
+ ...node,
72
+ consequent: stringifyBooleanBranch(node.consequent),
73
+ alternate: stringifyBooleanBranch(node.alternate),
74
+ }
75
+ }
76
+
77
+ function stringifyBooleanBranch(branch: ParsedExpr): ParsedExpr {
78
+ if (!isBooleanResultParsed(branch)) return stringifyBooleanTernaryBranches(branch)
79
+ if (branch.kind === 'literal') {
80
+ return { kind: 'literal', value: String(branch.value), literalType: 'string' }
81
+ }
82
+ return {
83
+ kind: 'conditional',
84
+ test: branch,
85
+ consequent: { kind: 'literal', value: 'true', literalType: 'string' },
86
+ alternate: { kind: 'literal', value: 'false', literalType: 'string' },
87
+ }
88
+ }
89
+
@@ -0,0 +1,29 @@
1
+ import type { IRLoop } from '../types.ts'
2
+ import { freeIdentifiers } from '../expression-parser.ts'
3
+
4
+ /**
5
+ * Names a `.filter().map()` loop's predicate captures from an enclosing row
6
+ * that the loop's own row binds again (its item, destructure bindings or
7
+ * index), so they shadow the capture where the predicate runs (#3402).
8
+ *
9
+ * `rows.filter(t => t === name).map(name => …)` inside a row bound as `name`:
10
+ * the predicate's `name` is the enclosing value, but adapters evaluate the
11
+ * predicate inside the `.map()` row, where `name` is the item. An adapter
12
+ * keeps each returned name under a loop-scoped alias declared before the
13
+ * loop and rewrites the predicate's reads to it.
14
+ *
15
+ * An unanalyzable predicate (`freeIdentifiers` returns null) yields no
16
+ * names, which keeps the adapter's previous emission.
17
+ */
18
+ export function filterCaptureCollisions(loop: IRLoop): string[] {
19
+ const filter = loop.filterPredicate
20
+ if (!filter?.predicate) return []
21
+ const free = freeIdentifiers(filter.predicate)
22
+ if (!free) return []
23
+ free.delete(filter.param)
24
+ const rowBound = new Set<string>(
25
+ loop.paramBindings && loop.paramBindings.length > 0 ? loop.paramBindings.map(b => b.name) : [loop.param],
26
+ )
27
+ if (loop.index) rowBound.add(loop.index)
28
+ return [...free].filter(name => rowBound.has(name)).sort()
29
+ }
@@ -287,6 +287,24 @@ export function isStringConcatBinary(
287
287
  return op === '+' && (isStringTypedOperand(left, isStringName) || isStringTypedOperand(right, isStringName))
288
288
  }
289
289
 
290
+ /**
291
+ * Whether a top-level expression yields a JS NUMBER from arithmetic: a
292
+ * `-` / `*` / `/` / `%` binary, a `+` that is not string concatenation, or
293
+ * a unary minus. Backends that print an output expression with the host
294
+ * language's own number stringification (Perl's `%.15g`) route such a
295
+ * result through their JS `Number::toString` helper instead (#3380).
296
+ */
297
+ export function isNumericArithmeticResult(
298
+ expr: ParsedExpr | null | undefined,
299
+ isStringName: (n: string, componentProperty?: boolean) => boolean,
300
+ ): boolean {
301
+ if (!expr) return false
302
+ if (expr.kind === 'unary') return expr.op === '-'
303
+ if (expr.kind !== 'binary') return false
304
+ if (expr.op === '+') return !isStringConcatBinary(expr.op, expr.left, expr.right, isStringName)
305
+ return expr.op === '-' || expr.op === '*' || expr.op === '/' || expr.op === '%'
306
+ }
307
+
290
308
  /**
291
309
  * Wrap an emitted binary/logical/ternary OPERAND in parentheses so the
292
310
  * source grouping the `ParsedExpr` tree encodes survives infix
@@ -0,0 +1,120 @@
1
+ import { BindingScope } from '../scope/binding-scope.ts'
2
+ import type { CompilerError, ComponentIR, IRNode } from '../types.ts'
3
+
4
+ /**
5
+ * BF105: two distinct source names of a component that an adapter's
6
+ * identifier mangling turns into the SAME template variable (#3404).
7
+ *
8
+ * Template engines rename a source name they reserve — `loop` becomes
9
+ * `__bf_loop` on Jinja, MiniJinja, Twig, Pebble and Blade, `none` becomes
10
+ * `none_` on Jinja. The mapping is per name and must be idempotent
11
+ * (some paths mangle an already-mangled name, and the runtimes re-mangle
12
+ * prop keys), so it cannot also be injective: whatever a reserved name
13
+ * becomes is itself a name a user may write. When a component writes both,
14
+ * the two reads would silently share one value, so the adapter refuses.
15
+ *
16
+ * The names checked are the ones the adapter turns into bare template
17
+ * variables: props, local consts and functions, signal getters and setters,
18
+ * memos, and the bindings of each loop row or `.filter()` callback together
19
+ * with its enclosing rows (`BindingScope`). `ident` is the adapter's own mangling
20
+ * (`jinjaIdent`, `twigIdent`, …). One error per colliding group.
21
+ */
22
+ export function templateNameCollisionErrors(
23
+ ir: ComponentIR,
24
+ propNames: Iterable<string>,
25
+ ident: (name: string) => string,
26
+ adapterName: string,
27
+ componentName: string,
28
+ ): CompilerError[] {
29
+ const { metadata } = ir
30
+ const rootNames = new Set<string>([
31
+ ...propNames,
32
+ ...metadata.localConstants.map(c => c.name),
33
+ ...metadata.localFunctions.map(f => f.name),
34
+ ...metadata.signals.flatMap(s => (s.setter ? [s.getter, s.setter] : [s.getter])),
35
+ ...metadata.memos.map(m => m.name),
36
+ ])
37
+ const errors: CompilerError[] = []
38
+ const reported = new Set<string>()
39
+ // Only names visible at the same point can collide: the component's own
40
+ // names plus the bindings of the enclosing loop rows. Sibling loops never
41
+ // see each other's bindings, so `a.map(loop => …)` next to
42
+ // `b.map(__bf_loop => …)` is fine.
43
+ const check = (scope: BindingScope): void => {
44
+ const byTarget = new Map<string, string[]>()
45
+ for (const name of new Set([...rootNames, ...scope.boundNames()])) {
46
+ const target = ident(name)
47
+ const group = byTarget.get(target)
48
+ if (group) group.push(name)
49
+ else byTarget.set(target, [name])
50
+ }
51
+ for (const [target, group] of byTarget) {
52
+ if (group.length < 2) continue
53
+ const key = `${target}\0${[...group].sort().join('\0')}`
54
+ if (reported.has(key)) continue
55
+ reported.add(key)
56
+ const list = group.map(n => `\`${n}\``).join(' and ')
57
+ errors.push({
58
+ code: 'BF105',
59
+ severity: 'error',
60
+ message: `${list} both become the ${adapterName} template variable \`${target}\`, so they would read the same value. ${adapterName} reserves some names and renames them, and the new name collides with another name in this component.`,
61
+ loc: { file: `${componentName}.tsx`, start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
62
+ suggestion: {
63
+ message: `Rename one of ${list} so the two names stay distinct after the ${adapterName} renaming.`,
64
+ escape: [{ kind: 'rewrite' }],
65
+ },
66
+ })
67
+ }
68
+ }
69
+ const visit = (node: IRNode | null | undefined, scope: BindingScope): void => {
70
+ if (!node) return
71
+ switch (node.type) {
72
+ case 'element':
73
+ case 'component':
74
+ case 'fragment':
75
+ case 'provider':
76
+ for (const child of node.children) visit(child, scope)
77
+ break
78
+ case 'async':
79
+ visit(node.fallback, scope)
80
+ for (const child of node.children) visit(child, scope)
81
+ break
82
+ case 'loop': {
83
+ // A `.filter()` predicate is its own callback: its param sees the
84
+ // enclosing scope, not the map row it feeds.
85
+ if (node.filterPredicate) check(scope.enterCallback([node.filterPredicate.param]))
86
+ const row = scope.enterLoopRow(node)
87
+ check(row)
88
+ for (const child of node.children) visit(child, row)
89
+ if (node.childComponent) {
90
+ for (const child of node.childComponent.children) visit(child, row)
91
+ }
92
+ for (const nested of node.nestedComponents ?? []) {
93
+ for (const child of nested.children) visit(child, row)
94
+ }
95
+ for (const seg of node.flatMapCallback?.segments ?? []) {
96
+ if (seg.kind === 'jsx') visit(seg.ir, row)
97
+ }
98
+ for (const seg of node.preamble?.segments ?? []) {
99
+ if (seg.kind === 'jsx') visit(seg.ir, row)
100
+ }
101
+ break
102
+ }
103
+ case 'conditional':
104
+ visit(node.whenTrue, scope)
105
+ visit(node.whenFalse, scope)
106
+ break
107
+ case 'if-statement':
108
+ visit(node.consequent, scope)
109
+ if (node.alternate) visit(node.alternate, scope)
110
+ break
111
+ case 'text':
112
+ case 'expression':
113
+ case 'slot':
114
+ break
115
+ }
116
+ }
117
+ check(BindingScope.EMPTY)
118
+ visit(ir.root, BindingScope.EMPTY)
119
+ return errors
120
+ }
@@ -28,6 +28,20 @@ import { type ExcludeRange, collectAllTypeRanges, reconstructWithoutTypes } from
28
28
  import type { CallbackBodyAcceptor } from './adapters/interface.ts'
29
29
  import { nodeContainsJsx } from './reactivity-checker.ts'
30
30
 
31
+ /**
32
+ * Whether the getJS trust-boundary assertion is armed (BF_ASSERT_NO_JSX_IN_GETJS=1).
33
+ *
34
+ * Read through `globalThis` rather than a bare `process` identifier: the
35
+ * compiler also runs where no Node `process` exists (the site playground
36
+ * bundles it into a browser Worker), and a bare reference there throws
37
+ * ReferenceError on the first getJS call. Evaluated per call, not at module
38
+ * load, because the test harnesses that arm it set the env var in `beforeAll`.
39
+ */
40
+ function isGetJsAssertionArmed(): boolean {
41
+ const env = (globalThis as { process?: { env?: Record<string, string | undefined> } }).process?.env
42
+ return env?.BF_ASSERT_NO_JSX_IN_GETJS === '1'
43
+ }
44
+
31
45
  /**
32
46
  * The props destructuring pattern's own source location. Carries no
33
47
  * diagnostic of its own — it is the more precise location other
@@ -327,7 +341,7 @@ export function createAnalyzerContext(
327
341
  // anything, so it must not silently disarm this assertion too (#2867)
328
342
  // — only `error` severity does.
329
343
  if (
330
- process.env.BF_ASSERT_NO_JSX_IN_GETJS === '1' &&
344
+ isGetJsAssertionArmed() &&
331
345
  !this.errors.some((e) => e.severity === 'error') &&
332
346
  nodeContainsJsx(node)
333
347
  ) {
package/src/errors.ts CHANGED
@@ -165,6 +165,14 @@ export const ErrorCodes = {
165
165
  // `/* @client */` before the ref expression. See
166
166
  // `packages/adapter-tests/limitations/ref-effect-attr-state-ssr.ts`.
167
167
  REF_ATTR_ABSENT_AT_SSR: 'BF063',
168
+ // A `ref` callback portals an element out of a `.map()` row
169
+ // (`createPortal(el, document.body, { ownerScope })`), but the row cannot
170
+ // be paired with the portaled element at hydration: the loop is nested or
171
+ // unkeyed, or the element is forwarded as a child component's children.
172
+ // SSR would place the element at its portal outlet with nothing linking it
173
+ // back to its row, so its delegated event handlers would stop running
174
+ // after hydration (#3318). A keyed top-level row is supported.
175
+ ROW_PORTAL_UNPAIRABLE: 'BF064',
168
176
 
169
177
  // Inline JSX-callback synthesis errors (BF080-BF089) — raised by the
170
178
  // preprocess-inline-jsx-callbacks pass (#1211) when an inline JSX-
@@ -298,6 +306,9 @@ const errorMessages: Record<ErrorCode, string> = {
298
306
  [ErrorCodes.REF_ATTR_ABSENT_AT_SSR]:
299
307
  'A ref callback writes an attribute on mount that the element\'s JSX never renders. A ref callback never runs at SSR, so the server HTML lacks the attribute and hydration adds it — the DOM visibly changes at the hydrate boundary.',
300
308
 
309
+ [ErrorCodes.ROW_PORTAL_UNPAIRABLE]:
310
+ 'A ref callback portals an element out of a .map() row that hydration cannot pair with the element (the row root itself, a nested or unkeyed loop, an element inside a reactive conditional in the row, or an element inside a child component\'s children), so its event handlers would stop running after hydration.',
311
+
301
312
  [ErrorCodes.INLINE_JSX_CALLBACK_CAPTURE]:
302
313
  "Inline JSX-returning arrow function captures a non-module identifier. Extract the callback into a top-level 'use client' component (e.g. `function MyNode(n) { return <div/> }` then `renderNode={MyNode}`) or pass captured values via component props.",
303
314
 
@@ -3801,6 +3801,38 @@ export function freeVarsInBody(body: ParsedExpr, params: ReadonlySet<string>): s
3801
3801
  return [...found].sort()
3802
3802
  }
3803
3803
 
3804
+ /**
3805
+ * `expr` with each free reference to a name in `renames` replaced by its
3806
+ * mapped name. An `arrow` param of the same name shadows the rename inside
3807
+ * its body; string literals, member property names and object-literal keys
3808
+ * are never touched, because they are not `identifier` nodes. Used to point a
3809
+ * `.filter()` predicate's captured enclosing names at loop-scoped aliases
3810
+ * before an adapter emits it, so target-language name mangling still applies
3811
+ * (#3402).
3812
+ */
3813
+ export function renameFreeIdentifiers(expr: ParsedExpr, renames: ReadonlyMap<string, string>): ParsedExpr {
3814
+ if (renames.size === 0) return expr
3815
+ const walk = (value: unknown, active: ReadonlyMap<string, string>): unknown => {
3816
+ if (Array.isArray(value)) return value.map(v => walk(v, active))
3817
+ if (value === null || typeof value !== 'object') return value
3818
+ const node = value as { kind?: unknown } & Record<string, unknown>
3819
+ if (node.kind === 'identifier' && typeof node.name === 'string') {
3820
+ const renamed = active.get(node.name)
3821
+ return renamed === undefined ? node : { ...node, name: renamed }
3822
+ }
3823
+ let inner = active
3824
+ if (node.kind === 'arrow' && Array.isArray(node.params)) {
3825
+ const shadowed = new Map(active)
3826
+ for (const p of node.params as string[]) shadowed.delete(p)
3827
+ inner = shadowed
3828
+ }
3829
+ const out: Record<string, unknown> = {}
3830
+ for (const [k, v] of Object.entries(node)) out[k] = walk(v, inner)
3831
+ return out
3832
+ }
3833
+ return walk(expr, renames) as ParsedExpr
3834
+ }
3835
+
3804
3836
  /**
3805
3837
  * Every value-position identifier in `expr` NOT bound by an enclosing arrow's
3806
3838
  * own parameters — with proper lexical scoping: an arrow's params bind only
package/src/index.ts CHANGED
@@ -117,17 +117,24 @@ export type {
117
117
  export { JsxAdapter } from './adapters/jsx-adapter.ts'
118
118
  export type { JsxAdapterConfig } from './adapters/jsx-adapter.ts'
119
119
  export { rewriteImportsForTemplate, rewriteDynamicImportsInSource } from './adapters/template-imports.ts'
120
- export { emitParsedExpr, groupBinaryOperand, groupObjectLiteralSegments, isStringTypedOperand, isStringConcatBinary } from './adapters/parsed-expr-emitter.ts'
120
+ export { emitParsedExpr, groupBinaryOperand, groupObjectLiteralSegments, isStringTypedOperand, isStringConcatBinary, isNumericArithmeticResult } from './adapters/parsed-expr-emitter.ts'
121
121
  export type { ParsedExprEmitter, LoweringEmitter, HigherOrderMethod, ArrayMethod, SortMethod, LiteralType } from './adapters/parsed-expr-emitter.ts'
122
122
  export { collectLoopBoundNames } from './adapters/loop-bound-names.ts'
123
+ export { filterCaptureCollisions } from './adapters/filter-capture-collisions.ts'
124
+ export { templateNameCollisionErrors } from './adapters/template-name-collisions.ts'
125
+ export { isBooleanResultParsed, stringifyBooleanTernaryBranches } from './adapters/boolean-result.ts'
123
126
  export { derivesScopeFromSlot } from './adapters/child-scope.ts'
124
127
  export { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
125
128
  export {
129
+ arithmeticOperandIsNull,
130
+ arithmeticOperandIsUndefined,
131
+ bareGetterCallName,
126
132
  attrValueMayBeNullish,
127
133
  collectNullableSignalGetters,
128
134
  collectNullishAttrContext,
129
135
  isNullableSignal,
130
136
  isNullishLiteral,
137
+ NULL_COERCING_ARITHMETIC_OPS,
131
138
  nullableSignalAttrGetter,
132
139
  type NullishAttrContext,
133
140
  } from './nullable-signal-attr.ts'
@@ -246,7 +253,7 @@ export { ErrorCodes, createError, formatError, generateCodeFrame } from './error
246
253
  export { isValueReferenceIdentifier, collectValueReferencedNames } from './value-references.ts'
247
254
 
248
255
  // Expression Parser
249
- export { parseExpression, tsNodeToParsedExpr, asCallbackMethodCall, CALLBACK_METHODS, sortComparatorFromArrow, serializeParsedExpr, freeVarsInBody, freeIdentifiers, materializeGetterCalls, isSupported, isSupportedValue, exprToString, stringifyParsedExpr, identifierPath, parseBlockBody, parseBlockBodyTolerant, foldBlockToExpr, predicateTernaryToLogical, containsHigherOrder, extractArrowBodyExpression, parseStyleObjectEntries, hasUnsafeStyleValue, parseProviderObjectLiteral, isFunctionShapedExpression, type ProviderObjectMember, type FoldBlockOptions } from './expression-parser.ts'
256
+ export { parseExpression, tsNodeToParsedExpr, asCallbackMethodCall, CALLBACK_METHODS, sortComparatorFromArrow, serializeParsedExpr, freeVarsInBody, freeIdentifiers, renameFreeIdentifiers, materializeGetterCalls, isSupported, isSupportedValue, exprToString, stringifyParsedExpr, identifierPath, parseBlockBody, parseBlockBodyTolerant, foldBlockToExpr, predicateTernaryToLogical, containsHigherOrder, extractArrowBodyExpression, parseStyleObjectEntries, hasUnsafeStyleValue, parseProviderObjectLiteral, isFunctionShapedExpression, type ProviderObjectMember, type FoldBlockOptions } from './expression-parser.ts'
250
257
  export type { StyleObjectEntry } from './expression-parser.ts'
251
258
  export { literalMemberIndex } from './literal-member-index.ts'
252
259
  export { PARSED_EXPR_KINDS, ARRAY_METHOD_NAMES, SORT_KEY_TYPES, SORT_KEY_TARGETS, SORT_KEY_DIRECTIONS } from './expression-parser.ts'