@barefootjs/jsx 0.39.7 → 0.39.9

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 (192) hide show
  1. package/dist/adapters/callback-method.d.ts +36 -7
  2. package/dist/adapters/callback-method.d.ts.map +1 -1
  3. package/dist/adapters/component-props.d.ts +80 -13
  4. package/dist/adapters/component-props.d.ts.map +1 -1
  5. package/dist/adapters/dsl-template-adapter.d.ts +153 -0
  6. package/dist/adapters/dsl-template-adapter.d.ts.map +1 -0
  7. package/dist/adapters/jsx-adapter.d.ts +4 -0
  8. package/dist/adapters/jsx-adapter.d.ts.map +1 -1
  9. package/dist/adapters/literal-value.d.ts +2 -2
  10. package/dist/adapters/literal-value.d.ts.map +1 -1
  11. package/dist/adapters/loop-plan.d.ts +133 -9
  12. package/dist/adapters/loop-plan.d.ts.map +1 -1
  13. package/dist/adapters/parsed-expr-emitter.d.ts +44 -0
  14. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  15. package/dist/adapters/style-object.d.ts +33 -0
  16. package/dist/adapters/style-object.d.ts.map +1 -0
  17. package/dist/analyzer.d.ts.map +1 -1
  18. package/dist/assignment-target.d.ts +26 -0
  19. package/dist/assignment-target.d.ts.map +1 -0
  20. package/dist/children-nullish.d.ts +22 -0
  21. package/dist/children-nullish.d.ts.map +1 -0
  22. package/dist/errors.d.ts +2 -0
  23. package/dist/errors.d.ts.map +1 -1
  24. package/dist/expression-parser.d.ts +9 -19
  25. package/dist/expression-parser.d.ts.map +1 -1
  26. package/dist/free-refs.d.ts +6 -0
  27. package/dist/free-refs.d.ts.map +1 -1
  28. package/dist/index.d.ts +17 -14
  29. package/dist/index.d.ts.map +1 -1
  30. package/dist/index.js +15040 -13899
  31. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  34. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  36. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  37. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +24 -1
  38. package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
  39. package/dist/ir-to-client-js/control-flow/shared.d.ts +16 -1
  40. package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts +6 -1
  42. package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  45. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/csr-substitute.d.ts +13 -2
  47. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  48. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  49. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  50. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  51. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  53. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  54. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  55. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  56. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  57. package/dist/ir-to-client-js/imports.d.ts +23 -2
  58. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  59. package/dist/ir-to-client-js/phases/props-extraction.d.ts +6 -3
  60. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  61. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +8 -0
  62. package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
  63. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  64. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  65. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  66. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  67. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  68. package/dist/ir-to-client-js/rewrite-props-object.d.ts.map +1 -1
  69. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  70. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  71. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +1 -0
  72. package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
  73. package/dist/ir-to-client-js/types.d.ts +3 -3
  74. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  75. package/dist/ir-to-client-js/utils.d.ts +2 -11
  76. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  77. package/dist/jsx-to-ir.d.ts.map +1 -1
  78. package/dist/nullable-signal-attr.d.ts +40 -10
  79. package/dist/nullable-signal-attr.d.ts.map +1 -1
  80. package/dist/prop-rewrite.d.ts +35 -8
  81. package/dist/prop-rewrite.d.ts.map +1 -1
  82. package/dist/props-binding.d.ts +66 -1
  83. package/dist/props-binding.d.ts.map +1 -1
  84. package/dist/scanner/js-scanner.d.ts.map +1 -1
  85. package/dist/scanner/js-scanner.js +30 -2
  86. package/dist/scope/binding-scope.d.ts +30 -2
  87. package/dist/scope/binding-scope.d.ts.map +1 -1
  88. package/dist/scope/lexical-scope-walk.d.ts +26 -0
  89. package/dist/scope/lexical-scope-walk.d.ts.map +1 -0
  90. package/dist/signal-prop-name-collision.d.ts +6 -5
  91. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  92. package/dist/ssr-defaults.d.ts +28 -0
  93. package/dist/ssr-defaults.d.ts.map +1 -1
  94. package/dist/ssr-seed-plan.d.ts +39 -14
  95. package/dist/ssr-seed-plan.d.ts.map +1 -1
  96. package/dist/types.d.ts +133 -19
  97. package/dist/types.d.ts.map +1 -1
  98. package/dist/value-references.d.ts +21 -0
  99. package/dist/value-references.d.ts.map +1 -1
  100. package/package.json +2 -2
  101. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  102. package/src/__tests__/adapter-output.test.ts +5 -3
  103. package/src/__tests__/analyzer.test.ts +33 -0
  104. package/src/__tests__/arithmetic-lowering.test.ts +48 -0
  105. package/src/__tests__/binding-scope.test.ts +29 -0
  106. package/src/__tests__/children-read.test.ts +226 -0
  107. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  108. package/src/__tests__/component-props.test.ts +68 -1
  109. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  110. package/src/__tests__/create-query.test.ts +1 -1
  111. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  112. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  113. package/src/__tests__/emit-to-string-call.test.ts +58 -0
  114. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  115. package/src/__tests__/expression-parser.test.ts +1 -44
  116. package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +90 -31
  117. package/src/__tests__/loop-plan.test.ts +131 -1
  118. package/src/__tests__/loop-row-child-children-handler.test.ts +129 -0
  119. package/src/__tests__/loop-row-child-children-inner-loop-shadow.test.ts +74 -0
  120. package/src/__tests__/loop-row-child-children-ref.test.ts +117 -0
  121. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  122. package/src/__tests__/props-alias-const.test.ts +60 -1
  123. package/src/__tests__/props-named-callback-param.test.ts +256 -0
  124. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  125. package/src/__tests__/renamed-body-destructure-template.test.ts +86 -0
  126. package/src/__tests__/rewrite-props-object.test.ts +90 -0
  127. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  128. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  129. package/src/__tests__/ssr-defaults.test.ts +19 -1
  130. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  131. package/src/__tests__/style-object-plan.test.ts +54 -0
  132. package/src/__tests__/written-binding-substitution.test.ts +430 -0
  133. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  134. package/src/adapters/callback-method.ts +48 -10
  135. package/src/adapters/component-props.ts +130 -12
  136. package/src/adapters/dsl-template-adapter.ts +259 -0
  137. package/src/adapters/jsx-adapter.ts +12 -6
  138. package/src/adapters/literal-value.ts +2 -2
  139. package/src/adapters/loop-plan.ts +201 -13
  140. package/src/adapters/parsed-expr-emitter.ts +67 -0
  141. package/src/adapters/style-object.ts +61 -0
  142. package/src/analyzer.ts +396 -16
  143. package/src/assignment-target.ts +79 -0
  144. package/src/children-nullish.ts +33 -0
  145. package/src/debug.ts +2 -2
  146. package/src/errors.ts +23 -0
  147. package/src/expression-parser.ts +56 -53
  148. package/src/free-refs.ts +28 -17
  149. package/src/index.ts +31 -10
  150. package/src/ir-to-client-js/compute-inlinability.ts +35 -5
  151. package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +21 -5
  152. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  153. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  154. package/src/ir-to-client-js/control-flow/plan/loop.ts +25 -1
  155. package/src/ir-to-client-js/control-flow/shared.ts +41 -3
  156. package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +23 -3
  157. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  158. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  159. package/src/ir-to-client-js/csr-substitute.ts +82 -24
  160. package/src/ir-to-client-js/emit-reactive.ts +3 -3
  161. package/src/ir-to-client-js/emit-registration.ts +34 -58
  162. package/src/ir-to-client-js/generate-init.ts +17 -1
  163. package/src/ir-to-client-js/html-template.ts +48 -57
  164. package/src/ir-to-client-js/identifiers.ts +75 -24
  165. package/src/ir-to-client-js/imports.ts +56 -19
  166. package/src/ir-to-client-js/index.ts +2 -1
  167. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  168. package/src/ir-to-client-js/phases/props-extraction.ts +39 -17
  169. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  170. package/src/ir-to-client-js/plan/build-static-array-child-init.ts +7 -0
  171. package/src/ir-to-client-js/plan/static-array-child-init.ts +8 -0
  172. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  173. package/src/ir-to-client-js/reactivity.ts +2 -2
  174. package/src/ir-to-client-js/rewrite-destructured-props.ts +22 -5
  175. package/src/ir-to-client-js/rewrite-props-object.ts +14 -8
  176. package/src/ir-to-client-js/safe-html.ts +29 -35
  177. package/src/ir-to-client-js/stringify/static-array-child-init.ts +4 -1
  178. package/src/ir-to-client-js/types.ts +3 -2
  179. package/src/ir-to-client-js/utils.ts +42 -122
  180. package/src/jsx-to-ir.ts +310 -90
  181. package/src/nullable-signal-attr.ts +149 -33
  182. package/src/prop-rewrite.ts +72 -72
  183. package/src/props-binding.ts +90 -3
  184. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  185. package/src/scanner/js-scanner.ts +64 -4
  186. package/src/scope/binding-scope.ts +34 -3
  187. package/src/scope/lexical-scope-walk.ts +167 -0
  188. package/src/signal-prop-name-collision.ts +50 -24
  189. package/src/ssr-defaults.ts +47 -20
  190. package/src/ssr-seed-plan.ts +103 -23
  191. package/src/types.ts +140 -20
  192. package/src/value-references.ts +132 -0
@@ -5,15 +5,19 @@
5
5
  * Every DSL adapter assembles them the same way: callback props and `ref`
6
6
  * are client-only and dropped; a named JSX-valued prop is captured as
7
7
  * HTML; `{...props}` (the component's own props object, which no DSL scope
8
- * holds as one value) enumerates the props params; any other spread is
9
- * folded in at its source position, so a later entry wins on a key
10
- * conflict, as in `{...a, ...b}`; then the compiler-controlled `_bf_slot`
11
- * and `children` entries come last, so a spread can never override them.
8
+ * holds as one value) enumerates the props params, and a param that
9
+ * something earlier in the call may have set is carried only when the
10
+ * caller passed it ({@link propsSpreadParam}); any other spread is folded
11
+ * in at its source position, so a later entry wins on a key conflict, as in
12
+ * `{...a, ...b}`; then the compiler-controlled `_bf_slot` and `children`
13
+ * entries come last, so a spread can never override them.
12
14
  * {@link planComponentProps} makes those decisions once. An adapter spells
13
15
  * the entries and spreads through {@link spellComponentProps}, keeps its
14
16
  * own capture mechanism (`{% set %}…{% endset %}`, `_erbout.slice!`,
15
17
  * `begin … end`, a Kolon macro), and folds the spelled segments into its
16
- * own hash literal.
18
+ * own hash literal. An adapter that builds the child's input as a typed
19
+ * literal at compile time instead (Go's `<Child>Input{...}`) reads the same
20
+ * plan one key at a time through {@link resolveComponentPropKeys}.
17
21
  */
18
22
 
19
23
  import { resolveJsxChildrenProp } from '@barefootjs/shared'
@@ -33,16 +37,60 @@ export type ComponentPropEntry =
33
37
  /** The forwarded children (nested `<Box>…</Box>`, or `children={<jsx/>}`): captured as HTML. */
34
38
  | { kind: 'children'; children: IRNode[] }
35
39
 
36
- /** A run of entries, or a spread folded in at its source position. */
40
+ /**
41
+ * A run of entries, a spread folded in at its source position, or one param
42
+ * of `{...props}` that the spread carries only when the caller passed it
43
+ * ({@link propsSpreadParam}). An adapter folds a `present-param` in like a
44
+ * spread of a one-key (or empty) hash.
45
+ */
37
46
  export type ComponentPropSegment =
38
47
  | { kind: 'entries'; entries: ComponentPropEntry[] }
39
48
  | { kind: 'spread'; value: SpreadAttr }
49
+ | { kind: 'present-param'; name: string }
50
+
51
+ /** A props param as `{...props}` enumerates it. */
52
+ export interface ComponentPropsParam {
53
+ name: string
54
+ /** `false` for a required param, which the caller always passes. Unknown counts as optional. */
55
+ optional?: boolean
56
+ }
40
57
 
41
58
  export interface ComponentPropsOptions {
42
59
  /** The SolidJS-style props identifier (`function C(props: P)`), if any. */
43
60
  propsObjectName: string | null
44
61
  /** The analyzer-extracted props params, which `{...props}` enumerates. */
45
- propsParams: ReadonlyArray<{ name: string }>
62
+ propsParams: ReadonlyArray<ComponentPropsParam>
63
+ }
64
+
65
+ /** What a call has set before a `{...props}` spread, as far as the compiler can see. */
66
+ export interface EarlierComponentProps {
67
+ /** The keys an earlier entry sets. */
68
+ keys: ReadonlySet<string>
69
+ /** Whether an earlier spread whose keys are unknown may have set any key. */
70
+ spread: boolean
71
+ }
72
+
73
+ /**
74
+ * How `{...props}` carries one param. JS spreads only the keys the props
75
+ * object has, so a param the caller left out keeps whatever an earlier entry
76
+ * or spread set: `<Tag size="s" {...props} />` keeps `size="s"` when the
77
+ * caller passes no `size`.
78
+ *
79
+ * - `'entry'`: an ordinary entry. Either nothing earlier can set the key, so
80
+ * an absent param and a nil one read the same to the child, or the param is
81
+ * required, so the caller always passes it and it always wins.
82
+ * - `'present'`: carried only when the caller passed it, so an absent param
83
+ * leaves the earlier value alone.
84
+ *
85
+ * A template backend reads an absent prop and an explicit `undefined` or
86
+ * `null` one as the same nil, so "passed" is spelled "not nil" there: a
87
+ * caller that passes `undefined`/`null` keeps the earlier value, where JS
88
+ * would override it with the nil (limitation
89
+ * `props-spread-explicit-null-override`).
90
+ */
91
+ export function propsSpreadParam(param: ComponentPropsParam, earlier: EarlierComponentProps): 'entry' | 'present' {
92
+ if (param.optional === false) return 'entry'
93
+ return earlier.spread || earlier.keys.has(param.name) ? 'present' : 'entry'
46
94
  }
47
95
 
48
96
  /** The key an entry sets in the props hash. */
@@ -54,12 +102,17 @@ export function componentPropKey(entry: ComponentPropEntry): string {
54
102
 
55
103
  /**
56
104
  * The ordered props segments for `comp`. The first segment is always an
57
- * (possibly empty) entries segment, and a spread is followed by a new one
58
- * only when an entry comes after it.
105
+ * (possibly empty) entries segment, and a spread or a `present-param` is
106
+ * followed by a new one only when an entry comes after it.
59
107
  */
60
- export function planComponentProps(comp: IRComponent, options: ComponentPropsOptions): ComponentPropSegment[] {
108
+ export function planComponentProps(
109
+ comp: Pick<IRComponent, 'props' | 'children' | 'slotId' | 'loopItemRoot'>,
110
+ options: ComponentPropsOptions,
111
+ ): ComponentPropSegment[] {
61
112
  const segments: ComponentPropSegment[] = [{ kind: 'entries', entries: [] }]
113
+ const earlier = { keys: new Set<string>(), spread: false }
62
114
  const push = (entry: ComponentPropEntry) => {
115
+ earlier.keys.add(componentPropKey(entry))
63
116
  const last = segments[segments.length - 1]!
64
117
  if (last.kind !== 'entries') {
65
118
  segments.push({ kind: 'entries', entries: [entry] })
@@ -72,6 +125,19 @@ export function planComponentProps(comp: IRComponent, options: ComponentPropsOpt
72
125
  if (at === -1) last.entries.push(entry)
73
126
  else last.entries[at] = entry
74
127
  }
128
+ const pushPropsSpread = () => {
129
+ // Every param is decided against what came before the spread, not
130
+ // against the params this same spread has already pushed.
131
+ const before: EarlierComponentProps = { keys: new Set(earlier.keys), spread: earlier.spread }
132
+ for (const param of options.propsParams) {
133
+ if (propsSpreadParam(param, before) === 'entry') {
134
+ push({ kind: 'props-param', name: param.name })
135
+ } else {
136
+ earlier.keys.add(param.name)
137
+ segments.push({ kind: 'present-param', name: param.name })
138
+ }
139
+ }
140
+ }
75
141
  for (const p of comp.props) {
76
142
  // Callback props and `ref` are client-only for SSR: Hono renders
77
143
  // neither, and the client JS wires them at hydration.
@@ -81,8 +147,9 @@ export function planComponentProps(comp: IRComponent, options: ComponentPropsOpt
81
147
  if (p.name !== 'children') push({ kind: 'named-slot', name: p.name, children: p.value.children })
82
148
  } else if (p.value.kind === 'spread') {
83
149
  if (options.propsObjectName !== null && options.propsObjectName === p.value.expr.trim()) {
84
- for (const param of options.propsParams) push({ kind: 'props-param', name: param.name })
150
+ pushPropsSpread()
85
151
  } else {
152
+ earlier.spread = true
86
153
  segments.push({ kind: 'spread', value: p.value })
87
154
  }
88
155
  } else {
@@ -96,7 +163,7 @@ export function planComponentProps(comp: IRComponent, options: ComponentPropsOpt
96
163
  return segments
97
164
  }
98
165
 
99
- /** A spelled segment: the entries' hash-literal parts, or the spread's expression. */
166
+ /** A spelled segment: the entries' hash-literal parts, or the expression a spread folds in. */
100
167
  export type SpelledComponentPropSegment = { kind: 'entries'; parts: string[] } | { kind: 'spread'; expr: string }
101
168
 
102
169
  export interface ComponentPropSpelling {
@@ -104,6 +171,12 @@ export interface ComponentPropSpelling {
104
171
  entry(entry: ComponentPropEntry): string
105
172
  /** The expression a spread folds in. */
106
173
  spread(value: SpreadAttr): string
174
+ /**
175
+ * The expression a `present-param` segment folds in like a spread: a
176
+ * one-key hash `{ name: <param> }` when the param is not nil, an empty
177
+ * hash when it is.
178
+ */
179
+ presentParam(name: string): string
107
180
  }
108
181
 
109
182
  /**
@@ -116,6 +189,7 @@ export function spellComponentProps(
116
189
  ): SpelledComponentPropSegment[] {
117
190
  return segments.map((segment) => {
118
191
  if (segment.kind === 'spread') return { kind: 'spread', expr: spelling.spread(segment.value) }
192
+ if (segment.kind === 'present-param') return { kind: 'spread', expr: spelling.presentParam(segment.name) }
119
193
  const parts: string[] = []
120
194
  for (const entry of segment.entries) {
121
195
  const part = spelling.entry(entry)
@@ -125,6 +199,50 @@ export function spellComponentProps(
125
199
  })
126
200
  }
127
201
 
202
+ /**
203
+ * One key of the props hash, resolved at compile time: the latest of
204
+ * `presentParams` the caller passed, else `base`.
205
+ */
206
+ export interface ResolvedComponentProp {
207
+ key: string
208
+ /** The last entry that sets the key unconditionally, or null when none does. */
209
+ base: ComponentPropEntry | null
210
+ /** The `{...props}` params that override `base` when passed, earliest first. */
211
+ presentParams: string[]
212
+ }
213
+
214
+ /**
215
+ * A plan resolved one key at a time, in the order the keys are first set,
216
+ * for an adapter that builds the child's input as a typed literal at
217
+ * compile time rather than merging hashes at render time. Null when the
218
+ * plan folds in a spread whose keys are unknown: only a render-time merge
219
+ * can resolve that.
220
+ */
221
+ export function resolveComponentPropKeys(segments: readonly ComponentPropSegment[]): ResolvedComponentProp[] | null {
222
+ const byKey = new Map<string, ResolvedComponentProp>()
223
+ const at = (key: string): ResolvedComponentProp => {
224
+ let resolved = byKey.get(key)
225
+ if (!resolved) {
226
+ resolved = { key, base: null, presentParams: [] }
227
+ byKey.set(key, resolved)
228
+ }
229
+ return resolved
230
+ }
231
+ for (const segment of segments) {
232
+ if (segment.kind === 'spread') return null
233
+ if (segment.kind === 'present-param') {
234
+ at(segment.name).presentParams.push(segment.name)
235
+ continue
236
+ }
237
+ for (const entry of segment.entries) {
238
+ const resolved = at(componentPropKey(entry))
239
+ resolved.base = entry
240
+ resolved.presentParams = []
241
+ }
242
+ }
243
+ return [...byKey.values()]
244
+ }
245
+
128
246
  /** Whether a spelled plan passes no props at all. */
129
247
  export function isEmptyComponentProps(segments: readonly SpelledComponentPropSegment[]): boolean {
130
248
  return segments.every((segment) => segment.kind === 'entries' && segment.parts.length === 0)
@@ -0,0 +1,259 @@
1
+ /**
2
+ * The `generate()` the eight DSL template adapters (Blade, ERB, Jinja,
3
+ * Mojolicious, Pebble, MiniJinja, Twig, Xslate) share (#3475), with the
4
+ * per-compile state it sets up. Each adapter renders the nodes in its own
5
+ * template language; how one compile begins and ends lives here once.
6
+ */
7
+
8
+ import { augmentInheritedPropAccesses, collectModuleStringConsts } from '../augment-inherited-props.ts'
9
+ import { buildImportAliasMap } from '../ir-to-client-js/component-scope.ts'
10
+ import { prepareLoweringMatchers, type LoweringMatcher } from '../lowering-registry.ts'
11
+ import {
12
+ collectNullableSignalGetters,
13
+ collectNullishAttrContext,
14
+ type NullishAttrContext,
15
+ } from '../nullable-signal-attr.ts'
16
+ import { BindingScope } from '../scope/binding-scope.ts'
17
+ import { rootPropAliasNames } from '../scope/root-prop-alias.ts'
18
+ import type { CompilerError, ComponentIR, IRIfStatement, IRMetadata } from '../types.ts'
19
+ import { collectImportedLoopChildComponentErrors } from './component-tree.ts'
20
+ import { computedConstContext, type ComputedConstContext } from './computed-const.ts'
21
+ import { searchParamsLocalNames } from './env-signal.ts'
22
+ import { BaseAdapter, type AdapterGenerateOptions, type AdapterOutput } from './interface.ts'
23
+ import { collectBooleanTypedProps, collectNullableOptionalProps } from './prop-classes.ts'
24
+ import { templateNameCollisionErrors } from './template-name-collisions.ts'
25
+
26
+ /**
27
+ * How an adapter that renames reserved names spells a source identifier as
28
+ * a template variable, and the engine name its collision diagnostic uses.
29
+ */
30
+ export interface TemplateIdentifierSpelling {
31
+ /** The adapter's mangling (`jinjaIdent`, `twigIdent`, …). */
32
+ ident(name: string): string
33
+ /** The engine name in the diagnostic ("Jinja", "MiniJinja", …). */
34
+ label: string
35
+ }
36
+
37
+ export abstract class DslTemplateAdapter extends BaseAdapter {
38
+ // ===========================================================================
39
+ // Per-compile state, set at `generate()` entry
40
+ // ===========================================================================
41
+
42
+ protected componentName: string = ''
43
+ /** Diagnostics collected while rendering, merged into `ir.errors` at the end. */
44
+ protected errors: CompilerError[] = []
45
+ /**
46
+ * SolidJS-style props identifier (`function(props: P)`). The spread
47
+ * emission builds a props-object bag from it without re-walking the IR.
48
+ */
49
+ protected propsObjectName: string | null = null
50
+ /**
51
+ * Name of the destructured `...rest` binding (`function X({ ...rest })`),
52
+ * if any. A closed-type rest-expanded attribute's expression is
53
+ * `${restPropsName}.${key}` (`expandSpreadAttribute`, #3057). Stripping
54
+ * this prefix the same way `propsObjectName.` is stripped lets the
55
+ * nullable-optional-props guard recognise it as a bare optional reference
56
+ * instead of falling through to unconditional emission.
57
+ */
58
+ protected restPropsName: string | null = null
59
+ protected propsParams: { name: string; optional: boolean }[] = []
60
+ /** Props whose declared TS type is boolean (`collectBooleanTypedProps`). */
61
+ protected booleanTypedProps: Set<string> = new Set()
62
+ /** Names (signal getters + props) whose value is a string (`stringValueNamesFor`). */
63
+ protected stringValueNames: Set<string> = new Set()
64
+ /**
65
+ * Module-scope pure-string consts (`const x = 'literal'`), keyed by name →
66
+ * unescaped value. A className template literal that references such a
67
+ * const (`className={`${x} ${className}`}`) must inline the literal: the
68
+ * const is module-scope, so it never reaches the per-render context.
69
+ */
70
+ protected moduleStringConsts: Map<string, string> = new Map()
71
+ /**
72
+ * (#1922) Local binding names the request-scoped `searchParams()` env
73
+ * signal is imported under (handles `import { searchParams as sp }`). When
74
+ * non-empty the emitter lowers a `<binding>().get(k)` call to a real method
75
+ * call on the per-request `searchParams` reader instead of the generic
76
+ * deref. Read by the top-level ParsedExpr emitter.
77
+ */
78
+ protected _searchParamsLocals: Set<string> = new Set()
79
+ /**
80
+ * Call-lowering matchers active for this component (#2057), read by the
81
+ * top-level emitter. Covers both userland plugins and the compiler's
82
+ * built-in plugins (e.g. `queryHref`, #2042): one uniform path, no per-API
83
+ * branch.
84
+ */
85
+ protected _loweringMatchers: LoweringMatcher[] = []
86
+ /** The component's computed consts, inlined where a template reads them (#3494). */
87
+ protected computedConsts: ComputedConstContext | null = null
88
+ /**
89
+ * Local + module constants from the IR, used by the conditional-spread and
90
+ * `Record<staticKeys, scalar>[propKey]` lowering paths (#textarea /
91
+ * #checkbox): the spread emission resolves a bare local const
92
+ * (`const sizeAttrs = size ? {…} : {}`) to its initializer text.
93
+ */
94
+ protected localConstants: IRMetadata['localConstants'] = []
95
+ /** Each prop's collision-free root alias (#3314), decided once per component. */
96
+ protected rootPropAliases: ReadonlyMap<string, string> = new Map()
97
+ /**
98
+ * The one canonical, position-accurate "names bound by an enclosing loop
99
+ * callback" service (#2482 Stage 2). Every shadow-guard site reads this
100
+ * one threaded, immutable scope: `renderLoop` enters the row with
101
+ * `enterLoopRow` around the loop's children and restores the outer scope
102
+ * by reference afterwards, mirroring `ctx.scope` in `jsx-to-ir.ts`.
103
+ * `IRLoop` structurally satisfies `LoopBindingSource`, so `renderLoop`
104
+ * passes the loop node straight to `enterLoopRow`.
105
+ */
106
+ protected scope: BindingScope = BindingScope.EMPTY
107
+ /**
108
+ * Optional, no-default props that are absent when the caller omits them
109
+ * (`collectNullableOptionalProps`). A bare-reference attribute of one is
110
+ * guarded with the template's presence test, so the attribute drops rather
111
+ * than rendering `attr=""` (Hono-style nullish omission, e.g. textarea's
112
+ * `rows`).
113
+ */
114
+ protected nullableOptionalProps: Set<string> = new Set()
115
+ /** Getters of nullable signals (`collectNullableSignalGetters`, #3304). */
116
+ protected nullableSignalGetters: Set<string> = new Set()
117
+ /** Signals and memos `attrValueMayBeNullish` reads (#3322). */
118
+ protected nullishAttrCtx: NullishAttrContext = { nullableSignals: new Set(), memos: new Map() }
119
+ /**
120
+ * Local alias -> declared/exported name for imported components (#2822,
121
+ * the SSR-side counterpart of #2777's client-JS registry-key fix). A child
122
+ * referenced under an import alias (`import { Foo as Bar }`, `<Bar/>`)
123
+ * must build its cross-template call against the child's own declared
124
+ * name (`Foo`, what `foo.tsx` registers its template as), never the
125
+ * caller-local binding. Read by `childTemplateName`.
126
+ */
127
+ protected importAliases: Map<string, string> = new Map()
128
+ /** Numbers the children captures of a child component that has no slot id. */
129
+ protected childrenCaptureCounter = 0
130
+
131
+ // ===========================================================================
132
+ // What each adapter supplies
133
+ // ===========================================================================
134
+
135
+ /** The adapter's name in the BF103 imported-loop-child diagnostic ("The Jinja adapter emits …"). */
136
+ protected abstract readonly loopChildDiagnosticName: string
137
+ /**
138
+ * For an adapter that renames reserved names: two source names the
139
+ * renaming turns into one template variable would read the same value, so
140
+ * `generate()` refuses them (#3404). `null` when the adapter renames none.
141
+ */
142
+ protected readonly templateIdentifierSpelling: TemplateIdentifierSpelling | null = null
143
+ /** The names whose value is a string, for `stringValueNames`. */
144
+ protected abstract stringValueNamesFor(ir: ComponentIR): Set<string>
145
+ /**
146
+ * Sets the adapter's own per-compile state. Runs after the shared state
147
+ * above and before any diagnostic or rendering.
148
+ */
149
+ protected resetAdapterState(_ir: ComponentIR): void {}
150
+
151
+ /** `render()` under `scope`, the current scope restored afterwards. */
152
+ protected renderInScope<T>(scope: BindingScope, render: () => T): T {
153
+ const outer = this.scope
154
+ this.scope = scope
155
+ try {
156
+ return render()
157
+ } finally {
158
+ this.scope = outer
159
+ }
160
+ }
161
+ /** The root `if` statement of a component with conditional returns. */
162
+ protected abstract renderIfStatement(ifStmt: IRIfStatement): string
163
+ /** The script registrations the template starts with. */
164
+ protected abstract generateScriptRegistrations(
165
+ ir: ComponentIR,
166
+ scriptBaseName?: string,
167
+ scriptAssets?: string[],
168
+ preloadAssets?: string[],
169
+ ): string
170
+ /**
171
+ * SSR context consumers (`const x = useContext(Ctx)`): seeds each local
172
+ * from the active provider value, or the `createContext` default. The
173
+ * provider side pushes the value via `emitProvider` (#1297).
174
+ */
175
+ protected abstract contextConsumerSeed(ir: ComponentIR): string
176
+ /**
177
+ * Prop/signal-derived memos with a `null` static SSR default (e.g.
178
+ * `createMemo(() => props.value * 10)`), computed in-template from the
179
+ * already-seeded prop/signal vars, mirroring Go's generated child
180
+ * constructor (#1297).
181
+ */
182
+ protected abstract derivedMemoSeed(ir: ComponentIR): string
183
+
184
+ generate(ir: ComponentIR, options?: AdapterGenerateOptions): AdapterOutput {
185
+ this.resetCompileState(ir)
186
+ this.collectCompileErrors(ir, options)
187
+
188
+ const templateBody = ir.root.type === 'if-statement'
189
+ ? this.renderIfStatement(ir.root as IRIfStatement)
190
+ : this.renderNode(ir.root)
191
+ const scriptReg = options?.skipScriptRegistration
192
+ ? ''
193
+ : this.generateScriptRegistrations(ir, options?.scriptBaseName, options?.scriptAssets, options?.preloadAssets)
194
+ const ctxSeed = this.contextConsumerSeed(ir)
195
+ const memoSeed = this.derivedMemoSeed(ir)
196
+ const template = `${scriptReg}${ctxSeed}${memoSeed}${templateBody}\n`
197
+
198
+ if (this.errors.length > 0) {
199
+ ir.errors.push(...this.errors)
200
+ }
201
+
202
+ // A DSL template has no JS-style imports / types / default-export
203
+ // sections. The `templatesPerComponent` mode emits one file per
204
+ // component using the raw `template` value; sections are populated for
205
+ // contract uniformity so the compiler never has to string-parse the
206
+ // template.
207
+ return {
208
+ template,
209
+ sections: { imports: '', types: '', component: template, defaultExport: '' },
210
+ extension: this.extension,
211
+ }
212
+ }
213
+
214
+ private resetCompileState(ir: ComponentIR): void {
215
+ this.componentName = ir.metadata.componentName
216
+ this.propsObjectName = ir.metadata.propsObjectName ?? null
217
+ this.restPropsName = ir.metadata.restPropsName ?? null
218
+ // (#checkbox) Enumerate the props-object pattern's inherited attribute
219
+ // accesses (`props.className`/`id`/`disabled`) into propsParams, before
220
+ // deriving `nullableOptionalProps` below, so a bare optional attribute
221
+ // like `id={props.id}` gets the template's presence guard. This mutates
222
+ // the IR: a harness that serialized it before `generate` doesn't see it.
223
+ augmentInheritedPropAccesses(ir)
224
+ this.propsParams = ir.metadata.propsParams.map(p => ({ name: p.name, optional: p.optional }))
225
+ this.booleanTypedProps = collectBooleanTypedProps(ir)
226
+ this.localConstants = ir.metadata.localConstants ?? []
227
+ this.rootPropAliases = rootPropAliasNames(ir, this.propsParams.map(p => p.name))
228
+ this.scope = BindingScope.EMPTY
229
+ this.nullableOptionalProps = collectNullableOptionalProps(ir)
230
+ this.nullableSignalGetters = collectNullableSignalGetters(ir)
231
+ this.nullishAttrCtx = collectNullishAttrContext(ir)
232
+ this.stringValueNames = this.stringValueNamesFor(ir)
233
+ this.moduleStringConsts = collectModuleStringConsts(ir.metadata.localConstants)
234
+ this._searchParamsLocals = searchParamsLocalNames(ir.metadata)
235
+ this._loweringMatchers = prepareLoweringMatchers(ir.metadata)
236
+ this.computedConsts = computedConstContext(ir.metadata, name => this.scope.isBound(name))
237
+ this.importAliases = buildImportAliasMap(ir.metadata.imports ?? [])
238
+ this.childrenCaptureCounter = 0
239
+ this.errors = []
240
+ this.resetAdapterState(ir)
241
+ }
242
+
243
+ private collectCompileErrors(ir: ComponentIR, options?: AdapterGenerateOptions): void {
244
+ const spelling = this.templateIdentifierSpelling
245
+ if (spelling) {
246
+ const propNames = this.propsParams.map(p => p.name)
247
+ this.errors.push(...templateNameCollisionErrors(ir, propNames, spelling.ident, spelling.label, this.componentName))
248
+ }
249
+ // A child component referenced inside a loop body that is imported from
250
+ // a sibling .tsx renders as a cross-template call, which resolves only if
251
+ // the sibling template is registered alongside the parent at render
252
+ // time. Surface it loudly here, unless the caller (e.g. the barefoot
253
+ // CLI) guarantees that every sibling template is registered on the same
254
+ // template instance.
255
+ if (!options?.siblingTemplatesRegistered) {
256
+ this.errors.push(...collectImportedLoopChildComponentErrors(ir, this.componentName, this.loopChildDiagnosticName))
257
+ }
258
+ }
259
+ }
@@ -258,11 +258,11 @@ export abstract class JsxAdapter extends BaseAdapter {
258
258
  lines.push(` ${keyword} ${constant.name}${typeAnnotation}`)
259
259
  continue
260
260
  }
261
- const value = constant.value.trim()
262
- // Skip client-only constructs in SSR:
261
+ // Skip client-only constructs in SSR (`ConstantInfo.systemConstructKind`,
262
+ // decided by the analyzer from the initializer's AST, #3542):
263
263
  // - createContext() — only used client-side via provideContext/useContext
264
264
  // - new WeakMap() — client-side cross-component shared state
265
- if (/^createContext\b/.test(value) || /^new WeakMap\b/.test(value)) continue
265
+ if (constant.systemConstructKind) continue
266
266
 
267
267
  // Skip unreachable constants (only used in event handler code paths)
268
268
  if (!reachable.has(constant.name)) continue
@@ -489,9 +489,8 @@ export abstract class JsxAdapter extends BaseAdapter {
489
489
  entries.push({ line: c.loc.start.line, text: `${exportKw}${keyword} ${c.name}${typeAnnotation}` })
490
490
  continue
491
491
  }
492
- const trimmed = c.value.trim()
493
- if (/^new WeakMap\b/.test(trimmed)) continue
494
- if (c.isExported && /^createContext\b/.test(trimmed)) continue
492
+ if (c.systemConstructKind === 'weakMap') continue
493
+ if (c.isExported && c.systemConstructKind === 'createContext') continue
495
494
  const value = preserveTypes ? (c.typedValue ?? c.value) : c.value
496
495
  // Preserve an explicit module-scope `let` type annotation from source
497
496
  // (#2589) — see the function-scope sibling above for rationale. `const`
@@ -565,8 +564,15 @@ export abstract class JsxAdapter extends BaseAdapter {
565
564
  * `expr` (a presence peel, a prop-ref rewrite) fails the identity check
566
565
  * and wins, so this can only ever add the annotation, never undo a
567
566
  * downstream edit.
567
+ *
568
+ * The same identity rule brings back the author's own type syntax
569
+ * (`value={store as never}`, #2573): `typed.tsx` is written only while
570
+ * `expr` is still the text it was captured beside.
568
571
  */
569
572
  protected expressionValueToJs(value: Extract<AttrValue, { kind: 'expression' }>): string {
573
+ if (this.jsxConfig.preserveTypes && value.typed && value.expr === value.typed.forExpr) {
574
+ return value.typed.tsx
575
+ }
570
576
  if (
571
577
  this.jsxConfig.preserveTypes &&
572
578
  value.parts &&
@@ -8,7 +8,7 @@
8
8
  */
9
9
 
10
10
  import type { ParsedExpr } from '../expression-parser.ts'
11
- import type { TypeInfo } from '../types.ts'
11
+ import type { TypeInfo, JsSourceText } from '../types.ts'
12
12
 
13
13
  /** True when `type` is the `string` primitive. */
14
14
  export function isStringTypeInfo(type: TypeInfo | undefined): boolean {
@@ -16,7 +16,7 @@ export function isStringTypeInfo(type: TypeInfo | undefined): boolean {
16
16
  }
17
17
 
18
18
  /** True when `initialValue` is a bare string-literal expression. */
19
- export function isBareStringLiteral(initialValue: string | undefined): boolean {
19
+ export function isBareStringLiteral(initialValue: JsSourceText | undefined): boolean {
20
20
  if (!initialValue) return false
21
21
  const v = initialValue.trim()
22
22
  return (v.startsWith("'") && v.endsWith("'")) || (v.startsWith('"') && v.endsWith('"'))