@barefootjs/jsx 0.39.6 → 0.39.7

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 (89) hide show
  1. package/dist/adapters/attr-plan.d.ts +8 -1
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/callback-method.d.ts +27 -0
  4. package/dist/adapters/callback-method.d.ts.map +1 -1
  5. package/dist/adapters/computed-const.d.ts +52 -0
  6. package/dist/adapters/computed-const.d.ts.map +1 -0
  7. package/dist/adapters/dangerous-inner-html.d.ts +10 -0
  8. package/dist/adapters/dangerous-inner-html.d.ts.map +1 -1
  9. package/dist/adapters/element-shell.d.ts +44 -0
  10. package/dist/adapters/element-shell.d.ts.map +1 -0
  11. package/dist/adapters/interface.d.ts +2 -0
  12. package/dist/adapters/interface.d.ts.map +1 -1
  13. package/dist/analyzer.d.ts.map +1 -1
  14. package/dist/augment-inherited-props.d.ts +7 -0
  15. package/dist/augment-inherited-props.d.ts.map +1 -1
  16. package/dist/fold-render-reassignments.d.ts +43 -0
  17. package/dist/fold-render-reassignments.d.ts.map +1 -0
  18. package/dist/free-refs.d.ts +9 -0
  19. package/dist/free-refs.d.ts.map +1 -1
  20. package/dist/index.d.ts +8 -4
  21. package/dist/index.d.ts.map +1 -1
  22. package/dist/index.js +2285 -1583
  23. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/csr-substitute.d.ts +0 -13
  25. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/html-template.d.ts +9 -10
  28. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/plan/declaration-emit.d.ts +5 -0
  31. package/dist/ir-to-client-js/plan/declaration-emit.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/prop-handling.d.ts +11 -12
  33. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/utils.d.ts +13 -0
  35. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  36. package/dist/jsx-to-ir.d.ts.map +1 -1
  37. package/dist/nullable-signal-attr.d.ts +3 -2
  38. package/dist/nullable-signal-attr.d.ts.map +1 -1
  39. package/dist/props-binding.d.ts +34 -5
  40. package/dist/props-binding.d.ts.map +1 -1
  41. package/dist/relocate.d.ts +16 -0
  42. package/dist/relocate.d.ts.map +1 -1
  43. package/dist/ssr-seed-plan.d.ts +0 -6
  44. package/dist/ssr-seed-plan.d.ts.map +1 -1
  45. package/dist/types.d.ts +54 -2
  46. package/dist/types.d.ts.map +1 -1
  47. package/package.json +2 -2
  48. package/src/__tests__/block-memo-type.test.ts +51 -0
  49. package/src/__tests__/callback-method.test.ts +75 -0
  50. package/src/__tests__/client-only-date-lowering.test.ts +2 -2
  51. package/src/__tests__/computed-const.test.ts +101 -0
  52. package/src/__tests__/element-shell.test.ts +78 -0
  53. package/src/__tests__/fold-render-reassignments.test.ts +96 -0
  54. package/src/__tests__/inlinable-local-method-call.test.ts +81 -0
  55. package/src/__tests__/memo-body-expr.test.ts +120 -0
  56. package/src/__tests__/prop-handling.test.ts +35 -16
  57. package/src/__tests__/props-alias-const.test.ts +65 -0
  58. package/src/__tests__/signal-prop-seed.test.ts +90 -0
  59. package/src/__tests__/ssr-seed-plan.test.ts +54 -1
  60. package/src/__tests__/static-template-reachability.test.ts +137 -0
  61. package/src/adapters/attr-plan.ts +29 -1
  62. package/src/adapters/callback-method.ts +62 -0
  63. package/src/adapters/computed-const.ts +185 -0
  64. package/src/adapters/dangerous-inner-html.ts +33 -0
  65. package/src/adapters/element-shell.ts +160 -0
  66. package/src/adapters/interface.ts +8 -0
  67. package/src/analyzer.ts +271 -82
  68. package/src/augment-inherited-props.ts +12 -0
  69. package/src/fold-render-reassignments.ts +314 -0
  70. package/src/free-refs.ts +49 -0
  71. package/src/index.ts +9 -2
  72. package/src/ir-to-client-js/compute-inlinability.ts +93 -17
  73. package/src/ir-to-client-js/csr-substitute.ts +13 -35
  74. package/src/ir-to-client-js/emit-registration.ts +3 -2
  75. package/src/ir-to-client-js/html-template.ts +26 -70
  76. package/src/ir-to-client-js/index.ts +3 -2
  77. package/src/ir-to-client-js/init-declarations.ts +1 -1
  78. package/src/ir-to-client-js/plan/build-declaration-emit.ts +25 -51
  79. package/src/ir-to-client-js/plan/declaration-emit.ts +5 -0
  80. package/src/ir-to-client-js/prop-handling.ts +13 -54
  81. package/src/ir-to-client-js/rewrite-destructured-props.ts +6 -5
  82. package/src/ir-to-client-js/stringify/declaration-emit.ts +1 -1
  83. package/src/ir-to-client-js/utils.ts +11 -0
  84. package/src/jsx-to-ir.ts +39 -52
  85. package/src/nullable-signal-attr.ts +7 -4
  86. package/src/props-binding.ts +100 -5
  87. package/src/relocate.ts +40 -8
  88. package/src/ssr-seed-plan.ts +18 -6
  89. package/src/types.ts +50 -2
@@ -0,0 +1,120 @@
1
+ /**
2
+ * #3510: a memo's value expression is read from the callback node
3
+ * (`MemoInfo.bodyExpr`), not by matching `() =>` in `computation`.
4
+ * Consumers substitute it for `memo()`, so every callback shape must yield
5
+ * an expression that evaluates to the memo's value — never the uncalled
6
+ * function.
7
+ */
8
+
9
+ import { describe, test, expect } from 'bun:test'
10
+ import { analyzeComponent } from '../analyzer'
11
+ import { compileJSX } from '../compiler'
12
+ import { TestAdapter } from '../adapters/test-adapter'
13
+
14
+ function memoOf(callback: string, props = '') {
15
+ const source = `
16
+ 'use client'
17
+ import { createSignal, createMemo } from '@barefootjs/client'
18
+ export function C(${props}) {
19
+ const [count] = createSignal(2)
20
+ const m = createMemo(${callback})
21
+ return <p>{m()}</p>
22
+ }
23
+ `
24
+ const memo = analyzeComponent(source, 'C.tsx').memos.find((x) => x.name === 'm')
25
+ if (!memo) throw new Error('memo not collected')
26
+ return memo
27
+ }
28
+
29
+ describe('MemoInfo.bodyExpr (#3510)', () => {
30
+ test.each([
31
+ ['() => count() * 2', 'count() * 2'],
32
+ ['(): number => count() * 2', 'count() * 2'],
33
+ ['() => { return count() * 2 }', 'count() * 2'],
34
+ ['function () { return count() * 2 }', 'count() * 2'],
35
+ ['(() => count() * 2)', 'count() * 2'],
36
+ ['(function () { return count() * 2 })', 'count() * 2'],
37
+ ])('%s yields its returned expression', (callback, expected) => {
38
+ expect(memoOf(callback).bodyExpr).toBe(expected)
39
+ })
40
+
41
+ test('a multi-statement body yields a call of the whole callback', () => {
42
+ expect(memoOf('() => { const k = count(); return k * 3 }').bodyExpr)
43
+ .toBe('(() => { const k = count(); return k * 3 })()')
44
+ expect(memoOf('function () { const k = count(); return k * 3 }').bodyExpr)
45
+ .toBe('(function () { const k = count(); return k * 3 })()')
46
+ })
47
+
48
+ test('a callback that is not a plain zero-parameter function is called as written', () => {
49
+ expect(memoOf('async () => count()').bodyExpr).toBe('(async () => count())()')
50
+ expect(memoOf('count').bodyExpr).toBe('(count)()')
51
+ })
52
+
53
+ test('templateBodyExpr rewrites a destructured prop read in the body', () => {
54
+ const memo = memoOf('function () { return count() + base }', '{ base }: { base: number }')
55
+ expect(memo.bodyExpr).toBe('count() + base')
56
+ expect(memo.templateBodyExpr).toBe('count() + _p.base')
57
+ })
58
+
59
+ test('a function expression carries the same structured parse as a block arrow', () => {
60
+ const fn = memoOf('function () { return count() * 2 }')
61
+ const arrow = memoOf('() => { return count() * 2 }')
62
+ expect(fn.parsedBlock).toEqual(arrow.parsedBlock)
63
+ expect(fn.parsedBlockComplete).toBe(true)
64
+ })
65
+
66
+ test('a function expression that needs its own scope is called as a whole', () => {
67
+ for (const callback of [
68
+ 'function base() { return typeof base }',
69
+ 'function () { return arguments.length }',
70
+ 'function () { return this }',
71
+ 'function () { return Object.keys({ [arguments.length]() {} })[0] }',
72
+ 'function () { return class extends (this ? Object : Object) {} }',
73
+ ]) {
74
+ const memo = memoOf(callback, '{ base }: { base: number }')
75
+ expect(memo.bodyExprIsCall).toBe(true)
76
+ expect(memo.bodyExpr).toBe(`(${callback})()`)
77
+ expect(memo.parsedBlock).toBeUndefined()
78
+ }
79
+ })
80
+
81
+ test('the CSR template evaluates a scope-bound callback to its own value', () => {
82
+ const source = `
83
+ 'use client'
84
+ import { createMemo } from '@barefootjs/client'
85
+ export function C({ base }: { base: number }) {
86
+ const named = createMemo(function base() { return typeof base })
87
+ const args = createMemo(function () { return arguments.length })
88
+ return <p>{named()}|{args()}</p>
89
+ }
90
+ `
91
+ const result = compileJSX(source, 'C.tsx', { adapter: new TestAdapter() })
92
+ const line = result.files.find((f) => f.type === 'clientJs')!.content.split('\n').find((l) => l.includes('hydrate('))!
93
+ const lambda = line.match(/template: (\(_p\) => `.*`) \}\)$/)![1]
94
+ const template = new Function('escapeTextOrMarkup', 'escapeText', 'escapeAttr', `return ${lambda}`)(String, String, String)
95
+ const html = template({ base: 7 })
96
+ expect(html).toContain('-->function<!--')
97
+ expect(html).toContain('-->0<!--')
98
+ })
99
+
100
+ test('a callback whose nested function only binds its own scope is still extracted', () => {
101
+ const memo = memoOf('function () { return [1].map(function () { return arguments.length })[0] }')
102
+ expect(memo.bodyExprIsCall).toBeUndefined()
103
+ })
104
+
105
+ test('a computed method name reading the callback\'s arguments renders its own value', () => {
106
+ const source = `
107
+ 'use client'
108
+ import { createMemo } from '@barefootjs/client'
109
+ export function C() {
110
+ const key = createMemo(function () { return Object.keys({ [arguments.length]() {} })[0] })
111
+ return <p>{key()}</p>
112
+ }
113
+ `
114
+ const result = compileJSX(source, 'C.tsx', { adapter: new TestAdapter() })
115
+ const line = result.files.find((f) => f.type === 'clientJs')!.content.split('\n').find((l) => l.includes('hydrate('))!
116
+ const lambda = line.match(/template: (\(_p\) => `.*`) \}\)$/)![1]
117
+ const template = new Function('escapeTextOrMarkup', 'escapeText', 'escapeAttr', `return ${lambda}`)(String, String, String)
118
+ expect(template({})).toContain('-->0<!--')
119
+ })
120
+ })
@@ -3,10 +3,15 @@
3
3
  *
4
4
  * Verifies that createSignal initializers referencing props are correctly
5
5
  * identified so the compiler generates sync effects for controlled components.
6
+ * The answer comes from `SignalInfo.propSeed`, which the analyzer records
7
+ * from the parsed initializer (`signalPropSeed`, #3508); `controlled` below
8
+ * sets it the same way.
6
9
  */
7
10
 
8
11
  import { describe, test, expect } from 'bun:test'
9
12
  import { getControlledPropName } from '../ir-to-client-js/prop-handling'
13
+ import { parseExpression } from '../expression-parser'
14
+ import { signalPropSeed } from '../props-binding'
10
15
  import type { ParamInfo, SignalInfo, TypeInfo } from '../types'
11
16
 
12
17
  const boolType: TypeInfo = { kind: 'primitive', raw: 'boolean', primitive: 'boolean' }
@@ -24,6 +29,14 @@ function makeSignal(initialValue: string): SignalInfo {
24
29
  }
25
30
  }
26
31
 
32
+ function controlled(initialValue: string, params: ParamInfo[], propsObjectName = 'props'): string | null {
33
+ const signal = makeSignal(initialValue)
34
+ const parsed = parseExpression(`(${initialValue})`)
35
+ const seed = signalPropSeed(parsed.kind === 'unsupported' ? undefined : parsed, params, propsObjectName)
36
+ if (seed) signal.propSeed = seed
37
+ return getControlledPropName(signal)
38
+ }
39
+
27
40
  const propsParams: ParamInfo[] = [
28
41
  { name: 'checked', type: boolType, optional: true },
29
42
  { name: 'value', type: strType, optional: true },
@@ -34,68 +47,74 @@ const propsParams: ParamInfo[] = [
34
47
 
35
48
  describe('getControlledPropName', () => {
36
49
  test('direct props.xxx reference', () => {
37
- expect(getControlledPropName(makeSignal('props.checked'), propsParams)).toBe('checked')
50
+ expect(controlled('props.checked', propsParams)).toBe('checked')
38
51
  })
39
52
 
40
53
  test('props.xxx ?? default (bug fix: #434)', () => {
41
- expect(getControlledPropName(makeSignal('props.initial ?? 0'), propsParams)).toBe('initial')
54
+ expect(controlled('props.initial ?? 0', propsParams)).toBe('initial')
42
55
  })
43
56
 
44
57
  test('props.xxx ?? string default (bug fix: #434)', () => {
45
- expect(getControlledPropName(makeSignal("props.value ?? ''"), propsParams)).toBe('value')
58
+ expect(controlled("props.value ?? ''", propsParams)).toBe('value')
46
59
  })
47
60
 
48
61
  test('props.xxx || fallback', () => {
49
- expect(getControlledPropName(makeSignal("props.value || ''"), propsParams)).toBe('value')
62
+ expect(controlled("props.value || ''", propsParams)).toBe('value')
50
63
  })
51
64
 
52
65
  test('default-prefixed prop is excluded', () => {
53
- expect(getControlledPropName(makeSignal('props.defaultChecked'), propsParams)).toBeNull()
66
+ expect(controlled('props.defaultChecked', propsParams)).toBeNull()
54
67
  })
55
68
 
56
69
  test('default-prefixed prop with ?? is excluded', () => {
57
- expect(getControlledPropName(makeSignal('props.defaultChecked ?? false'), propsParams)).toBeNull()
70
+ expect(controlled('props.defaultChecked ?? false', propsParams)).toBeNull()
58
71
  })
59
72
 
60
73
  test('destructured prop name', () => {
61
- expect(getControlledPropName(makeSignal('checked'), propsParams)).toBe('checked')
74
+ expect(controlled('checked', propsParams)).toBe('checked')
62
75
  })
63
76
 
64
77
  test('destructured prop with ?? fallback', () => {
65
- expect(getControlledPropName(makeSignal('checked ?? false'), propsParams)).toBe('checked')
78
+ expect(controlled('checked ?? false', propsParams)).toBe('checked')
66
79
  })
67
80
 
68
81
  test('destructured default-prefixed prop is excluded', () => {
69
- expect(getControlledPropName(makeSignal("defaultValue ?? ''"), propsParams)).toBeNull()
82
+ expect(controlled("defaultValue ?? ''", propsParams)).toBeNull()
70
83
  })
71
84
 
72
85
  test('complex expression returns null', () => {
73
- expect(getControlledPropName(makeSignal('someFunction(props.value)'), propsParams)).toBeNull()
86
+ expect(controlled('someFunction(props.value)', propsParams)).toBeNull()
87
+ })
88
+
89
+ test('an initializer that only starts with a prop read returns null (#3508)', () => {
90
+ for (const init of ["props.value && 'x'", 'props.initial + 1', "props.value ? 'a' : 'b'", 'props.value.trim()']) {
91
+ expect(controlled(init, propsParams)).toBeNull()
92
+ }
74
93
  })
75
94
 
76
95
  test('unknown prop name returns null', () => {
77
- expect(getControlledPropName(makeSignal('props.unknown'), propsParams)).toBeNull()
96
+ expect(controlled('props.unknown', propsParams)).toBeNull()
78
97
  })
79
98
 
80
99
  describe('custom props parameter name', () => {
81
100
  test('p.checked with propsObjectName="p"', () => {
82
- expect(getControlledPropName(makeSignal('p.checked'), propsParams, 'p')).toBe('checked')
101
+ expect(controlled('p.checked', propsParams, 'p')).toBe('checked')
83
102
  })
84
103
 
85
104
  test('p.initial ?? 0 with propsObjectName="p"', () => {
86
- expect(getControlledPropName(makeSignal('p.initial ?? 0'), propsParams, 'p')).toBe('initial')
105
+ expect(controlled('p.initial ?? 0', propsParams, 'p')).toBe('initial')
87
106
  })
88
107
 
89
108
  test('p.defaultChecked ?? false is excluded', () => {
90
- expect(getControlledPropName(makeSignal('p.defaultChecked ?? false'), propsParams, 'p')).toBeNull()
109
+ expect(controlled('p.defaultChecked ?? false', propsParams, 'p')).toBeNull()
91
110
  })
92
111
 
93
112
  test('prop.value || "" with propsObjectName="prop"', () => {
94
- expect(getControlledPropName(makeSignal("prop.value || ''"), propsParams, 'prop')).toBe('value')
113
+ expect(controlled("prop.value || ''", propsParams, 'prop')).toBe('value')
95
114
  })
96
115
 
97
116
  test('props.checked is not matched when propsObjectName="p"', () => {
98
- expect(getControlledPropName(makeSignal('props.checked'), propsParams, 'p')).toBeNull()
117
+ expect(controlled('props.checked', propsParams, 'p')).toBeNull()
99
118
  })
100
119
  })
101
120
  })
@@ -0,0 +1,65 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { analyzeComponent } from '../analyzer.ts'
3
+ import { isPropsAliasConst } from '../props-binding.ts'
4
+
5
+ /**
6
+ * Whether a const reads as its own prop (#3501): a bare `props.X` read, or
7
+ * an un-renamed body destructure (with or without a default), but not a
8
+ * hand-written `const X = props.X ?? d`, whose default the prop does not
9
+ * carry. The destructure is told apart by the analyzer's
10
+ * `ConstantInfo.propsDestructure`, not by the initializer text.
11
+ */
12
+ function constOf(body: string, name = 'label') {
13
+ const ctx = analyzeComponent(
14
+ `'use client'\nexport function S(props: { label?: string }) {\n ${body}\n return <p>{${name}}</p>\n}`,
15
+ 'S.tsx',
16
+ )
17
+ return { c: ctx.localConstants.find(x => x.name === name)!, propsObjectName: ctx.propsObjectName }
18
+ }
19
+
20
+ function aliasOf(body: string, name = 'label'): boolean {
21
+ const { c, propsObjectName } = constOf(body, name)
22
+ return isPropsAliasConst(c, propsObjectName)
23
+ }
24
+
25
+ describe('isPropsAliasConst', () => {
26
+ test('a bare props read is the prop', () => {
27
+ expect(aliasOf('const label = props.label')).toBe(true)
28
+ })
29
+
30
+ test('a body destructure is the prop, with or without a default', () => {
31
+ expect(aliasOf('const { label } = props')).toBe(true)
32
+ expect(aliasOf("const { label = 'Default' } = props")).toBe(true)
33
+ })
34
+
35
+ test('a hand-written `?? default` const is not the prop', () => {
36
+ expect(aliasOf("const label = props.label ?? 'Default'")).toBe(false)
37
+ expect(aliasOf("let label = props.label ?? 'Default'")).toBe(false)
38
+ })
39
+
40
+ test('a `?? default` binding whose reassignment cannot fold still reads the prop', () => {
41
+ expect(aliasOf("let label = props.label ?? 'Default'\n for (const t of [1]) label = 'Fallback'")).toBe(true)
42
+ })
43
+
44
+ test('a `?? default` binding whose reassignment folds is not the prop', () => {
45
+ expect(aliasOf("let label = props.label ?? 'Default'\n if (!label) label = 'Fallback'")).toBe(false)
46
+ })
47
+
48
+ test('a renamed destructure binding is not an alias of a prop of its own name', () => {
49
+ expect(aliasOf('const { label: text } = props', 'text')).toBe(false)
50
+ })
51
+
52
+ test('the analyzer records a body destructure on the const, and only that', () => {
53
+ expect(constOf("const { label = 'Default' } = props").c.propsDestructure).toEqual({ sourceKey: 'label' })
54
+ expect(constOf('const { label: text } = props', 'text').c.propsDestructure).toEqual({ sourceKey: 'label' })
55
+ expect(constOf("const label = props.label ?? 'Default'").c.propsDestructure).toBeUndefined()
56
+ })
57
+
58
+ test('a read of another prop or a derived value is not the prop', () => {
59
+ expect(aliasOf("const label = props.label + '!'")).toBe(false)
60
+ })
61
+
62
+ test('no props object means no alias', () => {
63
+ expect(isPropsAliasConst(constOf('const label = props.label').c, null)).toBe(false)
64
+ })
65
+ })
@@ -0,0 +1,90 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { compileJSX } from '../compiler'
3
+ import { TestAdapter } from '../adapters/test-adapter'
4
+
5
+ /**
6
+ * The CSR init body (`resolveSignalInitialValue`), the CSR template
7
+ * (`normalizeSignalInitial`) and the controlled-signal sync
8
+ * (`getControlledPropName`) read one fact, the analyzer's
9
+ * `SignalInfo.propSeed`, so they agree on every initializer shape (#3508).
10
+ */
11
+ function clientJs(init: string, params = 'props: { a?: string; b?: string; n?: number; row?: { count: number } }'): string {
12
+ const source = `'use client'
13
+ import { createSignal } from '@barefootjs/client'
14
+ export function T(${params}) {
15
+ const [v, setV] = createSignal(${init})
16
+ return <button onClick={() => setV(v())}>{String(v())}</button>
17
+ }
18
+ `
19
+ const result = compileJSX(source, 'T.tsx', { adapter: new TestAdapter() })
20
+ const file = result.files.find(f => f.path.endsWith('.client.js'))
21
+ if (!file) throw new Error('no client JS')
22
+ return file.content
23
+ }
24
+
25
+ const declaration = (js: string) => js.match(/createSignal\((.*)\)\n/)?.[1]
26
+ const parses = (js: string) => {
27
+ new Function(js.replace(/^import .*$/gm, '').replace(/^export /gm, ''))
28
+ return true
29
+ }
30
+
31
+ describe('signal prop seed', () => {
32
+ test('a `||` / `&&` initializer is kept as written in the init body and the template', () => {
33
+ for (const init of ["props.a || 'x'", "props.a && 'x'"]) {
34
+ const js = clientJs(init)
35
+ const expected = init.replace('props.', '_p.')
36
+ expect(declaration(js)).toBe(expected)
37
+ expect(js).toContain(`(${expected})`)
38
+ expect(parses(js)).toBe(true)
39
+ }
40
+ })
41
+
42
+ test('a bare props read gets the same type default in both places', () => {
43
+ const js = clientJs('props.n')
44
+ const seed = declaration(js)
45
+ expect(seed).toMatch(/^_p\.n \?\? \S+$/)
46
+ expect(js).toContain(`(${seed})`)
47
+ })
48
+
49
+ test('a nested props read gets the type default but is not controlled', () => {
50
+ const js = clientJs('props.row.count')
51
+ expect(declaration(js)).toMatch(/^_p\.row\.count \?\? \S+$/)
52
+ expect(js).not.toContain('if (__val !== undefined)')
53
+ })
54
+
55
+ test('a controlled `||` seed re-syncs to the initializer, not the raw prop', () => {
56
+ const js = clientJs("props.a || 'x'")
57
+ expect(js).toContain('const __val = _p.a')
58
+ expect(js).toContain("if (__val !== undefined) setV(_p.a || 'x')")
59
+ })
60
+
61
+ test('a controlled `??` seed re-syncs to the prop', () => {
62
+ const js = clientJs("props.a ?? 'x'")
63
+ expect(js).toContain('if (__val !== undefined) setV(__val)')
64
+ })
65
+
66
+ test('an expression that only starts with a props read gets no appended default', () => {
67
+ for (const init of ['props.n + 1', "props.a ? 'y' : 'n'"]) {
68
+ expect(declaration(clientJs(init))).toBe(init.replaceAll('props.', '_p.'))
69
+ }
70
+ })
71
+
72
+ test('a chained `??` seed stays controlled by its leftmost prop', () => {
73
+ const js = clientJs("props.a ?? props.b ?? 'x'")
74
+ expect(declaration(js)).toBe("_p.a ?? _p.b ?? 'x'")
75
+ expect(js).toContain('const __val = _p.a')
76
+ expect(js).toContain('if (__val !== undefined) setV(__val)')
77
+ })
78
+
79
+ test('a chained `||` seed stays controlled and re-syncs to the initializer', () => {
80
+ const js = clientJs("props.a || props.b || 'x'")
81
+ expect(js).toContain('const __val = _p.a')
82
+ expect(js).toContain("if (__val !== undefined) setV(_p.a || _p.b || 'x')")
83
+ })
84
+
85
+ test('a chained seed over destructured props stays controlled', () => {
86
+ const js = clientJs("a ?? b ?? 'x'", '{ a, b }: { a?: string; b?: string }')
87
+ expect(js).toContain('const __val = _p.a')
88
+ expect(js).toContain('if (__val !== undefined) setV(__val)')
89
+ })
90
+ })
@@ -162,7 +162,7 @@ describe('computeSsrSeedPlan', () => {
162
162
  }
163
163
  })
164
164
 
165
- test('block-bodied memo → opaque (v1 gates to expression-bodied memos)', () => {
165
+ test('block-bodied memo → derived from its fold (#3523)', () => {
166
166
  const plan = planFor(`
167
167
  'use client'
168
168
  import { createMemo, createSignal } from '@barefootjs/client'
@@ -176,11 +176,64 @@ describe('computeSsrSeedPlan', () => {
176
176
  }
177
177
  `)
178
178
 
179
+ const label = step(plan, 'label')
180
+ expect(label.kind).toBe('derived')
181
+ if (label.kind === 'derived') expect(label.frees).toContain('on')
182
+ })
183
+
184
+ test('block-bodied memo that does not fold → opaque', () => {
185
+ const plan = planFor(`
186
+ 'use client'
187
+ import { createMemo, createSignal } from '@barefootjs/client'
188
+ function C() {
189
+ const [on, setOn] = createSignal(false)
190
+ const label = createMemo(() => {
191
+ let n = 0
192
+ for (const x of [1, 2]) n += x
193
+ return on() ? n : 0
194
+ })
195
+ return <p>{label()}</p>
196
+ }
197
+ `)
198
+
179
199
  const label = step(plan, 'label')
180
200
  expect(label.kind).toBe('opaque')
181
201
  if (label.kind === 'opaque') expect(label.origin).toBe('memo')
182
202
  })
183
203
 
204
+ test.each([
205
+ ["(label = 'inner') => label"],
206
+ ["(label = 'inner') => { const k = label\n return k }"],
207
+ ])('memo callback with a parameter → opaque: %s', (callback) => {
208
+ const plan = planFor(`
209
+ 'use client'
210
+ import { createMemo, createSignal } from '@barefootjs/client'
211
+ function C({ label }: { label: string }) {
212
+ const [on] = createSignal(false)
213
+ const m = createMemo(${callback})
214
+ return <p>{m()}{on() ? 'y' : 'n'}</p>
215
+ }
216
+ `)
217
+ expect(step(plan, 'm').kind).toBe('opaque')
218
+ })
219
+
220
+ test('block memo with a /* @client */ directive → opaque', () => {
221
+ const plan = planFor(`
222
+ 'use client'
223
+ import { createMemo, createSignal } from '@barefootjs/client'
224
+ function C() {
225
+ const [date] = createSignal<Date | undefined>(undefined)
226
+ const label = createMemo(() => {
227
+ const d = date()
228
+ if (!d) return 'none'
229
+ return /* @client */ d.toLocaleDateString('en-US')
230
+ })
231
+ return <p>{label()}</p>
232
+ }
233
+ `)
234
+ expect(step(plan, 'label').kind).toBe('opaque')
235
+ })
236
+
184
237
  test('object-literal body → derived (#2696: value-position object literal, isSupportedValue)', () => {
185
238
  // Was `opaque` before `checkSupport` gained its `pos` parameter — a
186
239
  // memo's WHOLE body is a value position (an assignment, never a
@@ -0,0 +1,137 @@
1
+ /**
2
+ * #3509: whether a component's `template:` lambda takes the static path
3
+ * (`irToComponentTemplate`, expressions emitted as written) or the CSR path
4
+ * (`generateCsrTemplate`, signal/memo reads replaced by their initial values)
5
+ * is decided from the IR's free identifiers, not the expression text. The
6
+ * lambda runs at module scope, where a signal getter or memo is not defined,
7
+ * so an expression that reads one must take the CSR path wherever the read
8
+ * sits in it. The text check classified `label + count()` by its leading
9
+ * identifier (a prop) and sent it to the static path, which emitted a bare
10
+ * `count()`.
11
+ */
12
+
13
+ import { describe, test, expect } from 'bun:test'
14
+ import { compileJSX } from '../compiler'
15
+ import { TestAdapter } from '../adapters/test-adapter'
16
+
17
+ const adapter = new TestAdapter()
18
+
19
+ function templateLambda(source: string): string {
20
+ const result = compileJSX(source, 'T.tsx', { adapter })
21
+ expect(result.errors.filter((e) => e.severity === 'error')).toHaveLength(0)
22
+ const clientJs = result.files.find((f) => f.type === 'clientJs')!
23
+ const line = clientJs.content.split('\n').find((l) => l.includes('hydrate('))
24
+ if (!line) throw new Error('no hydrate() call in client JS')
25
+ const match = line.match(/template: (\(_p\) => `.*`) \}\)$/)
26
+ if (!match) throw new Error(`no template lambda in: ${line}`)
27
+ return match[1]
28
+ }
29
+
30
+ /** Evaluate the lambda at "module scope": only the escape helpers exist. */
31
+ function render(lambda: string, props: Record<string, unknown>): string {
32
+ const template = new Function('escapeTextOrMarkup', 'escapeText', 'escapeAttr', `return ${lambda}`)(String, String, String)
33
+ return template(props)
34
+ }
35
+
36
+ const header = `
37
+ 'use client'
38
+ import { createSignal, createMemo } from '@barefootjs/client'
39
+ `
40
+
41
+ describe('static template eligibility reads IR free identifiers (#3509)', () => {
42
+ test('a prop-first expression that calls a signal, in text, attribute and condition', () => {
43
+ const lambda = templateLambda(`${header}
44
+ export function PropFirst({ label }: { label: string }) {
45
+ const [count, setCount] = createSignal(0)
46
+ return (
47
+ <button data-x={label + count()} onClick={() => setCount(count() + 1)}>
48
+ {label + count()}
49
+ {label.length > count() ? <b>y</b> : <i>n</i>}
50
+ </button>
51
+ )
52
+ }`)
53
+ expect(lambda).not.toContain('count()')
54
+ const html = render(lambda, { label: 'Clicks: ' })
55
+ expect(html).toContain('data-x="Clicks: 0"')
56
+ expect(html).toContain('Clicks: 0')
57
+ expect(html).toContain('<b')
58
+ })
59
+
60
+ test('the result does not depend on operand order', () => {
61
+ const source = (expr: string) => `${header}
62
+ export function Order({ label }: { label: string }) {
63
+ const [count, setCount] = createSignal(0)
64
+ return <button onClick={() => setCount(count() + 1)}>{${expr}}</button>
65
+ }`
66
+ const propFirst = render(templateLambda(source('label + count()')), { label: 'n=' })
67
+ const signalFirst = render(templateLambda(source('count() + label')), { label: 'n=' })
68
+ expect(propFirst).toContain('n=0')
69
+ expect(signalFirst).toContain('0n=')
70
+ })
71
+
72
+ test('a prop-first expression that reads a memo', () => {
73
+ const lambda = templateLambda(`${header}
74
+ export function Derived({ label }: { label: string }) {
75
+ const [count, setCount] = createSignal(1)
76
+ const doubled = createMemo(() => count() * 2)
77
+ return (
78
+ <button onClick={() => setCount(count() + 1)}>
79
+ {label + doubled()}
80
+ </button>
81
+ )
82
+ }`)
83
+ expect(lambda).not.toContain('doubled()')
84
+ expect(render(lambda, { label: 'x' })).toContain('x2')
85
+ })
86
+
87
+ test('a prop-only expression with a call renders from the prop', () => {
88
+ const lambda = templateLambda(`${header}
89
+ export function PropOnly({ label }: { label: string }) {
90
+ const [count, setCount] = createSignal(0)
91
+ return <button onClick={() => setCount(count() + 1)}>{label.toUpperCase()}</button>
92
+ }`)
93
+ expect(render(lambda, { label: 'hi' })).toContain('HI')
94
+ })
95
+
96
+ test('a signal passed into an inlined JSX helper, in text, attribute and condition', () => {
97
+ const lambda = templateLambda(`${header}
98
+ export function Helper({ label }: { label: string }) {
99
+ const [count, setCount] = createSignal(0)
100
+ function text(value: number) {
101
+ return <span>{value}</span>
102
+ }
103
+ function attr(value: number) {
104
+ return <span data-x={value} />
105
+ }
106
+ function cond(value: number) {
107
+ return <span>{value ? <b>yes</b> : <i>no</i>}</span>
108
+ }
109
+ return (
110
+ <button onClick={() => setCount(count() + 1)}>
111
+ {label}
112
+ {text(count())}
113
+ {attr(count())}
114
+ {cond(count())}
115
+ </button>
116
+ )
117
+ }`)
118
+ expect(lambda).not.toContain('count()')
119
+ const html = render(lambda, { label: 'n' })
120
+ expect(html).toContain('data-x="0"')
121
+ expect(html).toContain('<i')
122
+ })
123
+
124
+ test('a signal passed into an inlined multi-return JSX helper', () => {
125
+ const lambda = templateLambda(`${header}
126
+ export function MultiHelper({ label }: { label: string }) {
127
+ const [count, setCount] = createSignal(0)
128
+ function pick(value: number) {
129
+ if (value > 0) return <b>{value}</b>
130
+ return <i>{value}</i>
131
+ }
132
+ return <button onClick={() => setCount(count() + 1)}>{label}{pick(count())}</button>
133
+ }`)
134
+ expect(lambda).not.toContain('count()')
135
+ expect(render(lambda, { label: 'n' })).toContain('<i')
136
+ })
137
+ })
@@ -13,7 +13,7 @@
13
13
  import { exprToString, isSupported, parseExpression, type ParsedExpr } from '../expression-parser.ts'
14
14
  import type { LoweringMatcher } from '../lowering-registry.ts'
15
15
  import { attrValueMayBeNullish, nullableSignalAttrGetter, type NullishAttrContext } from '../nullable-signal-attr.ts'
16
- import type { ConstantInfo, ExpressionAttr, SpreadAttr } from '../types.ts'
16
+ import type { CompilerError, ConstantInfo, ExpressionAttr, SpreadAttr } from '../types.ts'
17
17
  import { isBooleanAttr } from '../html-constants.ts'
18
18
 
19
19
  const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
@@ -41,6 +41,34 @@ export function unsupportedAttrExpression(
41
41
  return { reason: support.reason ?? (parsed.kind === 'unsupported' ? parsed.reason : undefined) }
42
42
  }
43
43
 
44
+ /**
45
+ * The BF101 for an attribute value {@link unsupportedAttrExpression}
46
+ * refuses, worded for one adapter (`adapterLabel`, e.g. `Mojo`) and its
47
+ * template language (`languageLabel`, e.g. `Embedded Perl`); `null` when the
48
+ * value goes on to {@link planAttrExpression}.
49
+ */
50
+ export function unsupportedAttrExpressionError(
51
+ expr: string,
52
+ attrName: string,
53
+ loweringMatchers: readonly LoweringMatcher[],
54
+ componentName: string,
55
+ adapterLabel: string,
56
+ languageLabel: string,
57
+ ): CompilerError | null {
58
+ const refusal = unsupportedAttrExpression(expr, loweringMatchers)
59
+ if (!refusal) return null
60
+ const reasonLine = refusal.reason ? `\n${refusal.reason}` : ''
61
+ return {
62
+ code: 'BF101',
63
+ severity: 'error',
64
+ message: `Expression not supported on attribute '${attrName}': ${expr.trim()}${reasonLine}`,
65
+ loc: { file: componentName + '.tsx', start: { line: 1, column: 0 }, end: { line: 1, column: 0 } },
66
+ suggestion: {
67
+ message: `The ${adapterLabel} adapter cannot lower JS object literals or tagged-template-literal expressions into ${languageLabel}. Move the expression into a \`'use client'\` component (so hydration computes it), or expand it into discrete attributes whose values are values the adapter can lower.`,
68
+ },
69
+ }
70
+ }
71
+
44
72
  /**
45
73
  * The emission of an `{expr}` attribute value.
46
74
  *