@barefootjs/jsx 0.40.1 → 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 (211) hide show
  1. package/dist/adapters/boolean-result.d.ts +32 -10
  2. package/dist/adapters/boolean-result.d.ts.map +1 -1
  3. package/dist/adapters/brace-delimiter-text.d.ts +18 -0
  4. package/dist/adapters/brace-delimiter-text.d.ts.map +1 -0
  5. package/dist/adapters/callback-method.d.ts +45 -5
  6. package/dist/adapters/callback-method.d.ts.map +1 -1
  7. package/dist/adapters/component-props.d.ts +3 -4
  8. package/dist/adapters/component-props.d.ts.map +1 -1
  9. package/dist/adapters/computed-const.d.ts +11 -1
  10. package/dist/adapters/computed-const.d.ts.map +1 -1
  11. package/dist/adapters/dsl-template-adapter.d.ts +24 -12
  12. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
  13. package/dist/adapters/loop-bound-names.d.ts +9 -1
  14. package/dist/adapters/loop-bound-names.d.ts.map +1 -1
  15. package/dist/adapters/loop-row-type.d.ts +59 -0
  16. package/dist/adapters/loop-row-type.d.ts.map +1 -0
  17. package/dist/adapters/nil-reading.d.ts +63 -0
  18. package/dist/adapters/nil-reading.d.ts.map +1 -0
  19. package/dist/adapters/non-primitive-equality.d.ts +33 -0
  20. package/dist/adapters/non-primitive-equality.d.ts.map +1 -0
  21. package/dist/adapters/number-value.d.ts +5 -3
  22. package/dist/adapters/number-value.d.ts.map +1 -1
  23. package/dist/adapters/operand-typing.d.ts +126 -0
  24. package/dist/adapters/operand-typing.d.ts.map +1 -0
  25. package/dist/adapters/parsed-expr-emitter.d.ts +80 -12
  26. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  27. package/dist/adapters/primitive-plan.d.ts +320 -0
  28. package/dist/adapters/primitive-plan.d.ts.map +1 -0
  29. package/dist/adapters/prop-classes.d.ts +5 -0
  30. package/dist/adapters/prop-classes.d.ts.map +1 -1
  31. package/dist/analyzer-context.d.ts +4 -0
  32. package/dist/analyzer-context.d.ts.map +1 -1
  33. package/dist/analyzer.d.ts.map +1 -1
  34. package/dist/augment-inherited-props.d.ts +63 -8
  35. package/dist/augment-inherited-props.d.ts.map +1 -1
  36. package/dist/compiler.d.ts.map +1 -1
  37. package/dist/event-handler-name.d.ts +12 -0
  38. package/dist/event-handler-name.d.ts.map +1 -1
  39. package/dist/expression-parser.d.ts +8 -0
  40. package/dist/expression-parser.d.ts.map +1 -1
  41. package/dist/index.d.ts +20 -11
  42. package/dist/index.d.ts.map +1 -1
  43. package/dist/index.js +4903 -2311
  44. package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/child-props-object.d.ts +106 -0
  46. package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -0
  47. package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +4 -2
  52. package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/imports.d.ts +2 -2
  55. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/index.d.ts +2 -6
  57. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -3
  59. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  60. package/dist/ir-to-client-js/plan/build-static-array-child-init.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +30 -18
  62. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  64. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +3 -1
  65. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  66. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +3 -2
  67. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  68. package/dist/jsx-to-ir.d.ts +1 -0
  69. package/dist/jsx-to-ir.d.ts.map +1 -1
  70. package/dist/nullable-signal-attr.d.ts +51 -34
  71. package/dist/nullable-signal-attr.d.ts.map +1 -1
  72. package/dist/prop-rewrite.d.ts +7 -0
  73. package/dist/prop-rewrite.d.ts.map +1 -1
  74. package/dist/props-binding.d.ts +58 -13
  75. package/dist/props-binding.d.ts.map +1 -1
  76. package/dist/props-object-whole-read.d.ts +15 -0
  77. package/dist/props-object-whole-read.d.ts.map +1 -0
  78. package/dist/rich-type-refusal.d.ts.map +1 -1
  79. package/dist/scope/binding-scope.d.ts +85 -10
  80. package/dist/scope/binding-scope.d.ts.map +1 -1
  81. package/dist/scope/lexical-scope-walk.d.ts +3 -2
  82. package/dist/scope/lexical-scope-walk.d.ts.map +1 -1
  83. package/dist/scope/root-prop-alias.d.ts +10 -7
  84. package/dist/scope/root-prop-alias.d.ts.map +1 -1
  85. package/dist/ssr-defaults.d.ts +39 -3
  86. package/dist/ssr-defaults.d.ts.map +1 -1
  87. package/dist/strip-types.d.ts +13 -0
  88. package/dist/strip-types.d.ts.map +1 -1
  89. package/dist/template-position-walk.d.ts +21 -3
  90. package/dist/template-position-walk.d.ts.map +1 -1
  91. package/dist/types.d.ts +90 -0
  92. package/dist/types.d.ts.map +1 -1
  93. package/package.json +2 -2
  94. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +9 -9
  95. package/src/__tests__/binding-scope.test.ts +89 -1
  96. package/src/__tests__/body-destructure-props-object-alias.test.ts +123 -0
  97. package/src/__tests__/body-destructured-prop-default-arrow.test.ts +2 -2
  98. package/src/__tests__/body-destructured-props-live.test.ts +5 -5
  99. package/src/__tests__/boolean-result.test.ts +22 -5
  100. package/src/__tests__/brace-delimiter-text.test.ts +26 -0
  101. package/src/__tests__/callback-method.test.ts +62 -2
  102. package/src/__tests__/child-components-in-map.test.ts +1 -1
  103. package/src/__tests__/client-js-generation.test.ts +3 -3
  104. package/src/__tests__/computed-const.test.ts +103 -0
  105. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +7 -7
  106. package/src/__tests__/destructured-props-live.test.ts +1 -1
  107. package/src/__tests__/emit-to-string-call.test.ts +2 -1
  108. package/src/__tests__/hydration-payload-analysis.test.ts +166 -0
  109. package/src/__tests__/issue-2724-prop-alias-loop-not-static.test.ts +7 -7
  110. package/src/__tests__/issue-2754-rest-spread-needs-slot.test.ts +5 -2
  111. package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +1 -1
  112. package/src/__tests__/issue-2835-props-type-member-name-collision.test.ts +4 -4
  113. package/src/__tests__/issue-3044-nested-prop-object-array-not-static.test.ts +1 -1
  114. package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +2 -1
  115. package/src/__tests__/issue-3713-props-spread-loop-row.test.ts +65 -0
  116. package/src/__tests__/issue-3861-object-spread-child.test.ts +102 -0
  117. package/src/__tests__/lookup-literal-const.test.ts +9 -3
  118. package/src/__tests__/loop-index-reactivity.test.ts +2 -2
  119. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +1 -1
  120. package/src/__tests__/loop-plan.test.ts +1 -1
  121. package/src/__tests__/loop-row-const-initializer-shadow.test.ts +146 -0
  122. package/src/__tests__/loop-row-type.test.ts +64 -0
  123. package/src/__tests__/lowering-value-position.test.ts +4 -0
  124. package/src/__tests__/memo-body-expr.test.ts +2 -2
  125. package/src/__tests__/module-const-destructure-default.test.ts +156 -0
  126. package/src/__tests__/nested-loop-index-param.test.ts +1 -1
  127. package/src/__tests__/nested-loop-reactive-attrs.test.ts +2 -2
  128. package/src/__tests__/nested-row-shadowing.test.ts +2 -2
  129. package/src/__tests__/nil-reading.test.ts +78 -0
  130. package/src/__tests__/nullable-signal-attr.test.ts +109 -48
  131. package/src/__tests__/primitive-plan.test.ts +494 -0
  132. package/src/__tests__/profile-loop-binding-ids.test.ts +2 -2
  133. package/src/__tests__/profile-nested-binding-ids.test.ts +2 -2
  134. package/src/__tests__/prop-default-undefined-only.test.ts +115 -0
  135. package/src/__tests__/prop-references.test.ts +2 -2
  136. package/src/__tests__/props-destructuring.test.ts +17 -0
  137. package/src/__tests__/props-object-whole-read.test.ts +40 -0
  138. package/src/__tests__/prune-unused-prop-extractions.test.ts +3 -3
  139. package/src/__tests__/reactive-attrs-in-map.test.ts +1 -1
  140. package/src/__tests__/reactive-factory-inlining.test.ts +4 -1
  141. package/src/__tests__/renamed-body-destructure-template.test.ts +7 -7
  142. package/src/__tests__/rest-binding-gaps.test.ts +192 -0
  143. package/src/__tests__/rewrite-destructured-props.test.ts +1 -1
  144. package/src/__tests__/root-prop-alias.test.ts +53 -8
  145. package/src/__tests__/ssr-defaults.test.ts +113 -25
  146. package/src/__tests__/static-loop-csr-materialize.test.ts +2 -2
  147. package/src/__tests__/static-record-literal-array.test.ts +171 -0
  148. package/src/__tests__/string-concat-identifier.test.ts +40 -1
  149. package/src/__tests__/written-binding-substitution.test.ts +8 -8
  150. package/src/adapters/boolean-result.ts +72 -66
  151. package/src/adapters/brace-delimiter-text.ts +25 -0
  152. package/src/adapters/callback-method.ts +159 -27
  153. package/src/adapters/component-props.ts +3 -4
  154. package/src/adapters/computed-const.ts +238 -4
  155. package/src/adapters/dsl-template-adapter.ts +62 -26
  156. package/src/adapters/loop-bound-names.ts +9 -1
  157. package/src/adapters/loop-plan.ts +1 -1
  158. package/src/adapters/loop-row-type.ts +149 -0
  159. package/src/adapters/nil-reading.ts +295 -0
  160. package/src/adapters/non-primitive-equality.ts +92 -0
  161. package/src/adapters/number-value.ts +17 -4
  162. package/src/adapters/operand-typing.ts +522 -0
  163. package/src/adapters/parsed-expr-emitter.ts +183 -19
  164. package/src/adapters/primitive-plan.ts +765 -0
  165. package/src/adapters/prop-classes.ts +16 -3
  166. package/src/analyzer-context.ts +6 -0
  167. package/src/analyzer.ts +532 -26
  168. package/src/augment-inherited-props.ts +108 -10
  169. package/src/compiler.ts +17 -0
  170. package/src/event-handler-name.ts +15 -0
  171. package/src/expression-parser.ts +70 -1
  172. package/src/index.ts +35 -16
  173. package/src/ir-to-client-js/build-references.ts +69 -0
  174. package/src/ir-to-client-js/child-props-object.ts +240 -0
  175. package/src/ir-to-client-js/collect-elements.ts +31 -63
  176. package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +8 -1
  177. package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +31 -28
  178. package/src/ir-to-client-js/control-flow/shared.ts +20 -22
  179. package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +5 -3
  180. package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +2 -2
  181. package/src/ir-to-client-js/control-flow/stringify/lazy-row.ts +1 -1
  182. package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +2 -2
  183. package/src/ir-to-client-js/control-flow/stringify/loop.ts +1 -1
  184. package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +3 -3
  185. package/src/ir-to-client-js/html-template.ts +43 -17
  186. package/src/ir-to-client-js/imports.ts +2 -2
  187. package/src/ir-to-client-js/index.ts +53 -11
  188. package/src/ir-to-client-js/phases/props-extraction.ts +11 -7
  189. package/src/ir-to-client-js/plan/build-declaration-emit.ts +40 -7
  190. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +31 -14
  191. package/src/ir-to-client-js/plan/static-array-child-init.ts +27 -18
  192. package/src/ir-to-client-js/prop-handling.ts +22 -3
  193. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +58 -5
  194. package/src/ir-to-client-js/rewrite-destructured-props.ts +31 -1
  195. package/src/ir-to-client-js/stringify/static-array-child-init.ts +26 -10
  196. package/src/jsx-to-ir.ts +459 -37
  197. package/src/nullable-signal-attr.ts +200 -110
  198. package/src/prop-rewrite.ts +30 -6
  199. package/src/props-binding.ts +84 -19
  200. package/src/props-object-whole-read.ts +87 -0
  201. package/src/rich-type-refusal.ts +2 -1
  202. package/src/scope/binding-scope.ts +182 -18
  203. package/src/scope/lexical-scope-walk.ts +4 -3
  204. package/src/scope/root-prop-alias.ts +15 -8
  205. package/src/ssr-defaults.ts +100 -11
  206. package/src/strip-types.ts +31 -3
  207. package/src/template-position-walk.ts +57 -28
  208. package/src/types.ts +87 -0
  209. package/dist/adapters/ambiguous-nil-arithmetic.d.ts +0 -41
  210. package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +0 -1
  211. package/src/adapters/ambiguous-nil-arithmetic.ts +0 -94
@@ -0,0 +1,494 @@
1
+ /**
2
+ * The JS primitive plan's classifier and decision (#3824,
3
+ * `spec/js-primitive-semantics.md` "Decision point"): `collectOperandTyping`
4
+ * and its scoped view, `operandFacts`, and `planPrimitive` over a
5
+ * `NativeSafeTable`.
6
+ */
7
+
8
+ import { describe, test, expect } from 'bun:test'
9
+ import {
10
+ analyzeComponent,
11
+ BindingScope,
12
+ buildMetadata,
13
+ collectOperandTyping,
14
+ EMPTY_OPERAND_TYPING,
15
+ operandFacts,
16
+ parseExpression,
17
+ planPrimitive,
18
+ foldNegatedNumberLiteral,
19
+ mayHoldObject,
20
+ numberLiteralSpelling,
21
+ collectNullableOptionalProps,
22
+ nilTestOperand,
23
+ exprToString,
24
+ refuseUnspelledNilTest,
25
+ strictEqSpelling,
26
+ type IRMetadata,
27
+ type NativeSafeTable,
28
+ type OperandFacts,
29
+ type ScopedOperandTyping,
30
+ type TypeInfo,
31
+ } from '../index'
32
+
33
+ const prim = (primitive: 'string' | 'number' | 'boolean' | 'null' | 'undefined'): TypeInfo => ({ kind: 'primitive', raw: primitive, primitive })
34
+ const union = (...unionTypes: TypeInfo[]): TypeInfo => ({ kind: 'union', raw: unionTypes.map(t => t.raw).join(' | '), unionTypes })
35
+ const array = (elementType: TypeInfo): TypeInfo => ({ kind: 'array', raw: `${elementType.raw}[]`, elementType })
36
+
37
+ type Meta = Pick<IRMetadata, 'signals' | 'memos' | 'propsParams' | 'localConstants' | 'propsObjectName' | 'typeDefinitions'>
38
+
39
+ function meta(partial: Partial<Meta>): Meta {
40
+ return { signals: [], memos: [], propsParams: [], localConstants: [], propsObjectName: null, typeDefinitions: [], ...partial }
41
+ }
42
+
43
+ function param(name: string, type: TypeInfo, optional = false, defaultValue?: string): Meta['propsParams'][number] {
44
+ return { name, type, optional, ...(defaultValue !== undefined ? { defaultValue } : {}) } as Meta['propsParams'][number]
45
+ }
46
+
47
+ function signal(getter: string, type: TypeInfo, initialValue: string): Meta['signals'][number] {
48
+ return { getter, setter: null, type, initialValue, parsed: parseExpression(initialValue) } as unknown as Meta['signals'][number]
49
+ }
50
+
51
+ const COMPONENT = meta({
52
+ propsObjectName: 'props',
53
+ propsParams: [
54
+ param('n', prim('number')),
55
+ param('s', prim('string')),
56
+ param('on', prim('boolean')),
57
+ param('maybe', prim('number'), true),
58
+ param('nothing', union(prim('number'), prim('null'))),
59
+ param('either', union(prim('number'), prim('null')), true),
60
+ param('size', prim('string'), true, "'md'"),
61
+ param('rows', array(prim('number'))),
62
+ ],
63
+ signals: [signal('count', prim('number'), '0'), signal('und', prim('number'), ''), signal('label', { kind: 'unknown', raw: 'unknown' }, "'x'")],
64
+ })
65
+
66
+ const typing = collectOperandTyping(COMPONENT).at(BindingScope.forComponent('props'))
67
+
68
+ /** `facts.types` as a sorted list, with the nil reading when there is one. */
69
+ function show(facts: OperandFacts): string {
70
+ const types = [...facts.types].sort().join('|')
71
+ return facts.nil ? `${types} (${facts.nil})` : types
72
+ }
73
+
74
+ const factsOf = (src: string, at: ScopedOperandTyping = typing) => show(operandFacts(parseExpression(src), at))
75
+
76
+ describe('collectOperandTyping', () => {
77
+ test('a required prop is its declared type; an optional one without a default may be undefined', () => {
78
+ expect(factsOf('props.n')).toBe('number')
79
+ expect(factsOf('props.s')).toBe('string')
80
+ expect(factsOf('props.on')).toBe('boolean')
81
+ expect(factsOf('props.maybe')).toBe('nil|number (undefined)')
82
+ expect(factsOf('props.nothing')).toBe('nil|number (null)')
83
+ expect(factsOf('props.either')).toBe('nil|number (either)')
84
+ // With a props object, a default comes from a body destructure and
85
+ // types that local binding, not `props.size`.
86
+ expect(factsOf('props.size')).toBe('nil|string (undefined)')
87
+ })
88
+
89
+ test('a signal is its declared type or literal seed, nil when it has none', () => {
90
+ expect(factsOf('count()')).toBe('number')
91
+ expect(factsOf('und()')).toBe('nil|number (undefined)')
92
+ expect(factsOf('label()')).toBe('string')
93
+ })
94
+
95
+ test('destructured props are bare names; a props object reads them only as members', () => {
96
+ const destructured = collectOperandTyping(meta({ propsParams: [param('n', prim('number'))] })).at(BindingScope.EMPTY)
97
+ expect(factsOf('n', destructured)).toBe('number')
98
+ expect(factsOf('n')).toBe('unknown')
99
+ })
100
+
101
+ test('a loop binding shadows an outer name; a loop index is a non-negative integer', () => {
102
+ const row = BindingScope.forComponent('props').enterLoopRow({ param: 'count', index: 'i' })
103
+ const at = collectOperandTyping(COMPONENT).at(row)
104
+ expect(factsOf('count', at)).toBe('unknown')
105
+ const index = operandFacts(parseExpression('i'), at)
106
+ expect(show(index)).toBe('number')
107
+ expect(index.index).toBe(true)
108
+ })
109
+
110
+ test('a row read takes its type from the loop row type', () => {
111
+ const rowType: TypeInfo = {
112
+ kind: 'object',
113
+ raw: '{ id: string; n?: number }',
114
+ properties: [
115
+ { name: 'id', type: prim('string'), optional: false, readonly: false },
116
+ { name: 'n', type: prim('number'), optional: true, readonly: false },
117
+ ],
118
+ }
119
+ const row = BindingScope.forComponent('props').enterLoopRow({ param: 'r', itemType: rowType })
120
+ const at = collectOperandTyping(COMPONENT).at(row)
121
+ expect(factsOf('r.id', at)).toBe('string')
122
+ expect(factsOf('r.n', at)).toBe('nil|number (undefined)')
123
+ expect(factsOf('r', at)).toBe('object')
124
+ })
125
+
126
+ test('a binding named `props` reads its own member, not the prop', () => {
127
+ const shadow = BindingScope.forComponent('props').enterCallback(['props'])
128
+ expect(factsOf('props.n', collectOperandTyping(COMPONENT).at(shadow))).toBe('unknown')
129
+ })
130
+ })
131
+
132
+ describe('operandFacts', () => {
133
+ test('literals and structural results', () => {
134
+ expect(factsOf("'a'")).toBe('string')
135
+ expect(factsOf('1')).toBe('number')
136
+ expect(factsOf('true')).toBe('boolean')
137
+ expect(factsOf('null')).toBe('nil (null)')
138
+ expect(factsOf('undefined')).toBe('nil (undefined)')
139
+ expect(factsOf('`a${props.n}`')).toBe('string')
140
+ expect(factsOf('props.n < 1')).toBe('boolean')
141
+ expect(factsOf('!props.n')).toBe('boolean')
142
+ expect(factsOf('-props.s')).toBe('number')
143
+ expect(factsOf('props.n % 2')).toBe('number')
144
+ expect(factsOf('[1, 2]')).toBe('object')
145
+ })
146
+
147
+ test('`+` is a string when either side is one, a number when neither can be', () => {
148
+ expect(factsOf("props.n + 'x'")).toBe('string')
149
+ expect(factsOf('props.n + count()')).toBe('number')
150
+ expect(factsOf('props.n + props.maybe')).toBe('number')
151
+ expect(factsOf('props.n + label2()')).toBe('unknown')
152
+ })
153
+
154
+ test('`&&` / `||` / `?:` are the union of their values; `??` drops the nil of its left side', () => {
155
+ expect(factsOf('props.on && props.n > 1')).toBe('boolean')
156
+ expect(factsOf("props.on ? 'a' : 1")).toBe('number|string')
157
+ expect(factsOf("props.on ? 'a' : null")).toBe('nil|string (null)')
158
+ expect(factsOf('props.maybe ?? 0')).toBe('number')
159
+ expect(factsOf('props.on || x()')).toBe('unknown')
160
+ })
161
+
162
+ test('a method result and an index read are not typed in step 0', () => {
163
+ expect(factsOf('props.rows.includes(1)')).toBe('unknown')
164
+ expect(factsOf('props.rows[0]')).toBe('unknown')
165
+ })
166
+ })
167
+
168
+ const NONE: 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 = {
175
+ 'to-boolean': ['boolean', 'unproven'],
176
+ 'to-number': ['number-pair', 'number', 'unproven'],
177
+ plus: ['number-pair', 'string', 'unproven'],
178
+ 'strict-eq': ['number-pair', 'string-pair', 'boolean-pair', 'unproven'],
179
+ relational: ['number-pair', 'unproven'],
180
+ neg: ['number', 'unproven'],
181
+ 'number-literal': ['safe-integer', 'unproven'],
182
+ nullish: ['non-nil', 'unproven'],
183
+ get: ['array-index', 'unproven'],
184
+ } as unknown as NativeSafeTable
185
+ const PROVEN_ONLY: NativeSafeTable = {
186
+ 'to-boolean': ['boolean'],
187
+ 'to-number': ['number-pair', 'number'],
188
+ plus: ['number-pair', 'string'],
189
+ 'strict-eq': ['number-pair', 'string-pair', 'boolean-pair'],
190
+ relational: ['number-pair'],
191
+ neg: ['number'],
192
+ 'number-literal': ['safe-integer'],
193
+ nullish: ['non-nil'],
194
+ get: ['array-index'],
195
+ }
196
+
197
+ /** The plan as `mode op proof|helper`. */
198
+ function plan(src: string, target: NativeSafeTable, at: ScopedOperandTyping = typing): string {
199
+ const p = planPrimitive(parseExpression(src), at, target)
200
+ if (p === null) return 'none'
201
+ if (p.mode === 'native') return `native ${p.op} ${p.proof}`
202
+ if (p.mode === 'helper') return `helper ${p.op} ${p.helper} ${p.proof}`
203
+ if (p.mode === 'const') return `const ${p.op} ${p.value}`
204
+ return `refuse ${p.op}`
205
+ }
206
+
207
+ describe('planPrimitive', () => {
208
+ test('ToBoolean (a test position) is native only for a proven boolean the target claims', () => {
209
+ expect(plan('!props.on', PROVEN_ONLY)).toBe('native to-boolean boolean')
210
+ expect(plan('!props.s', PROVEN_ONLY)).toBe('helper to-boolean truthy unproven')
211
+ expect(plan('props.on ? 1 : 2', NONE)).toBe('helper to-boolean truthy boolean')
212
+ expect(plan('props.s && 1', PROVEN_ONLY)).toBe('helper to-boolean truthy unproven')
213
+ })
214
+
215
+ test('relational and arithmetic are native only for two proven non-nil numbers', () => {
216
+ expect(plan('props.n < count()', PROVEN_ONLY)).toBe('native relational number-pair')
217
+ expect(plan('props.n <= props.maybe', PROVEN_ONLY)).toBe('helper relational le unproven')
218
+ expect(plan("props.s > '9'", PROVEN_ONLY)).toBe('helper relational gt unproven')
219
+ expect(plan('props.n - 1', PROVEN_ONLY)).toBe('native to-number number-pair')
220
+ expect(plan('props.n * props.nothing', PROVEN_ONLY)).toBe('helper to-number mul unproven')
221
+ expect(plan('props.n - props.maybe', NONE)).toBe('helper to-number sub unproven')
222
+ })
223
+
224
+ test('`/` and `%` always name their helper', () => {
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')
227
+ })
228
+
229
+ test('`+` adds two numbers, concatenates over a proven string, and is `plus` otherwise', () => {
230
+ expect(plan('props.n + 1', PROVEN_ONLY)).toBe('native plus number-pair')
231
+ expect(plan('props.n + 1', NONE)).toBe('helper plus add number-pair')
232
+ expect(plan("props.n + 'x'", PROVEN_ONLY)).toBe('native plus string')
233
+ expect(plan('props.maybe + 1', PROVEN_ONLY)).toBe('helper plus plus unproven')
234
+ })
235
+
236
+ test('`===` is native for a same-typed pair the target pins, and constant across proven types', () => {
237
+ expect(plan("props.s === 'a'", PROVEN_ONLY)).toBe('native strict-eq string-pair')
238
+ expect(plan('props.n === count()', PROVEN_ONLY)).toBe('native strict-eq number-pair')
239
+ expect(plan('props.maybe === 1', PROVEN_ONLY)).toBe('helper strict-eq strict_eq unproven')
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')
242
+ })
243
+
244
+ test('unary minus over a non-zero number literal folds into the literal; any other operand takes `neg`', () => {
245
+ expect(plan('-1', PROVEN_ONLY)).toBe('native number-literal safe-integer')
246
+ expect(plan('-1.5', PROVEN_ONLY)).toBe('helper number-literal number unproven')
247
+ // `-0` does not fold: the zero operand is the case `neg` exists for.
248
+ expect(plan('-0', PROVEN_ONLY)).toBe('helper neg neg unproven')
249
+ expect(plan('-props.n', PROVEN_ONLY)).toBe('helper neg neg unproven')
250
+ expect(plan('+props.n', PROVEN_ONLY)).toBe('native to-number number')
251
+ })
252
+
253
+ test('a number literal is native only when it is a safe integer', () => {
254
+ expect(plan('42', PROVEN_ONLY)).toBe('native number-literal safe-integer')
255
+ expect(plan('9007199254740991', PROVEN_ONLY)).toBe('native number-literal safe-integer')
256
+ expect(plan('9007199254740992', PROVEN_ONLY)).toBe('helper number-literal number unproven')
257
+ expect(plan('1.5', PROVEN_ONLY)).toBe('helper number-literal number unproven')
258
+ expect(plan('1e21', PROVEN_ONLY)).toBe('helper number-literal number unproven')
259
+ expect(plan('100000000000000000000', PROVEN_ONLY)).toBe('helper number-literal number unproven')
260
+ expect(plan("'42'", PROVEN_ONLY)).toBe('none')
261
+ })
262
+
263
+ test('a number literal is spelled from its plan: host literal, `number` over the JS spelling, or `neg(0)`', () => {
264
+ const spell = (src: string) => {
265
+ const node = parseExpression(src)
266
+ const literal = foldNegatedNumberLiteral(node) ?? node
267
+ const value = literal.kind === 'literal' && typeof literal.value === 'number' ? literal.value : -0
268
+ return numberLiteralSpelling(value, planPrimitive(node, typing, PROVEN_ONLY))
269
+ }
270
+ expect(spell('42')).toEqual({ kind: 'native', text: '42' })
271
+ expect(spell('-3')).toEqual({ kind: 'native', text: '-3' })
272
+ expect(spell('1e21')).toEqual({ kind: 'parse', text: '1e+21' })
273
+ expect(spell('1e-7')).toEqual({ kind: 'parse', text: '1e-7' })
274
+ expect(spell('1e20')).toEqual({ kind: 'parse', text: '100000000000000000000' })
275
+ expect(spell('-1.5')).toEqual({ kind: 'parse', text: '-1.5' })
276
+ expect(spell('9007199254740993')).toEqual({ kind: 'parse', text: '9007199254740992' })
277
+ expect(numberLiteralSpelling(-0, null)).toEqual({ kind: 'negative-zero' })
278
+ // A null plan (an emitter reached outside the dispatcher) gets the safe-integer claim.
279
+ expect(numberLiteralSpelling(7, null)).toEqual({ kind: 'native', text: '7' })
280
+ expect(numberLiteralSpelling(0.5, null)).toEqual({ kind: 'parse', text: '0.5' })
281
+ })
282
+
283
+ test('`??` is native when its left side is proven never nil', () => {
284
+ expect(plan("props.s ?? 'x'", PROVEN_ONLY)).toBe('native nullish non-nil')
285
+ expect(plan('props.maybe ?? 0', PROVEN_ONLY)).toBe('helper nullish coalesce unproven')
286
+ })
287
+
288
+ test('an index read is native only for a proven array read by a loop index', () => {
289
+ const row = BindingScope.forComponent('props').enterLoopRow({ param: 'item', index: 'i' })
290
+ const at = collectOperandTyping(COMPONENT).at(row)
291
+ expect(plan('props.rows[i]', PROVEN_ONLY, at)).toBe('native get array-index')
292
+ expect(plan('props.rows[props.n]', PROVEN_ONLY, at)).toBe('helper get get unproven')
293
+ // A literal key is a computed member, never a proven index.
294
+ expect(plan('props.rows[0]', PROVEN_ONLY, at)).toBe('helper get get unproven')
295
+ expect(plan('props.rows.length', PROVEN_ONLY, at)).toBe('none')
296
+ })
297
+
298
+ test('loose equality and other operators are not planned', () => {
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')
302
+ })
303
+
304
+ test('the empty typing proves only structure', () => {
305
+ const empty = EMPTY_OPERAND_TYPING.at(BindingScope.EMPTY)
306
+ expect(plan('!props.on', PROVEN_ONLY, empty)).toBe('helper to-boolean truthy unproven')
307
+ expect(plan('!(a < b)', PROVEN_ONLY, empty)).toBe('native to-boolean boolean')
308
+ })
309
+ })
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
+
382
+ /** The typing of the one component in `src`, at component scope, from the analyzer's metadata. */
383
+ function analyzed(src: string): ScopedOperandTyping {
384
+ const metadata = buildMetadata(analyzeComponent(src, 'foo.tsx'))
385
+ return collectOperandTyping(metadata).at(BindingScope.forComponent(metadata.propsObjectName))
386
+ }
387
+
388
+ const NON_NIL_NULLISH: NativeSafeTable = { nullish: ['non-nil'] }
389
+
390
+ describe('defaults, from analyzed components', () => {
391
+ test('a renamed body-destructure default types the local binding, not the original property', () => {
392
+ const at = analyzed(
393
+ "export function Foo(props: { label?: string }) { const { label: text = 'none' } = props; return <div>{props.label ?? 'fallback'}{text}</div> }",
394
+ )
395
+ expect(factsOf('props.label', at)).toBe('nil|string (undefined)')
396
+ expect(plan("props.label ?? 'fallback'", NON_NIL_NULLISH, at)).toBe('helper nullish coalesce unproven')
397
+ expect(factsOf('text', at)).toBe('string')
398
+ expect(plan("text ?? 'fallback'", NON_NIL_NULLISH, at)).toBe('native nullish non-nil')
399
+ })
400
+
401
+ test('an unrenamed body-destructure default types the local binding, not the original property', () => {
402
+ const at = analyzed(
403
+ "export function Foo(props: { label?: string }) { const { label = 'none' } = props; return <div>{props.label ?? 'fallback'}{label}</div> }",
404
+ )
405
+ expect(factsOf('props.label', at)).toBe('nil|string (undefined)')
406
+ expect(plan("props.label ?? 'fallback'", NON_NIL_NULLISH, at)).toBe('helper nullish coalesce unproven')
407
+ expect(factsOf('label', at)).toBe('string')
408
+ })
409
+
410
+ test('a body destructure without a default keeps the optional nil', () => {
411
+ const at = analyzed('export function Foo(props: { label?: string }) { const { label } = props; return <div>{label}</div> }')
412
+ expect(factsOf('label', at)).toBe('nil|string (undefined)')
413
+ })
414
+
415
+ test('a literal parameter default proves its own type; an `undefined` default does not prove non-nil', () => {
416
+ const at = analyzed(
417
+ "export function Foo({ on = undefined, n = 1, size = 'md', off = false, alias = off }: { on?: boolean; n?: number; size?: string; off?: boolean; alias?: boolean }) { return <div>{on ?? true}{n}{size}{alias}</div> }",
418
+ )
419
+ expect(factsOf('on', at)).toBe('boolean|nil (undefined)')
420
+ expect(plan('on ?? true', NON_NIL_NULLISH, at)).toBe('helper nullish coalesce unproven')
421
+ expect(factsOf('n', at)).toBe('number')
422
+ expect(plan('n ?? 0', NON_NIL_NULLISH, at)).toBe('native nullish non-nil')
423
+ expect(factsOf('size', at)).toBe('string')
424
+ // A default reading an earlier binding takes that binding's facts.
425
+ expect(factsOf('alias', at)).toBe('boolean')
426
+ })
427
+
428
+ test('a destructuring default replaces only `undefined`: a declared `null` survives it', () => {
429
+ const param = analyzed("export function Foo({ label = 'none' }: { label?: string | null }) { return <div>{label ?? 'fallback'}</div> }")
430
+ expect(factsOf('label', param)).toBe('nil|string (null)')
431
+ expect(plan("label ?? 'fallback'", NON_NIL_NULLISH, param)).toBe('helper nullish coalesce unproven')
432
+ const renamed = analyzed(
433
+ "export function Foo(props: { label?: string | null }) { const { label: text = 'none' } = props; return <div>{text ?? 'fallback'}</div> }",
434
+ )
435
+ expect(factsOf('text', renamed)).toBe('nil|string (null)')
436
+ expect(plan("text ?? 'fallback'", NON_NIL_NULLISH, renamed)).toBe('helper nullish coalesce unproven')
437
+ const unrenamed = analyzed(
438
+ "export function Foo(props: { label?: string | null }) { const { label = 'none' } = props; return <div>{label ?? 'fallback'}</div> }",
439
+ )
440
+ expect(factsOf('label', unrenamed)).toBe('nil|string (null)')
441
+ // A required nullable prop keeps its `null` too.
442
+ const required = analyzed("export function Foo({ label = 'none' }: { label: string | null }) { return <div>{label}</div> }")
443
+ expect(factsOf('label', required)).toBe('nil|string (null)')
444
+ })
445
+
446
+ test('a hand-written `??` const is never nil: `??` replaces `null` too', () => {
447
+ const at = analyzed(
448
+ "export function Foo(props: { label?: string | null }) { const text = props.label ?? 'none'; return <div>{text ?? 'fallback'}</div> }",
449
+ )
450
+ expect(factsOf('text', at)).toBe('string')
451
+ expect(plan("text ?? 'fallback'", NON_NIL_NULLISH, at)).toBe('native nullish non-nil')
452
+ })
453
+
454
+ test('`||` and `&&` initializers prove nothing (a falsy non-nil left side survives `||`)', () => {
455
+ const at = analyzed(
456
+ "export function Foo(props: { label?: string | null; n: number }) { const a = props.label || 'none'; const b = props.n && 'x'; return <div>{a}{b}</div> }",
457
+ )
458
+ expect(factsOf('a', at)).toBe('unknown')
459
+ expect(factsOf('b', at)).toBe('unknown')
460
+ })
461
+
462
+ test('a default that may be nil, or proves nothing, does not prove non-nil', () => {
463
+ const at = analyzed(
464
+ 'export function Foo({ a = null, b = make() }: { a?: number | null; b?: number }) { return <div>{a}{b}</div> }\nfunction make(): number { return 1 }',
465
+ )
466
+ expect(factsOf('a', at)).toBe('nil|number (null)')
467
+ expect(factsOf('b', at)).toBe('unknown')
468
+ expect(plan('b ?? 0', NON_NIL_NULLISH, at)).toBe('helper nullish coalesce unproven')
469
+ })
470
+ })
471
+
472
+ describe('array element evidence through a union (#3824 step 8)', () => {
473
+ const row: TypeInfo = { kind: 'interface', raw: 'Row' }
474
+ const withRows = (type: TypeInfo, optional = false) =>
475
+ collectOperandTyping(meta({ propsParams: [param('rows', type, optional)] })).at(BindingScope.EMPTY)
476
+ const isRow = (name: string) => name === 'Row'
477
+
478
+ test('an optional or nullable object array keeps its element evidence for the refusal', () => {
479
+ for (const at of [withRows(array(row), true), withRows(union(array(row), prim('null')))]) {
480
+ expect(mayHoldObject(parseExpression('rows[0]'), at, isRow)).toBe(true)
481
+ expect(mayHoldObject(parseExpression('rows.at(0)'), at, isRow)).toBe(true)
482
+ }
483
+ })
484
+
485
+ test('the kept element evidence does not prove a nullable array an array', () => {
486
+ const facts = operandFacts(parseExpression('rows'), withRows(array(row), true))
487
+ expect(facts.array).toBeUndefined()
488
+ expect(facts.types.has('nil')).toBe(true)
489
+ })
490
+
491
+ test('a primitive element array is still not refused', () => {
492
+ expect(mayHoldObject(parseExpression('rows[0]'), withRows(array(prim('number')), true), isRow)).toBe(false)
493
+ })
494
+ })
@@ -52,8 +52,8 @@ describe('loop-child binding-effect ids (#1795 Phase 2)', () => {
52
52
  const on = clientJs(true)
53
53
  // Both `{it.t}` and `{it.n}` text effects write through the row's
54
54
  // claimed 'text' slot writer (slot unification A3).
55
- expect(on).toMatch(/__bfw_\w+\('s\d+', String\(it\(\)\.t\)\) }, "List#binding:s\d+"\)/)
56
- expect(on).toMatch(/__bfw_\w+\('s\d+', String\(it\(\)\.n\)\) }, "List#binding:s\d+"\)/)
55
+ expect(on).toMatch(/__bfw_\w+\('s\d+', textOrNode\(it\(\)\.t\)\) }, "List#binding:s\d+"\)/)
56
+ expect(on).toMatch(/__bfw_\w+\('s\d+', textOrNode\(it\(\)\.n\)\) }, "List#binding:s\d+"\)/)
57
57
  })
58
58
 
59
59
  test('profile on: the loop-child attribute effect carries a #binding id', () => {
@@ -122,7 +122,7 @@ describe('nested loop binding ids (#1795 Phase 3)', () => {
122
122
  // a live Node passes through untouched.
123
123
  expect(on).toMatch(/__bfw_\w+\('s\d+', escapeTextOrNode\(r\(\)\.label\)\) }, "Nested#binding:s\d+"\)/)
124
124
  // The inner loop's child text (`{t}`).
125
- expect(on).toMatch(/String\(t\(\)\)\) }, "Nested#binding:s\d+"\)/)
125
+ expect(on).toMatch(/textOrNode\(t\(\)\)\) }, "Nested#binding:s\d+"\)/)
126
126
  })
127
127
 
128
128
  test('branch-scoped loop (loop inside a conditional) attributes its mapArray', () => {
@@ -137,7 +137,7 @@ describe('nested loop binding ids (#1795 Phase 3)', () => {
137
137
  const emitted = assertNoCoverageGap(staticLoopSource, 'StaticLoop')
138
138
  expect(emitted.length).toBeGreaterThanOrEqual(1)
139
139
  const on = clientJs(staticLoopSource, 'StaticLoop', true)
140
- expect(on).toMatch(/__bfw_\w+\('s\d+', String\(n\(\)\)\) }, "StaticLoop#binding:s\d+"\)/)
140
+ expect(on).toMatch(/__bfw_\w+\('s\d+', textOrNode\(n\(\)\)\) }, "StaticLoop#binding:s\d+"\)/)
141
141
  })
142
142
 
143
143
  test('component loop attributes its mapArray', () => {
@@ -0,0 +1,115 @@
1
+ /**
2
+ * A destructure default applies to an absent or `undefined` prop only; an
3
+ * explicit `null` keeps `null` (`spec/js-undefined-value.md`, "Decisions"
4
+ * (6)). Every client-JS read of a defaulted prop is
5
+ * `_p.x === undefined ? d : _p.x`: the live reads in effects, the CSR
6
+ * template, a signal seed, a controlled signal's seed, a written prop's
7
+ * local, the `children` extraction and a body destructure of the props
8
+ * object. A compiler-supplied guard of a defaultless prop (`?? []` for a
9
+ * loop array) keeps replacing either nil.
10
+ */
11
+
12
+ import { describe, test, expect } from 'bun:test'
13
+ import { compileJSX } from '../compiler'
14
+ import { TestAdapter } from '../adapters/test-adapter'
15
+
16
+ function clientJs(source: string): string {
17
+ const result = compileJSX(source, 'Demo.tsx', { adapter: new TestAdapter() })
18
+ expect(result.errors.filter(e => e.severity === 'error')).toEqual([])
19
+ return result.files.find(f => f.type === 'clientJs')!.content
20
+ }
21
+
22
+ describe('a destructure default in client JS applies to undefined only', () => {
23
+ test('text, attribute, CSR template and signal seeds', () => {
24
+ const js = clientJs(`
25
+ 'use client'
26
+ import { createSignal } from '@barefootjs/client'
27
+ export function Demo({ label = 'D', start = 0 }: { label?: string | null; start?: number | null }) {
28
+ const [copy] = createSignal(label)
29
+ return <p title={label} data-s={start}>{label}{copy()}</p>
30
+ }
31
+ `)
32
+ expect(js).toContain("(_p.label === undefined ? 'D' : _p.label)")
33
+ expect(js).toContain("createSignal(_p.label === undefined ? 'D' : _p.label)")
34
+ expect(js).toContain('(_p.start === undefined ? 0 : _p.start)')
35
+ expect(js).not.toContain('_p.label ??')
36
+ expect(js).not.toContain('_p.start ??')
37
+ })
38
+
39
+ test('a body destructure of the props object and a written prop', () => {
40
+ const js = clientJs(`
41
+ 'use client'
42
+ export function Demo(props: { label?: string | null; n?: number | null }) {
43
+ const { label = 'D' } = props
44
+ return <p>{label}</p>
45
+ }
46
+ export function Counter({ n = 1 }: { n?: number | null }) {
47
+ n = n + 1
48
+ return <p>{n}</p>
49
+ }
50
+ `)
51
+ expect(js).toContain("(_p.label === undefined ? 'D' : _p.label)")
52
+ expect(js).toContain('let n = _p.n === undefined ? 1 : _p.n')
53
+ expect(js).not.toContain('_p.label ??')
54
+ expect(js).not.toContain('_p.n ??')
55
+ })
56
+
57
+ test('a default reading an earlier binding kept as a local reads that local', () => {
58
+ const js = clientJs(`
59
+ 'use client'
60
+ export function Demo(props: { a?: string[]; b?: string[] }) {
61
+ let { a = [], b = a } = props
62
+ a.push('x')
63
+ return <p>{b.length}</p>
64
+ }
65
+ export function Assigned(props: { a?: number; b?: number; c?: number }) {
66
+ let { a = 1, b = (a = 2), c = a } = props
67
+ return <p>{c}</p>
68
+ }
69
+ export function Kept(props: { a?: string[]; b?: string[] }) {
70
+ const { a = [], b = a } = props
71
+ a.push('x')
72
+ return <p>{b.length}</p>
73
+ }
74
+ `)
75
+ expect(js).toContain('let b = _p.b === undefined ? a : _p.b')
76
+ // An unread binding whose default assigns stays, so the assignment runs.
77
+ expect(js).toContain('let b = _p.b === undefined ? (a = 2) : _p.b')
78
+ expect(js).toContain('let c = _p.c === undefined ? a : _p.c')
79
+ expect(js).toContain('const b = _p.b === undefined ? a : _p.b')
80
+ expect(js).not.toContain('let b = _p.b === undefined ? (_p.a')
81
+ expect(js).not.toContain('const b = _p.b === undefined ? (_p.a')
82
+ })
83
+
84
+ test('an arrow default keeps its own parens', () => {
85
+ const js = clientJs(`
86
+ 'use client'
87
+ export function Demo({ fmt = (v: string) => v + '!' }: { fmt?: (v: string) => string }) {
88
+ return <p>{fmt('x')}</p>
89
+ }
90
+ `)
91
+ expect(js).toContain("(_p.fmt === undefined ? ((v) => v + '!') : _p.fmt)('x')")
92
+ })
93
+
94
+ test("an author's `??` over a prop keeps replacing null", () => {
95
+ const js = clientJs(`
96
+ 'use client'
97
+ export function Demo(props: { label?: string | null }) {
98
+ const label = props.label ?? 'x'
99
+ return <p>{label.toUpperCase()}</p>
100
+ }
101
+ `)
102
+ expect(js).toContain("(_p.label ?? 'x')")
103
+ expect(js).not.toContain('_p.label === undefined')
104
+ })
105
+
106
+ test('a defaultless loop array keeps its nil guard', () => {
107
+ const js = clientJs(`
108
+ 'use client'
109
+ export function Demo({ items }: { items?: string[] | null }) {
110
+ return <ul>{items.map(i => <li key={i}>{i}</li>)}</ul>
111
+ }
112
+ `)
113
+ expect(js).toContain('(_p.items ?? [])')
114
+ })
115
+ })
@@ -307,9 +307,9 @@ describe('ClientJS generation with semantic prop refs', () => {
307
307
  const clientJs = result.files.find((f) => f.type === 'clientJs')
308
308
  expect(clientJs).toBeDefined()
309
309
  // No captured-once local — the live read carries the default at the
310
- // read site itself: `(_p.open ?? false)`.
310
+ // read site itself: `(_p.open === undefined ? false : _p.open)`.
311
311
  expect(clientJs?.content).not.toContain('const open = ')
312
- expect(clientJs?.content).toMatch(/\(_p\.open \?\? false\)/)
312
+ expect(clientJs?.content).toMatch(/\(_p\.open === undefined \? false : _p\.open\)/)
313
313
  })
314
314
  })
315
315