@barefootjs/jsx 0.39.4 → 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 (52) hide show
  1. package/dist/adapters/filter-capture-collisions.d.ts +17 -0
  2. package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
  3. package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
  4. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  5. package/dist/adapters/template-name-collisions.d.ts +21 -0
  6. package/dist/adapters/template-name-collisions.d.ts.map +1 -0
  7. package/dist/analyzer-context.d.ts.map +1 -1
  8. package/dist/expression-parser.d.ts +10 -0
  9. package/dist/expression-parser.d.ts.map +1 -1
  10. package/dist/index.d.ts +5 -3
  11. package/dist/index.d.ts.map +1 -1
  12. package/dist/index.js +358 -132
  13. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  14. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +8 -0
  15. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  16. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
  17. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  18. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  20. package/dist/ir-to-client-js/utils.d.ts +39 -1
  21. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  22. package/dist/nullable-signal-attr.d.ts +12 -0
  23. package/dist/nullable-signal-attr.d.ts.map +1 -1
  24. package/dist/scope/binding-scope.d.ts +10 -0
  25. package/dist/scope/binding-scope.d.ts.map +1 -1
  26. package/dist/types.d.ts +7 -0
  27. package/dist/types.d.ts.map +1 -1
  28. package/package.json +2 -2
  29. package/src/__tests__/binding-scope-ratchet.test.ts +1 -1
  30. package/src/__tests__/binding-scope.test.ts +11 -0
  31. package/src/__tests__/compile-without-node-process.test.ts +78 -0
  32. package/src/__tests__/doc-examples.test.ts +1 -0
  33. package/src/__tests__/nested-row-shadowing.test.ts +57 -0
  34. package/src/__tests__/rename-free-identifiers.test.ts +26 -0
  35. package/src/__tests__/template-name-collisions.test.ts +81 -0
  36. package/src/adapters/filter-capture-collisions.ts +29 -0
  37. package/src/adapters/parsed-expr-emitter.ts +18 -0
  38. package/src/adapters/template-name-collisions.ts +120 -0
  39. package/src/analyzer-context.ts +15 -1
  40. package/src/expression-parser.ts +32 -0
  41. package/src/index.ts +6 -2
  42. package/src/ir-to-client-js/collect-elements.ts +11 -7
  43. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +31 -10
  44. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
  45. package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
  46. package/src/ir-to-client-js/control-flow/shared.ts +4 -1
  47. package/src/ir-to-client-js/html-template.ts +13 -7
  48. package/src/ir-to-client-js/index.ts +7 -2
  49. package/src/ir-to-client-js/utils.ts +81 -7
  50. package/src/nullable-signal-attr.ts +38 -6
  51. package/src/scope/binding-scope.ts +19 -0
  52. package/src/types.ts +7 -0
@@ -0,0 +1,26 @@
1
+ /**
2
+ * `renameFreeIdentifiers` (#3402): only free `identifier` references to a
3
+ * renamed name change. String literals, member property names, and names an
4
+ * `arrow` param rebinds stay as they are.
5
+ */
6
+ import { describe, test, expect } from 'bun:test'
7
+ import { parseExpression, renameFreeIdentifiers, stringifyParsedExpr } from '../expression-parser'
8
+
9
+ const rename = (src: string, map: Record<string, string>) =>
10
+ stringifyParsedExpr(renameFreeIdentifiers(parseExpression(src), new Map(Object.entries(map))))
11
+
12
+ describe('renameFreeIdentifiers', () => {
13
+ test('renames free references only', () => {
14
+ expect(rename('t === name || t === "name"', { name: 'alias' })).toBe(stringifyParsedExpr(parseExpression('t === alias || t === "name"')))
15
+ })
16
+ test('leaves member property names alone', () => {
17
+ expect(rename('t.name === name', { name: 'alias' })).toBe(stringifyParsedExpr(parseExpression('t.name === alias')))
18
+ })
19
+ test('an arrow param shadows the rename in its body', () => {
20
+ expect(rename('xs.some(name => name === t) && name', { name: 'alias' })).toBe(stringifyParsedExpr(parseExpression('xs.some(name => name === t) && alias')))
21
+ })
22
+ test('an empty map returns the same tree', () => {
23
+ const e = parseExpression('a + b')
24
+ expect(renameFreeIdentifiers(e, new Map())).toBe(e)
25
+ })
26
+ })
@@ -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,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
  ) {
@@ -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,14 +117,18 @@ 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'
123
125
  export { isBooleanResultParsed, stringifyBooleanTernaryBranches } from './adapters/boolean-result.ts'
124
126
  export { derivesScopeFromSlot } from './adapters/child-scope.ts'
125
127
  export { evaluateStaticLiteral, isFullyStaticLiteral, resolveStaticLoopSource } from './static-literal.ts'
126
128
  export {
127
129
  arithmeticOperandIsNull,
130
+ arithmeticOperandIsUndefined,
131
+ bareGetterCallName,
128
132
  attrValueMayBeNullish,
129
133
  collectNullableSignalGetters,
130
134
  collectNullishAttrContext,
@@ -249,7 +253,7 @@ export { ErrorCodes, createError, formatError, generateCodeFrame } from './error
249
253
  export { isValueReferenceIdentifier, collectValueReferencedNames } from './value-references.ts'
250
254
 
251
255
  // Expression Parser
252
- 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'
253
257
  export type { StyleObjectEntry } from './expression-parser.ts'
254
258
  export { literalMemberIndex } from './literal-member-index.ts'
255
259
  export { PARSED_EXPR_KINDS, ARRAY_METHOD_NAMES, SORT_KEY_TYPES, SORT_KEY_TARGETS, SORT_KEY_DIRECTIONS } from './expression-parser.ts'
@@ -4,7 +4,7 @@
4
4
 
5
5
  import { type IRNode, type IRElement, type IRComponent, type IRConditional, type IRLoop, type IRProp, pickAttrMetaFromIR } from '../types.ts'
6
6
  import type { ClientJsContext, ConditionalBranchChildComponent, ConditionalBranchReactiveAttr, BranchLoop, ConditionalBranchTextEffect, ConditionalElement, LoopChildBindings, LoopChildBranchSummary, LoopChildConditional, LoopOffset, NestedLoop } from './types.ts'
7
- import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, toHtmlAttrName, type LoopParamSpec } from './utils.ts'
7
+ import { attrValueToString, freeIdsFromRefs, quotePropName, PROPS_PARAM, toHtmlAttrName, rowBoundNames, withRowAccessor, type LoopParamSpec } from './utils.ts'
8
8
  import { classifyReactivity, needsEffectWrapper, decideWrapForAttr, decideWrapForChildProp, decideWrapFromAstFlags, collectEventHandlersFromIR, collectConditionalBranchEvents, collectConditionalBranchRefs, collectConditionalBranchChildComponents, collectConditionalBranchComponentNodes, collectLoopChildEventsWithNesting, collectLoopChildReactiveAttrs, collectLoopChildReactiveTexts, collectLoopChildRefs, emptyLoopChildBindings, buildLoopRowScope, anyNameIn } from './reactivity.ts'
9
9
  import { irToHtmlTemplate, irToPlaceholderTemplate, irChildrenToJsExpr, jsxChildrenPropGetterExpr, buildLoopSkeletonTemplate, computeSkeletonSlotPaths, renderFlatMapClientBody, renderFlatMapProjectionClientBody, flatMapCallbackHasKeyedLeaf, type SkeletonSlotPaths } from './html-template.ts'
10
10
  import { detectRootNamespaceWrapTag } from './control-flow/stringify/template-parse.ts'
@@ -328,12 +328,16 @@ export function collectInnerLoops(
328
328
  },
329
329
  loop: ({ node: n, scope, descend }) => {
330
330
  const emitDepth = fixedDepth ?? scope.depth + 1
331
+ // This nested row reads its destructure bindings through its own
332
+ // accessor, not the enclosing row's `__bfItem` (#3397).
333
+ const rowBindings = withRowAccessor(n.paramBindings, n.markerId)
331
334
  // Generate item template for CSR rendering in mapArray.
332
335
  // Pass loopParams so expressions are wrapped at generation time (not post-hoc regex).
333
336
  // Forward destructured bindings (#951) so inner-loop template
334
337
  // references to the destructured locals are rewritten.
338
+ // The outer spec skips the names this row rebinds (#3394).
335
339
  const loopParamsForTemplate = outerSpec
336
- ? [outerSpec, { param: n.param, bindings: n.paramBindings, index: n.index }]
340
+ ? [{ ...outerSpec, shadowed: rowBoundNames(n) }, { param: n.param, bindings: rowBindings, index: n.index }]
337
341
  : undefined
338
342
  const template = n.children.map(c => irToPlaceholderTemplate(c, undefined, emitDepth, loopParamsForTemplate)).join('')
339
343
  // Per-item bindings for inner loop body, collected uniformly when
@@ -369,8 +373,8 @@ export function collectInnerLoops(
369
373
  // guarantees the branch's marker is mounted the moment this
370
374
  // effect first runs (issue-2706-nested-loop-conditional-slot
371
375
  // .test.ts's original repro).
372
- bindings.reactiveTexts.push(...collectLoopChildReactiveTexts(child, ctx, n.param, n.paramBindings, true, innerPreambleNames, n.index, scope.bindingScope))
373
- bindings.reactiveAttrs.push(...collectLoopChildReactiveAttrs(child, ctx, n.param, n.paramBindings, true, innerPreambleNames, n.index, scope.bindingScope))
376
+ bindings.reactiveTexts.push(...collectLoopChildReactiveTexts(child, ctx, n.param, rowBindings, true, innerPreambleNames, n.index, scope.bindingScope))
377
+ bindings.reactiveAttrs.push(...collectLoopChildReactiveAttrs(child, ctx, n.param, rowBindings, true, innerPreambleNames, n.index, scope.bindingScope))
374
378
  bindings.refs.push(...collectLoopChildRefs(child))
375
379
  }
376
380
  bindings.conditionals.push(...collectLoopChildConditionals(
@@ -378,7 +382,7 @@ export function collectInnerLoops(
378
382
  ctx,
379
383
  siblingOffsets,
380
384
  n.param,
381
- n.paramBindings,
385
+ rowBindings,
382
386
  innerPreambleNames,
383
387
  n.index,
384
388
  // Render a branch's HTML against the FULL ancestor chain (outer
@@ -427,7 +431,7 @@ export function collectInnerLoops(
427
431
  array: n.array,
428
432
  arrayFreeIdentifiers: n.arrayFreeIdentifiers,
429
433
  param: n.param,
430
- paramBindings: n.paramBindings,
434
+ paramBindings: rowBindings,
431
435
  index: n.index,
432
436
  key: n.key,
433
437
  markerId: n.markerId,
@@ -451,7 +455,7 @@ export function collectInnerLoops(
451
455
  descend({
452
456
  ...scope,
453
457
  depth: scope.depth + 1,
454
- bindingScope: buildLoopRowScope(n.param, n.paramBindings, innerPreambleNames, n.index, scope.bindingScope),
458
+ bindingScope: buildLoopRowScope(n.param, rowBindings, innerPreambleNames, n.index, scope.bindingScope),
455
459
  })
456
460
  }
457
461
  },
@@ -36,6 +36,9 @@ import type {
36
36
  import { AttrValueOf, pickAttrMeta } from '../../../types.ts'
37
37
  import {
38
38
  wrapLoopParamAsAccessor,
39
+ rowBoundNames,
40
+ unionNames,
41
+ type ShadowableWrap,
39
42
  attrValueToString,
40
43
  } from '../../utils.ts'
41
44
  import { buildChildRefBindings } from '../shared.ts'
@@ -93,6 +96,13 @@ export interface BuildInnerLoopsArgs {
93
96
  * inside it is looked up through the row's registered roots (`qsaItem`).
94
97
  */
95
98
  rowHasPortal?: boolean
99
+ /**
100
+ * Every enclosing loop's accessor rewrite, composed (#3397). A recursion
101
+ * for a deeper level passes it so a row two or more loops deep still
102
+ * rewrites its grandparent's bindings; the top call builds it from
103
+ * `outerLoopParam`.
104
+ */
105
+ wrapOuter?: ShadowableWrap
96
106
  }
97
107
 
98
108
  /**
@@ -102,9 +112,9 @@ export interface BuildInnerLoopsArgs {
102
112
  */
103
113
  export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
104
114
  const { levels, parentElVar, outerLoopParam, outerLoopParamBindings, outerLoopIndex, rowHasPortal } = args
105
- const wrapOuter = outerLoopParam
106
- ? (expr: string) => wrapLoopParamAsAccessor(expr, outerLoopParam, outerLoopParamBindings, outerLoopIndex)
107
- : (expr: string) => expr
115
+ const wrapOuter: ShadowableWrap = args.wrapOuter ?? (outerLoopParam
116
+ ? (expr, shadowed) => wrapLoopParamAsAccessor(expr, outerLoopParam, outerLoopParamBindings, outerLoopIndex, shadowed)
117
+ : expr => expr)
108
118
 
109
119
  const plan: InnerLoopPlan[] = []
110
120
  let i = 0
@@ -142,6 +152,12 @@ export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
142
152
  outerLoopParam: inner.param,
143
153
  outerLoopParamBindings: inner.paramBindings,
144
154
  outerLoopIndex: inner.index,
155
+ // This row's accessor over every enclosing one, so a deeper row
156
+ // still rewrites the outer rows' bindings (#3397).
157
+ wrapOuter: (expr, shadowed) => wrapLoopParamAsAccessor(
158
+ wrapOuter(expr, unionNames(rowBoundNames(inner), shadowed)),
159
+ inner.param, inner.paramBindings, inner.index, shadowed,
160
+ ),
145
161
  })
146
162
  : []
147
163
 
@@ -170,14 +186,19 @@ export function buildInnerLoopsPlan(args: BuildInnerLoopsArgs): InnerLoopsPlan {
170
186
  function buildReactiveEmit(
171
187
  inner: NestedLoop,
172
188
  level: DepthLevel,
173
- wrapOuter: (expr: string) => string,
189
+ wrapOuter: ShadowableWrap,
174
190
  uidSuffix: string,
175
191
  outerLoopParam?: string,
176
192
  outerLoopParamBindings?: readonly LoopParamBinding[],
177
193
  outerLoopIndex?: string | null,
178
194
  ): InnerLoopReactiveEmit {
179
195
  const wrapInner = (expr: string) => wrapLoopParamAsAccessor(expr, inner.param, inner.paramBindings, inner.index)
180
- const wrapBoth = (expr: string) => wrapLoopParamAsAccessor(wrapOuter(expr), inner.param, inner.paramBindings, inner.index)
196
+ // Inside the inner row, a name it rebinds (item, index, destructure
197
+ // binding, preamble local) is not the outer row's binding (#3394).
198
+ const innerShadowed = rowBoundNames(inner)
199
+ const wrapOuterRow: ShadowableWrap = (expr, shadowed) => wrapOuter(expr, unionNames(innerShadowed, shadowed))
200
+ const wrapBoth: ShadowableWrap = (expr, shadowed) =>
201
+ wrapLoopParamAsAccessor(wrapOuterRow(expr, shadowed), inner.param, inner.paramBindings, inner.index, shadowed)
181
202
  const { head: paramHead, unwrap: paramUnwrap } = destructureLoopParam(inner.param, inner.paramBindings)
182
203
  const wrappedKey = inner.key
183
204
  ? wrapLoopParamAsAccessor(inner.key, inner.param, inner.paramBindings, inner.index)
@@ -217,12 +238,12 @@ function buildReactiveEmit(
217
238
 
218
239
  const reactiveTexts: InnerLoopText[] = inner.bindings.reactiveTexts.map(text => ({
219
240
  slotId: text.slotId,
220
- wrappedExpression: wrapLoopParamAsAccessor(wrapOuter(text.expression), inner.param, inner.paramBindings, inner.index),
241
+ wrappedExpression: wrapLoopParamAsAccessor(wrapOuterRow(text.expression), inner.param, inner.paramBindings, inner.index),
221
242
  insideConditional: !!text.insideConditional,
222
243
  }))
223
244
 
224
245
  const reactiveAttrs: InnerLoopReactiveAttr[] = inner.bindings.reactiveAttrs.map(attr => {
225
- const wrapped = wrapLoopParamAsAccessor(wrapOuter(attr.expression), inner.param, inner.paramBindings, inner.index)
246
+ const wrapped = wrapLoopParamAsAccessor(wrapOuterRow(attr.expression), inner.param, inner.paramBindings, inner.index)
226
247
  return {
227
248
  slotId: attr.childSlotId,
228
249
  attrName: attr.attrName,
@@ -252,15 +273,15 @@ function buildReactiveEmit(
252
273
  if (paramUnwrap) preludeStatements.push(paramUnwrap)
253
274
  if (inner.preamble) {
254
275
  // Leaf JSX renders under both param contexts, mirroring the
255
- // wrapInner(wrapOuter(...)) applied to the js text.
276
+ // wrapInner(wrapOuterRow(...)) applied to the js text.
256
277
  const leafLoopParams = outerLoopParam
257
278
  ? [
258
- { param: outerLoopParam, bindings: outerLoopParamBindings, index: outerLoopIndex },
279
+ { param: outerLoopParam, bindings: outerLoopParamBindings, index: outerLoopIndex, shadowed: innerShadowed },
259
280
  { param: inner.param, bindings: inner.paramBindings, index: inner.index },
260
281
  ]
261
282
  : [{ param: inner.param, bindings: inner.paramBindings, index: inner.index }]
262
283
  preludeStatements.push(renderPreamble(inner.preamble, {
263
- transformJs: (t) => wrapInner(wrapOuter(t)),
284
+ transformJs: (t) => wrapInner(wrapOuterRow(t)),
264
285
  renderLeaf: (ir) => irToHtmlTemplate(ir, undefined, 1, leafLoopParams, undefined),
265
286
  }))
266
287
  }
@@ -24,7 +24,7 @@ import type {
24
24
  LoopParamBinding,
25
25
  } from '../../../types.ts'
26
26
  import { AttrValueOf, pickAttrMeta } from '../../../types.ts'
27
- import { quotePropName, wrapLoopParamAsAccessor, attrValueToString } from '../../utils.ts'
27
+ import { quotePropName, wrapLoopParamAsAccessor, attrValueToString, rowBoundNames, unionNames, type ShadowableWrap } from '../../utils.ts'
28
28
  import { addCondAttrToTemplate, irChildrenToJsExpr } from '../../html-template.ts'
29
29
  import type { ReactiveAttrSlot } from './reactive-effects.ts'
30
30
 
@@ -234,7 +234,7 @@ export interface BuildBranchInnerLoopsArgs {
234
234
  * Outer-wrap closure — defaults to wrapping with `outerLoopParam`. Overridden
235
235
  * by `emitNestedLoopChildConditionals` recursion (which threads its own wrap).
236
236
  */
237
- wrapOuter: (expr: string) => string
237
+ wrapOuter: ShadowableWrap
238
238
  }
239
239
 
240
240
  /**
@@ -269,7 +269,14 @@ export function buildBranchInnerLoopsPlan(
269
269
  if (!inner.template) continue
270
270
 
271
271
  const wrapInner = (expr: string) => wrapLoopParamAsAccessor(expr, inner.param, inner.paramBindings, inner.index)
272
- const wrapBoth = (expr: string) => wrapLoopParamAsAccessor(wrapOuter(expr), inner.param, inner.paramBindings, inner.index)
272
+ // Inside the inner row, a name it rebinds is not the outer row's
273
+ // binding (#3394).
274
+ // `wrapOuter` already composes every enclosing loop's rewrite; pass the
275
+ // shadowed names through it so each of them skips them.
276
+ const innerShadowed = rowBoundNames(inner)
277
+ const wrapOuterRow: ShadowableWrap = (expr, shadowed) => wrapOuter(expr, unionNames(innerShadowed, shadowed))
278
+ const wrapBoth: ShadowableWrap = (expr, shadowed) =>
279
+ wrapLoopParamAsAccessor(wrapOuterRow(expr, shadowed), inner.param, inner.paramBindings, inner.index, shadowed)
273
280
 
274
281
  const csl = inner.containerSlotId
275
282
  // Inner loop's container: host-side `bf="<slot>"` slot marker first,
@@ -378,7 +385,7 @@ export interface BuildLoopChildConditionalsArgs {
378
385
  /** Element variable used as `insert(scopeVar, ...)` first arg. */
379
386
  scopeVar: string
380
387
  /** Wrap closure for condition / HTML / handlers. */
381
- wrap: (expr: string) => string
388
+ wrap: ShadowableWrap
382
389
  /**
383
390
  * Loop param identifier — the wrap that wires the recursion's nested
384
391
  * inner loops uses this. Typically equals the inner loop's param when
@@ -501,7 +508,7 @@ export function buildArmTextsPlan(
501
508
 
502
509
  interface BuildLoopChildArmArgs {
503
510
  branch: LoopChildBranchSummary
504
- wrap: (expr: string) => string
511
+ wrap: ShadowableWrap
505
512
  loopParam: string
506
513
  loopParamBindings?: readonly LoopParamBinding[]
507
514
  /** Loop's index param name, when it declares one (#2861). */
@@ -29,7 +29,7 @@ import type {
29
29
  } from '../../types.ts'
30
30
  import type { LoopParamBinding } from '../../../types.ts'
31
31
  import { pickAttrMeta } from '../../../types.ts'
32
- import { wrapLoopParamAsAccessor } from '../../utils.ts'
32
+ import { wrapLoopParamAsAccessor, type ShadowableWrap } from '../../utils.ts'
33
33
  import { addCondAttrToTemplate } from '../../html-template.ts'
34
34
  import {
35
35
  buildArmAttrsPlan,
@@ -65,7 +65,7 @@ export function buildReactiveEffectsPlan(
65
65
  args: BuildReactiveEffectsArgs,
66
66
  ): ReactiveEffectsPlan {
67
67
  const { attrs, texts, conditionals, loopParam, loopParamBindings, loopIndex, profileComponentName } = args
68
- const wrap = (expr: string) => wrapLoopParamAsAccessor(expr, loopParam, loopParamBindings, loopIndex)
68
+ const wrap: ShadowableWrap = (expr, shadowed) => wrapLoopParamAsAccessor(expr, loopParam, loopParamBindings, loopIndex, shadowed)
69
69
 
70
70
  // 1. Group attrs by slot, preserving declaration order (Map insertion order
71
71
  // matches the legacy iteration that produced byte-identical output).
@@ -232,7 +232,10 @@ export function destructureLoopParam(
232
232
  ): { head: string; unwrap: string } {
233
233
  if (param.startsWith('[') || param.startsWith('{')) {
234
234
  if (paramBindings && paramBindings.length > 0) {
235
- return { head: '__bfItem', unwrap: '' }
235
+ // A nested row names its accessor after its loop (`withRowAccessor`,
236
+ // #3397), so it does not shadow an enclosing row's `__bfItem`.
237
+ const accessor = paramBindings[0].accessor
238
+ return { head: accessor ? accessor.replace(/\(\)$/, '') : '__bfItem', unwrap: '' }
236
239
  }
237
240
  return {
238
241
  head: '__bfItem',