@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
package/src/analyzer.ts CHANGED
@@ -34,7 +34,11 @@ import { CATALOGUED_RICH_TYPE_NAMES } from './date-lowering.ts'
34
34
  import path from 'node:path'
35
35
  import fs from 'node:fs'
36
36
  import { signalSecondBinding } from './signal-initializer.ts'
37
+ import { observesWholePropsObject } from './props-object-whole-read.ts'
37
38
  import { separateSignalPropBindings, programWithSeparatedSource } from './signal-prop-name-collision.ts'
39
+ import { isAssignmentTargetIdentifier } from './assignment-target.ts'
40
+ import { addSourceReplacement } from './strip-types.ts'
41
+ import { walkWithScope } from './scope/lexical-scope-walk.ts'
38
42
 
39
43
  // =============================================================================
40
44
  // TypeScript Program Creation
@@ -855,6 +859,7 @@ function analyzeComponentBody(
855
859
  if (node.parameters.length > 0) {
856
860
  extractProps(node.parameters[0], ctx)
857
861
  }
862
+ if (ctx.propsObjectName) ctx.propsObjectObservedWhole = observesWholePropsObject(node, ctx.propsObjectName)
858
863
 
859
864
  // Visit component body
860
865
  const body = ts.isFunctionDeclaration(node) ? node.body : getArrowFunctionBody(node)
@@ -936,16 +941,8 @@ function visitComponentBody(node: ts.Node, ctx: AnalyzerContext): void {
936
941
  if (ts.isIdentifier(decl.name)) {
937
942
  const isLet = (node.declarationList.flags & ts.NodeFlags.Let) !== 0
938
943
  collectConstant(decl, ctx, false, isLet ? 'let' : 'const')
939
- } else if (
940
- ts.isObjectBindingPattern(decl.name) &&
941
- decl.initializer &&
942
- ts.isIdentifier(decl.initializer) &&
943
- ctx.propsObjectName === decl.initializer.text
944
- ) {
945
- // Body-level destructure from `props` — `collectConstant` handles
946
- // the expansion into one entry per destructured name.
947
- const isLet = (node.declarationList.flags & ts.NodeFlags.Let) !== 0
948
- collectConstant(decl, ctx, false, isLet ? 'let' : 'const')
944
+ } else if (ts.isObjectBindingPattern(decl.name)) {
945
+ collectBodyDestructure(decl, node.declarationList.flags, isTopLevel, ctx)
949
946
  }
950
947
  }
951
948
  }
@@ -3791,10 +3788,11 @@ function bindingElementDefaultFields(
3791
3788
  initializer: ts.Expression | undefined,
3792
3789
  ctx: AnalyzerContext,
3793
3790
  earlier: ReadonlyMap<string, PropDefaultRead> = new Map(),
3794
- ): Pick<ParamInfo, 'defaultValue' | 'parsed' | 'defaultContainsArrow' | 'defaultParts'> {
3791
+ ): Pick<ParamInfo, 'defaultValue' | 'parsed' | 'defaultContainsArrow' | 'defaultFreeIdentifiers' | 'defaultParts'> {
3795
3792
  const defaultValue = initializer ? ctx.getJS(initializer) : undefined
3796
3793
  const defaultContainsArrow = initializer ? nodeContainsArrow(initializer) : false
3797
3794
  const parsedDefault = initializer ? tsNodeToParsedExpr(initializer) : undefined
3795
+ const defaultFreeIdentifiers = initializer ? [...extractFreeIdentifiersFromNode(initializer)] : []
3798
3796
  const defaultParts = initializer && defaultValue !== undefined
3799
3797
  ? defaultPartsReadingEarlierBindings(initializer, defaultValue, earlier)
3800
3798
  : undefined
@@ -3802,6 +3800,7 @@ function bindingElementDefaultFields(
3802
3800
  defaultValue,
3803
3801
  ...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
3804
3802
  defaultContainsArrow: defaultContainsArrow || undefined,
3803
+ ...(defaultFreeIdentifiers.length > 0 && { defaultFreeIdentifiers }),
3805
3804
  ...(defaultParts && { defaultParts }),
3806
3805
  }
3807
3806
  }
@@ -3833,6 +3832,418 @@ function defaultPartsReadingEarlierBindings(
3833
3832
  )
3834
3833
  }
3835
3834
 
3835
+ /**
3836
+ * Whether `decl` is a component-body object destructure of the props object
3837
+ * (`const { x } = props`) — the one decision both `visitComponentBody` and
3838
+ * `collectConstant` use to expand it into per-name prop reads.
3839
+ *
3840
+ * The initializer may also be a component-scope `const` alias of the props
3841
+ * object (`const p = props; const { x } = p`, transitively). Anything else
3842
+ * is NOT the props object. The alias is resolved from real bindings: the
3843
+ * alias declaration and the destructure must both be direct statements of
3844
+ * the component body (no nested block can shadow the alias between them),
3845
+ * and the alias must be declared before the destructure. A `let` alias is
3846
+ * refused, since a reassignment can make it name another object. Any alias
3847
+ * is refused when the props parameter itself is assigned anywhere in the
3848
+ * body (`props = …`): the alias keeps the object it captured, so it may no
3849
+ * longer be what `props` names.
3850
+ */
3851
+ function destructuresPropsObject(
3852
+ decl: ts.VariableDeclaration,
3853
+ ctx: AnalyzerContext,
3854
+ ): decl is ts.VariableDeclaration & { name: ts.ObjectBindingPattern; initializer: ts.Expression } {
3855
+ if (!ts.isObjectBindingPattern(decl.name) || !decl.initializer || ctx.propsObjectName === null) return false
3856
+ return isPropsObjectReference(decl.initializer, decl, ctx, new Set())
3857
+ }
3858
+
3859
+ function isPropsObjectReference(
3860
+ expr: ts.Expression,
3861
+ use: ts.VariableDeclaration,
3862
+ ctx: AnalyzerContext,
3863
+ visiting: Set<ts.VariableDeclaration>,
3864
+ ): boolean {
3865
+ if (!ts.isIdentifier(expr)) return false
3866
+ if (expr.text === ctx.propsObjectName) return true
3867
+ const body = ctx.componentBodyBlock
3868
+ if (body === null || !isComponentBodyStatementDeclaration(use, body)) return false
3869
+ // A const alias keeps the object it captured, but the props parameter can
3870
+ // be reassigned after the capture. Then the alias is not the props object.
3871
+ if (assignsIdentifier(body, ctx.propsObjectName)) return false
3872
+ const alias = componentConstDeclaration(expr.text, body)
3873
+ if (alias === null || alias.pos >= use.pos || visiting.has(alias) || !alias.initializer) return false
3874
+ visiting.add(alias)
3875
+ return isPropsObjectReference(alias.initializer, alias, ctx, visiting)
3876
+ }
3877
+
3878
+ /**
3879
+ * Whether anything under `root` writes the identifier `name`, by the shared
3880
+ * assignment-target rule (`isAssignmentTargetIdentifier`): an assignment or
3881
+ * compound assignment, `++` / `--`, a destructuring-assignment target or a
3882
+ * `for (… of / in …)` head. Conservative: a nested binding that shadows
3883
+ * `name` counts too.
3884
+ */
3885
+ function assignsIdentifier(root: ts.Node, name: string | null): boolean {
3886
+ if (name === null) return false
3887
+ let found = false
3888
+ const visit = (node: ts.Node): void => {
3889
+ if (found) return
3890
+ if (ts.isIdentifier(node) && node.text === name && isAssignmentTargetIdentifier(node)) {
3891
+ found = true
3892
+ return
3893
+ }
3894
+ ts.forEachChild(node, visit)
3895
+ }
3896
+ visit(root)
3897
+ return found
3898
+ }
3899
+
3900
+ /** Whether `decl` belongs to a variable statement that is a direct child of `body`. */
3901
+ function isComponentBodyStatementDeclaration(decl: ts.VariableDeclaration, body: ts.Block): boolean {
3902
+ const statement = decl.parent?.parent
3903
+ return statement !== undefined && ts.isVariableStatement(statement) && statement.parent === body
3904
+ }
3905
+
3906
+ /** The `const <name> = …` declaration among `body`'s direct statements, or null. */
3907
+ function componentConstDeclaration(name: string, body: ts.Block): ts.VariableDeclaration | null {
3908
+ for (const stmt of body.statements) {
3909
+ if (!ts.isVariableStatement(stmt)) continue
3910
+ for (const d of stmt.declarationList.declarations) {
3911
+ if (!ts.isIdentifier(d.name) || d.name.text !== name) continue
3912
+ return (stmt.declarationList.flags & ts.NodeFlags.Const) !== 0 ? d : null
3913
+ }
3914
+ }
3915
+ return null
3916
+ }
3917
+
3918
+ /**
3919
+ * The rest element of a component-body destructure of the props object
3920
+ * (`const { label, ...rest } = props`): it binds the component's rest props
3921
+ * exactly as a signature rest (`({ label, ...rest })`) does, so it is
3922
+ * recorded the same way: `restPropsName`, and the closed-type keys it
3923
+ * holds (`restPropsExpandedKeys`), which are the props type's keys minus the
3924
+ * ones the destructure takes. `restPropsOmittedKeys` records those taken
3925
+ * keys for a backend that runs the body as JS. A component already holding
3926
+ * a rest binding keeps it.
3927
+ */
3928
+ function collectBodyRestBinding(pattern: ts.ObjectBindingPattern, ctx: AnalyzerContext): void {
3929
+ const restElement = pattern.elements.find(el => el.dotDotDotToken)
3930
+ if (!restElement || !ts.isIdentifier(restElement.name) || ctx.restPropsName !== null) return
3931
+ const restName = restElement.name.text
3932
+ const taken: string[] = []
3933
+ for (const el of pattern.elements) {
3934
+ if (el.dotDotDotToken) continue
3935
+ const key = bindingElementKey(el)
3936
+ if (key !== null) taken.push(key)
3937
+ }
3938
+ ctx.restPropsName = restName
3939
+ ctx.restPropsOmittedKeys = taken
3940
+ const param = ctx.componentNode?.parameters[0]
3941
+ const allKeys = param?.type ? collectTypeKeys(param.type, ctx) : null
3942
+ if (allKeys) ctx.restPropsExpandedKeys = allKeys.filter(k => !taken.includes(k))
3943
+ respellBodyRestMemberReads(restName, taken, ctx)
3944
+ }
3945
+
3946
+ /**
3947
+ * Respell each member read of a props-object body rest (`const { label,
3948
+ * ...rest } = props`, `rest.id`) as the read of the props object it is
3949
+ * (#3854): the rest holds the props object's keys minus the ones the
3950
+ * destructure takes, so `rest.id` reads `props.id`; a read of a taken key
3951
+ * (`rest.label`) is refused ({@link refuseTakenKeyRestRead}). Every backend
3952
+ * then reads it as it reads the props object: a template binds each
3953
+ * declared prop as its own variable, while its rest bag holds only the keys
3954
+ * the props type does not declare, so the read can't go to the bag.
3955
+ *
3956
+ * Decided here, where the rest is recorded, and spelled through `getJS`
3957
+ * (`addSourceReplacement`): every expression, const and handler built from
3958
+ * the source afterwards carries the respelled read. Only a read the rest
3959
+ * binding reaches is respelled: not one a nested binding of the same name
3960
+ * shadows (`items.map(rest => rest.id)`, `walkWithScope`), not an
3961
+ * assignment target, and not a key the props type does not declare (that
3962
+ * one stays a read of the rest bag, which holds it). A read where a nested
3963
+ * binding shadows the props object's name is refused
3964
+ * ({@link refuseRestReadUnderShadowedProps}).
3965
+ */
3966
+ function respellBodyRestMemberReads(restName: string, taken: readonly string[], ctx: AnalyzerContext): void {
3967
+ const body = ctx.componentBodyBlock
3968
+ const propsName = ctx.propsObjectName
3969
+ if (body === null || propsName === null) return
3970
+ const declared = new Set([...ctx.restPropsExpandedKeys, ...taken])
3971
+ for (const stmt of body.statements) {
3972
+ walkWithScope(stmt, (ident, parent, shadowed, isShadowed) => {
3973
+ if (shadowed || ident.text !== restName || parent === undefined) return
3974
+ const key = restMemberReadKey(ident, parent)
3975
+ if (key === null || !declared.has(key) || isWrittenAccess(parent)) return
3976
+ if (taken.includes(key)) {
3977
+ refuseTakenKeyRestRead(parent, restName, key, ctx)
3978
+ return
3979
+ }
3980
+ if (isShadowed(propsName)) {
3981
+ refuseRestReadUnderShadowedProps(parent, propsName, ctx)
3982
+ return
3983
+ }
3984
+ addSourceReplacement(ctx.typeExcludeRanges, { start: parent.getStart(ctx.sourceFile), end: parent.getEnd(), replacement: propsMemberRead(propsName, key) })
3985
+ })
3986
+ }
3987
+ }
3988
+
3989
+ /**
3990
+ * BF101 for a read through a props-object body rest of a key the same
3991
+ * destructure takes (`const { label, ...rest } = props`, `rest.label`):
3992
+ * the rest never holds it, so the read is always `undefined`. No backend
3993
+ * spells a bare `undefined` read the way JS renders it, so the read is
3994
+ * refused rather than respelled ({@link respellBodyRestMemberReads}).
3995
+ */
3996
+ function refuseTakenKeyRestRead(access: ts.Node, restName: string, key: string, ctx: AnalyzerContext): void {
3997
+ ctx.errors.push({
3998
+ code: 'BF101',
3999
+ severity: 'error',
4000
+ message: `\`${access.getText(ctx.sourceFile)}\` reads '${key}' through the rest \`${restName}\`, but the same destructure takes '${key}', so the rest never holds it and the read is always undefined.`,
4001
+ loc: getSourceLocation(access, ctx.sourceFile, ctx.filePath),
4002
+ suggestion: { message: `Read the destructured '${key}' binding instead, or drop the read.` },
4003
+ })
4004
+ }
4005
+
4006
+ /**
4007
+ * BF101 for a read through a props-object body rest where a nested binding
4008
+ * shadows the props object's name (`rows.map(props => rest.id)`): the read
4009
+ * would be respelled `props.id`, which there names the nested binding, and
4010
+ * no other spelling reaches the component's prop on every backend
4011
+ * ({@link respellBodyRestMemberReads}).
4012
+ */
4013
+ function refuseRestReadUnderShadowedProps(access: ts.Node, propsName: string, ctx: AnalyzerContext): void {
4014
+ ctx.errors.push({
4015
+ code: 'BF101',
4016
+ severity: 'error',
4017
+ message: `\`${access.getText(ctx.sourceFile)}\` reads the component's props through a rest, inside a binding that shadows the props object's name \`${propsName}\`, so the read has no spelling that reaches the component's prop.`,
4018
+ loc: getSourceLocation(access, ctx.sourceFile, ctx.filePath),
4019
+ suggestion: { message: `Rename the inner \`${propsName}\` binding, or read the value into a const outside it.` },
4020
+ })
4021
+ }
4022
+
4023
+ /** The key `parent` reads off `ident` (`ident.key`, `ident?.key`, `ident['key']`), or null when `parent` is no such read. */
4024
+ function restMemberReadKey(ident: ts.Identifier, parent: ts.Node): string | null {
4025
+ if (ts.isPropertyAccessExpression(parent) && parent.expression === ident && ts.isIdentifier(parent.name)) return parent.name.text
4026
+ if (ts.isElementAccessExpression(parent) && parent.expression === ident && ts.isStringLiteralLike(parent.argumentExpression)) {
4027
+ return parent.argumentExpression.text
4028
+ }
4029
+ return null
4030
+ }
4031
+
4032
+ /** Whether the member access `access` is written (`a.b = 1`, `a.b += 1`, `a.b++`, `delete a.b`) rather than read. */
4033
+ function isWrittenAccess(access: ts.Node): boolean {
4034
+ const parent = access.parent
4035
+ if (ts.isBinaryExpression(parent)) {
4036
+ const op = parent.operatorToken.kind
4037
+ return parent.left === access && op >= ts.SyntaxKind.FirstAssignment && op <= ts.SyntaxKind.LastAssignment
4038
+ }
4039
+ if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) {
4040
+ return parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken
4041
+ }
4042
+ return ts.isDeleteExpression(parent)
4043
+ }
4044
+
4045
+ /** `props.key`, or `props["key"]` for a key that is not an identifier. */
4046
+ function propsMemberRead(propsName: string, key: string): string {
4047
+ return isIdentifierName(key) ? `${propsName}.${key}` : `${propsName}[${JSON.stringify(key)}]`
4048
+ }
4049
+
4050
+ /** The property key a binding element reads (`{ a }`, `{ a: b }`, `{ 'a-b': c }`), or null for a computed key. */
4051
+ function bindingElementKey(el: ts.BindingElement): string | null {
4052
+ const name = el.propertyName ?? el.name
4053
+ if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text
4054
+ return null
4055
+ }
4056
+
4057
+ /**
4058
+ * A component-body object destructure. One of the props object (or a
4059
+ * component-scope `const` alias of it) — `collectConstant` expands it into
4060
+ * one entry per destructured name. A top-level `const` one of another const
4061
+ * object — {@link collectConstDestructure}. Any other top-level one binds
4062
+ * names nothing declares, so it is refused ({@link refuseBodyDestructure}).
4063
+ */
4064
+ function collectBodyDestructure(decl: ts.VariableDeclaration, flags: ts.NodeFlags, isTopLevel: boolean, ctx: AnalyzerContext): void {
4065
+ if (destructuresPropsObject(decl, ctx)) {
4066
+ collectConstant(decl, ctx, false, (flags & ts.NodeFlags.Let) !== 0 ? 'let' : 'const')
4067
+ } else if (isTopLevel && !((flags & ts.NodeFlags.Const) !== 0 && collectConstDestructure(decl, ctx))) {
4068
+ refuseBodyDestructure(decl, flags, ctx)
4069
+ }
4070
+ }
4071
+
4072
+ /**
4073
+ * BF101 for a component-body object destructure no backend binds (#3854):
4074
+ * a `let` one, one whose source is not an identifier naming a const object
4075
+ * (`getConf()`, `props.nested`, an imported name), or one with an element
4076
+ * that has no const form (a rest element, a non-literal default, a computed
4077
+ * key). The compiler rebuilds the body from what it collects, so such a
4078
+ * statement used to be dropped, leaving its names unbound in every output.
4079
+ */
4080
+ function refuseBodyDestructure(decl: ts.VariableDeclaration, flags: ts.NodeFlags, ctx: AnalyzerContext): void {
4081
+ ctx.errors.push({
4082
+ code: 'BF101',
4083
+ severity: 'error',
4084
+ message: `The destructure \`${decl.getText(ctx.sourceFile)}\` has no compiled form: ${bodyDestructureRefusalReason(decl, flags, ctx)}.`,
4085
+ loc: getSourceLocation(decl, ctx.sourceFile, ctx.filePath),
4086
+ suggestion: {
4087
+ message:
4088
+ 'Destructure the props object or a `const` object declared before it, with plain or literal-defaulted elements; or read the values directly (`const a = getConf().a`).',
4089
+ },
4090
+ })
4091
+ }
4092
+
4093
+ /** Why {@link refuseBodyDestructure} refuses `decl`, for its message. */
4094
+ function bodyDestructureRefusalReason(decl: ts.VariableDeclaration, flags: ts.NodeFlags, ctx: AnalyzerContext): string {
4095
+ if ((flags & ts.NodeFlags.Const) === 0) return 'only a `const` destructure is collected'
4096
+ let source: ts.Expression | undefined = decl.initializer
4097
+ while (source && ts.isParenthesizedExpression(source)) source = source.expression
4098
+ if (!source || !ts.isIdentifier(source)) return 'its source is not a plain name'
4099
+ if (!isConstObjectSource(source.text, decl, ctx)) return `\`${source.text}\` is not the props object or a \`const\` object declared before it`
4100
+ return 'an element is a rest element, has a non-literal default, or has a computed key'
4101
+ }
4102
+
4103
+ /**
4104
+ * A component-body `const` object destructure of a const object or of the
4105
+ * rest props (`const conf = { tone: 'info' }; const { tone } = conf`,
4106
+ * `const { tone } = rest`, `const { a: { b } } = MODULE_CONF`). It binds
4107
+ * each name to the path it reads off the source, so it is collected as one
4108
+ * const per binding, exactly as if the source had written
4109
+ * `const tone = conf.tone`: every backend then reads it through the same
4110
+ * const handling as any other computed const, instead of reading a name
4111
+ * nothing declares.
4112
+ *
4113
+ * The source is an identifier the destructure statement sees as a const
4114
+ * object: the rest props binding, a component-body `const` declared before
4115
+ * the statement, or a module `const` no component binding shadows. A binding
4116
+ * element may rename (`{ tone: t }`), nest an object pattern, or default to
4117
+ * a literal (`{ tone = 'x' }` reads `conf.tone === undefined ? 'x' :
4118
+ * conf.tone`). False, collecting nothing, for any other source or a
4119
+ * statement with any other element (a rest element, a computed key, an
4120
+ * array pattern, a non-literal default); the caller refuses it.
4121
+ */
4122
+ function collectConstDestructure(decl: ts.VariableDeclaration, ctx: AnalyzerContext): boolean {
4123
+ if (!ts.isObjectBindingPattern(decl.name) || !decl.initializer) return false
4124
+ let source: ts.Expression = decl.initializer
4125
+ while (ts.isParenthesizedExpression(source)) source = source.expression
4126
+ if (!ts.isIdentifier(source) || !isConstObjectSource(source.text, decl, ctx)) return false
4127
+ // A rest a body destructure of the props object binds holds the props
4128
+ // object's keys minus the ones that destructure takes: its key reads are
4129
+ // the props object's, and a taken key reads `undefined`.
4130
+ const bodyRest = source.text === ctx.restPropsName && ctx.restPropsOmittedKeys && ctx.propsObjectName
4131
+ const path = bodyRest ? ctx.propsObjectName! : source.text
4132
+ const bindings: ConstDestructureBinding[] = []
4133
+ if (!collectConstDestructureBindings(decl.name, path, bindings)) return false
4134
+ const loc = getSourceLocation(decl, ctx.sourceFile, ctx.filePath)
4135
+ for (const { name, key, value: read, fallback } of bindings) {
4136
+ const value = bodyRest && ctx.restPropsOmittedKeys!.includes(key) ? (fallback ?? 'undefined') : read
4137
+ ctx.localConstants.push({
4138
+ name,
4139
+ value,
4140
+ parsed: parseExpression(`(${value})`),
4141
+ declarationKind: 'const',
4142
+ isExported: false,
4143
+ type: null,
4144
+ loc,
4145
+ freeIdentifiers: new Set([path]),
4146
+ origin: { phase: 'hydrate', scope: 'init', effect: 'pure' },
4147
+ })
4148
+ }
4149
+ return true
4150
+ }
4151
+
4152
+ /**
4153
+ * Whether `name`, read by the destructure `use`, names a const object (see
4154
+ * {@link collectConstDestructure}): the rest props, a component-body `const`
4155
+ * declared before `use`, or a module `const` that no component binding
4156
+ * shadows.
4157
+ */
4158
+ function isConstObjectSource(name: string, use: ts.VariableDeclaration, ctx: AnalyzerContext): boolean {
4159
+ if (name === ctx.restPropsName) return true
4160
+ const body = ctx.componentBodyBlock
4161
+ if (body === null || !isComponentBodyStatementDeclaration(use, body)) return false
4162
+ const local = componentConstDeclaration(name, body)
4163
+ if (local !== null) return local.pos < use.pos && ts.isIdentifier(local.name)
4164
+ if (componentBodyBindsName(name, body) || ctx.propsObjectName === name) return false
4165
+ if (ctx.propsObjectName === null && ctx.propsParams.some(p => p.name === name)) return false
4166
+ return ctx.localConstants.some(c => c.isModule && c.name === name && (c.declarationKind ?? 'const') === 'const')
4167
+ }
4168
+
4169
+ /** Whether a direct statement of `body` declares `name` (any binding form, `let` included). */
4170
+ function componentBodyBindsName(name: string, body: ts.Block): boolean {
4171
+ for (const stmt of body.statements) {
4172
+ if (ts.isFunctionDeclaration(stmt) && stmt.name?.text === name) return true
4173
+ if (!ts.isVariableStatement(stmt)) continue
4174
+ for (const d of stmt.declarationList.declarations) {
4175
+ if (bindingNameDeclares(d.name, name)) return true
4176
+ }
4177
+ }
4178
+ return false
4179
+ }
4180
+
4181
+ function bindingNameDeclares(binding: ts.BindingName, name: string): boolean {
4182
+ if (ts.isIdentifier(binding)) return binding.text === name
4183
+ return binding.elements.some(el => !ts.isOmittedExpression(el) && bindingNameDeclares(el.name, name))
4184
+ }
4185
+
4186
+ /** One const a {@link collectConstDestructure} binding element binds. */
4187
+ interface ConstDestructureBinding {
4188
+ name: string
4189
+ /** What it reads off the source path. */
4190
+ value: string
4191
+ /** The key of the destructure's own element it sits under. */
4192
+ key: string
4193
+ /** The source text of its literal default, if any. */
4194
+ fallback?: string
4195
+ }
4196
+
4197
+ /**
4198
+ * The `{ name, value }` const each element of `pattern` binds, read off
4199
+ * `path` (see {@link collectConstDestructure}), with the key of `pattern`'s
4200
+ * own element it sits under. False when an element has no such const form.
4201
+ */
4202
+ function collectConstDestructureBindings(
4203
+ pattern: ts.ObjectBindingPattern,
4204
+ path: string,
4205
+ out: ConstDestructureBinding[],
4206
+ topKey?: string,
4207
+ ): boolean {
4208
+ for (const el of pattern.elements) {
4209
+ const key = el.dotDotDotToken ? null : bindingElementKey(el)
4210
+ if (key === null) return false
4211
+ const access = isIdentifierName(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`
4212
+ if (ts.isObjectBindingPattern(el.name) && !el.initializer) {
4213
+ if (!collectConstDestructureBindings(el.name, access, out, topKey ?? key)) return false
4214
+ continue
4215
+ }
4216
+ if (!ts.isIdentifier(el.name)) return false
4217
+ const fallback = el.initializer ? literalDefaultText(el.initializer) : undefined
4218
+ if (fallback === null) return false
4219
+ const value = fallback === undefined ? access : `${access} === undefined ? ${fallback} : ${access}`
4220
+ out.push({ name: el.name.text, value, key: topKey ?? key, ...(fallback !== undefined && { fallback }) })
4221
+ }
4222
+ return true
4223
+ }
4224
+
4225
+ /** Whether `key` is spelled as an identifier, so `obj.key` reads it. */
4226
+ function isIdentifierName(key: string): boolean {
4227
+ const chars = [...key]
4228
+ return chars.length > 0 && chars.every((ch, i) => {
4229
+ const code = ch.codePointAt(0)!
4230
+ return i === 0 ? ts.isIdentifierStart(code, ts.ScriptTarget.Latest) : ts.isIdentifierPart(code, ts.ScriptTarget.Latest)
4231
+ })
4232
+ }
4233
+
4234
+ /** The source text of a literal default (`'x'`, `1`, `-1`, `true`, `null`), or null for any other one. */
4235
+ function literalDefaultText(node: ts.Expression): string | null {
4236
+ if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return JSON.stringify(node.text)
4237
+ if (ts.isNumericLiteral(node)) return node.text
4238
+ if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) {
4239
+ return `-${node.operand.text}`
4240
+ }
4241
+ if (node.kind === ts.SyntaxKind.TrueKeyword) return 'true'
4242
+ if (node.kind === ts.SyntaxKind.FalseKeyword) return 'false'
4243
+ if (node.kind === ts.SyntaxKind.NullKeyword) return 'null'
4244
+ return null
4245
+ }
4246
+
3836
4247
  /** {@link propDefaultReadOf} for a body destructure's binding (`const { label: text = 'x' } = props`). */
3837
4248
  function bodyBindingRead(
3838
4249
  localName: string,
@@ -3872,17 +4283,15 @@ function collectConstant(
3872
4283
  // declarations from `localConstants`). Expand into one `localConstants`
3873
4284
  // entry per destructured name, valued `props.X`, so the late-stage
3874
4285
  // props-object rename turns them into `const X = _p.X` in the init body.
3875
- if (
3876
- !_isModule &&
3877
- ts.isObjectBindingPattern(node.name) &&
3878
- node.initializer &&
3879
- ts.isIdentifier(node.initializer) &&
3880
- ctx.propsObjectName === node.initializer.text
3881
- ) {
3882
- const propsName = node.initializer.text
4286
+ if (!_isModule && ctx.propsObjectName !== null && destructuresPropsObject(node, ctx)) {
4287
+ // Always the props object's own name, even when the destructure reads
4288
+ // it through a `const` alias (`const p = props; const { x } = p`), so
4289
+ // every downstream `props.X` recognizer sees one spelling.
4290
+ const propsName = ctx.propsObjectName
3883
4291
  // Bindings already destructured by this pattern, by local name: a later
3884
4292
  // default reads them (`const { off = false, on = off } = props`, #3531).
3885
4293
  const earlier = new Map<string, PropDefaultRead>()
4294
+ collectBodyRestBinding(node.name, ctx)
3886
4295
  for (const el of node.name.elements) {
3887
4296
  if (!ts.isBindingElement(el) || !ts.isIdentifier(el.name) || el.dotDotDotToken) continue
3888
4297
  const localName = el.name.text
@@ -4268,6 +4677,7 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
4268
4677
  name: localName,
4269
4678
  type: resolvedType,
4270
4679
  ...unresolvedDeclaredType(member),
4680
+ ...propLiteralKeys(param.type, sourcePropName, ctx),
4271
4681
  // The type's `?` and a destructure default (`{ x = 1 }`) both mean
4272
4682
  // the caller may omit the prop.
4273
4683
  optional: !!member?.optional || !!element.initializer,
@@ -4393,9 +4803,10 @@ function collectKeysFromMembers(
4393
4803
  * same check, recursively. A same-file object type referenced by name
4394
4804
  * (`Item` in `items: Item[]`) is checked through its declaration's members
4395
4805
  * (`LocalObjectMemberTypes`) the same way an inline object literal's are.
4396
- * A union, a function, or any other named
4397
- * type reachable ANYWHERE inside the shape declines the WHOLE member (not
4398
- * just that one leaf): `collectMemberTypes` is an all-or-nothing gate per
4806
+ * A leaf typed `T | null` / `T | undefined` inside the shape resolves when
4807
+ * `T` does (`isNilUnionOfResolvable`). Any other union, a function, or any
4808
+ * other named type reachable ANYWHERE inside the shape declines the WHOLE
4809
+ * member (not just that one leaf): `collectMemberTypes` is an all-or-nothing gate per
4399
4810
  * member, so a partially-resolvable structural type must still decline —
4400
4811
  * per-field graceful degradation is `typeInfoToGo`'s job downstream, not
4401
4812
  * this gate's.
@@ -4422,8 +4833,9 @@ function isResolvableMemberType(
4422
4833
  info: TypeInfo,
4423
4834
  localObjectMembers?: LocalObjectMemberTypes,
4424
4835
  visiting: ReadonlySet<string> = new Set(),
4836
+ nested = false,
4425
4837
  ): boolean {
4426
- const recurse = (t: TypeInfo): boolean => isResolvableMemberType(t, localObjectMembers, visiting)
4838
+ const recurse = (t: TypeInfo): boolean => isResolvableMemberType(t, localObjectMembers, visiting, true)
4427
4839
  switch (info.kind) {
4428
4840
  case 'primitive':
4429
4841
  return info.primitive === 'string' || info.primitive === 'number' || info.primitive === 'boolean'
@@ -4437,18 +4849,35 @@ function isResolvableMemberType(
4437
4849
  const members = localObjectMembers(info.raw)
4438
4850
  if (!members) return false
4439
4851
  const inner = new Set(visiting).add(info.raw)
4440
- return members.every(t => isResolvableMemberType(t, localObjectMembers, inner))
4852
+ return members.every(t => isResolvableMemberType(t, localObjectMembers, inner, true))
4441
4853
  }
4442
4854
  case 'array':
4443
4855
  return !!info.elementType && recurse(info.elementType)
4444
4856
  case 'object':
4445
4857
  return info.properties !== undefined && info.properties.every(prop => recurse(prop.type))
4446
- // Unions, functions, and `unknown` all decline — see docstring.
4858
+ case 'union':
4859
+ // A field or element of a structural shape typed `T | null` /
4860
+ // `T | undefined` (`{ label?: string | null }`): the shape itself is
4861
+ // resolvable when `T` is, exactly as the `props`-object form already
4862
+ // resolves it. Every runtime carries `null` and `undefined` as values
4863
+ // (spec/js-undefined-value.md), and the field keeps its union type, so
4864
+ // a reader still sees that it may be nil. A top-level member typed
4865
+ // with a union still declines.
4866
+ return nested && isNilUnionOfResolvable(info, recurse)
4867
+ // Functions, other unions and `unknown` all decline — see docstring.
4447
4868
  default:
4448
4869
  return false
4449
4870
  }
4450
4871
  }
4451
4872
 
4873
+ /** A union of `null` / `undefined` with at least one other member, every other member resolvable. */
4874
+ function isNilUnionOfResolvable(info: TypeInfo, resolves: (t: TypeInfo) => boolean): boolean {
4875
+ const isNil = (t: TypeInfo) => t.kind === 'primitive' && (t.primitive === 'null' || t.primitive === 'undefined')
4876
+ const members = info.unionTypes ?? []
4877
+ const present = members.filter(t => !isNil(t))
4878
+ return present.length > 0 && present.length < members.length && present.every(resolves)
4879
+ }
4880
+
4452
4881
  /**
4453
4882
  * Member types of a same-file, non-generic object type declared by name —
4454
4883
  * an `interface` with no `extends` clause, or a `type X = { … }` alias —
@@ -4520,7 +4949,8 @@ function localObjectMemberTypesFor(ctx: AnalyzerContext): LocalObjectMemberTypes
4520
4949
  * - A member resolves a type when it is a PRIMITIVE (string/number/boolean),
4521
4950
  * a CATALOGUED rich type (`Date`), or a STRUCTURAL shape (array/object,
4522
4951
  * inline or a same-file object type referenced by name) built entirely
4523
- * out of those, recursively (#2677). Unions, functions, and other named
4952
+ * out of those, recursively (#2677), a field of one possibly typed
4953
+ * `T | null` / `T | undefined`. Other unions, functions, and other named
4524
4954
  * types (imports, generics, `Map`, `Set`, …) are left as `unknown` — see
4525
4955
  * `isResolvableMemberType`'s own docstring for why the structural cases
4526
4956
  * are safe to admit and why those three still are not.
@@ -4542,6 +4972,80 @@ function unresolvedDeclaredType(member: DestructuredMemberType | undefined): Pic
4542
4972
  return member && !member.type && member.declared ? { declaredType: member.declared } : {}
4543
4973
  }
4544
4974
 
4975
+ /** Upper bound on alias / intersection hops a type walk follows, a guard against a cycle. */
4976
+ const MAX_TYPE_HOPS = 8
4977
+
4978
+ /**
4979
+ * `ParamInfo.literalKeys` for the member `name` of a props type node: the
4980
+ * member's declared type node, found through a type literal, a same-file
4981
+ * interface or type alias, or an intersection of those (`{ name: N } &
4982
+ * IconProps`), read by {@link literalKeyDomain}. Empty when the member is
4983
+ * not found or its type is not such a union.
4984
+ */
4985
+ function propLiteralKeys(typeNode: ts.TypeNode | undefined, name: string, ctx: AnalyzerContext): Pick<ParamInfo, 'literalKeys'> {
4986
+ const memberType = typeNode ? memberTypeNode(typeNode, name, ctx, 0) : null
4987
+ const literalKeys = memberType ? literalKeyDomain(memberType, ctx) : null
4988
+ return literalKeys ? { literalKeys } : {}
4989
+ }
4990
+
4991
+ function memberTypeNode(typeNode: ts.TypeNode, name: string, ctx: AnalyzerContext, hops: number): ts.TypeNode | null {
4992
+ if (hops > MAX_TYPE_HOPS) return null
4993
+ if (ts.isParenthesizedTypeNode(typeNode)) return memberTypeNode(typeNode.type, name, ctx, hops + 1)
4994
+ if (ts.isIntersectionTypeNode(typeNode)) {
4995
+ for (const part of typeNode.types) {
4996
+ const found = memberTypeNode(part, name, ctx, hops + 1)
4997
+ if (found) return found
4998
+ }
4999
+ return null
5000
+ }
5001
+ const members = ts.isTypeLiteralNode(typeNode) ? typeNode.members : null
5002
+ if (members) return memberSignatureType(members, name, ctx)
5003
+ if (!ts.isTypeReferenceNode(typeNode)) return null
5004
+ const decl = findTypeDeclaration(typeNode.typeName.getText(ctx.sourceFile), ctx.sourceFile)
5005
+ if (!decl) return null
5006
+ if (ts.isInterfaceDeclaration(decl)) return memberSignatureType(decl.members, name, ctx)
5007
+ return memberTypeNode(decl.type, name, ctx, hops + 1)
5008
+ }
5009
+
5010
+ function memberSignatureType(members: ts.NodeArray<ts.TypeElement>, name: string, ctx: AnalyzerContext): ts.TypeNode | null {
5011
+ for (const member of members) {
5012
+ if (ts.isPropertySignature(member) && member.name.getText(ctx.sourceFile) === name) return member.type ?? null
5013
+ }
5014
+ return null
5015
+ }
5016
+
5017
+ /**
5018
+ * The string literals, `null` and `undefined` a type node admits when it
5019
+ * admits nothing else (`'ok' | 'err' | undefined`, or a same-file alias of
5020
+ * such a union), or null.
5021
+ */
5022
+ function literalKeyDomain(typeNode: ts.TypeNode, ctx: AnalyzerContext, hops = 0): ParamInfo['literalKeys'] | null {
5023
+ if (hops > MAX_TYPE_HOPS) return null
5024
+ if (ts.isParenthesizedTypeNode(typeNode)) return literalKeyDomain(typeNode.type, ctx, hops + 1)
5025
+ if (ts.isTypeReferenceNode(typeNode)) {
5026
+ const decl = findTypeDeclaration(typeNode.typeName.getText(ctx.sourceFile), ctx.sourceFile)
5027
+ return decl && ts.isTypeAliasDeclaration(decl) ? literalKeyDomain(decl.type, ctx, hops + 1) : null
5028
+ }
5029
+ if (!ts.isUnionTypeNode(typeNode)) return literalTypeKey(typeNode)
5030
+ const keys: string[] = []
5031
+ const nullish = new Set<'null' | 'undefined'>()
5032
+ for (const part of typeNode.types) {
5033
+ const inner = literalKeyDomain(part, ctx, hops + 1)
5034
+ if (!inner) return null
5035
+ keys.push(...inner.keys)
5036
+ for (const n of inner.nullish) nullish.add(n)
5037
+ }
5038
+ return { keys, nullish: [...nullish] }
5039
+ }
5040
+
5041
+ /** {@link literalKeyDomain} for one non-union, non-reference type node: a string literal, `null` or `undefined`. */
5042
+ function literalTypeKey(typeNode: ts.TypeNode): ParamInfo['literalKeys'] | null {
5043
+ if (typeNode.kind === ts.SyntaxKind.UndefinedKeyword) return { keys: [], nullish: ['undefined'] }
5044
+ if (!ts.isLiteralTypeNode(typeNode)) return null
5045
+ if (typeNode.literal.kind === ts.SyntaxKind.NullKeyword) return { keys: [], nullish: ['null'] }
5046
+ return ts.isStringLiteral(typeNode.literal) ? { keys: [typeNode.literal.text], nullish: [] } : null
5047
+ }
5048
+
4545
5049
  function collectMemberTypes(
4546
5050
  typeNode: ts.TypeNode,
4547
5051
  ctx: AnalyzerContext
@@ -4625,9 +5129,11 @@ function extractPropsFromTypeMembers(
4625
5129
  ? typeNodeToTypeInfo(member.type, ctx.sourceFile)
4626
5130
  : { kind: 'unknown' as const, raw: 'unknown' }
4627
5131
 
5132
+ const literalKeys = member.type ? literalKeyDomain(member.type, ctx) : null
4628
5133
  ctx.propsParams.push({
4629
5134
  name: propName,
4630
5135
  type: propType ?? { kind: 'unknown', raw: 'unknown' },
5136
+ ...(literalKeys && { literalKeys }),
4631
5137
  optional: isOptional,
4632
5138
  defaultValue: undefined,
4633
5139
  })