@barefootjs/jsx 0.40.2 → 0.41.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.
Files changed (88) hide show
  1. package/dist/adapters/callback-method.d.ts +8 -1
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +3 -4
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +3 -12
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  7. package/dist/adapters/loop-row-type.d.ts +7 -0
  8. package/dist/adapters/loop-row-type.d.ts.map +1 -1
  9. package/dist/adapters/nil-reading.d.ts +15 -20
  10. package/dist/adapters/nil-reading.d.ts.map +1 -1
  11. package/dist/adapters/non-primitive-equality.d.ts +1 -1
  12. package/dist/adapters/parsed-expr-emitter.d.ts +11 -1
  13. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  14. package/dist/adapters/primitive-plan.d.ts +40 -11
  15. package/dist/adapters/primitive-plan.d.ts.map +1 -1
  16. package/dist/adapters/prop-classes.d.ts +5 -0
  17. package/dist/adapters/prop-classes.d.ts.map +1 -1
  18. package/dist/analyzer.d.ts.map +1 -1
  19. package/dist/index.d.ts +5 -6
  20. package/dist/index.d.ts.map +1 -1
  21. package/dist/index.js +390 -228
  22. package/dist/ir-to-client-js/child-props-object.d.ts +43 -1
  23. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -1
  24. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  26. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/imports.d.ts +2 -2
  29. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -3
  31. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +3 -1
  33. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  34. package/dist/jsx-to-ir.d.ts.map +1 -1
  35. package/dist/nullable-signal-attr.d.ts +4 -46
  36. package/dist/nullable-signal-attr.d.ts.map +1 -1
  37. package/dist/props-binding.d.ts +58 -13
  38. package/dist/props-binding.d.ts.map +1 -1
  39. package/dist/ssr-defaults.d.ts +39 -3
  40. package/dist/ssr-defaults.d.ts.map +1 -1
  41. package/package.json +2 -2
  42. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +6 -6
  43. package/src/__tests__/body-destructured-prop-default-arrow.test.ts +2 -2
  44. package/src/__tests__/body-destructured-props-live.test.ts +5 -5
  45. package/src/__tests__/client-js-generation.test.ts +3 -3
  46. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +7 -7
  47. package/src/__tests__/destructured-props-live.test.ts +1 -1
  48. package/src/__tests__/issue-3861-object-spread-child.test.ts +102 -0
  49. package/src/__tests__/memo-body-expr.test.ts +2 -2
  50. package/src/__tests__/nil-reading.test.ts +3 -2
  51. package/src/__tests__/nullable-signal-attr.test.ts +30 -103
  52. package/src/__tests__/primitive-plan.test.ts +90 -12
  53. package/src/__tests__/prop-default-undefined-only.test.ts +115 -0
  54. package/src/__tests__/prop-references.test.ts +2 -2
  55. package/src/__tests__/props-destructuring.test.ts +17 -0
  56. package/src/__tests__/prune-unused-prop-extractions.test.ts +3 -3
  57. package/src/__tests__/renamed-body-destructure-template.test.ts +7 -7
  58. package/src/__tests__/rewrite-destructured-props.test.ts +1 -1
  59. package/src/__tests__/ssr-defaults.test.ts +113 -25
  60. package/src/__tests__/written-binding-substitution.test.ts +8 -8
  61. package/src/adapters/callback-method.ts +13 -5
  62. package/src/adapters/component-props.ts +3 -4
  63. package/src/adapters/dsl-template-adapter.ts +26 -28
  64. package/src/adapters/loop-row-type.ts +10 -0
  65. package/src/adapters/nil-reading.ts +23 -25
  66. package/src/adapters/non-primitive-equality.ts +1 -1
  67. package/src/adapters/parsed-expr-emitter.ts +31 -2
  68. package/src/adapters/primitive-plan.ts +84 -15
  69. package/src/adapters/prop-classes.ts +16 -3
  70. package/src/analyzer.ts +27 -7
  71. package/src/index.ts +4 -11
  72. package/src/ir-to-client-js/child-props-object.ts +140 -6
  73. package/src/ir-to-client-js/collect-elements.ts +7 -14
  74. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +4 -2
  75. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +4 -2
  76. package/src/ir-to-client-js/html-template.ts +18 -9
  77. package/src/ir-to-client-js/imports.ts +1 -1
  78. package/src/ir-to-client-js/phases/props-extraction.ts +11 -7
  79. package/src/ir-to-client-js/plan/build-declaration-emit.ts +40 -7
  80. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +58 -5
  81. package/src/ir-to-client-js/rewrite-destructured-props.ts +31 -1
  82. package/src/jsx-to-ir.ts +15 -2
  83. package/src/nullable-signal-attr.ts +11 -138
  84. package/src/props-binding.ts +84 -19
  85. package/src/ssr-defaults.ts +100 -11
  86. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +0 -42
  87. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +0 -1
  88. package/src/adapters/ambiguous-nil-arithmetic.ts +0 -103
@@ -136,7 +136,7 @@ describe('body-destructured prop with an arrow-function default (#2940)', () =>
136
136
  const js = clientJs!.content
137
137
 
138
138
  expect(parseDiagnosticCount(js)).toBe(0)
139
- expect(js).toContain("(_p.fmt ?? ((v) => 'v' + v))(1)")
140
- expect(js).not.toContain("(_p.fmt ?? (((v) => 'v' + v)))(1)")
139
+ expect(js).toContain("(_p.fmt === undefined ? ((v) => 'v' + v) : _p.fmt)(1)")
140
+ expect(js).not.toContain("(_p.fmt === undefined ? (((v) => 'v' + v)) : _p.fmt)(1)")
141
141
  })
142
142
  })
@@ -76,7 +76,7 @@ describe('body-destructured props compile to live reads', () => {
76
76
 
77
77
  // `items`'s destructure default survives as a live fallback, not a
78
78
  // one-time extraction.
79
- expect(content).toContain('(_p.items ?? []).length')
79
+ expect(content).toContain('(_p.items === undefined ? [] : _p.items).length')
80
80
  })
81
81
 
82
82
  test('the CSR template lambda also reads a defaulted body alias live, matching the parameter form (#2934)', () => {
@@ -104,8 +104,8 @@ describe('body-destructured props compile to live reads', () => {
104
104
  `
105
105
  const { content } = compileClientJs(source, 'Child.tsx')
106
106
  expect(content).not.toMatch(/const label = /)
107
- expect(content).toContain("escapeAttr((_p.label ?? 'none'))")
108
- expect(content).toContain("escapeTextOrMarkup((_p.label ?? 'none'))")
107
+ expect(content).toContain("escapeAttr((_p.label === undefined ? 'none' : _p.label))")
108
+ expect(content).toContain("escapeTextOrMarkup((_p.label === undefined ? 'none' : _p.label))")
109
109
  // Never the bare, default-dropping form.
110
110
  expect(content).not.toMatch(/\(_p\.label\) != null/)
111
111
  })
@@ -124,8 +124,8 @@ describe('body-destructured props compile to live reads', () => {
124
124
  `
125
125
  const { content } = compileClientJs(source, 'Child.tsx')
126
126
  expect(content).not.toMatch(/const text = /)
127
- expect(content).toContain("escapeAttr((_p.label ?? 'none'))")
128
- expect(content).toContain("escapeTextOrMarkup((_p.label ?? 'none'))")
127
+ expect(content).toContain("escapeAttr((_p.label === undefined ? 'none' : _p.label))")
128
+ expect(content).toContain("escapeTextOrMarkup((_p.label === undefined ? 'none' : _p.label))")
129
129
  })
130
130
 
131
131
  test('a renamed body-destructured prop (`onPick: pick`) reads the caller-facing key live everywhere', () => {
@@ -2541,7 +2541,7 @@ describe('Client JS generation', () => {
2541
2541
  expect(content).toContain('sizeMap')
2542
2542
  expect(content).not.toContain('sizeMap'.replace('size', 'props.size'))
2543
2543
  // The standalone size reference should be rewritten
2544
- expect(content).toContain("_p.size ?? 'sm'")
2544
+ expect(content).toContain("_p.size === undefined ? 'sm' : _p.size")
2545
2545
  })
2546
2546
 
2547
2547
  test('default values from destructuring are included in rewrite', () => {
@@ -2566,7 +2566,7 @@ describe('Client JS generation', () => {
2566
2566
 
2567
2567
  expect(content).toContain('createEffect')
2568
2568
  // Should include the default value in the rewrite
2569
- expect(content).toContain("_p.label ?? 'tag'")
2569
+ expect(content).toContain("_p.label === undefined ? 'tag' : _p.label")
2570
2570
  })
2571
2571
 
2572
2572
  test('text node renders empty string for nullish reactive values', () => {
@@ -3077,7 +3077,7 @@ describe('Client JS generation', () => {
3077
3077
  // The destructure default rides the signal seed (and its controlled
3078
3078
  // effect) — the standalone `const size = …` extraction is pruned when
3079
3079
  // nothing else in the init reads it.
3080
- expect(js).toContain('_p.size ?? 5')
3080
+ expect(js).toContain('_p.size === undefined ? 5 : _p.size')
3081
3081
  expect(js).not.toContain('_p.size ?? 0')
3082
3082
  })
3083
3083
  })
@@ -72,7 +72,7 @@ describe('client JS reads the earlier prop live', () => {
72
72
  return <p>{String(on && true)}</p>
73
73
  }
74
74
  `)
75
- expect(js).toContain('(_p.on ?? (_p.off ?? false))')
75
+ expect(js).toContain('(_p.on === undefined ? (_p.off === undefined ? false : _p.off) : _p.on)')
76
76
  expect(js).not.toContain('_p.on ?? off)')
77
77
  })
78
78
 
@@ -83,8 +83,8 @@ describe('client JS reads the earlier prop live', () => {
83
83
  return <p>{c}{String(on)}</p>
84
84
  }
85
85
  `)
86
- expect(js).toContain(`(_p.c ?? (_p.b ?? (_p.a ?? 'x')))`)
87
- expect(js).toContain('(_p.on ?? !(_p.off ?? false))')
86
+ expect(js).toContain(`(_p.c === undefined ? (_p.b === undefined ? (_p.a === undefined ? 'x' : _p.a) : _p.b) : _p.c)`)
87
+ expect(js).toContain('(_p.on === undefined ? !(_p.off === undefined ? false : _p.off) : _p.on)')
88
88
  })
89
89
 
90
90
  test('a renamed earlier binding reads its caller-facing key', () => {
@@ -94,7 +94,7 @@ describe('client JS reads the earlier prop live', () => {
94
94
  return <p>{String(on)}</p>
95
95
  }
96
96
  `)
97
- expect(js).toContain('(_p.on ?? (_p.off ?? false))')
97
+ expect(js).toContain('(_p.on === undefined ? (_p.off === undefined ? false : _p.off) : _p.on)')
98
98
  })
99
99
 
100
100
  test('body form: the init body reads the earlier prop live too', () => {
@@ -106,7 +106,7 @@ describe('client JS reads the earlier prop live', () => {
106
106
  }
107
107
  `)
108
108
  expect(js).not.toMatch(/_p\.on \?\? off\b/)
109
- expect(js).toContain('(_p.on ?? (_p.off ?? false))')
109
+ expect(js).toContain('(_p.on === undefined ? (_p.off === undefined ? false : _p.off) : _p.on)')
110
110
  })
111
111
 
112
112
  test('the CSR template reads a signal seed and a memo over the prop with its default', () => {
@@ -120,8 +120,8 @@ describe('client JS reads the earlier prop live', () => {
120
120
  }
121
121
  `)
122
122
  const template = js.slice(js.indexOf('template: (_p) =>'))
123
- expect(template).toContain('String(((_p.on ?? (_p.off ?? false))))')
124
- expect(template).toContain('String((!(_p.on ?? (_p.off ?? false))))')
123
+ expect(template).toContain('String(((_p.on === undefined ? (_p.off === undefined ? false : _p.off) : _p.on)))')
124
+ expect(template).toContain('String((!(_p.on === undefined ? (_p.off === undefined ? false : _p.off) : _p.on)))')
125
125
  })
126
126
 
127
127
  test('a controlled signal seeded by the prop reads the earlier prop live', () => {
@@ -79,7 +79,7 @@ describe('destructured props compile to live reads', () => {
79
79
 
80
80
  // `items`'s destructure default survives as a live fallback, not a
81
81
  // one-time extraction.
82
- expect(content).toContain('(_p.items ?? []).length')
82
+ expect(content).toContain('(_p.items === undefined ? [] : _p.items).length')
83
83
 
84
84
  // No BF043 diagnostic (retired) anywhere in errors/warnings.
85
85
  expect(result.errors.some((e) => e.code === 'BF043')).toBe(false)
@@ -0,0 +1,102 @@
1
+ /**
2
+ * #3861 — a spread of an object other than the component's own props onto
3
+ * a child component (`<Chip {...row} />`, a loop row's `{...r}`). The client
4
+ * merges it with the call's explicit props in source order, in the CSR
5
+ * template (`renderChild`) and in init (`spreadChildProps`), instead of
6
+ * dropping it. A const alias of a closed-type rest (`const a = rest`) is the
7
+ * rest itself, so its spread unrolls per key like `{...rest}` does.
8
+ *
9
+ * The rendered output is pinned by the `object-spread-loop-row-child`,
10
+ * `object-spread-prop-child` and `rest-alias-spread-child` fixtures; the
11
+ * runtime merge by `packages/client/__tests__/runtime/spread-child-props.test.ts`.
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 compile(source: string): { js: string; errors: string[] } {
20
+ const result = compileJSX(source, 'Repro.tsx', { adapter })
21
+ const js = result.files.filter(f => f.path.endsWith('.js')).map(f => f.content).join('\n')
22
+ return { js, errors: result.errors.map(e => `${e.code} ${e.message}`) }
23
+ }
24
+
25
+ const CHIP = `function Chip(props: { id?: string; label?: string; tone?: string; size?: number }) {
26
+ return <span data-id={props.id} data-tone={props.tone} data-size={props.size}>{props.label}</span>
27
+ }`
28
+
29
+ describe('#3861 — an object spread onto a child component', () => {
30
+ test('a loop row spread reaches the CSR template and each row init', () => {
31
+ const { js, errors } = compile(`'use client'
32
+ ${CHIP}
33
+ type Row = { id: string; label: string }
34
+ export function List({ rows }: { rows: Row[] }) {
35
+ return <div>{rows.map(r => <Chip key={r.id} tone="base" {...r} />)}</div>
36
+ }`)
37
+ expect(errors).toEqual([])
38
+ expect(js).toContain(`renderChild('Chip`)
39
+ expect(js).toContain(`{tone: "base", ...r}`)
40
+ expect(js).toContain(`spreadChildProps({ get tone() { return "base" } }, () => (r()))`)
41
+ })
42
+
43
+ test('an object prop spread merges with explicit props in source order', () => {
44
+ const { js, errors } = compile(`'use client'
45
+ ${CHIP}
46
+ export function One({ row }: { row: { id: string; label: string } }) {
47
+ return <div><Chip label="ignored" {...row} id="fixed" /></div>
48
+ }`)
49
+ expect(errors).toEqual([])
50
+ expect(js).toContain(`{label: "ignored", ..._p.row, id: "fixed"}`)
51
+ expect(js).toContain(`spreadChildProps({ label: "ignored" }, () => (_p.row), { id: "fixed" })`)
52
+ })
53
+
54
+ test('an object spread next to a props-object spread merges both as parts', () => {
55
+ const { js, errors } = compile(`'use client'
56
+ ${CHIP}
57
+ export function Both(props: { row: { id: string }; tone?: string }) {
58
+ return <div><Chip label="d" {...props.row} {...props} tone="t" /></div>
59
+ }`)
60
+ expect(errors).toEqual([])
61
+ expect(js).toContain(`spreadChildProps({ label: "d" }, () => (_p.row), () => _p, { tone: "t" })`)
62
+ })
63
+
64
+ test('an object spread an init-only local holds defers the child to init', () => {
65
+ const { js, errors } = compile(`'use client'
66
+ ${CHIP}
67
+ export function Local({ n }: { n: string }) {
68
+ let count = 0
69
+ const extra = { id: n, label: 'L' + (count++) }
70
+ return <div><Chip {...extra} /></div>
71
+ }`)
72
+ expect(errors).toEqual([])
73
+ expect(js).toContain('data-bf-ph="s0"')
74
+ expect(js).toContain(`upsertChild(__scope, 'Chip`)
75
+ expect(js).toContain('spreadChildProps(() => (extra))')
76
+ })
77
+
78
+ test('an object spread before a rest bag merges the bag as a later part', () => {
79
+ const { js, errors } = compile(`'use client'
80
+ ${CHIP}
81
+ export function Mixed({ row, className, ...rest }: { row: { id: string }; className?: string; [key: string]: unknown }) {
82
+ return <div><Chip {...row} {...rest} tone={className} /></div>
83
+ }`)
84
+ expect(errors).toEqual([])
85
+ expect(js).toContain(`spreadChildProps(() => (_p.row), forwardProps(_p, {}, ["row","className"]), { get tone() { return _p.className } })`)
86
+ })
87
+
88
+ test('a const alias of a closed rest unrolls per key and leaves out the destructured keys', () => {
89
+ const { js, errors } = compile(`'use client'
90
+ ${CHIP}
91
+ export function Alias({ label, ...rest }: { label: string; tone?: string; size?: number }) {
92
+ const a = rest
93
+ const b = a
94
+ return <div><Chip {...b} tone="override" label={label} /><Chip {...a} /></div>
95
+ }`)
96
+ expect(errors).toEqual([])
97
+ expect(js).toContain(`{tone: _p.tone, size: _p.size, tone: "override", label: _p.label}`)
98
+ expect(js).toContain(`{tone: _p.tone, size: _p.size}, undefined, 's1'`)
99
+ expect(js).toContain(`{ get tone() { return _p.tone }, get size() { return _p.size } }`)
100
+ expect(js).not.toContain('forwardProps(')
101
+ })
102
+ })
@@ -130,7 +130,7 @@ describe('template text over a body destructure binding in a (props)-arg compone
130
130
  }
131
131
  `, 'C.tsx')
132
132
  }
133
- const read = "(_p.b ?? (['y', ''].filter((x) => x !== '')))"
133
+ const read = "(_p.b === undefined ? (['y', ''].filter((x) => x !== '')) : _p.b)"
134
134
 
135
135
  test('a memo body reads a renamed binding with a callback default as its prop', () => {
136
136
  const ctx = analyze(`
@@ -252,6 +252,6 @@ describe('template text keeps a local named like a typed prop (props)-arg compon
252
252
  const { value = 4 } = props
253
253
  const n = createMemo(() => value * 2)
254
254
  `)
255
- expect(ctx.memos.find(m => m.name === 'n')?.templateBodyExpr).toBe('(_p.value ?? 4) * 2')
255
+ expect(ctx.memos.find(m => m.name === 'n')?.templateBodyExpr).toBe('(_p.value === undefined ? 4 : _p.value) * 2')
256
256
  })
257
257
  })
@@ -62,9 +62,10 @@ describe('rewriteNilReadings', () => {
62
62
  expect(rewrite('props.s + 1')).toBe('((props.s ?? NaN) + 1)')
63
63
  })
64
64
 
65
- test('an either nil keeps the display reading, and a dynamic + is left alone', () => {
65
+ test('an either nil and a dynamic + are left to the helper', () => {
66
66
  expect(rewrite('(props.e * 2)')).toBe('(props.e * 2)')
67
- expect(rewrite("'btn ' + props.c")).toBe("('btn ' + (props.c ?? ''))")
67
+ expect(rewrite("'btn ' + props.c")).toBe("('btn ' + props.c)")
68
+ expect(rewrite('`${props.c}`')).toBe('`${props.c}`')
68
69
  expect(rewrite('(props.n + props.x)')).toBe('(props.n + props.x)')
69
70
  })
70
71
 
@@ -1,13 +1,10 @@
1
1
  import { describe, test, expect } from 'bun:test'
2
- import { arithmeticCoercionOrRefuse, refuseAmbiguousNilArithmetic } from '../adapters/ambiguous-nil-arithmetic'
3
2
  import { analyzeComponent } from '../analyzer'
4
- import { exprToString, parseExpression } from '../expression-parser'
3
+ import { parseExpression } from '../expression-parser'
5
4
  import {
6
- ambiguousNilArithmeticOperands,
7
5
  arithmeticOperandCoercion,
8
6
  arithmeticOperandIsNull,
9
7
  arithmeticOperandIsUndefined,
10
- arithmeticOperandNilIsAmbiguous,
11
8
  attrValueMayBeNullish,
12
9
  collectAbsentPropSeedReads,
13
10
  collectNullableSignalGetters,
@@ -16,7 +13,6 @@ import {
16
13
  nullablePropsYieldedBy,
17
14
  nullableSignalAttrGetter,
18
15
  } from '../nullable-signal-attr'
19
- import { BindingScope } from '../scope/binding-scope'
20
16
  import type { ComponentIR } from '../types'
21
17
 
22
18
  function nullableGetters(decls: string): Set<string> {
@@ -218,9 +214,9 @@ describe('arithmeticOperandCoercion (#3474)', () => {
218
214
  for (const op of ['-', '*', '/', '%', '**']) expect(coercion(ctx, op, 'props.b', 'x')).toBe('undefined')
219
215
  expect(coercion(ctx, '+', 'props.b', '-2')).toBe('undefined')
220
216
  expect(coercion(ctx, '*', 'props.u', '2')).toBe('undefined')
221
- // A type that admits both keeps the null spelling; the arithmetic over it
222
- // is refused (`arithmeticOperandNilIsAmbiguous`, #3700).
223
- expect(coercion(ctx, '*', 'props.both', '2')).toBe('null')
217
+ // A type that admits both is left to the runtime's helper, which reads
218
+ // `null` and `UNDEF` apart (spec/js-undefined-value.md).
219
+ expect(coercion(ctx, '*', 'props.both', '2')).toBeNull()
224
220
  })
225
221
 
226
222
  test('unary minus passes no other operand and coerces like binary minus (#3533)', () => {
@@ -279,7 +275,7 @@ describe('arithmeticOperandCoercion (#3474)', () => {
279
275
  })
280
276
  })
281
277
 
282
- describe('arithmeticOperandNilIsAmbiguous (#3700)', () => {
278
+ describe("an operand whose nil may be either is left to the runtime's helper", () => {
283
279
  function ctxOf(signature: string, decls = ''): ReturnType<typeof collectNullishAttrContext> {
284
280
  const source = `
285
281
  'use client'
@@ -291,106 +287,58 @@ describe('arithmeticOperandNilIsAmbiguous (#3700)', () => {
291
287
  `
292
288
  return collectNullishAttrContext({ metadata: analyzeComponent(source, 'C.tsx') } as unknown as ComponentIR)
293
289
  }
294
- const ambiguous = (ctx: ReturnType<typeof collectNullishAttrContext>, op: string, operand: string, other?: string) =>
295
- arithmeticOperandNilIsAmbiguous(op, parseExpression(operand), other === undefined ? undefined : parseExpression(other), ctx)
290
+ const coercion = (ctx: ReturnType<typeof collectNullishAttrContext>, op: string, operand: string, other?: string) =>
291
+ arithmeticOperandCoercion(op, parseExpression(operand), other === undefined ? undefined : parseExpression(other), ctx)
296
292
 
297
293
  test('a number prop that admits both null and absence, in either props form', () => {
298
294
  for (const signature of ['props: { n?: number | null }', 'props: { n: number | null | undefined }']) {
299
295
  const ctx = ctxOf(signature)
300
- for (const op of ['-', '*', '/', '%', '**']) expect(ambiguous(ctx, op, 'props.n', 'x')).toBe(true)
301
- expect(ambiguous(ctx, '+', 'props.n', '1')).toBe(true)
302
- expect(ambiguous(ctx, '-', 'props.n')).toBe(true)
303
- expect(ambiguous(ctx, '+', 'props.n')).toBe(true)
304
- // `+` against a non-number may concatenate: no `ToNumber`, no ambiguity.
305
- expect(ambiguous(ctx, '+', 'props.n', "'px'")).toBe(false)
296
+ for (const op of ['-', '*', '/', '%', '**']) expect(coercion(ctx, op, 'props.n', 'x')).toBeNull()
297
+ expect(coercion(ctx, '+', 'props.n', '1')).toBeNull()
298
+ expect(coercion(ctx, '-', 'props.n')).toBeNull()
299
+ expect(coercion(ctx, '+', 'props.n')).toBeNull()
306
300
  }
307
301
  const destructured = ctxOf('{ n, m: alias }: { n?: number | null; m?: null | number }')
308
- expect(ambiguous(destructured, '*', 'n', '2')).toBe(true)
309
- expect(ambiguous(destructured, '*', 'alias', '2')).toBe(true)
302
+ expect(coercion(destructured, '*', 'n', '2')).toBeNull()
303
+ expect(coercion(destructured, '*', 'alias', '2')).toBeNull()
310
304
  })
311
305
 
312
- test('a relational operand is a numeric consumer too (#3824 step 3)', () => {
306
+ test('a relational operand: only the one nil reading is spelled (#3824 step 3)', () => {
313
307
  const ctx = ctxOf('props: { n?: number | null; a: number | null; b?: number }')
314
308
  for (const op of ['<', '<=', '>', '>=']) {
315
- expect(ambiguous(ctx, op, 'props.n', '1')).toBe(true)
316
- expect(ambiguous(ctx, op, 'props.n', "'x'")).toBe(true)
317
- expect(ambiguous(ctx, op, 'props.a', '1')).toBe(false)
318
- expect(ambiguous(ctx, op, 'props.b', '1')).toBe(false)
309
+ expect(coercion(ctx, op, 'props.n', '1')).toBeNull()
310
+ expect(coercion(ctx, op, 'props.a', '1')).toBeNull()
311
+ expect(coercion(ctx, op, 'props.b', '1')).toBe('undefined')
319
312
  }
320
- // The spelling keeps the helper's null reading for the refused operand.
321
- expect(arithmeticOperandCoercion('<', parseExpression('props.n'), parseExpression('1'), ctx)).toBeNull()
322
- expect(arithmeticOperandCoercion('<', parseExpression('props.b'), parseExpression('1'), ctx)).toBe('undefined')
323
- expect(arithmeticOperandCoercion('<', parseExpression('props.a'), parseExpression('1'), ctx)).toBeNull()
324
313
  })
325
314
 
326
- test('a string or boolean prop admitting both nils is ambiguous under a comparison only (#3824 step 3)', () => {
315
+ test('a string or boolean prop admitting both nils under a comparison (#3824 step 3)', () => {
327
316
  const ctx = ctxOf('props: { s?: string | null; b?: boolean | null; t?: string; m: string | null }', 'const id = createMemo(() => props.s)')
328
317
  for (const op of ['<', '<=', '>', '>=']) {
329
- expect(ambiguous(ctx, op, 'props.s', '1')).toBe(true)
330
- expect(ambiguous(ctx, op, 'props.s', "'a'")).toBe(true)
331
- expect(ambiguous(ctx, op, 'props.b', '1')).toBe(true)
332
- expect(ambiguous(ctx, op, 'id()', '1')).toBe(true)
333
- expect(ambiguous(ctx, op, 'props.t', '1')).toBe(false)
334
- expect(ambiguous(ctx, op, 'props.m', '1')).toBe(false)
318
+ expect(coercion(ctx, op, 'props.s', '1')).toBeNull()
319
+ expect(coercion(ctx, op, 'props.b', '1')).toBeNull()
320
+ expect(coercion(ctx, op, 'id()', '1')).toBeNull()
321
+ expect(coercion(ctx, op, 'props.t', '1')).toBe('undefined-keep')
322
+ expect(coercion(ctx, op, 'props.m', '1')).toBeNull()
335
323
  }
336
- expect(ambiguous(ctx, '*', 'props.s', '2')).toBe(false)
337
- expect(ambiguous(ctx, '+', 'props.s')).toBe(false)
338
324
  })
339
325
 
340
- test('a prop with one nil reading, a defaulted one and a shadowed one are not ambiguous', () => {
341
- const ctx = ctxOf('props: { a: number | null; b?: number; c: number }')
342
- for (const operand of ['props.a', 'props.b', 'props.c']) expect(ambiguous(ctx, '*', operand, '2')).toBe(false)
343
- expect(ambiguous(ctxOf('{ n = 1 }: { n?: number | null }'), '*', 'n', '2')).toBe(false)
326
+ test('a defaulted one and a shadowed one keep their own coercion', () => {
327
+ expect(coercion(ctxOf('{ n = 1 }: { n?: number | null }'), '*', 'n', '2')).toBeNull()
344
328
  const destructured = ctxOf('{ n }: { n?: number | null }')
345
- expect(arithmeticOperandNilIsAmbiguous('*', parseExpression('n'), parseExpression('2'), destructured, name => name === 'n')).toBe(false)
329
+ expect(arithmeticOperandCoercion('*', parseExpression('n'), parseExpression('2'), destructured, name => name === 'n')).toBeNull()
346
330
  })
347
331
 
348
- test('an identity memo over the prop is ambiguous too; the null spelling is kept for it', () => {
332
+ test('an identity memo over the prop is left to the helper too', () => {
349
333
  const ctx = ctxOf('props: { n?: number | null }', 'const m = createMemo(() => props.n)')
350
- expect(ambiguous(ctx, '*', 'm()', '2')).toBe(true)
351
- expect(arithmeticOperandCoercion('*', parseExpression('m()'), parseExpression('2'), ctx)).toBe('null')
334
+ expect(coercion(ctx, '*', 'm()', '2')).toBeNull()
352
335
  expect(arithmeticOperandIsNull(parseExpression('m()'), ctx)).toBe(true)
353
336
  })
354
337
 
355
338
  test('a destructured union binding keeps its declared type for the classification', () => {
356
339
  const ctx = ctxOf('{ a, u }: { a: number | null; u?: number | undefined }')
357
- expect(arithmeticOperandCoercion('*', parseExpression('a'), parseExpression('2'), ctx)).toBe('null')
358
- expect(arithmeticOperandCoercion('*', parseExpression('u'), parseExpression('2'), ctx)).toBe('undefined')
359
- })
360
- })
361
-
362
- describe('ambiguousNilArithmeticOperands (#3700)', () => {
363
- const ctx = collectNullishAttrContext({
364
- metadata: analyzeComponent(
365
- `export function C({ n, items }: { n?: number | null; items: number[] }) { return <p>x</p> }`,
366
- 'C.tsx',
367
- ),
368
- } as unknown as ComponentIR)
369
- const found = (source: string, scope?: BindingScope) =>
370
- ambiguousNilArithmeticOperands(parseExpression(source), ctx, scope).map(exprToString)
371
-
372
- test('finds the operands in nested positions', () => {
373
- expect(found("items.filter(i => i > n * 2).length")).toEqual(['n'])
374
- expect(found("(-n > 1 ? `a${n + 1}` : 'b')")).toEqual(['n', 'n'])
375
- })
376
-
377
- test('finds a unary plus operand (#3824 step 3)', () => {
378
- expect(found('+n')).toEqual(['n'])
379
- expect(found('+n > 1 ? 1 : 0')).toEqual(['n'])
380
- })
381
-
382
- test('finds a relational operand, in a predicate and at the top level', () => {
383
- expect(found('items.filter(i => i < n).length')).toEqual(['n'])
384
- expect(found('n >= 1')).toEqual(['n'])
385
- expect(found('items.filter(n => n < 1).length')).toEqual([])
386
- })
387
-
388
- test('an arrow param or an enclosing binding of the same name shadows the prop', () => {
389
- expect(found("items.filter(n => n * 2 > 1).length")).toEqual([])
390
- expect(found("items.map(i => items.filter(n => n > i).length * n)")).toEqual(['n'])
391
- expect(found('n * 2', BindingScope.EMPTY.enterCallback(['n']))).toEqual([])
392
- // A sibling arrow's param does not leak out of its own body.
393
- expect(found('items.filter(n => n > 1).length * n')).toEqual(['n'])
340
+ expect(coercion(ctx, '*', 'a', '2')).toBe('null')
341
+ expect(coercion(ctx, '*', 'u', '2')).toBe('undefined')
394
342
  })
395
343
  })
396
344
 
@@ -439,24 +387,3 @@ describe('a prop that can be absent, and an operand that is never nullish', () =
439
387
  expect(isNeverNullishOperand(parseExpression('opt')!, destructured, () => false)).toBe(false)
440
388
  })
441
389
  })
442
-
443
- describe('the BF101 of an ambiguous nil names the prop family (#3824 step 3)', () => {
444
- const ctx = collectNullishAttrContext({
445
- metadata: analyzeComponent(
446
- `export function C(props: { n?: number | null; s?: string | null; b?: boolean | null }) { return <p>x</p> }`,
447
- 'C.tsx',
448
- ),
449
- } as unknown as ComponentIR)
450
-
451
- test('a numeric operand keeps the arithmetic message; a string or boolean one names its type', () => {
452
- const sink = { errors: [] as import('../types').CompilerError[], componentName: 'C' }
453
- arithmeticCoercionOrRefuse('*', parseExpression('props.n'), parseExpression('2'), ctx, () => false, sink)
454
- arithmeticCoercionOrRefuse('<', parseExpression('props.s'), parseExpression('1'), ctx, () => false, sink)
455
- refuseAmbiguousNilArithmetic(parseExpression('props.b >= 1'), ctx, BindingScope.EMPTY, sink)
456
- expect(sink.errors.map(e => e.code)).toEqual(['BF101', 'BF101', 'BF101'])
457
- expect(sink.errors[0]!.message).toStartWith('Arithmetic over `props.n` reads a number prop declared both optional and nullable (`?: number | null`).')
458
- expect(sink.errors[1]!.message).toStartWith('A comparison over `props.s` reads a string prop declared both optional and nullable (`?: string | null`).')
459
- expect(sink.errors[2]!.message).toStartWith('A comparison over `props.b` reads a boolean prop')
460
- expect(sink.errors[1]!.suggestion?.message).toContain('`?: string`')
461
- })
462
- })
@@ -18,6 +18,11 @@ import {
18
18
  foldNegatedNumberLiteral,
19
19
  mayHoldObject,
20
20
  numberLiteralSpelling,
21
+ collectNullableOptionalProps,
22
+ nilTestOperand,
23
+ exprToString,
24
+ refuseUnspelledNilTest,
25
+ strictEqSpelling,
21
26
  type IRMetadata,
22
27
  type NativeSafeTable,
23
28
  type OperandFacts,
@@ -161,7 +166,12 @@ describe('operandFacts', () => {
161
166
  })
162
167
 
163
168
  const NONE: NativeSafeTable = {}
164
- const ALL: NativeSafeTable = {
169
+ /**
170
+ * A table that claims `unproven` too, which the type forbids: the plan must
171
+ * still take the helper for an operand Phase 1 does not prove, since it may
172
+ * be `UNDEF` (spec/js-undefined-value.md).
173
+ */
174
+ const CLAIMS_UNPROVEN = {
165
175
  'to-boolean': ['boolean', 'unproven'],
166
176
  'to-number': ['number-pair', 'number', 'unproven'],
167
177
  plus: ['number-pair', 'string', 'unproven'],
@@ -171,7 +181,7 @@ const ALL: NativeSafeTable = {
171
181
  'number-literal': ['safe-integer', 'unproven'],
172
182
  nullish: ['non-nil', 'unproven'],
173
183
  get: ['array-index', 'unproven'],
174
- }
184
+ } as unknown as NativeSafeTable
175
185
  const PROVEN_ONLY: NativeSafeTable = {
176
186
  'to-boolean': ['boolean'],
177
187
  'to-number': ['number-pair', 'number'],
@@ -198,7 +208,6 @@ describe('planPrimitive', () => {
198
208
  test('ToBoolean (a test position) is native only for a proven boolean the target claims', () => {
199
209
  expect(plan('!props.on', PROVEN_ONLY)).toBe('native to-boolean boolean')
200
210
  expect(plan('!props.s', PROVEN_ONLY)).toBe('helper to-boolean truthy unproven')
201
- expect(plan('!props.s', ALL)).toBe('native to-boolean unproven')
202
211
  expect(plan('props.on ? 1 : 2', NONE)).toBe('helper to-boolean truthy boolean')
203
212
  expect(plan('props.s && 1', PROVEN_ONLY)).toBe('helper to-boolean truthy unproven')
204
213
  })
@@ -213,8 +222,8 @@ describe('planPrimitive', () => {
213
222
  })
214
223
 
215
224
  test('`/` and `%` always name their helper', () => {
216
- expect(plan('props.n / 2', ALL)).toBe('helper to-number div number-pair')
217
- expect(plan('props.n % 2', ALL)).toBe('helper to-number mod number-pair')
225
+ expect(plan('props.n / 2', CLAIMS_UNPROVEN)).toBe('helper to-number div number-pair')
226
+ expect(plan('props.n % 2', CLAIMS_UNPROVEN)).toBe('helper to-number mod number-pair')
218
227
  })
219
228
 
220
229
  test('`+` adds two numbers, concatenates over a proven string, and is `plus` otherwise', () => {
@@ -228,16 +237,14 @@ describe('planPrimitive', () => {
228
237
  expect(plan("props.s === 'a'", PROVEN_ONLY)).toBe('native strict-eq string-pair')
229
238
  expect(plan('props.n === count()', PROVEN_ONLY)).toBe('native strict-eq number-pair')
230
239
  expect(plan('props.maybe === 1', PROVEN_ONLY)).toBe('helper strict-eq strict_eq unproven')
231
- expect(plan("props.n === 'a'", ALL)).toBe('const strict-eq false')
232
- expect(plan("props.n !== 'a'", ALL)).toBe('const strict-eq true')
240
+ expect(plan("props.n === 'a'", CLAIMS_UNPROVEN)).toBe('const strict-eq false')
241
+ expect(plan("props.n !== 'a'", CLAIMS_UNPROVEN)).toBe('const strict-eq true')
233
242
  })
234
243
 
235
244
  test('unary minus over a non-zero number literal folds into the literal; any other operand takes `neg`', () => {
236
245
  expect(plan('-1', PROVEN_ONLY)).toBe('native number-literal safe-integer')
237
246
  expect(plan('-1.5', PROVEN_ONLY)).toBe('helper number-literal number unproven')
238
- expect(plan('-1e21', ALL)).toBe('native number-literal unproven')
239
247
  // `-0` does not fold: the zero operand is the case `neg` exists for.
240
- expect(plan('-0', ALL)).toBe('native neg unproven')
241
248
  expect(plan('-0', PROVEN_ONLY)).toBe('helper neg neg unproven')
242
249
  expect(plan('-props.n', PROVEN_ONLY)).toBe('helper neg neg unproven')
243
250
  expect(plan('+props.n', PROVEN_ONLY)).toBe('native to-number number')
@@ -289,9 +296,9 @@ describe('planPrimitive', () => {
289
296
  })
290
297
 
291
298
  test('loose equality and other operators are not planned', () => {
292
- expect(plan('props.n == 1', ALL)).toBe('none')
293
- expect(plan("'a' in props", ALL)).toBe('none')
294
- expect(plan('typeof props.n', ALL)).toBe('none')
299
+ expect(plan('props.n == 1', CLAIMS_UNPROVEN)).toBe('none')
300
+ expect(plan("'a' in props", CLAIMS_UNPROVEN)).toBe('none')
301
+ expect(plan('typeof props.n', CLAIMS_UNPROVEN)).toBe('none')
295
302
  })
296
303
 
297
304
  test('the empty typing proves only structure', () => {
@@ -301,6 +308,77 @@ describe('planPrimitive', () => {
301
308
  })
302
309
  })
303
310
 
311
+ describe('every target carries undefined (spec/js-undefined-value.md)', () => {
312
+ test('an operand Phase 1 does not prove takes the helper, even under a claim of `unproven`', () => {
313
+ for (const target of [PROVEN_ONLY, CLAIMS_UNPROVEN]) {
314
+ expect(plan('!props.s', target)).toBe('helper to-boolean truthy unproven')
315
+ expect(plan('props.n - props.maybe', target)).toBe('helper to-number sub unproven')
316
+ expect(plan('props.n <= props.maybe', target)).toBe('helper relational le unproven')
317
+ expect(plan('props.maybe ?? 0', target)).toBe('helper nullish coalesce unproven')
318
+ expect(plan('-props.n', target)).toBe('helper neg neg unproven')
319
+ expect(plan('-1e21', target)).toBe('helper number-literal number unproven')
320
+ expect(plan('props.rows[props.n]', target)).toBe('helper get get unproven')
321
+ // A dynamic `+` (neither side a proven number pair or a proven string).
322
+ expect(plan('props.maybe + props.n', target)).toBe('helper plus plus unproven')
323
+ }
324
+ })
325
+
326
+ test('a numeric either operand is planned as the helper, not refused', () => {
327
+ expect(plan('props.either * 2', PROVEN_ONLY)).toBe('helper to-number mul unproven')
328
+ })
329
+
330
+ test('`=== null` / `=== undefined` are strict and `== null` is nullish', () => {
331
+ const target = PROVEN_ONLY
332
+ expect(plan('props.maybe === null', target)).toBe('helper nil-test is_null unproven')
333
+ expect(plan('props.maybe !== null', target)).toBe('helper nil-test is_null unproven')
334
+ expect(plan('props.maybe === undefined', target)).toBe('helper nil-test is_undefined unproven')
335
+ expect(plan('undefined !== props.maybe', target)).toBe('helper nil-test is_undefined unproven')
336
+ expect(plan('null === props.maybe', target)).toBe('helper nil-test is_null unproven')
337
+ expect(plan('props.maybe == null', target)).toBe('helper nil-test is_nullish unproven')
338
+ expect(plan('props.maybe != undefined', target)).toBe('helper nil-test is_nullish unproven')
339
+ // Both sides nil literals: the right one names the test.
340
+ expect(plan('null === undefined', target)).toBe('helper nil-test is_undefined unproven')
341
+ // A bound `undefined` is a name, not the nil literal.
342
+ const shadowed = collectOperandTyping(COMPONENT).at(BindingScope.forComponent('props').enterCallback(['undefined']))
343
+ expect(plan('props.n === undefined', target, shadowed)).toBe('helper strict-eq strict_eq unproven')
344
+ // Loose equality against anything but a nil literal stays unplanned.
345
+ expect(plan('props.n == 1', target)).toBe('none')
346
+ })
347
+
348
+ test('an emitter that receives a nil test without a spelling refuses loudly', () => {
349
+ const p = planPrimitive(parseExpression('props.maybe === null'), typing, PROVEN_ONLY)
350
+ expect(() => refuseUnspelledNilTest(p)).toThrow('`is_null` nil test')
351
+ expect(() => strictEqSpelling('===', parseExpression('props.maybe'), parseExpression('null'), p)).toThrow('no spelling')
352
+ expect(() => refuseUnspelledNilTest(planPrimitive(parseExpression('props.n === 1'), typing, PROVEN_ONLY))).not.toThrow()
353
+ expect(strictEqSpelling('===', parseExpression('props.maybe'), parseExpression('null'), null)).toEqual({ kind: 'nullish' })
354
+ })
355
+
356
+ test('the operand of a nil test is the side that is not the nil literal', () => {
357
+ const operand = (src: string) => {
358
+ const e = parseExpression(src)
359
+ if (e.kind !== 'binary') throw new Error(src)
360
+ return exprToString(nilTestOperand(e.left, e.right, typing))
361
+ }
362
+ expect(operand('props.maybe === null')).toBe('props.maybe')
363
+ expect(operand('undefined !== props.maybe')).toBe('props.maybe')
364
+ expect(operand('null === undefined')).toBe('null')
365
+ })
366
+
367
+ test('a defaulted prop typed with `null` is presence-uncertain: the default does not apply to `null`', () => {
368
+ const ir = {
369
+ metadata: meta({
370
+ propsParams: [
371
+ param('v', union(prim('string'), prim('null')), true, "'D'"),
372
+ param('w', prim('string'), true, "'D'"),
373
+ param('x', prim('string'), true),
374
+ ],
375
+ }),
376
+ } as unknown as Parameters<typeof collectNullableOptionalProps>[0]
377
+ const withMeta = { ...ir, metadata: { ...ir.metadata, restPropsExpandedKeys: [] } } as typeof ir
378
+ expect([...collectNullableOptionalProps(withMeta)].sort()).toEqual(['v', 'x'])
379
+ })
380
+ })
381
+
304
382
  /** The typing of the one component in `src`, at component scope, from the analyzer's metadata. */
305
383
  function analyzed(src: string): ScopedOperandTyping {
306
384
  const metadata = buildMetadata(analyzeComponent(src, 'foo.tsx'))