@barefootjs/jsx 0.35.7 → 0.36.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/directives.d.ts +70 -0
- package/dist/directives.d.ts.map +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +174 -120
- package/dist/ir-to-client-js/compute-inlinability.d.ts +10 -0
- package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
- package/dist/ir-to-client-js/compute-scope.d.ts.map +1 -1
- package/dist/ir-to-client-js/csr-substitute.d.ts +25 -5
- package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
- package/dist/ir-to-client-js/emit-module-level.d.ts.map +1 -1
- package/dist/ir-to-client-js/imports.d.ts +2 -2
- package/dist/ir-to-client-js/imports.d.ts.map +1 -1
- package/dist/jsx-to-ir.d.ts.map +1 -1
- package/dist/preprocess-inline-jsx-callbacks.d.ts.map +1 -1
- package/dist/ssr-defaults.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/csr-substitute-bare-getter.test.ts +117 -0
- package/src/__tests__/csr-template-scope-soundness.test.ts +125 -0
- package/src/__tests__/module-function-helper-chain-3000.test.ts +200 -0
- package/src/__tests__/module-helper-scope-2986.test.ts +296 -0
- package/src/__tests__/module-scope-arrow-const-2988.test.ts +180 -0
- package/src/__tests__/reactive-factory-cross-file.test.ts +37 -0
- package/src/__tests__/ssr-defaults.test.ts +24 -2
- package/src/analyzer.ts +48 -19
- package/src/directives.ts +75 -0
- package/src/index.ts +3 -0
- package/src/ir-to-client-js/compute-inlinability.ts +92 -16
- package/src/ir-to-client-js/compute-scope.ts +72 -18
- package/src/ir-to-client-js/csr-substitute.ts +61 -11
- package/src/ir-to-client-js/emit-module-level.ts +10 -1
- package/src/ir-to-client-js/imports.ts +5 -0
- package/src/jsx-to-ir.ts +1 -1
- package/src/preprocess-inline-jsx-callbacks.ts +2 -1
- package/src/ssr-defaults.ts +32 -0
|
@@ -0,0 +1,296 @@
|
|
|
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
|
+
// `score` closes over nothing but its own params, so #2988's
|
|
63
|
+
// compute-scope fixpoint now promotes it to true module scope
|
|
64
|
+
// (`var score = score ?? (...)`, parenthesised — an arrow is not a
|
|
65
|
+
// valid bare `??` operand) instead of leaving it a per-instance
|
|
66
|
+
// `const` inside `initSearch`. This is the shape #2988 exists to
|
|
67
|
+
// produce; pre-#2988 this assertion read
|
|
68
|
+
// `expect(clientJs).toContain('const score = (title, term) => {')`.
|
|
69
|
+
expect(clientJs).toContain('var score = score ?? ((title, term) => {')
|
|
70
|
+
// The Hono reference adapter's marked template is TSX source rendered
|
|
71
|
+
// through the JSX runtime, so it legitimately contains the helper
|
|
72
|
+
// once, correctly scoped — pre-fix it was duplicated here too.
|
|
73
|
+
expect(countOccurrences(markedTemplate, 'const t = title.toLowerCase()')).toBe(1)
|
|
74
|
+
})
|
|
75
|
+
|
|
76
|
+
test('async helper: no top-level-of-init await, async wrapper intact, no bare await in the template', () => {
|
|
77
|
+
const { result, clientJs, markedTemplate } = compile(`
|
|
78
|
+
'use client'
|
|
79
|
+
import { createSignal, onMount } from '@barefootjs/client'
|
|
80
|
+
const loadData = async (): Promise<string[]> => {
|
|
81
|
+
const res = await fetch('/data.json')
|
|
82
|
+
return res.json()
|
|
83
|
+
}
|
|
84
|
+
function Widget() {
|
|
85
|
+
const [items, setItems] = createSignal<string[]>([])
|
|
86
|
+
onMount(() => { void loadData().then(setItems) })
|
|
87
|
+
return <div>{items().length}</div>
|
|
88
|
+
}
|
|
89
|
+
export default Widget
|
|
90
|
+
`)
|
|
91
|
+
expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
92
|
+
expect(countOccurrences(clientJs, "await fetch('/data.json')")).toBe(1)
|
|
93
|
+
// Same #2988 promotion as the sync case above: `loadData` closes
|
|
94
|
+
// over nothing but its own (empty) params, so it is now hoisted to
|
|
95
|
+
// real module scope instead of staying a per-instance `const`.
|
|
96
|
+
expect(clientJs).toContain('var loadData = loadData ?? (async () => {')
|
|
97
|
+
// Same reasoning as the sync case: the reference adapter's marked
|
|
98
|
+
// template is TSX source, so `loadData` legitimately appears once,
|
|
99
|
+
// correctly scoped — pre-fix its inner `await` was duplicated here.
|
|
100
|
+
expect(countOccurrences(markedTemplate, "await fetch('/data.json')")).toBe(1)
|
|
101
|
+
})
|
|
102
|
+
|
|
103
|
+
test('object-literal property arrow: an async method on a module-level object const does not leak', () => {
|
|
104
|
+
const { result, clientJs } = compile(`
|
|
105
|
+
'use client'
|
|
106
|
+
import { createSignal } from '@barefootjs/client'
|
|
107
|
+
const api = {
|
|
108
|
+
load: async () => {
|
|
109
|
+
const res = await fetch('/data.json')
|
|
110
|
+
return res.json()
|
|
111
|
+
},
|
|
112
|
+
}
|
|
113
|
+
export function Widget() {
|
|
114
|
+
const [count, setCount] = createSignal(0)
|
|
115
|
+
return <button onClick={() => { void api.load(); setCount(count() + 1) }}>{count()}</button>
|
|
116
|
+
}
|
|
117
|
+
`)
|
|
118
|
+
expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
119
|
+
expect(countOccurrences(clientJs, "await fetch('/data.json')")).toBe(1)
|
|
120
|
+
})
|
|
121
|
+
|
|
122
|
+
test('nested function inside a module arrow does not escape to module scope', () => {
|
|
123
|
+
const { result, clientJs } = compile(`
|
|
124
|
+
'use client'
|
|
125
|
+
import { createSignal } from '@barefootjs/client'
|
|
126
|
+
const outer = (v: number) => {
|
|
127
|
+
function inner(q: number) { return q + v }
|
|
128
|
+
return inner(1)
|
|
129
|
+
}
|
|
130
|
+
export function Widget() {
|
|
131
|
+
const [count, setCount] = createSignal(0)
|
|
132
|
+
return <button onClick={() => setCount(outer(count()))}>{count()}</button>
|
|
133
|
+
}
|
|
134
|
+
`)
|
|
135
|
+
expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
136
|
+
expect(clientJs).not.toMatch(/var inner = inner \?\?/)
|
|
137
|
+
})
|
|
138
|
+
|
|
139
|
+
test('factory arrow containing createSignal: no false BF011 (SIGNAL_OUTSIDE_COMPONENT)', () => {
|
|
140
|
+
const { result } = compile(`
|
|
141
|
+
'use client'
|
|
142
|
+
import { createSignal } from '@barefootjs/client'
|
|
143
|
+
const mk = () => {
|
|
144
|
+
const [a, setA] = createSignal(0)
|
|
145
|
+
return a
|
|
146
|
+
}
|
|
147
|
+
export function Widget() {
|
|
148
|
+
const a = mk()
|
|
149
|
+
return <div>{a()}</div>
|
|
150
|
+
}
|
|
151
|
+
`)
|
|
152
|
+
expect(result.errors.filter(e => e.code === 'BF011')).toEqual([])
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
test('component-body object method: an inline method on a component-local const does not leak into init', () => {
|
|
156
|
+
const { result, clientJs } = compile(`
|
|
157
|
+
'use client'
|
|
158
|
+
import { createSignal } from '@barefootjs/client'
|
|
159
|
+
export function Widget() {
|
|
160
|
+
const [count, setCount] = createSignal(0)
|
|
161
|
+
const api = {
|
|
162
|
+
load() {
|
|
163
|
+
const r = 1
|
|
164
|
+
return r
|
|
165
|
+
},
|
|
166
|
+
}
|
|
167
|
+
return <button onClick={() => setCount(count() + api.load())}>{count()}</button>
|
|
168
|
+
}
|
|
169
|
+
`)
|
|
170
|
+
expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
171
|
+
expect(countOccurrences(clientJs, 'const r = 1')).toBe(1)
|
|
172
|
+
})
|
|
173
|
+
|
|
174
|
+
test('guard: a component-body async function declaration referencing component scope still lowers to an async arrow in init', () => {
|
|
175
|
+
const { result, clientJs } = compile(`
|
|
176
|
+
'use client'
|
|
177
|
+
import { createSignal } from '@barefootjs/client'
|
|
178
|
+
export function Widget() {
|
|
179
|
+
const [items, setItems] = createSignal<string[]>([])
|
|
180
|
+
async function fetchItems() {
|
|
181
|
+
const res = await fetch('/data.json')
|
|
182
|
+
setItems(await res.json())
|
|
183
|
+
}
|
|
184
|
+
return <button onClick={() => fetchItems()}>{items().length}</button>
|
|
185
|
+
}
|
|
186
|
+
`)
|
|
187
|
+
expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
188
|
+
// References `setItems` (component scope), so `compute-scope`'s
|
|
189
|
+
// fixpoint must demote it to init scope, same as the #1130 pin.
|
|
190
|
+
expect(clientJs).toMatch(/const\s+fetchItems\s*=\s*async\s*\(/)
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
test('guard: a module-level async helper with no component-scope references is safely promoted to module scope', () => {
|
|
194
|
+
const { result, clientJs } = compile(`
|
|
195
|
+
'use client'
|
|
196
|
+
import { createSignal, onMount } from '@barefootjs/client'
|
|
197
|
+
export function Widget() {
|
|
198
|
+
const [items, setItems] = createSignal<string[]>([])
|
|
199
|
+
async function fetchItems() {
|
|
200
|
+
const res = await fetch('/data.json')
|
|
201
|
+
return res.json()
|
|
202
|
+
}
|
|
203
|
+
onMount(() => { void fetchItems().then(setItems) })
|
|
204
|
+
return <div>{items().length}</div>
|
|
205
|
+
}
|
|
206
|
+
`)
|
|
207
|
+
expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
208
|
+
// `fetchItems` closes over nothing component-scoped, so it is free to
|
|
209
|
+
// live at true module scope; it must still be a valid, complete async
|
|
210
|
+
// function exactly once (not leaked/duplicated into init).
|
|
211
|
+
expect(countOccurrences(clientJs, "await fetch('/data.json')")).toBe(1)
|
|
212
|
+
})
|
|
213
|
+
|
|
214
|
+
test('guard: an arrow component still collects a function declared inside its own body', () => {
|
|
215
|
+
const { result, clientJs } = compile(`
|
|
216
|
+
'use client'
|
|
217
|
+
import { createSignal } from '@barefootjs/client'
|
|
218
|
+
const Widget = () => {
|
|
219
|
+
function helper(n: number) { return n * 2 }
|
|
220
|
+
const [count, setCount] = createSignal(0)
|
|
221
|
+
return <button onClick={() => setCount(helper(count()))}>{count()}</button>
|
|
222
|
+
}
|
|
223
|
+
export default Widget
|
|
224
|
+
`)
|
|
225
|
+
expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
226
|
+
expect(clientJs).toContain('helper')
|
|
227
|
+
})
|
|
228
|
+
|
|
229
|
+
describe('parity between the `const` arrow form and the `function` declaration form', () => {
|
|
230
|
+
test('sync block-bodied helper: neither form duplicates the inner statement', () => {
|
|
231
|
+
const arrowForm = compile(`
|
|
232
|
+
'use client'
|
|
233
|
+
import { createSignal } from '@barefootjs/client'
|
|
234
|
+
const score = (title: string, term: string): number => {
|
|
235
|
+
const t = title.toLowerCase()
|
|
236
|
+
return t.includes(term) ? 1 : 0
|
|
237
|
+
}
|
|
238
|
+
export function Search() {
|
|
239
|
+
const [term, setTerm] = createSignal('')
|
|
240
|
+
return <div onClick={() => setTerm('x')}>{score('hello', term())}</div>
|
|
241
|
+
}
|
|
242
|
+
`)
|
|
243
|
+
const functionForm = compile(`
|
|
244
|
+
'use client'
|
|
245
|
+
import { createSignal } from '@barefootjs/client'
|
|
246
|
+
function score(title: string, term: string): number {
|
|
247
|
+
const t = title.toLowerCase()
|
|
248
|
+
return t.includes(term) ? 1 : 0
|
|
249
|
+
}
|
|
250
|
+
export function Search() {
|
|
251
|
+
const [term, setTerm] = createSignal('')
|
|
252
|
+
return <div onClick={() => setTerm('x')}>{score('hello', term())}</div>
|
|
253
|
+
}
|
|
254
|
+
`)
|
|
255
|
+
expect(arrowForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
256
|
+
expect(functionForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
257
|
+
expect(countOccurrences(arrowForm.clientJs, 'const t = title.toLowerCase()')).toBe(1)
|
|
258
|
+
expect(countOccurrences(functionForm.clientJs, 'const t = title.toLowerCase()')).toBe(1)
|
|
259
|
+
})
|
|
260
|
+
|
|
261
|
+
test('async helper: neither form duplicates the inner await', () => {
|
|
262
|
+
const arrowForm = compile(`
|
|
263
|
+
'use client'
|
|
264
|
+
import { createSignal, onMount } from '@barefootjs/client'
|
|
265
|
+
const loadData = async (): Promise<string[]> => {
|
|
266
|
+
const res = await fetch('/data.json')
|
|
267
|
+
return res.json()
|
|
268
|
+
}
|
|
269
|
+
function Widget() {
|
|
270
|
+
const [items, setItems] = createSignal<string[]>([])
|
|
271
|
+
onMount(() => { void loadData().then(setItems) })
|
|
272
|
+
return <div>{items().length}</div>
|
|
273
|
+
}
|
|
274
|
+
export default Widget
|
|
275
|
+
`)
|
|
276
|
+
const functionForm = compile(`
|
|
277
|
+
'use client'
|
|
278
|
+
import { createSignal, onMount } from '@barefootjs/client'
|
|
279
|
+
async function loadData(): Promise<string[]> {
|
|
280
|
+
const res = await fetch('/data.json')
|
|
281
|
+
return res.json()
|
|
282
|
+
}
|
|
283
|
+
function Widget() {
|
|
284
|
+
const [items, setItems] = createSignal<string[]>([])
|
|
285
|
+
onMount(() => { void loadData().then(setItems) })
|
|
286
|
+
return <div>{items().length}</div>
|
|
287
|
+
}
|
|
288
|
+
export default Widget
|
|
289
|
+
`)
|
|
290
|
+
expect(arrowForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
291
|
+
expect(functionForm.result.errors.filter(e => e.severity === 'error')).toEqual([])
|
|
292
|
+
expect(countOccurrences(arrowForm.clientJs, "await fetch('/data.json')")).toBe(1)
|
|
293
|
+
expect(countOccurrences(functionForm.clientJs, "await fetch('/data.json')")).toBe(1)
|
|
294
|
+
})
|
|
295
|
+
})
|
|
296
|
+
})
|
|
@@ -0,0 +1,180 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Regression tests for #2988: a module-top-level helper declared as
|
|
3
|
+
* `const name = (params) => expr` (arrow form) that closes over nothing
|
|
4
|
+
* but its own parameters is safe to reference from a component's CSR
|
|
5
|
+
* template lambda by bare name — same as the equivalent
|
|
6
|
+
* `function name(params) { ... }` declaration form. Pre-fix,
|
|
7
|
+
* `compute-inlinability.ts`'s `classifyConstantInitial` returned
|
|
8
|
+
* `arrow-literal` (template-unsafe) for EVERY arrow-valued constant
|
|
9
|
+
* unconditionally, ignoring `isModule` entirely — so the CSR-emitted
|
|
10
|
+
* template lambda substituted `${''}` for the slot instead of the real
|
|
11
|
+
* value, even though `compute-scope.ts` had no equivalent
|
|
12
|
+
* forward-reachability fixpoint for constants either (it fell straight
|
|
13
|
+
* to `'init'` scope, disagreeing with `relocate.ts`'s independent
|
|
14
|
+
* `'module-local'` classification, which reads only the raw `isModule`
|
|
15
|
+
* flag).
|
|
16
|
+
*
|
|
17
|
+
* The fix folds arrow-valued module constants into the SAME
|
|
18
|
+
* forward-reachability fixpoint `compute-scope.ts` already runs for
|
|
19
|
+
* module-level functions, and has `compute-inlinability.ts` read that
|
|
20
|
+
* one answer (via a fresh, pure call to `computeDeclarationScopes`)
|
|
21
|
+
* instead of re-deriving an independent verdict.
|
|
22
|
+
*
|
|
23
|
+
* These tests exercise `compileJSX` — the same entry point
|
|
24
|
+
* `@barefootjs/vite`'s plugin and `packages/adapter-tests/src/csr-render.ts`
|
|
25
|
+
* call — and evaluate the extracted CSR template body as a real
|
|
26
|
+
* template-literal function, mirroring what `hydrate()` does at runtime
|
|
27
|
+
* (minus the DOM). This is the closest unit-level stand-in for the real
|
|
28
|
+
* pipeline: `compileJSX` performs the exact analysis → compute-scope →
|
|
29
|
+
* compute-inlinability → html-template sequence `generateClientJsWithSourceMap`
|
|
30
|
+
* runs in production (`packages/jsx/src/ir-to-client-js/generate-init.ts`
|
|
31
|
+
* L66-73), with nothing mocked.
|
|
32
|
+
*/
|
|
33
|
+
import { describe, test, expect } from 'bun:test'
|
|
34
|
+
import { compileJSX } from '../compiler'
|
|
35
|
+
import { HonoAdapter } from '../../../adapter-hono/src/adapter/hono-adapter'
|
|
36
|
+
import { extractTemplateBody } from './staged-ir/helpers'
|
|
37
|
+
import { RUNTIME_IMPORT_CANDIDATES } from '../ir-to-client-js/imports'
|
|
38
|
+
|
|
39
|
+
const onlyErrors = (errors: { severity?: string }[]) =>
|
|
40
|
+
errors.filter((e) => e.severity === 'error')
|
|
41
|
+
|
|
42
|
+
function compileTemplateBody(source: string, fileName: string): { templateBody: string; clientJs: string } {
|
|
43
|
+
const result = compileJSX(source, fileName, { adapter: new HonoAdapter() })
|
|
44
|
+
expect(onlyErrors(result.errors)).toHaveLength(0)
|
|
45
|
+
const clientJs = result.files.find((f) => f.type === 'clientJs')!.content
|
|
46
|
+
return { templateBody: extractTemplateBody(clientJs), clientJs }
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/** Module-level declarations (`var fmt = fmt ?? (...)`, etc.) sit
|
|
50
|
+
* between the import line and `export function init<Name>` in the
|
|
51
|
+
* compiled bundle. The template lambda runs at real module scope in
|
|
52
|
+
* production, closing over these by normal JS scoping — reproduce
|
|
53
|
+
* that here instead of leaving them undeclared in the sandbox. */
|
|
54
|
+
function extractModulePreamble(clientJs: string): string {
|
|
55
|
+
const m = clientJs.match(/\n\n([\s\S]*?)\nexport function init\w+/)
|
|
56
|
+
return m ? m[1] : ''
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/** Evaluate an extracted CSR template body as a real template-literal
|
|
60
|
+
* function, with every runtime helper the compiler might reference
|
|
61
|
+
* stubbed to identity/no-op, and the compiled bundle's module-level
|
|
62
|
+
* declarations (if any) in scope. Mirrors `hydrate()` minus the DOM. */
|
|
63
|
+
function evalTemplate(templateBody: string, props: Record<string, unknown>, modulePreamble = ''): string {
|
|
64
|
+
const helperNames = [...RUNTIME_IMPORT_CANDIDATES]
|
|
65
|
+
const stubs = helperNames.map((name) => {
|
|
66
|
+
if (name === 'escapeAttr' || name === 'escapeText' || name === 'escapeTextOrMarkup' || name === 'styleToCss') {
|
|
67
|
+
return (v: unknown) => String(v)
|
|
68
|
+
}
|
|
69
|
+
return (..._args: unknown[]) => ''
|
|
70
|
+
})
|
|
71
|
+
// eslint-disable-next-line no-new-func
|
|
72
|
+
const fn = new Function('_p', ...helperNames, `${modulePreamble}\nreturn \`${templateBody}\``)
|
|
73
|
+
return fn(props, ...stubs)
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
describe('CSR template: module-scope arrow-valued const helper (#2988)', () => {
|
|
77
|
+
test('an arrow-valued module const applied to a prop renders its real value, not an empty seed', () => {
|
|
78
|
+
const source = `
|
|
79
|
+
'use client'
|
|
80
|
+
import { createSignal } from '@barefootjs/client'
|
|
81
|
+
|
|
82
|
+
const fmt = (s: string) => s.toUpperCase()
|
|
83
|
+
|
|
84
|
+
export function Widget({ label }: { label: string }) {
|
|
85
|
+
const [count, setCount] = createSignal(0)
|
|
86
|
+
return (
|
|
87
|
+
<div>
|
|
88
|
+
<span>{fmt(label)}</span>
|
|
89
|
+
<button onClick={() => setCount(count() + 1)}>{count()}</button>
|
|
90
|
+
</div>
|
|
91
|
+
)
|
|
92
|
+
}
|
|
93
|
+
`
|
|
94
|
+
const { templateBody, clientJs } = compileTemplateBody(source, 'Widget.tsx')
|
|
95
|
+
|
|
96
|
+
// The module-level declaration is emitted once, parenthesised on
|
|
97
|
+
// the right of `??` (an arrow function is NOT a valid `??` operand
|
|
98
|
+
// unwrapped — `x ?? (s) => …` is a SyntaxError).
|
|
99
|
+
expect(clientJs).toContain('var fmt = fmt ?? ((s) => s.toUpperCase())')
|
|
100
|
+
|
|
101
|
+
// `fmt` is referenced by bare name in the template (wrapped in
|
|
102
|
+
// relocate/CSR-substitution parens, so match on the word boundary
|
|
103
|
+
// rather than the literal call-site text), not substituted away as
|
|
104
|
+
// an unsafe/empty fallback.
|
|
105
|
+
expect(/\bfmt\b/.test(templateBody)).toBe(true)
|
|
106
|
+
expect(templateBody).not.toBe('')
|
|
107
|
+
|
|
108
|
+
const html = evalTemplate(templateBody, { label: 'hi' }, extractModulePreamble(clientJs))
|
|
109
|
+
expect(html).toContain('HI')
|
|
110
|
+
expect(html).not.toContain('undefined')
|
|
111
|
+
})
|
|
112
|
+
|
|
113
|
+
test('the function-declaration form of the same helper renders identically (parity check)', () => {
|
|
114
|
+
const arrowSource = `
|
|
115
|
+
'use client'
|
|
116
|
+
import { createSignal } from '@barefootjs/client'
|
|
117
|
+
const fmt = (s: string) => s.toUpperCase()
|
|
118
|
+
export function Widget({ label }: { label: string }) {
|
|
119
|
+
const [count] = createSignal(0)
|
|
120
|
+
return <div>{fmt(label)}{count()}</div>
|
|
121
|
+
}
|
|
122
|
+
`
|
|
123
|
+
const functionSource = `
|
|
124
|
+
'use client'
|
|
125
|
+
import { createSignal } from '@barefootjs/client'
|
|
126
|
+
function fmt(s: string) { return s.toUpperCase() }
|
|
127
|
+
export function Widget({ label }: { label: string }) {
|
|
128
|
+
const [count] = createSignal(0)
|
|
129
|
+
return <div>{fmt(label)}{count()}</div>
|
|
130
|
+
}
|
|
131
|
+
`
|
|
132
|
+
const arrow = compileTemplateBody(arrowSource, 'ArrowWidget.tsx')
|
|
133
|
+
const fn = compileTemplateBody(functionSource, 'FunctionWidget.tsx')
|
|
134
|
+
|
|
135
|
+
const arrowHtml = evalTemplate(arrow.templateBody, { label: 'hi' }, extractModulePreamble(arrow.clientJs))
|
|
136
|
+
const fnHtml = evalTemplate(fn.templateBody, { label: 'hi' }, extractModulePreamble(fn.clientJs))
|
|
137
|
+
|
|
138
|
+
expect(arrowHtml).toBe(fnHtml)
|
|
139
|
+
expect(arrowHtml).toContain('HI')
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
test('an arrow-valued module const that reads a signal stays template-unsafe (no over-widening)', () => {
|
|
143
|
+
// `fmt` here closes over the module-scope-invisible signal getter
|
|
144
|
+
// `count`, so it must stay classified unsafe — #2988's fixpoint
|
|
145
|
+
// must demote it to 'init' scope exactly like a module-scope
|
|
146
|
+
// FUNCTION that touches component internals already is.
|
|
147
|
+
const source = `
|
|
148
|
+
'use client'
|
|
149
|
+
import { createSignal } from '@barefootjs/client'
|
|
150
|
+
|
|
151
|
+
const fmt = (s: string) => \`\${s}-\${count()}\`
|
|
152
|
+
|
|
153
|
+
export function Widget({ label }: { label: string }) {
|
|
154
|
+
const [count, setCount] = createSignal(0)
|
|
155
|
+
return <div>{fmt(label)}</div>
|
|
156
|
+
}
|
|
157
|
+
`
|
|
158
|
+
const { templateBody } = compileTemplateBody(source, 'UnsafeWidget.tsx')
|
|
159
|
+
// Falls back to the empty-slot sentinel, same as pre-#2988 behavior
|
|
160
|
+
// for any const that genuinely can't be hoisted to module scope —
|
|
161
|
+
// NOT a bare `fmt(...)` reference (which would ReferenceError: `fmt`
|
|
162
|
+
// never gets a module-level declaration for this shape).
|
|
163
|
+
expect(templateBody).not.toContain('fmt(')
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
test('a component-scope (non-module) arrow const of the same shape stays template-unsafe', () => {
|
|
167
|
+
const source = `
|
|
168
|
+
'use client'
|
|
169
|
+
import { createSignal } from '@barefootjs/client'
|
|
170
|
+
|
|
171
|
+
export function Widget({ label }: { label: string }) {
|
|
172
|
+
const [count, setCount] = createSignal(0)
|
|
173
|
+
const fmt = (s: string) => s.toUpperCase()
|
|
174
|
+
return <div>{fmt(label)}{count()}</div>
|
|
175
|
+
}
|
|
176
|
+
`
|
|
177
|
+
const { templateBody } = compileTemplateBody(source, 'LocalArrowWidget.tsx')
|
|
178
|
+
expect(templateBody).not.toContain('fmt(')
|
|
179
|
+
})
|
|
180
|
+
})
|
|
@@ -878,6 +878,43 @@ export function Ticker() {
|
|
|
878
878
|
expect(clientJs!.content).toMatch(/import\s*\{[^}]*onMount[^}]*\}\s*from\s*'@barefootjs\/client\/runtime'/)
|
|
879
879
|
})
|
|
880
880
|
|
|
881
|
+
// This is a COMPILE-TIME assertion only (the generated import list), not
|
|
882
|
+
// a runtime behavior test — `batch` around a single `setCount` call has
|
|
883
|
+
// no observable effect at runtime (batching only matters for coalescing
|
|
884
|
+
// MULTIPLE signal writes into one effect flush; see `batch`'s doc comment
|
|
885
|
+
// in `packages/client/src/reactive.ts`). It's used here purely as the
|
|
886
|
+
// smallest fixture that calls `batch` from a cross-file factory, to pin
|
|
887
|
+
// #2985: `batch` was missing from `RUNTIME_IMPORT_CANDIDATES`
|
|
888
|
+
// (`ir-to-client-js/imports.ts`), so it compiled clean but was silently
|
|
889
|
+
// dropped from the emitted `@barefootjs/client/runtime` import, throwing
|
|
890
|
+
// `ReferenceError: batch is not defined` at hydration.
|
|
891
|
+
test('M17b: batch is provisioned from usage for a cross-file factory (#2985)', () => {
|
|
892
|
+
writeFixture('matrix17b/useCounter.tsx', `'use client'
|
|
893
|
+
import { batch, createSignal } from '@barefootjs/client'
|
|
894
|
+
|
|
895
|
+
export function useCounter() {
|
|
896
|
+
const [count, setCount] = createSignal(0)
|
|
897
|
+
const increment = () => batch(() => setCount(count() + 1))
|
|
898
|
+
return { count, increment }
|
|
899
|
+
}
|
|
900
|
+
`)
|
|
901
|
+
const consumerSource = `'use client'
|
|
902
|
+
import { useCounter } from './useCounter'
|
|
903
|
+
|
|
904
|
+
export function Counter() {
|
|
905
|
+
const { count, increment } = useCounter()
|
|
906
|
+
return <button onClick={increment}>{count()}</button>
|
|
907
|
+
}
|
|
908
|
+
`
|
|
909
|
+
const consumerPath = writeFixture('matrix17b/Counter.tsx', consumerSource)
|
|
910
|
+
|
|
911
|
+
const result = compileJSX(consumerSource, consumerPath, { adapter })
|
|
912
|
+
expect(result.errors.filter(e => e.severity === 'error')).toHaveLength(0)
|
|
913
|
+
const clientJs = result.files.find(f => f.type === 'clientJs')
|
|
914
|
+
expect(clientJs).toBeDefined()
|
|
915
|
+
expect(clientJs!.content).toMatch(/import\s*\{[^}]*\bbatch\b[^}]*\}\s*from\s*'@barefootjs\/client\/runtime'/)
|
|
916
|
+
})
|
|
917
|
+
|
|
881
918
|
test('M18: a type-only helper import does not trigger BF112 and is re-provisioned as `import type` (#2350)', () => {
|
|
882
919
|
writeFixture('matrix18/todo-types.ts', `export interface Todo {
|
|
883
920
|
id: number
|
|
@@ -641,6 +641,26 @@ describe('extractSsrDefaults', () => {
|
|
|
641
641
|
expect(defaults?.label).toEqual({ propName: 'label', value: null })
|
|
642
642
|
expect(defaults?.labelAlias).toBe(defaults?.label)
|
|
643
643
|
})
|
|
644
|
+
|
|
645
|
+
// #2924 review follow-up (pullfrog nitpick on the PR fixing the setter
|
|
646
|
+
// case): the setter-symmetric shape of the #2813 getter-alias test above
|
|
647
|
+
// — a bare local-const alias of a signal SETTER must be seeded under its
|
|
648
|
+
// own name too, not just the setter's own name.
|
|
649
|
+
test('a bare local-const alias of a signal setter is seeded under the alias name too', () => {
|
|
650
|
+
const metadata = metadataFor(`
|
|
651
|
+
'use client'
|
|
652
|
+
import { createSignal } from '@barefootjs/client'
|
|
653
|
+
function C() {
|
|
654
|
+
const [count, setCount] = createSignal(5)
|
|
655
|
+
const setCountAlias = setCount
|
|
656
|
+
return <button onClick={() => setCountAlias(6)}>{count()}</button>
|
|
657
|
+
}
|
|
658
|
+
`)
|
|
659
|
+
|
|
660
|
+
const defaults = extractSsrDefaults(metadata)
|
|
661
|
+
expect(defaults?.setCount).toEqual({ value: null })
|
|
662
|
+
expect(defaults?.setCountAlias).toEqual({ value: null })
|
|
663
|
+
})
|
|
644
664
|
})
|
|
645
665
|
|
|
646
666
|
// TS twin of the Ruby/Python/PHP/Perl/Rust `derive*FromDefaults` runtime
|
|
@@ -711,8 +731,10 @@ describe('deriveStashFromDefaults', () => {
|
|
|
711
731
|
`)
|
|
712
732
|
const defaults = extractSsrDefaults(metadata)!
|
|
713
733
|
|
|
714
|
-
|
|
715
|
-
|
|
734
|
+
// `setLabel` also gets a stash entry (#2924's SSR-half fix) — every
|
|
735
|
+
// signal setter is seeded unconditionally, same as every getter.
|
|
736
|
+
expect(deriveStashFromDefaults(defaults, { label: 'Hello' })).toEqual({ label: 'Hello', setLabel: null })
|
|
737
|
+
expect(deriveStashFromDefaults(defaults, {})).toEqual({ label: null, setLabel: null })
|
|
716
738
|
})
|
|
717
739
|
|
|
718
740
|
test('propName-less entry (signal / memo local): always uses the static value', () => {
|