@barefootjs/jsx 0.35.6 → 0.35.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.
@@ -0,0 +1,117 @@
1
+ /**
2
+ * #2924 — a BARE (uncalled) reference to a `call`-kind `CsrSubstitution`
3
+ * entry (a signal/memo getter) must substitute as a thunk over the
4
+ * accessor's value, not the value itself.
5
+ *
6
+ * `buildSignalMemoEnv` registers signal getters and memos as `kind: 'call'`
7
+ * entries: the CALL SITE `count()` substitutes to the accessor's value
8
+ * directly (`(5)`), because calling the accessor IS reading the value. A
9
+ * BARE reference to the same name (`count`, uncalled — e.g. passed as a
10
+ * component prop, `<Display value={count} />`) is not a read: it's the
11
+ * accessor itself, which only exists as a real closure inside `initXxx`'s
12
+ * function scope. Before this fix, `csrSubstituteOnce`'s bare-identifier
13
+ * and shorthand-property branches only matched `kind === 'identifier'`, so
14
+ * a bare `count` fell through untouched and leaked into the module-scope
15
+ * `template` lambda as a genuine free identifier — a guaranteed
16
+ * `ReferenceError` on CSR-fresh-mount.
17
+ *
18
+ * The fix: a bare reference to a `call`-kind entry now substitutes to
19
+ * `(() => (value))` — a thunk over the same value the call form produces.
20
+ * This mirrors the reference adapter's (Hono's) SSR shim for the same
21
+ * shape (`const count = () => 5`), so the CSR template and SSR markup
22
+ * agree on what a bare accessor prop evaluates to.
23
+ *
24
+ * Direct unit coverage of `csrSubstitute` itself; `csr-template-scope-
25
+ * soundness.test.ts`'s case D exercises the same fix through the full
26
+ * compile pipeline.
27
+ */
28
+
29
+ import { describe, test, expect } from 'bun:test'
30
+ import { csrSubstitute, type CsrEnv } from '../ir-to-client-js/csr-substitute.ts'
31
+ import { BindingScope } from '../scope/binding-scope.ts'
32
+
33
+ function callEnv(name: string, replacement: string): CsrEnv {
34
+ return {
35
+ substitutions: new Map([[name, { kind: 'call', replacement, freeIdentifiers: new Set() }]]),
36
+ propsObjectName: null,
37
+ }
38
+ }
39
+
40
+ describe('csrSubstitute: bare reference to a call-kind entry (#2924)', () => {
41
+ test('a called reference still substitutes to the plain value', () => {
42
+ const { rewritten, freeIdentifiers } = csrSubstitute('count()', callEnv('count', '5'))
43
+ expect(rewritten).toBe('(5)')
44
+ expect(freeIdentifiers.size).toBe(0)
45
+ })
46
+
47
+ test('a bare reference substitutes to a thunk over the same value', () => {
48
+ const { rewritten, freeIdentifiers } = csrSubstitute('count', callEnv('count', '5'))
49
+ expect(rewritten).toBe('(() => (5))')
50
+ expect(freeIdentifiers.size).toBe(0)
51
+ })
52
+
53
+ test('a bare reference nested in an object literal value position substitutes to a thunk', () => {
54
+ const { rewritten } = csrSubstitute('{ v: count }', callEnv('count', '5'))
55
+ expect(rewritten).toBe('{ v: (() => (5)) }')
56
+ })
57
+
58
+ test('a bare reference in shorthand-property position substitutes to a thunk, keyed correctly', () => {
59
+ const { rewritten } = csrSubstitute('{ count }', callEnv('count', '5'))
60
+ expect(rewritten).toBe('{ count: (() => (5)) }')
61
+ })
62
+
63
+ test('member access on the bare name is untouched (structural protection, #1100)', () => {
64
+ const { rewritten, freeIdentifiers } = csrSubstitute('ctx.count', callEnv('count', '5'))
65
+ expect(rewritten).toBe('ctx.count')
66
+ expect(freeIdentifiers.has('ctx')).toBe(true)
67
+ expect(freeIdentifiers.has('count')).toBe(false)
68
+ })
69
+
70
+ test('a getter call INSIDE a memo body thunk still substitutes (fixed-point loop)', () => {
71
+ const env: CsrEnv = {
72
+ substitutions: new Map([
73
+ ['count', { kind: 'call', replacement: '5', freeIdentifiers: new Set() }],
74
+ ['doubled', { kind: 'call', replacement: 'count() * 2', freeIdentifiers: new Set(['count']) }],
75
+ ]),
76
+ propsObjectName: null,
77
+ }
78
+ const { rewritten, freeIdentifiers } = csrSubstitute('doubled', env)
79
+ expect(rewritten).toBe('(() => ((5) * 2))')
80
+ expect(freeIdentifiers.size).toBe(0)
81
+ })
82
+
83
+ test('a .map() row parameter shadowing the getter name is not substituted', () => {
84
+ const scope = BindingScope.EMPTY.enterLoopRow({ param: 'count' })
85
+ const { rewritten } = csrSubstitute('count', callEnv('count', '5'), scope)
86
+ expect(rewritten).toBe('count')
87
+ })
88
+
89
+ test('an identifier-kind entry (inlinable const) is unaffected by the thunk rule', () => {
90
+ const env: CsrEnv = {
91
+ substitutions: new Map([['label', { kind: 'identifier', replacement: "'hi'", freeIdentifiers: new Set() }]]),
92
+ propsObjectName: null,
93
+ }
94
+ const { rewritten } = csrSubstitute('label', env)
95
+ expect(rewritten).toBe("('hi')")
96
+ })
97
+ })
98
+
99
+ describe('csrSubstitute: bare reference to a signal setter (#2924, setter-symmetric case)', () => {
100
+ function setterEnv(name: string): CsrEnv {
101
+ return {
102
+ substitutions: new Map([[name, { kind: 'identifier', replacement: '() => {}', freeIdentifiers: new Set() }]]),
103
+ propsObjectName: null,
104
+ }
105
+ }
106
+
107
+ test('a bare setter reference substitutes to the noop shim (identifier-kind, no thunk-wrapping)', () => {
108
+ const { rewritten, freeIdentifiers } = csrSubstitute('setCount', setterEnv('setCount'))
109
+ expect(rewritten).toBe('(() => {})')
110
+ expect(freeIdentifiers.size).toBe(0)
111
+ })
112
+
113
+ test('a setter reference nested in an object literal value position also substitutes', () => {
114
+ const { rewritten } = csrSubstitute('{ onChange: setCount }', setterEnv('setCount'))
115
+ expect(rewritten).toBe('{ onChange: (() => {}) }')
116
+ })
117
+ })
@@ -15,6 +15,14 @@
15
15
  * C. a getter-elided signal (`const [, setActive] = createSignal(0)`)
16
16
  * was dropped from init entirely while its setter stayed referenced
17
17
  * by the emitted handler.
18
+ *
19
+ * D. a component prop whose value is (or contains) a BARE — uncalled —
20
+ * reference to a local signal/memo getter (`<Display value={count} />`,
21
+ * #2924) kept the bare source-level name in the `renderChild(...)`
22
+ * props literal instead of substituting a thunk over its value.
23
+ * E. the setter-symmetric case (`<Display update={setCount} />`, #2924):
24
+ * a bare reference to a signal SETTER hit the identical gap — no
25
+ * substitution entry existed for the setter's name at all.
18
26
  */
19
27
 
20
28
  import { describe, test, expect } from 'bun:test'
@@ -93,6 +101,123 @@ export function Fire() {
93
101
  // statement must exist in the emitted init.
94
102
  expect(clientJs).toMatch(/setFlag\s*\]\s*=\s*createSignal\(0\)/)
95
103
  })
104
+
105
+ test('D: a bare signal getter passed as a component prop substitutes a thunk in the template', () => {
106
+ const clientJs = clientJsOf(`
107
+ "use client"
108
+ import { createSignal } from '@barefootjs/client'
109
+
110
+ function Display(props: { value: () => number }) {
111
+ return <span class="value">{props.value()}</span>
112
+ }
113
+
114
+ export function Counter() {
115
+ const [count, setCount] = createSignal(5)
116
+ return (
117
+ <div class="root">
118
+ <Display value={count} />
119
+ </div>
120
+ )
121
+ }
122
+ `)
123
+ const template = templateLambdaOf(clientJs, 'Counter')
124
+ expect(template).toContain('value: (() => (5))')
125
+ expect(template).not.toMatch(/value:\s*count\b/)
126
+ })
127
+
128
+ test('D: a bare memo getter passed as a component prop substitutes a thunk over its computation', () => {
129
+ const clientJs = clientJsOf(`
130
+ "use client"
131
+ import { createSignal, createMemo } from '@barefootjs/client'
132
+
133
+ function Display(props: { value: () => number }) {
134
+ return <span class="value">{props.value()}</span>
135
+ }
136
+
137
+ export function Counter() {
138
+ const [count] = createSignal(5)
139
+ const doubled = createMemo(() => count() * 2)
140
+ return (
141
+ <div class="root">
142
+ <Display value={doubled} />
143
+ </div>
144
+ )
145
+ }
146
+ `)
147
+ const template = templateLambdaOf(clientJs, 'Counter')
148
+ expect(template).toContain('value: (() => ((5) * 2))')
149
+ expect(template).not.toMatch(/value:\s*doubled\b/)
150
+ })
151
+
152
+ test('D: a bare getter wrapped in an object literal prop also substitutes a thunk (Context-Provider idiom)', () => {
153
+ const clientJs = clientJsOf(`
154
+ "use client"
155
+ import { createSignal } from '@barefootjs/client'
156
+
157
+ function Display(props: { value: { v: () => number } }) {
158
+ return <span class="value">{props.value.v()}</span>
159
+ }
160
+
161
+ export function Counter() {
162
+ const [count, setCount] = createSignal(5)
163
+ return (
164
+ <div class="root">
165
+ <Display value={{ v: count }} />
166
+ </div>
167
+ )
168
+ }
169
+ `)
170
+ const template = templateLambdaOf(clientJs, 'Counter')
171
+ expect(template).toContain('{ v: (() => (5)) }')
172
+ expect(template).not.toMatch(/\{\s*v:\s*count\s*\}/)
173
+ })
174
+
175
+ test('D: a getter-only const alias (e.g. `const c2 = count`) inlines the same thunk, not a deferred placeholder', () => {
176
+ const clientJs = clientJsOf(`
177
+ "use client"
178
+ import { createSignal } from '@barefootjs/client'
179
+
180
+ function Display(props: { value: () => number }) {
181
+ return <span class="value">{props.value()}</span>
182
+ }
183
+
184
+ export function Counter() {
185
+ const [count, setCount] = createSignal(5)
186
+ const c2 = count
187
+ return (
188
+ <div class="root">
189
+ <Display value={c2} />
190
+ </div>
191
+ )
192
+ }
193
+ `)
194
+ const template = templateLambdaOf(clientJs, 'Counter')
195
+ expect(template).toContain('value: (() => (5))')
196
+ expect(template).not.toContain('data-bf-ph')
197
+ })
198
+
199
+ test('E: a bare signal setter passed as a component prop substitutes the SSR noop shim', () => {
200
+ const clientJs = clientJsOf(`
201
+ "use client"
202
+ import { createSignal } from '@barefootjs/client'
203
+
204
+ function Display(props: { update: () => void }) {
205
+ return <button onClick={() => props.update()}>go</button>
206
+ }
207
+
208
+ export function Counter() {
209
+ const [count, setCount] = createSignal(5)
210
+ return (
211
+ <div class="root">
212
+ <Display update={setCount} />
213
+ </div>
214
+ )
215
+ }
216
+ `)
217
+ const template = templateLambdaOf(clientJs, 'Counter')
218
+ expect(template).toContain('update: (() => {})')
219
+ expect(template).not.toMatch(/update:\s*setCount\b/)
220
+ })
96
221
  })
97
222
 
98
223
  /**
@@ -0,0 +1,141 @@
1
+ /**
2
+ * #2960 — `addCondAttrToTemplate`'s `isSingleRootElement` heuristic
3
+ * mis-classified a multi-root ternary branch as a single element root
4
+ * whenever its LAST element happened to share its FIRST element's tag
5
+ * name (`<div>...</div><div>...</div>`): the check was "does the string
6
+ * end with a closing tag of the root's own tag name", which a second,
7
+ * unrelated sibling of the same tag name satisfies just as well as a
8
+ * genuine single root's own closing tag.
9
+ *
10
+ * Compiled wrong, this stamps `bf-c="<id>"` onto only the first element
11
+ * instead of comment-wrapping the whole branch — which routes the
12
+ * runtime's branch swap through `insert()`'s `updateElementConditional`
13
+ * (`fragment.firstChild`-only) instead of `updateFragmentConditional`
14
+ * (which moves every top-level node), silently dropping every sibling
15
+ * but the first on a live branch swap.
16
+ */
17
+ import { describe, test, expect } from 'bun:test'
18
+ import { compileJSX } from '../compiler'
19
+ import { TestAdapter } from '../adapters/test-adapter'
20
+ import { addCondAttrToTemplate } from '../ir-to-client-js/html-template'
21
+
22
+ const adapter = new TestAdapter()
23
+
24
+ describe('#2960: multi-root cond branch whose roots share a tag name', () => {
25
+ test('comment-wraps a same-tag-name multi-root branch instead of stamping bf-c on only the first element', () => {
26
+ const source = `
27
+ 'use client'
28
+ import { createSignal } from '@barefootjs/client'
29
+
30
+ export function Repro() {
31
+ const [open, setOpen] = createSignal(false)
32
+ return (
33
+ <div>
34
+ <button onClick={() => setOpen(true)}>open</button>
35
+ {open() === false ? (
36
+ <div id="welcome">Welcome</div>
37
+ ) : (
38
+ <>
39
+ <div id="before">before</div>
40
+ <div id="after">after</div>
41
+ </>
42
+ )}
43
+ </div>
44
+ )
45
+ }
46
+ `
47
+
48
+ const result = compileJSX(source, 'Repro.tsx', { adapter })
49
+ expect(result.errors).toHaveLength(0)
50
+
51
+ const clientJs = result.files.find(f => f.type === 'clientJs')
52
+ expect(clientJs).toBeDefined()
53
+
54
+ // The multi-root branch must be comment-wrapped ...
55
+ expect(clientJs!.content).toContain('bf-cond-start:')
56
+ expect(clientJs!.content).toContain('bf-cond-end:')
57
+ // ... and BOTH of its sibling elements must appear inside the
58
+ // template literal, not just the first one.
59
+ expect(clientJs!.content).toMatch(/id=\\?"before\\?"/)
60
+ expect(clientJs!.content).toMatch(/id=\\?"after\\?"/)
61
+ })
62
+
63
+ test('a genuine single-root branch (no same-tag sibling) still gets bf-c, not comment markers', () => {
64
+ const source = `
65
+ 'use client'
66
+ import { createSignal } from '@barefootjs/client'
67
+
68
+ export function Simple() {
69
+ const [on, setOn] = createSignal(false)
70
+ return <div>{on() ? <span id="a">A</span> : <span id="b">B</span>}</div>
71
+ }
72
+ `
73
+
74
+ const result = compileJSX(source, 'Simple.tsx', { adapter })
75
+ expect(result.errors).toHaveLength(0)
76
+
77
+ const clientJs = result.files.find(f => f.type === 'clientJs')
78
+ expect(clientJs).toBeDefined()
79
+ expect(clientJs!.content).toContain('bf-c=')
80
+ expect(clientJs!.content).not.toContain('bf-cond-start:')
81
+ })
82
+
83
+ // The depth-tracking fix above must not widen which shapes are treated
84
+ // as "single root" beyond what the sibling `bf-c` splice regex
85
+ // (`html.replace(/^(<\w+)(\s|>)/, ...)`) can actually stamp — a
86
+ // self-closing root's own `/` or a hyphenated custom-element tag name
87
+ // both fail that splice. Every one of these must still come back
88
+ // comment-wrapped (never bare, unmodified HTML with neither `bf-c` nor
89
+ // markers, which would make `insert()` unable to find the branch at all).
90
+ describe('does not widen single-root detection into shapes the bf-c splice cannot stamp', () => {
91
+ const unstampable = [
92
+ ['<input/>', 'self-closing void element root'],
93
+ ['<my-widget>a</my-widget>', 'hyphenated custom-element root'],
94
+ ['<my-widget>a</my-widget><my-widget>b</my-widget>', 'multi-root, same hyphenated tag'],
95
+ ] as const
96
+
97
+ for (const [html, label] of unstampable) {
98
+ test(label, () => {
99
+ const result = addCondAttrToTemplate(html, 'c1')
100
+ expect(result).toContain('bf-cond-start:c1')
101
+ expect(result).toContain('bf-cond-end:c1')
102
+ })
103
+ }
104
+ })
105
+
106
+ // The depth-tracking walk must not treat BarefootJS's own marker
107
+ // comments (`<!--bf:sN-->`, its `<!--/-->` pair) as if they were real
108
+ // tags — an earlier version of this fix's tag-matching regex matched
109
+ // any `<...>` run indiscriminately, so a perfectly ordinary single-root
110
+ // branch with an internal reactive text slot got miscounted into an
111
+ // unbalanced depth and wrongly comment-wrapped instead of getting
112
+ // `bf-c`. Caught by `doc-examples.test.ts`'s snapshot drifting on the
113
+ // `count() > 0 ? <p>...</p> : <p>No items</p>` example.
114
+ test('a single root containing internal bf: slot marker comments still gets bf-c, not comment-wrap', () => {
115
+ const html = '<p bf="s2"><!--bf:s1-->${__bfSlot(count(), __slots)}<!--/--> items</p>'
116
+ const result = addCondAttrToTemplate(html, 's0')
117
+ expect(result).toContain('bf-c="s0"')
118
+ expect(result).not.toContain('bf-cond-start:')
119
+ })
120
+
121
+ // A self-closing/void root followed by a real sibling element
122
+ // (`<input .../><label>...</label>`, todo-app's "mark all as complete"
123
+ // branch) is genuinely two roots. The whole-string self-closing check
124
+ // only catches a self-closing tag with NOTHING else in the string, so
125
+ // this shape still reaches the depth-tracking walk — an earlier version
126
+ // of that walk unconditionally `continue`d past every self-closing tag
127
+ // on the theory that one could never be the outermost token by the time
128
+ // the walk runs, which is wrong: the initial tag-name gate only checks
129
+ // the tag name and the character right after it, not whether the tag
130
+ // later turns out to self-close. That version silently merged the
131
+ // `<input/>` and `<label>` into a false single root, stamping `bf-c`
132
+ // onto only the `<input/>` and dropping `<label>` on a live swap.
133
+ // Caught by `generate-expected-html.ts` drifting the `todo-app` fixture.
134
+ test('a self-closing root followed by a sibling element is multi-root, not single', () => {
135
+ const html = '<input id="toggle-all" class="toggle-all" type="checkbox" bf="s2" /><label for="toggle-all">Mark all as complete</label>'
136
+ const result = addCondAttrToTemplate(html, 's1')
137
+ expect(result).toContain('bf-cond-start:s1')
138
+ expect(result).toContain('bf-cond-end:s1')
139
+ expect(result).not.toContain('bf-c=')
140
+ })
141
+ })
@@ -0,0 +1,286 @@
1
+ /**
2
+ * Module-level helper functions referenced from a component (#2986).
3
+ *
4
+ * `visit()`'s module-level walk used to descend into the body of a
5
+ * module-level `const f = (…) => { … }` and collect that body's inner
6
+ * `const`/`function` declarations as if they were declarations of the
7
+ * FILE itself — hoisted into both the component's init function and the
8
+ * marked template, where their references to the helper's own
9
+ * parameters are unbound. The `function f(…) { … }` declaration form was
10
+ * immune (the module-level branch `return`s right after collecting it,
11
+ * so it is never walked into) — that asymmetry is what the issue
12
+ * reported as "function vs const arrow" being inlined differently.
13
+ *
14
+ * Pre-fix, the leaked inner declaration appeared TWICE in the emitted
15
+ * client JS: once (broken — unbound param refs) hoisted to the top of
16
+ * init, and once more correctly inside the helper's own body. Every
17
+ * "does not leak" assertion below therefore checks the occurrence COUNT
18
+ * of the inner statement, not just its presence — a bare `.toContain`
19
+ * would pass on both the broken and the fixed output.
20
+ *
21
+ * Every parity case asserts that the `const` arrow form and the
22
+ * `function` declaration form agree — that agreement is the property
23
+ * whose absence produced the bug, and the guard this test protects
24
+ * (`isFunctionScope`, `analyzer.ts`) is now the single shared answer to
25
+ * "does this node open a new function scope?" for both the module-level
26
+ * walk (`visit`) and the component-body walk (`visitComponentBody`).
27
+ */
28
+
29
+ import { describe, test, expect } from 'bun:test'
30
+ import { compileJSX } from '../index'
31
+ import { HonoAdapter } from '../../../adapter-hono/src/adapter'
32
+
33
+ function compile(source: string) {
34
+ const result = compileJSX(source, 'ModuleHelper.tsx', { adapter: new HonoAdapter() })
35
+ const clientJs = result.files.find(f => f.type === 'clientJs')?.content ?? ''
36
+ const markedTemplate = result.files.find(f => f.type === 'markedTemplate')?.content ?? ''
37
+ return { result, clientJs, markedTemplate }
38
+ }
39
+
40
+ function countOccurrences(haystack: string, needle: string): number {
41
+ return haystack.split(needle).length - 1
42
+ }
43
+
44
+ describe('module-level helper functions (#2986)', () => {
45
+ test('sync block-bodied helper: inner declaration stays inside the helper, not hoisted into init', () => {
46
+ const { result, clientJs, markedTemplate } = compile(`
47
+ 'use client'
48
+ import { createSignal } from '@barefootjs/client'
49
+ const score = (title: string, term: string): number => {
50
+ const t = title.toLowerCase()
51
+ return t.includes(term) ? 1 : 0
52
+ }
53
+ export function Search() {
54
+ const [term, setTerm] = createSignal('')
55
+ return <div onClick={() => setTerm('x')}>{score('hello', term())}</div>
56
+ }
57
+ `)
58
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
59
+ // Pre-fix this line was duplicated: once (broken) at the top of init
60
+ // and once inside `score`'s own body. It must appear exactly once.
61
+ expect(countOccurrences(clientJs, 'const t = title.toLowerCase()')).toBe(1)
62
+ expect(clientJs).toContain('const score = (title, term) => {')
63
+ // The Hono reference adapter's marked template is TSX source rendered
64
+ // through the JSX runtime, so it legitimately contains the helper
65
+ // once, correctly scoped — pre-fix it was duplicated here too.
66
+ expect(countOccurrences(markedTemplate, 'const t = title.toLowerCase()')).toBe(1)
67
+ })
68
+
69
+ test('async helper: no top-level-of-init await, async wrapper intact, no bare await in the template', () => {
70
+ const { result, clientJs, markedTemplate } = compile(`
71
+ 'use client'
72
+ import { createSignal, onMount } from '@barefootjs/client'
73
+ const loadData = async (): Promise<string[]> => {
74
+ const res = await fetch('/data.json')
75
+ return res.json()
76
+ }
77
+ function Widget() {
78
+ const [items, setItems] = createSignal<string[]>([])
79
+ onMount(() => { void loadData().then(setItems) })
80
+ return <div>{items().length}</div>
81
+ }
82
+ export default Widget
83
+ `)
84
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
85
+ expect(countOccurrences(clientJs, "await fetch('/data.json')")).toBe(1)
86
+ expect(clientJs).toContain('const loadData = async () => {')
87
+ // Same reasoning as the sync case: the reference adapter's marked
88
+ // template is TSX source, so `loadData` legitimately appears once,
89
+ // correctly scoped — pre-fix its inner `await` was duplicated here.
90
+ expect(countOccurrences(markedTemplate, "await fetch('/data.json')")).toBe(1)
91
+ })
92
+
93
+ test('object-literal property arrow: an async method on a module-level object const does not leak', () => {
94
+ const { result, clientJs } = compile(`
95
+ 'use client'
96
+ import { createSignal } from '@barefootjs/client'
97
+ const api = {
98
+ load: async () => {
99
+ const res = await fetch('/data.json')
100
+ return res.json()
101
+ },
102
+ }
103
+ export function Widget() {
104
+ const [count, setCount] = createSignal(0)
105
+ return <button onClick={() => { void api.load(); setCount(count() + 1) }}>{count()}</button>
106
+ }
107
+ `)
108
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
109
+ expect(countOccurrences(clientJs, "await fetch('/data.json')")).toBe(1)
110
+ })
111
+
112
+ test('nested function inside a module arrow does not escape to module scope', () => {
113
+ const { result, clientJs } = compile(`
114
+ 'use client'
115
+ import { createSignal } from '@barefootjs/client'
116
+ const outer = (v: number) => {
117
+ function inner(q: number) { return q + v }
118
+ return inner(1)
119
+ }
120
+ export function Widget() {
121
+ const [count, setCount] = createSignal(0)
122
+ return <button onClick={() => setCount(outer(count()))}>{count()}</button>
123
+ }
124
+ `)
125
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
126
+ expect(clientJs).not.toMatch(/var inner = inner \?\?/)
127
+ })
128
+
129
+ test('factory arrow containing createSignal: no false BF011 (SIGNAL_OUTSIDE_COMPONENT)', () => {
130
+ const { result } = compile(`
131
+ 'use client'
132
+ import { createSignal } from '@barefootjs/client'
133
+ const mk = () => {
134
+ const [a, setA] = createSignal(0)
135
+ return a
136
+ }
137
+ export function Widget() {
138
+ const a = mk()
139
+ return <div>{a()}</div>
140
+ }
141
+ `)
142
+ expect(result.errors.filter(e => e.code === 'BF011')).toEqual([])
143
+ })
144
+
145
+ test('component-body object method: an inline method on a component-local const does not leak into init', () => {
146
+ const { result, clientJs } = compile(`
147
+ 'use client'
148
+ import { createSignal } from '@barefootjs/client'
149
+ export function Widget() {
150
+ const [count, setCount] = createSignal(0)
151
+ const api = {
152
+ load() {
153
+ const r = 1
154
+ return r
155
+ },
156
+ }
157
+ return <button onClick={() => setCount(count() + api.load())}>{count()}</button>
158
+ }
159
+ `)
160
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
161
+ expect(countOccurrences(clientJs, 'const r = 1')).toBe(1)
162
+ })
163
+
164
+ test('guard: a component-body async function declaration referencing component scope still lowers to an async arrow in init', () => {
165
+ const { result, clientJs } = compile(`
166
+ 'use client'
167
+ import { createSignal } from '@barefootjs/client'
168
+ export function Widget() {
169
+ const [items, setItems] = createSignal<string[]>([])
170
+ async function fetchItems() {
171
+ const res = await fetch('/data.json')
172
+ setItems(await res.json())
173
+ }
174
+ return <button onClick={() => fetchItems()}>{items().length}</button>
175
+ }
176
+ `)
177
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
178
+ // References `setItems` (component scope), so `compute-scope`'s
179
+ // fixpoint must demote it to init scope, same as the #1130 pin.
180
+ expect(clientJs).toMatch(/const\s+fetchItems\s*=\s*async\s*\(/)
181
+ })
182
+
183
+ test('guard: a module-level async helper with no component-scope references is safely promoted to module scope', () => {
184
+ const { result, clientJs } = compile(`
185
+ 'use client'
186
+ import { createSignal, onMount } from '@barefootjs/client'
187
+ export function Widget() {
188
+ const [items, setItems] = createSignal<string[]>([])
189
+ async function fetchItems() {
190
+ const res = await fetch('/data.json')
191
+ return res.json()
192
+ }
193
+ onMount(() => { void fetchItems().then(setItems) })
194
+ return <div>{items().length}</div>
195
+ }
196
+ `)
197
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
198
+ // `fetchItems` closes over nothing component-scoped, so it is free to
199
+ // live at true module scope; it must still be a valid, complete async
200
+ // function exactly once (not leaked/duplicated into init).
201
+ expect(countOccurrences(clientJs, "await fetch('/data.json')")).toBe(1)
202
+ })
203
+
204
+ test('guard: an arrow component still collects a function declared inside its own body', () => {
205
+ const { result, clientJs } = compile(`
206
+ 'use client'
207
+ import { createSignal } from '@barefootjs/client'
208
+ const Widget = () => {
209
+ function helper(n: number) { return n * 2 }
210
+ const [count, setCount] = createSignal(0)
211
+ return <button onClick={() => setCount(helper(count()))}>{count()}</button>
212
+ }
213
+ export default Widget
214
+ `)
215
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
216
+ expect(clientJs).toContain('helper')
217
+ })
218
+
219
+ describe('parity between the `const` arrow form and the `function` declaration form', () => {
220
+ test('sync block-bodied helper: neither form duplicates the inner statement', () => {
221
+ const arrowForm = compile(`
222
+ 'use client'
223
+ import { createSignal } from '@barefootjs/client'
224
+ const score = (title: string, term: string): number => {
225
+ const t = title.toLowerCase()
226
+ return t.includes(term) ? 1 : 0
227
+ }
228
+ export function Search() {
229
+ const [term, setTerm] = createSignal('')
230
+ return <div onClick={() => setTerm('x')}>{score('hello', term())}</div>
231
+ }
232
+ `)
233
+ const functionForm = compile(`
234
+ 'use client'
235
+ import { createSignal } from '@barefootjs/client'
236
+ function score(title: string, term: string): number {
237
+ const t = title.toLowerCase()
238
+ return t.includes(term) ? 1 : 0
239
+ }
240
+ export function Search() {
241
+ const [term, setTerm] = createSignal('')
242
+ return <div onClick={() => setTerm('x')}>{score('hello', term())}</div>
243
+ }
244
+ `)
245
+ expect(arrowForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
246
+ expect(functionForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
247
+ expect(countOccurrences(arrowForm.clientJs, 'const t = title.toLowerCase()')).toBe(1)
248
+ expect(countOccurrences(functionForm.clientJs, 'const t = title.toLowerCase()')).toBe(1)
249
+ })
250
+
251
+ test('async helper: neither form duplicates the inner await', () => {
252
+ const arrowForm = compile(`
253
+ 'use client'
254
+ import { createSignal, onMount } from '@barefootjs/client'
255
+ const loadData = async (): Promise<string[]> => {
256
+ const res = await fetch('/data.json')
257
+ return res.json()
258
+ }
259
+ function Widget() {
260
+ const [items, setItems] = createSignal<string[]>([])
261
+ onMount(() => { void loadData().then(setItems) })
262
+ return <div>{items().length}</div>
263
+ }
264
+ export default Widget
265
+ `)
266
+ const functionForm = compile(`
267
+ 'use client'
268
+ import { createSignal, onMount } from '@barefootjs/client'
269
+ async function loadData(): Promise<string[]> {
270
+ const res = await fetch('/data.json')
271
+ return res.json()
272
+ }
273
+ function Widget() {
274
+ const [items, setItems] = createSignal<string[]>([])
275
+ onMount(() => { void loadData().then(setItems) })
276
+ return <div>{items().length}</div>
277
+ }
278
+ export default Widget
279
+ `)
280
+ expect(arrowForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
281
+ expect(functionForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
282
+ expect(countOccurrences(arrowForm.clientJs, "await fetch('/data.json')")).toBe(1)
283
+ expect(countOccurrences(functionForm.clientJs, "await fetch('/data.json')")).toBe(1)
284
+ })
285
+ })
286
+ })