@barefootjs/jsx 0.41.0 → 0.41.2

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 (101) hide show
  1. package/dist/adapters/attr-plan.d.ts +8 -0
  2. package/dist/adapters/attr-plan.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +11 -1
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/computed-const.d.ts +19 -0
  6. package/dist/adapters/computed-const.d.ts.map +1 -1
  7. package/dist/adapters/dsl-template-adapter.d.ts +2 -1
  8. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  9. package/dist/adapters/inherited-const-server-read.d.ts +37 -0
  10. package/dist/adapters/inherited-const-server-read.d.ts.map +1 -0
  11. package/dist/adapters/loop-row-type.d.ts +18 -0
  12. package/dist/adapters/loop-row-type.d.ts.map +1 -1
  13. package/dist/adapters/non-primitive-equality.d.ts +8 -2
  14. package/dist/adapters/non-primitive-equality.d.ts.map +1 -1
  15. package/dist/adapters/number-value.d.ts +2 -1
  16. package/dist/adapters/number-value.d.ts.map +1 -1
  17. package/dist/adapters/unapplied-prop-default.d.ts +34 -0
  18. package/dist/adapters/unapplied-prop-default.d.ts.map +1 -0
  19. package/dist/adapters/uninlinable-seed-call.d.ts +29 -0
  20. package/dist/adapters/uninlinable-seed-call.d.ts.map +1 -0
  21. package/dist/analyzer.d.ts.map +1 -1
  22. package/dist/augment-inherited-props.d.ts +4 -22
  23. package/dist/augment-inherited-props.d.ts.map +1 -1
  24. package/dist/const-identity.d.ts +38 -0
  25. package/dist/const-identity.d.ts.map +1 -0
  26. package/dist/index.d.ts +10 -5
  27. package/dist/index.d.ts.map +1 -1
  28. package/dist/index.js +2500 -1475
  29. package/dist/ir-to-client-js/child-props-object.d.ts +39 -41
  30. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -1
  31. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/component-scope.d.ts +13 -2
  33. package/dist/ir-to-client-js/component-scope.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  38. package/dist/jsx-to-ir.d.ts.map +1 -1
  39. package/dist/local-call-body.d.ts +112 -0
  40. package/dist/local-call-body.d.ts.map +1 -0
  41. package/dist/nullable-signal-attr.d.ts +10 -0
  42. package/dist/nullable-signal-attr.d.ts.map +1 -1
  43. package/dist/prop-default-resolution.d.ts +52 -0
  44. package/dist/prop-default-resolution.d.ts.map +1 -0
  45. package/dist/props-binding.d.ts +15 -0
  46. package/dist/props-binding.d.ts.map +1 -1
  47. package/dist/server-read-walk.d.ts +66 -0
  48. package/dist/server-read-walk.d.ts.map +1 -0
  49. package/dist/ssr-defaults.d.ts.map +1 -1
  50. package/dist/ssr-seed-plan.d.ts +24 -1
  51. package/dist/ssr-seed-plan.d.ts.map +1 -1
  52. package/dist/static-const-member.d.ts +92 -0
  53. package/dist/static-const-member.d.ts.map +1 -0
  54. package/dist/types.d.ts +59 -0
  55. package/dist/types.d.ts.map +1 -1
  56. package/package.json +2 -2
  57. package/src/__tests__/computed-const.test.ts +7 -1
  58. package/src/__tests__/const-identity-child-prop.test.ts +127 -0
  59. package/src/__tests__/inherited-const-server-read.test.ts +116 -0
  60. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +8 -3
  61. package/src/__tests__/issue-3714-open-rest-spread-child.test.ts +188 -0
  62. package/src/__tests__/local-call-body.test.ts +101 -0
  63. package/src/__tests__/prop-default-resolution.test.ts +185 -0
  64. package/src/__tests__/props-spread-shadowed.test.ts +113 -0
  65. package/src/__tests__/server-read-walk.test.ts +125 -0
  66. package/src/__tests__/ssr-defaults.test.ts +67 -7
  67. package/src/__tests__/static-const-child-prop.test.ts +85 -0
  68. package/src/__tests__/static-record-literal-array.test.ts +82 -11
  69. package/src/adapters/attr-plan.ts +12 -1
  70. package/src/adapters/component-props.ts +19 -3
  71. package/src/adapters/computed-const.ts +108 -12
  72. package/src/adapters/dsl-template-adapter.ts +17 -4
  73. package/src/adapters/inherited-const-server-read.ts +174 -0
  74. package/src/adapters/loop-row-type.ts +69 -2
  75. package/src/adapters/non-primitive-equality.ts +17 -2
  76. package/src/adapters/number-value.ts +26 -2
  77. package/src/adapters/unapplied-prop-default.ts +83 -0
  78. package/src/adapters/uninlinable-seed-call.ts +62 -0
  79. package/src/analyzer.ts +43 -3
  80. package/src/augment-inherited-props.ts +4 -49
  81. package/src/compiler.ts +4 -4
  82. package/src/const-identity.ts +189 -0
  83. package/src/index.ts +10 -5
  84. package/src/ir-to-client-js/child-props-object.ts +94 -62
  85. package/src/ir-to-client-js/collect-elements.ts +28 -22
  86. package/src/ir-to-client-js/component-scope.ts +16 -2
  87. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +1 -0
  88. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +1 -0
  89. package/src/ir-to-client-js/html-template.ts +24 -4
  90. package/src/ir-to-client-js/index.ts +2 -2
  91. package/src/ir-to-client-js/prop-handling.ts +4 -0
  92. package/src/jsx-to-ir.ts +121 -60
  93. package/src/local-call-body.ts +191 -0
  94. package/src/nullable-signal-attr.ts +39 -17
  95. package/src/prop-default-resolution.ts +195 -0
  96. package/src/props-binding.ts +16 -0
  97. package/src/server-read-walk.ts +174 -0
  98. package/src/ssr-defaults.ts +93 -10
  99. package/src/ssr-seed-plan.ts +104 -18
  100. package/src/static-const-member.ts +243 -0
  101. package/src/types.ts +56 -0
@@ -0,0 +1,113 @@
1
+ /**
2
+ * `{...props}` where a binding named like the component's props object is in
3
+ * scope (#3727). Phase 1 marks the spread (`SpreadAttr.shadowsPropsObject`)
4
+ * and `spreadsPropsObject` is the one answer every adapter reads, so a row
5
+ * named `props` spreads the row and every other `{...props}` still spreads
6
+ * the component's props. The rendered output is pinned by the
7
+ * `loop-param-named-props-spread-*` conformance fixtures.
8
+ */
9
+
10
+ import { describe, test, expect } from 'bun:test'
11
+ import { compileJSX } from '../compiler'
12
+ import { TestAdapter } from '../adapters/test-adapter'
13
+ import { planComponentProps } from '../adapters/component-props'
14
+ import { planSpreadAttr, spreadsPropsObject } from '../adapters/attr-plan'
15
+ import type { ComponentIR, IRNode, SpreadAttr } from '../types'
16
+
17
+ function irOf(source: string): ComponentIR {
18
+ const file = compileJSX(source, 'Component.tsx', { adapter: new TestAdapter(), outputIR: true }).files.find(f => f.type === 'ir')
19
+ if (!file) throw new Error('no IR')
20
+ return JSON.parse(file.content) as ComponentIR
21
+ }
22
+
23
+ /** Every spread value in `node`'s tree, on elements and on component calls. */
24
+ function spreads(node: IRNode): SpreadAttr[] {
25
+ const out: SpreadAttr[] = []
26
+ const visit = (n: unknown): void => {
27
+ if (Array.isArray(n)) return n.forEach(visit)
28
+ if (n === null || typeof n !== 'object') return
29
+ const rec = n as { kind?: string }
30
+ if (rec.kind === 'spread') out.push(n as SpreadAttr)
31
+ for (const v of Object.values(n)) visit(v)
32
+ }
33
+ visit(node)
34
+ return out
35
+ }
36
+
37
+ const propsObjectName = 'props'
38
+
39
+ describe('the Phase 1 mark on a spread of a binding named like the props object', () => {
40
+ test.each([
41
+ ['a loop row', `rows.map((props) => <li key={props.id}><span {...props} /></li>)`],
42
+ ['a destructured row field', `rows.map(({ props }) => <li key={props.id}><span {...props} /></li>)`],
43
+ ['a row-local const', `rows.map((r) => { const props = r; return <li key={r.id}><span {...props} /></li> })`],
44
+ ['an inner loop row', `rows.map((r) => <li key={r.id}>{[r].map((props) => <i key={props.id} {...props} />)}</li>)`],
45
+ ['a parenthesized spread', `rows.map((props) => <li key={props.id}><span {...(props)} /></li>)`],
46
+ ])('%s is marked and is not the props object', (_name, body) => {
47
+ const ir = irOf(`
48
+ type Row = { id: string; props?: { id: string } }
49
+ export function C(props: { rows: Row[]; id: string }) {
50
+ const rows = props.rows
51
+ return <ul>{${body}}</ul>
52
+ }
53
+ `)
54
+ const found = spreads(ir.root)
55
+ expect(found).toHaveLength(1)
56
+ expect(found[0]!.shadowsPropsObject).toBe(true)
57
+ expect(found[0]!.callerBag).toBeUndefined()
58
+ expect(spreadsPropsObject(found[0]!, propsObjectName)).toBe(false)
59
+ })
60
+
61
+ test('a custom props name is shadowed by a row of that name, not by one named props', () => {
62
+ const ir = irOf(`
63
+ export function C(p: { rows: { id: string }[] }) {
64
+ return <ul>{p.rows.map((p) => <li key={p.id}><span {...p} /></li>)}{p.rows.map((props) => <li key={props.id}><span {...props} /></li>)}</ul>
65
+ }
66
+ `)
67
+ const [shadowed, other] = spreads(ir.root)
68
+ expect(shadowed!.shadowsPropsObject).toBe(true)
69
+ expect(spreadsPropsObject(shadowed!, 'p')).toBe(false)
70
+ expect(other!.shadowsPropsObject).toBeUndefined()
71
+ expect(spreadsPropsObject(other!, 'p')).toBe(false)
72
+ })
73
+
74
+ test.each([
75
+ ['at the top level', `<div {...props} />`],
76
+ ['in a row not named props', `props.rows.map((row) => <li key={row.id} {...props} />)`],
77
+ ['in a row beside an outer spread', `<div {...props}>{props.rows.map((r) => <i key={r.id} />)}</div>`],
78
+ ])('%s is the props object', (_name, body) => {
79
+ const ir = irOf(`
80
+ export function C(props: { rows: { id: string }[]; id: string }) {
81
+ return <section>{${body}}</section>
82
+ }
83
+ `)
84
+ const found = spreads(ir.root)
85
+ expect(found.length).toBeGreaterThan(0)
86
+ for (const value of found) {
87
+ expect(value.shadowsPropsObject).toBeUndefined()
88
+ expect(spreadsPropsObject(value, propsObjectName)).toBe(true)
89
+ }
90
+ })
91
+ })
92
+
93
+ describe('the planners on a marked spread', () => {
94
+ const shadowed = { kind: 'spread', expr: 'props', shadowsPropsObject: true } as SpreadAttr
95
+ const plain = { kind: 'spread', expr: 'props' } as SpreadAttr
96
+
97
+ test('an element spread of a shadowing binding spreads its own value', () => {
98
+ const ctx = { propsObjectName, propsParams: [{ name: 'id' }], localConstants: [], isBound: () => true }
99
+ expect(planSpreadAttr(shadowed, ctx).kind).toBe('value')
100
+ expect(planSpreadAttr(plain, { ...ctx, isBound: () => false }).kind).toBe('props-object')
101
+ })
102
+
103
+ test('a child spread of a shadowing binding is a spread segment, not the props params', () => {
104
+ const comp = (value: SpreadAttr) => ({
105
+ props: [{ name: '', value, loc: {} }],
106
+ children: [],
107
+ slotId: null,
108
+ }) as unknown as Parameters<typeof planComponentProps>[0]
109
+ const options = { propsObjectName, propsParams: [{ name: 'id' }] }
110
+ expect(planComponentProps(comp(shadowed), options).map(s => s.kind)).toEqual(['entries', 'spread'])
111
+ expect(planComponentProps(comp(plain), options).some(s => s.kind === 'spread')).toBe(false)
112
+ })
113
+ })
@@ -0,0 +1,125 @@
1
+ // Which declarations a component's server render reads (`walkServerReads`),
2
+ // against IR built by the real pipeline. The refusals built on it are
3
+ // rendered by the conformance fixtures
4
+ // `signal-seed-const-from-uninlinable-local-function`,
5
+ // `signal-seed-wrapped-uninlinable-local-function` and
6
+ // `loop-row-named-like-uninlinable-memo`.
7
+
8
+ import { describe, test, expect } from 'bun:test'
9
+ import { analyzeComponent } from '../analyzer'
10
+ import { buildMetadata } from '../compiler'
11
+ import { jsxToIR } from '../jsx-to-ir'
12
+ import { walkServerReads } from '../server-read-walk'
13
+ import type { ComponentIR } from '../types'
14
+
15
+ const UNINLINABLE = 'function value() { const x = 1; return x }'
16
+
17
+ function irFor(body: string, signature = '', preamble = ''): ComponentIR {
18
+ const ctx = analyzeComponent(`
19
+ 'use client'
20
+ import { createSignal, createMemo } from '@barefootjs/client'
21
+ function Child(props: { onPick?: () => void; f?: () => number }) { return <b>x</b> }
22
+ ${preamble}
23
+ export function C(${signature}) {
24
+ ${body}
25
+ }
26
+ `, 'C.tsx', 'C')
27
+ return { version: '0.1', metadata: buildMetadata(ctx), root: jsxToIR(ctx)!, errors: [] }
28
+ }
29
+
30
+ function readsOf(ir: ComponentIR): string[] {
31
+ const out: string[] = []
32
+ walkServerReads(ir, r => out.push(`${r.kind} ${r.name}@${r.scope}${r.refusedCalls.length ? ` !${r.refusedCalls.join(',')}` : ''}`))
33
+ return out.sort()
34
+ }
35
+
36
+ function reads(body: string, signature = '', preamble = ''): string[] {
37
+ return readsOf(irFor(body, signature, preamble))
38
+ }
39
+
40
+ describe('walkServerReads', () => {
41
+ test('a signal seeded from a const whose initializer calls an uninlinable function', () => {
42
+ expect(reads(`${UNINLINABLE}
43
+ const initial = value()
44
+ const [n] = createSignal(initial)
45
+ return <p>{n()}</p>`)).toEqual(['const initial@component !value', 'signal n@component'])
46
+ })
47
+
48
+ test('a signal seeded through an inlinable wrapper, a function declaration or an arrow const', () => {
49
+ expect(reads(`${UNINLINABLE}
50
+ function wrap() { return value() }
51
+ const [n] = createSignal(wrap())
52
+ return <p>{n()}</p>`)).toEqual(['function wrap@component !value', 'signal n@component'])
53
+ expect(reads(`${UNINLINABLE}
54
+ const wrap = () => value()
55
+ const [n] = createSignal(wrap())
56
+ return <p>{n()}</p>`)).toEqual(['function wrap@component !value', 'signal n@component'])
57
+ })
58
+
59
+ test('a memo of a memo reports the call on the memo that makes it', () => {
60
+ expect(reads(`${UNINLINABLE}
61
+ const a = createMemo(() => value())
62
+ const b = createMemo(() => a() + 1)
63
+ return <p>{b()}</p>`)).toEqual(['memo a@component !value', 'memo b@component'])
64
+ })
65
+
66
+ test('a loop row named like a memo is not a read of the memo', () => {
67
+ expect(reads(`${UNINLINABLE}
68
+ const n = createMemo(() => value())
69
+ return <ul>{['row'].map(n => <li key={n} title={n}>{n}</li>)}</ul>`)).toEqual([])
70
+ })
71
+
72
+ test('a callback param and a preamble local named like a memo are not reads of it', () => {
73
+ expect(reads(`${UNINLINABLE}
74
+ const n = createMemo(() => value())
75
+ return <p>{['a'].filter(n => n !== '').length}</p>`)).toEqual([])
76
+ expect(reads(`${UNINLINABLE}
77
+ const n = createMemo(() => value())
78
+ return <ul>{['a'].map(item => { const n = item + '!'; return <li key={item}>{n}</li> })}</ul>`)).toEqual([])
79
+ })
80
+
81
+ test('the loop array is read outside the row', () => {
82
+ expect(reads(`${UNINLINABLE}
83
+ const n = createMemo(() => [value()])
84
+ return <ul>{n().map(n => <li key={n}>{n}</li>)}</ul>`)).toEqual(['memo n@component !value'])
85
+ })
86
+
87
+ test('a /* @client */ read and an event handler prop read nothing', () => {
88
+ expect(reads(`${UNINLINABLE}
89
+ const initial = value()
90
+ const [n] = createSignal(initial)
91
+ const m = createMemo(() => value())
92
+ return <p>{/* @client */ n()}{/* @client */ initial}<Child onPick={() => console.log(m())} /></p>`)).toEqual([])
93
+ })
94
+
95
+ test('a function passed on uncalled is not read', () => {
96
+ expect(reads(`${UNINLINABLE}
97
+ const wrap = () => value()
98
+ return <p><Child f={wrap} /></p>`)).toEqual([])
99
+ })
100
+
101
+ test('a destructured prop named like a module function is the prop', () => {
102
+ expect(reads(`const [n] = createSignal(value())
103
+ return <p>{n()}</p>`, '{ value }: { value: () => number }', UNINLINABLE)).toEqual(['signal n@component'])
104
+ })
105
+
106
+ test("a module function's body reads the module's names, not the component's", () => {
107
+ expect(reads(`${UNINLINABLE}
108
+ const [n] = createSignal(outer())
109
+ return <p>{n()}</p>`, '', 'function value() { return 1 } function outer() { return value() }'))
110
+ .toEqual(['function outer@module', 'function value@module', 'signal n@component'])
111
+ })
112
+
113
+ test('a module const initialized by an uninlinable module function', () => {
114
+ expect(reads(`const [n] = createSignal(initial)
115
+ return <p>{n()}</p>`, '', `${UNINLINABLE}\nconst initial = value()`))
116
+ .toEqual(['const initial@module !value', 'signal n@component'])
117
+ })
118
+
119
+ test('an IR that went through JSON, whose block-bodied memo has no tree, is walked', () => {
120
+ const ir = irFor(`const [items] = createSignal([1, 2])
121
+ const visible = createMemo(() => { const out = []; for (const i of items()) out.push(i); return out })
122
+ return <p>{visible().length}</p>`)
123
+ expect(readsOf(JSON.parse(JSON.stringify(ir)))).toContain('memo visible@component')
124
+ })
125
+ })
@@ -304,12 +304,9 @@ describe('extractSsrDefaults', () => {
304
304
  // const-chain widening only ever ADDS prop references it finds by
305
305
  // actually walking through `props.X`, never invents one.
306
306
  //
307
- // (The value resolves to `null`, not `'sig'`: `tryStaticEval` doesn't
308
- // bind component-scope const locals into its evaluation `bindings` —
309
- // see the signal loop's `bindings` comment above — so `mid` itself is
310
- // unresolved for VALUE purposes independent of this fix; only the
311
- // separate `propName`-detection walk this test is pinning follows the
312
- // const chain.)
307
+ // (The value is `'sig'`: a component-scope const that evaluates without
308
+ // reading a prop is bound for the signal seeds and memo bodies, #3721.
309
+ // The `propName`-detection walk this test pins is independent of it.)
313
310
  const metadata = metadataFor(`
314
311
  'use client'
315
312
  import { createSignal } from '@barefootjs/client'
@@ -324,7 +321,7 @@ describe('extractSsrDefaults', () => {
324
321
  // prop (`separateSignalPropBindings`): the signal keeps a plain entry
325
322
  // under its own name, and the prop keeps its prop entry.
326
323
  const defaults = extractSsrDefaults(metadata)
327
- expect(defaults?.bfSignal_label).toEqual({ value: null })
324
+ expect(defaults?.bfSignal_label).toEqual({ value: 'sig' })
328
325
  expect(defaults?.label).toEqual({ propName: 'label' })
329
326
  })
330
327
 
@@ -916,3 +913,66 @@ describe('deriveStashFromDefaults', () => {
916
913
  })
917
914
  })
918
915
  })
916
+
917
+ // A called function's returned expression is evaluated in the scope the
918
+ // function is declared in (#3721). Rendered by the conformance fixtures
919
+ // `module-function-reads-module-binding` and
920
+ // `signal-seed-uninlinable-local-function-hides-module-function`.
921
+ describe('extractSsrDefaults: local function calls resolve lexically', () => {
922
+ const values = (source: string) =>
923
+ Object.fromEntries(Object.entries(extractSsrDefaults(metadataFor(source)) ?? {}).map(([k, d]) => [k, 'value' in d ? d.value : undefined]))
924
+
925
+ test("a module function reads the module's const beside a component const of the same name", () => {
926
+ expect(values(`
927
+ import { createSignal, createMemo } from '@barefootjs/client'
928
+ const label = 'module'
929
+ function value() { return label }
930
+ function C() {
931
+ const label = 'component'
932
+ const [n] = createSignal(value())
933
+ const m = createMemo(() => value() + label)
934
+ return <p>{n()}{m()}</p>
935
+ }
936
+ `)).toMatchObject({ n: 'module', m: 'modulecomponent' })
937
+ })
938
+
939
+ test('a component function reads the component const, and a module const the component shadows is not its value', () => {
940
+ expect(values(`
941
+ import { createSignal } from '@barefootjs/client'
942
+ const label = 'module'
943
+ function C(props: { x?: string }) {
944
+ const label = props.x
945
+ function value() { return label }
946
+ const [n] = createSignal(value())
947
+ const [l] = createSignal(label)
948
+ return <p>{n()}{l()}</p>
949
+ }
950
+ `)).toMatchObject({ n: null, l: null })
951
+ })
952
+
953
+ test('a component function a template cannot inline hides the module function of its name', () => {
954
+ expect(values(`
955
+ import { createSignal } from '@barefootjs/client'
956
+ function value() { return 1 }
957
+ function C() {
958
+ function value() { const two = 2; return two }
959
+ const [n] = createSignal(value())
960
+ return <p>{n()}</p>
961
+ }
962
+ `)).toMatchObject({ n: null })
963
+ })
964
+
965
+ test('a const initializer and a wrapper calling an inlinable function evaluate', () => {
966
+ expect(values(`
967
+ import { createSignal } from '@barefootjs/client'
968
+ function C() {
969
+ function value() { return 1 }
970
+ const wrap = () => value() + 1
971
+ const initial = value()
972
+ const [n] = createSignal(initial)
973
+ const [w] = createSignal(wrap())
974
+ return <p>{n()}{w()}</p>
975
+ }
976
+ `)).toMatchObject({ n: 1, w: 2 })
977
+ })
978
+ })
@@ -0,0 +1,85 @@
1
+ import { describe, expect, test } from 'bun:test'
2
+ import { analyzeComponent } from '../analyzer'
3
+ import { jsxToIR } from '../jsx-to-ir'
4
+ import type { IRNode, IRProp } from '../types'
5
+
6
+ /**
7
+ * Every component prop named `xs` in the IR tree, in source order: the
8
+ * literal a template passes (`staticConstLiteral`), or `null` when the prop
9
+ * carries none.
10
+ */
11
+ function xsProps(source: string): Array<string | null> {
12
+ const out: Array<string | null> = []
13
+ const visit = (node: IRNode | null | undefined): void => {
14
+ if (!node || typeof node !== 'object') return
15
+ if (node.type === 'component') {
16
+ for (const p of node.props as IRProp[]) {
17
+ if (p.name !== 'xs') continue
18
+ // JS-runtime consumers read `expr`, which stays the const's name.
19
+ if (p.value.kind === 'expression') expect(p.value.expr.startsWith('[') || p.value.expr.startsWith('{')).toBe(false)
20
+ out.push(p.value.kind === 'expression' ? (p.value.staticConstLiteral?.expr ?? null) : null)
21
+ }
22
+ }
23
+ for (const value of Object.values(node)) {
24
+ if (Array.isArray(value)) for (const child of value) visit(child as IRNode)
25
+ else if (value && typeof value === 'object' && 'type' in value) visit(value as IRNode)
26
+ }
27
+ }
28
+ visit(jsxToIR(analyzeComponent(source, 'C.tsx')))
29
+ return out
30
+ }
31
+
32
+ describe('a const holding a static literal, passed whole as a child prop, carries the literal for templates', () => {
33
+ test('a module array, a module object and a component-local array', () => {
34
+ expect(xsProps(`
35
+ import { Kid } from './kid'
36
+ const QS = ['a', 'b"c']
37
+ const REC = { lf: 'r', n: 3 }
38
+ export function C() {
39
+ const local = [1e3, .5]
40
+ return <div><Kid xs={QS} /><Kid xs={REC} /><Kid xs={local} /></div>
41
+ }
42
+ `)).toEqual([`['a', 'b"c']`, `{ lf: 'r', n: 3 }`, '[1e3, .5]'])
43
+ })
44
+
45
+ test('a loop row or a prop of the same name is that binding', () => {
46
+ expect(xsProps(`
47
+ import { Kid } from './kid'
48
+ const QS = ['a', 'b']
49
+ const PS = ['m']
50
+ export function C({ PS }: { PS: string[] }) {
51
+ return (
52
+ <div>
53
+ {[['r']].map(QS => <Kid key={QS[0]} xs={QS} />)}
54
+ <Kid xs={PS} />
55
+ </div>
56
+ )
57
+ }
58
+ `)).toEqual([null, null])
59
+ })
60
+
61
+ test('a const that reads a name, calls something or is changed carries no literal', () => {
62
+ expect(xsProps(`
63
+ import { Kid } from './kid'
64
+ const BASE = 'b'
65
+ const READS = [BASE]
66
+ const CALLS = [String(1)]
67
+ export function C(props: { v: string }) {
68
+ const fromProp = [props.v]
69
+ const changed = ['x']
70
+ changed.push('y')
71
+ return <div><Kid xs={READS} /><Kid xs={CALLS} /><Kid xs={fromProp} /><Kid xs={changed} /></div>
72
+ }
73
+ `)).toEqual([null, null, null, null])
74
+ })
75
+
76
+ test('a /* @client */ prop carries no literal', () => {
77
+ expect(xsProps(`
78
+ import { Kid } from './kid'
79
+ const QS = ['a']
80
+ export function C() {
81
+ return <div><Kid xs={/* @client */ QS} /></div>
82
+ }
83
+ `)).toEqual([null])
84
+ })
85
+ })
@@ -1,5 +1,6 @@
1
1
  import { describe, expect, test } from 'bun:test'
2
- import { lookupStaticArrayElement, lookupStaticRecordLiteral } from '../augment-inherited-props.ts'
2
+ import { lookupStaticRecordLiteral } from '../augment-inherited-props.ts'
3
+ import { lookupStaticConstMember, readStaticConstMember, staticIndexKey } from '../static-const-member.ts'
3
4
  import { parseExpression } from '../expression-parser.ts'
4
5
  import { analyzeComponent } from '../analyzer.ts'
5
6
  import { buildMetadata } from '../compiler.ts'
@@ -11,7 +12,8 @@ function moduleConst(name: string, value: string, extra: Partial<ConstantInfo> =
11
12
  return {
12
13
  name,
13
14
  value: value as ConstantInfo['value'],
14
- parsed: parseExpression(value),
15
+ // Parenthesised, as the analyzer parses it, so an object literal is not a block.
16
+ parsed: parseExpression(`(${value})`),
15
17
  declarationKind: 'const',
16
18
  isModule: true,
17
19
  type: null,
@@ -23,8 +25,12 @@ function moduleConst(name: string, value: string, extra: Partial<ConstantInfo> =
23
25
  const notShadowed = () => false
24
26
  const num = (value: number) => ({ kind: 'literal', value, literalType: 'number', raw: String(value) })
25
27
  const str = (value: string) => ({ kind: 'literal', value, literalType: 'string' })
28
+ const UNDEFINED = { kind: 'identifier', name: 'undefined' }
29
+ const ident = (name: string) => ({ kind: 'identifier' as const, name })
30
+ const lookupStaticArrayElement = (name: string, key: string, constants: ConstantInfo[] | undefined, isShadowed: (n: string) => boolean) =>
31
+ lookupStaticConstMember(ident(name), key, constants, isShadowed)
26
32
 
27
- describe('lookupStaticArrayElement', () => {
33
+ describe('lookupStaticConstMember: an array literal', () => {
28
34
  const QS = moduleConst('QS', `['a1', "b\\"c", \`m1\nm2\`, 1e3, 0x10, .5, -0, -1.5]`)
29
35
  const read = (key: string) => lookupStaticArrayElement('QS', key, [QS], notShadowed)
30
36
 
@@ -46,11 +52,17 @@ describe('lookupStaticArrayElement', () => {
46
52
  expect(read('length')).toEqual(num(8))
47
53
  })
48
54
 
49
- test('a key that names no element falls back to the generic lowering', () => {
50
- expect(read('01')).toBeNull()
51
- expect(read('8')).toBeNull()
52
- expect(read('-1')).toBeNull()
53
- expect(read('x')).toBeNull()
55
+ test('a key that names no element reads undefined', () => {
56
+ expect(read('01')).toEqual(UNDEFINED)
57
+ expect(read('8')).toEqual(UNDEFINED)
58
+ expect(read('-1')).toEqual(UNDEFINED)
59
+ expect(read('x')).toEqual(UNDEFINED)
60
+ })
61
+
62
+ test('a key only Array.prototype has is inherited, not undefined', () => {
63
+ expect(read('map')).toBeNull()
64
+ expect(readStaticConstMember(ident('QS'), 'map', [QS], notShadowed)).toEqual({ kind: 'inherited', key: 'map' })
65
+ expect(readStaticConstMember(ident('QS'), 'constructor', [QS], notShadowed)).toEqual({ kind: 'inherited', key: 'constructor' })
54
66
  })
55
67
 
56
68
  test('a hole, a spread or a non-literal element is not resolved', () => {
@@ -58,8 +70,13 @@ describe('lookupStaticArrayElement', () => {
58
70
  expect(lookupStaticArrayElement('H', '0', [holes], notShadowed)).toEqual(str('a'))
59
71
  expect(lookupStaticArrayElement('H', '2', [holes], notShadowed)).toBeNull()
60
72
  expect(lookupStaticArrayElement('H', 'length', [holes], notShadowed)).toBeNull()
73
+ // Past the end is unknown once a hole or spread hides the length, but a
74
+ // non-index key is missing either way.
75
+ expect(lookupStaticArrayElement('H', '9', [holes], notShadowed)).toBeNull()
76
+ expect(lookupStaticArrayElement('H', '01', [holes], notShadowed)).toEqual(UNDEFINED)
61
77
  const spread = moduleConst('S', `[...xs, 'b']`)
62
78
  expect(lookupStaticArrayElement('S', '1', [spread], notShadowed)).toBeNull()
79
+ expect(lookupStaticArrayElement('S', '9', [spread], notShadowed)).toBeNull()
63
80
  const ref = moduleConst('R', `[other, 'b']`)
64
81
  expect(lookupStaticArrayElement('R', '0', [ref], notShadowed)).toBeNull()
65
82
  expect(lookupStaticArrayElement('R', '1', [ref], notShadowed)).toEqual(str('b'))
@@ -73,13 +90,67 @@ describe('lookupStaticArrayElement', () => {
73
90
  expect(lookupStaticArrayElement('QS', 'length', [mutated], notShadowed)).toBeNull()
74
91
  })
75
92
 
76
- test('a record const is not an array, and the record lookup no longer reads arrays', () => {
77
- const rec = moduleConst('REC', `{ lf: 'r1' }`)
78
- expect(lookupStaticArrayElement('REC', 'lf', [rec], notShadowed)).toBeNull()
93
+ test('the record lookup does not read arrays', () => {
79
94
  expect(lookupStaticRecordLiteral('QS', '0', [QS], notShadowed)).toBeNull()
80
95
  })
81
96
  })
82
97
 
98
+ describe('lookupStaticConstMember: an object literal and a nested read', () => {
99
+ const REC = moduleConst('REC', `{ k: 'v', n: 3, k2: 'a', k2: 'b' }`)
100
+ const NEST = moduleConst('NEST', `{ a: { b: 1, q: ['x'] } }`)
101
+ const member = (object: Parameters<typeof lookupStaticConstMember>[0], key: string) =>
102
+ lookupStaticConstMember(object, key, [REC, NEST], notShadowed)
103
+ const nestA = { kind: 'member' as const, object: ident('NEST'), property: 'a', computed: false, optional: false }
104
+
105
+ test('a listed key reads its value, the last entry winning', () => {
106
+ expect(member(ident('REC'), 'k')).toEqual(str('v'))
107
+ expect(member(ident('REC'), 'n')).toEqual(num(3))
108
+ expect(member(ident('REC'), 'k2')).toEqual(str('b'))
109
+ expect(member(nestA, 'b')).toEqual(num(1))
110
+ })
111
+
112
+ test('a key the literal does not list reads undefined, nested too', () => {
113
+ expect(member(ident('REC'), 'nope')).toEqual(UNDEFINED)
114
+ expect(member(ident('REC'), 'length')).toEqual(UNDEFINED)
115
+ expect(member(nestA, 'c')).toEqual(UNDEFINED)
116
+ expect(member({ kind: 'member', object: nestA, property: 'q', computed: false, optional: false }, '1')).toEqual(UNDEFINED)
117
+ })
118
+
119
+ test('a key only Object.prototype has is inherited', () => {
120
+ for (const key of ['toString', 'constructor', 'hasOwnProperty', '__proto__']) {
121
+ expect(member(ident('REC'), key)).toBeNull()
122
+ expect(readStaticConstMember(ident('REC'), key, [REC], notShadowed)).toEqual({ kind: 'inherited', key })
123
+ }
124
+ expect(readStaticConstMember(nestA, 'toString', [NEST], notShadowed)).toEqual({ kind: 'inherited', key: 'toString' })
125
+ })
126
+
127
+ test('a spread or an __proto__ entry makes a missing key unknown', () => {
128
+ const spread = moduleConst('SP', `{ ...base, k: 'v' }`)
129
+ const proto = moduleConst('PR', `{ __proto__: base, k: 'v' }`)
130
+ expect(lookupStaticConstMember(ident('SP'), 'nope', [spread], notShadowed)).toBeNull()
131
+ expect(lookupStaticConstMember(ident('PR'), 'nope', [proto], notShadowed)).toBeNull()
132
+ })
133
+
134
+ test('a value that is not a string or number has no compile-time value', () => {
135
+ expect(member(ident('NEST'), 'a')).toBeNull()
136
+ expect(member(nestA, 'q')).toBeNull()
137
+ })
138
+
139
+ test('a shadowed root keeps the read live', () => {
140
+ expect(lookupStaticConstMember(ident('REC'), 'nope', [REC], name => name === 'REC')).toBeNull()
141
+ })
142
+ })
143
+
144
+ describe('staticIndexKey', () => {
145
+ test('a literal index is its JS property key', () => {
146
+ expect(staticIndexKey(num(1))).toBe('1')
147
+ expect(staticIndexKey(str('01'))).toBe('01')
148
+ expect(staticIndexKey({ kind: 'unary', op: '-', argument: num(1) } as never)).toBe('-1')
149
+ expect(staticIndexKey({ kind: 'unary', op: '-', argument: num(0) } as never)).toBe('0')
150
+ expect(staticIndexKey(ident('i'))).toBeNull()
151
+ })
152
+ })
153
+
83
154
  describe('resolveStaticConstBinding: a component-local literal const', () => {
84
155
  const constantsOf = (source: string) => buildMetadata(analyzeComponent(source, 'c.tsx')).localConstants
85
156
  const element = (source: string, key = '0') => lookupStaticArrayElement('QS', key, constantsOf(source), notShadowed)
@@ -160,10 +160,21 @@ export interface SpreadPlanContext {
160
160
  isBound(name: string): boolean
161
161
  }
162
162
 
163
+ /**
164
+ * Whether `value` spreads the component's own props object whole. The one
165
+ * answer every adapter uses: the spread names `propsObjectName` and Phase 1
166
+ * did not find a binding of that name in scope at the spread
167
+ * (`SpreadAttr.shadowsPropsObject`, #3727), so `rows.map((props) => <li
168
+ * {...props} />)` spreads the row.
169
+ */
170
+ export function spreadsPropsObject(value: SpreadAttr, propsObjectName: string | null): boolean {
171
+ return propsObjectName !== null && value.expr.trim() === propsObjectName && value.shadowsPropsObject !== true
172
+ }
173
+
163
174
  /** Plan a `{...spread}` attribute. */
164
175
  export function planSpreadAttr(value: SpreadAttr, ctx: SpreadPlanContext): SpreadAttrPlan {
165
176
  const trimmed = value.expr.trim()
166
- if (ctx.propsObjectName && ctx.propsObjectName === trimmed) {
177
+ if (spreadsPropsObject(value, ctx.propsObjectName)) {
167
178
  return { kind: 'props-object', params: ctx.propsParams.map((p) => p.name) }
168
179
  }
169
180
  const candidates: Array<ParsedExpr | undefined> = [value.parsed]
@@ -22,6 +22,7 @@
22
22
 
23
23
  import { resolveJsxChildrenProp } from '@barefootjs/shared'
24
24
  import type { AttrValue, IRComponent, IRNode, SpreadAttr } from '../types.ts'
25
+ import { spreadsPropsObject } from './attr-plan.ts'
25
26
  import { derivesScopeFromSlot } from './child-scope.ts'
26
27
 
27
28
  /** One entry of the props hash. */
@@ -163,7 +164,7 @@ export function planComponentProps(
163
164
  // `children={<jsx/>}` is forwarded as the `children` entry below.
164
165
  if (p.name !== 'children') push({ kind: 'named-slot', name: p.name, children: p.value.children })
165
166
  } else if (p.value.kind === 'spread') {
166
- if (options.propsObjectName !== null && options.propsObjectName === p.value.expr.trim()) {
167
+ if (spreadsPropsObject(p.value, options.propsObjectName)) {
167
168
  pushPropsSpread()
168
169
  } else {
169
170
  earlier.spread = true
@@ -180,6 +181,18 @@ export function planComponentProps(
180
181
  return segments
181
182
  }
182
183
 
184
+ /**
185
+ * The value a template passes for a component prop. A bare read of a const
186
+ * holding a static literal (`ExpressionAttr.staticConstLiteral`, `xs={QS}`)
187
+ * is that literal, as if the source had written it in place: a template
188
+ * holds the props, not the consts. Any other value is itself.
189
+ */
190
+ export function templatePropValue(value: AttrValue): AttrValue {
191
+ if (value.kind !== 'expression' || !value.staticConstLiteral) return value
192
+ const { expr, parsed } = value.staticConstLiteral
193
+ return { kind: 'expression', expr, parsed }
194
+ }
195
+
183
196
  /** A spelled segment: the entries' hash-literal parts, or the expression a spread folds in. */
184
197
  export type SpelledComponentPropSegment = { kind: 'entries'; parts: string[] } | { kind: 'spread'; expr: string }
185
198
 
@@ -200,7 +213,10 @@ export interface ComponentPropSpelling {
200
213
 
201
214
  /**
202
215
  * Spell a plan in source order, so the captures an entry's spelling emits
203
- * (named slots, then the children) keep their order and counter values.
216
+ * (named slots, then the children) keep their order and counter values. A
217
+ * `value` entry is spelled as the template passes it
218
+ * ({@link templatePropValue}); the plan keeps the IR's own value, which
219
+ * callers compare by identity.
204
220
  */
205
221
  export function spellComponentProps(
206
222
  segments: readonly ComponentPropSegment[],
@@ -211,7 +227,7 @@ export function spellComponentProps(
211
227
  if (segment.kind === 'present-param') return { kind: 'spread', expr: spelling.presentParam(segment.name) }
212
228
  const parts: string[] = []
213
229
  for (const entry of segment.entries) {
214
- const part = spelling.entry(entry)
230
+ const part = spelling.entry(entry.kind === 'value' ? { ...entry, value: templatePropValue(entry.value) } : entry)
215
231
  if (part) parts.push(part)
216
232
  }
217
233
  return { kind: 'entries', parts }