@barefootjs/jsx 0.39.7 → 0.39.8

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 (146) hide show
  1. package/dist/adapters/callback-method.d.ts +17 -0
  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 +151 -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/parsed-expr-emitter.d.ts +27 -0
  12. package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
  13. package/dist/adapters/style-object.d.ts +33 -0
  14. package/dist/adapters/style-object.d.ts.map +1 -0
  15. package/dist/analyzer.d.ts.map +1 -1
  16. package/dist/children-nullish.d.ts +22 -0
  17. package/dist/children-nullish.d.ts.map +1 -0
  18. package/dist/errors.d.ts +1 -0
  19. package/dist/errors.d.ts.map +1 -1
  20. package/dist/expression-parser.d.ts +9 -19
  21. package/dist/expression-parser.d.ts.map +1 -1
  22. package/dist/free-refs.d.ts +6 -0
  23. package/dist/free-refs.d.ts.map +1 -1
  24. package/dist/index.d.ts +14 -11
  25. package/dist/index.d.ts.map +1 -1
  26. package/dist/index.js +14685 -14000
  27. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  28. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +2 -1
  29. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts +2 -2
  31. package/dist/ir-to-client-js/control-flow/plan/insert.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  33. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +10 -9
  34. package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
  35. package/dist/ir-to-client-js/csr-substitute.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/emit-reactive.d.ts +1 -1
  37. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/emit-registration.d.ts +10 -8
  39. package/dist/ir-to-client-js/emit-registration.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  41. package/dist/ir-to-client-js/html-template.d.ts +0 -9
  42. package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/identifiers.d.ts +6 -8
  44. package/dist/ir-to-client-js/identifiers.d.ts.map +1 -1
  45. package/dist/ir-to-client-js/imports.d.ts +23 -2
  46. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  47. package/dist/ir-to-client-js/phases/props-extraction.d.ts +3 -2
  48. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  49. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +1 -1
  50. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  51. package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
  52. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +1 -1
  53. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -1
  54. package/dist/ir-to-client-js/safe-html.d.ts +20 -2
  55. package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
  56. package/dist/ir-to-client-js/types.d.ts +3 -3
  57. package/dist/ir-to-client-js/types.d.ts.map +1 -1
  58. package/dist/ir-to-client-js/utils.d.ts +2 -11
  59. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  60. package/dist/jsx-to-ir.d.ts.map +1 -1
  61. package/dist/nullable-signal-attr.d.ts +40 -10
  62. package/dist/nullable-signal-attr.d.ts.map +1 -1
  63. package/dist/prop-rewrite.d.ts +18 -0
  64. package/dist/prop-rewrite.d.ts.map +1 -1
  65. package/dist/props-binding.d.ts +9 -1
  66. package/dist/props-binding.d.ts.map +1 -1
  67. package/dist/scanner/js-scanner.d.ts.map +1 -1
  68. package/dist/scanner/js-scanner.js +30 -2
  69. package/dist/signal-prop-name-collision.d.ts +6 -5
  70. package/dist/signal-prop-name-collision.d.ts.map +1 -1
  71. package/dist/ssr-defaults.d.ts +28 -0
  72. package/dist/ssr-defaults.d.ts.map +1 -1
  73. package/dist/ssr-seed-plan.d.ts +39 -14
  74. package/dist/ssr-seed-plan.d.ts.map +1 -1
  75. package/dist/types.d.ts +108 -18
  76. package/dist/types.d.ts.map +1 -1
  77. package/dist/value-references.d.ts +21 -0
  78. package/dist/value-references.d.ts.map +1 -1
  79. package/package.json +2 -2
  80. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +18 -18
  81. package/src/__tests__/adapter-output.test.ts +5 -3
  82. package/src/__tests__/analyzer.test.ts +33 -0
  83. package/src/__tests__/arithmetic-lowering.test.ts +44 -0
  84. package/src/__tests__/children-read.test.ts +226 -0
  85. package/src/__tests__/client-template-escape-soundness.test.ts +31 -1
  86. package/src/__tests__/component-props.test.ts +68 -1
  87. package/src/__tests__/constant-inlining-tree.test.ts +136 -0
  88. package/src/__tests__/destructure-default-reads-earlier-param.test.ts +138 -0
  89. package/src/__tests__/dsl-template-adapter.test.ts +173 -0
  90. package/src/__tests__/event-handler-verbatim.test.ts +73 -0
  91. package/src/__tests__/expression-parser.test.ts +1 -44
  92. package/src/__tests__/nullable-signal-attr.test.ts +67 -3
  93. package/src/__tests__/reference-graph-identifiers.test.ts +161 -0
  94. package/src/__tests__/runtime-import-detection.test.ts +134 -0
  95. package/src/__tests__/signal-prop-name-collision.test.ts +30 -0
  96. package/src/__tests__/ssr-defaults.test.ts +19 -1
  97. package/src/__tests__/ssr-seed-plan.test.ts +119 -0
  98. package/src/__tests__/style-object-plan.test.ts +54 -0
  99. package/src/__tests__/zero-param-helper-inline.test.ts +57 -0
  100. package/src/adapters/callback-method.ts +23 -0
  101. package/src/adapters/component-props.ts +130 -12
  102. package/src/adapters/dsl-template-adapter.ts +248 -0
  103. package/src/adapters/jsx-adapter.ts +12 -6
  104. package/src/adapters/literal-value.ts +2 -2
  105. package/src/adapters/parsed-expr-emitter.ts +34 -0
  106. package/src/adapters/style-object.ts +61 -0
  107. package/src/analyzer.ts +114 -15
  108. package/src/children-nullish.ts +33 -0
  109. package/src/debug.ts +2 -2
  110. package/src/errors.ts +12 -0
  111. package/src/expression-parser.ts +56 -53
  112. package/src/free-refs.ts +28 -17
  113. package/src/index.ts +18 -8
  114. package/src/ir-to-client-js/compute-inlinability.ts +29 -2
  115. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +2 -1
  116. package/src/ir-to-client-js/control-flow/plan/insert.ts +2 -2
  117. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +3 -2
  118. package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +13 -12
  119. package/src/ir-to-client-js/csr-substitute.ts +12 -2
  120. package/src/ir-to-client-js/emit-reactive.ts +2 -2
  121. package/src/ir-to-client-js/emit-registration.ts +28 -57
  122. package/src/ir-to-client-js/generate-init.ts +17 -1
  123. package/src/ir-to-client-js/html-template.ts +30 -50
  124. package/src/ir-to-client-js/identifiers.ts +75 -24
  125. package/src/ir-to-client-js/imports.ts +56 -19
  126. package/src/ir-to-client-js/index.ts +2 -1
  127. package/src/ir-to-client-js/phases/event-handlers.ts +2 -2
  128. package/src/ir-to-client-js/phases/props-extraction.ts +16 -15
  129. package/src/ir-to-client-js/plan/build-declaration-emit.ts +2 -2
  130. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +7 -4
  131. package/src/ir-to-client-js/reactivity.ts +2 -2
  132. package/src/ir-to-client-js/rewrite-destructured-props.ts +21 -4
  133. package/src/ir-to-client-js/safe-html.ts +29 -35
  134. package/src/ir-to-client-js/types.ts +3 -2
  135. package/src/ir-to-client-js/utils.ts +2 -26
  136. package/src/jsx-to-ir.ts +279 -78
  137. package/src/nullable-signal-attr.ts +149 -33
  138. package/src/prop-rewrite.ts +41 -0
  139. package/src/props-binding.ts +17 -2
  140. package/src/scanner/__tests__/js-scanner.test.ts +37 -0
  141. package/src/scanner/js-scanner.ts +64 -4
  142. package/src/signal-prop-name-collision.ts +50 -24
  143. package/src/ssr-defaults.ts +47 -20
  144. package/src/ssr-seed-plan.ts +103 -23
  145. package/src/types.ts +115 -19
  146. 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,248 @@
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
+ /** The root `if` statement of a component with conditional returns. */
151
+ protected abstract renderIfStatement(ifStmt: IRIfStatement): string
152
+ /** The script registrations the template starts with. */
153
+ protected abstract generateScriptRegistrations(
154
+ ir: ComponentIR,
155
+ scriptBaseName?: string,
156
+ scriptAssets?: string[],
157
+ preloadAssets?: string[],
158
+ ): string
159
+ /**
160
+ * SSR context consumers (`const x = useContext(Ctx)`): seeds each local
161
+ * from the active provider value, or the `createContext` default. The
162
+ * provider side pushes the value via `emitProvider` (#1297).
163
+ */
164
+ protected abstract contextConsumerSeed(ir: ComponentIR): string
165
+ /**
166
+ * Prop/signal-derived memos with a `null` static SSR default (e.g.
167
+ * `createMemo(() => props.value * 10)`), computed in-template from the
168
+ * already-seeded prop/signal vars, mirroring Go's generated child
169
+ * constructor (#1297).
170
+ */
171
+ protected abstract derivedMemoSeed(ir: ComponentIR): string
172
+
173
+ generate(ir: ComponentIR, options?: AdapterGenerateOptions): AdapterOutput {
174
+ this.resetCompileState(ir)
175
+ this.collectCompileErrors(ir, options)
176
+
177
+ const templateBody = ir.root.type === 'if-statement'
178
+ ? this.renderIfStatement(ir.root as IRIfStatement)
179
+ : this.renderNode(ir.root)
180
+ const scriptReg = options?.skipScriptRegistration
181
+ ? ''
182
+ : this.generateScriptRegistrations(ir, options?.scriptBaseName, options?.scriptAssets, options?.preloadAssets)
183
+ const ctxSeed = this.contextConsumerSeed(ir)
184
+ const memoSeed = this.derivedMemoSeed(ir)
185
+ const template = `${scriptReg}${ctxSeed}${memoSeed}${templateBody}\n`
186
+
187
+ if (this.errors.length > 0) {
188
+ ir.errors.push(...this.errors)
189
+ }
190
+
191
+ // A DSL template has no JS-style imports / types / default-export
192
+ // sections. The `templatesPerComponent` mode emits one file per
193
+ // component using the raw `template` value; sections are populated for
194
+ // contract uniformity so the compiler never has to string-parse the
195
+ // template.
196
+ return {
197
+ template,
198
+ sections: { imports: '', types: '', component: template, defaultExport: '' },
199
+ extension: this.extension,
200
+ }
201
+ }
202
+
203
+ private resetCompileState(ir: ComponentIR): void {
204
+ this.componentName = ir.metadata.componentName
205
+ this.propsObjectName = ir.metadata.propsObjectName ?? null
206
+ this.restPropsName = ir.metadata.restPropsName ?? null
207
+ // (#checkbox) Enumerate the props-object pattern's inherited attribute
208
+ // accesses (`props.className`/`id`/`disabled`) into propsParams, before
209
+ // deriving `nullableOptionalProps` below, so a bare optional attribute
210
+ // like `id={props.id}` gets the template's presence guard. This mutates
211
+ // the IR: a harness that serialized it before `generate` doesn't see it.
212
+ augmentInheritedPropAccesses(ir)
213
+ this.propsParams = ir.metadata.propsParams.map(p => ({ name: p.name, optional: p.optional }))
214
+ this.booleanTypedProps = collectBooleanTypedProps(ir)
215
+ this.localConstants = ir.metadata.localConstants ?? []
216
+ this.rootPropAliases = rootPropAliasNames(ir, this.propsParams.map(p => p.name))
217
+ this.scope = BindingScope.EMPTY
218
+ this.nullableOptionalProps = collectNullableOptionalProps(ir)
219
+ this.nullableSignalGetters = collectNullableSignalGetters(ir)
220
+ this.nullishAttrCtx = collectNullishAttrContext(ir)
221
+ this.stringValueNames = this.stringValueNamesFor(ir)
222
+ this.moduleStringConsts = collectModuleStringConsts(ir.metadata.localConstants)
223
+ this._searchParamsLocals = searchParamsLocalNames(ir.metadata)
224
+ this._loweringMatchers = prepareLoweringMatchers(ir.metadata)
225
+ this.computedConsts = computedConstContext(ir.metadata, name => this.scope.isBound(name))
226
+ this.importAliases = buildImportAliasMap(ir.metadata.imports ?? [])
227
+ this.childrenCaptureCounter = 0
228
+ this.errors = []
229
+ this.resetAdapterState(ir)
230
+ }
231
+
232
+ private collectCompileErrors(ir: ComponentIR, options?: AdapterGenerateOptions): void {
233
+ const spelling = this.templateIdentifierSpelling
234
+ if (spelling) {
235
+ const propNames = this.propsParams.map(p => p.name)
236
+ this.errors.push(...templateNameCollisionErrors(ir, propNames, spelling.ident, spelling.label, this.componentName))
237
+ }
238
+ // A child component referenced inside a loop body that is imported from
239
+ // a sibling .tsx renders as a cross-template call, which resolves only if
240
+ // the sibling template is registered alongside the parent at render
241
+ // time. Surface it loudly here, unless the caller (e.g. the barefoot
242
+ // CLI) guarantees that every sibling template is registered on the same
243
+ // template instance.
244
+ if (!options?.siblingTemplatesRegistered) {
245
+ this.errors.push(...collectImportedLoopChildComponentErrors(ir, this.componentName, this.loopChildDiagnosticName))
246
+ }
247
+ }
248
+ }
@@ -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('"'))
@@ -305,6 +305,29 @@ export function isNumericArithmeticResult(
305
305
  return expr.op === '-' || expr.op === '*' || expr.op === '/' || expr.op === '%'
306
306
  }
307
307
 
308
+ /** A runtime helper of the template-helper catalogue (`spec/template-helpers.md`)
309
+ * that a binary arithmetic operator lowers to. */
310
+ export type ArithmeticHelper = 'mod'
311
+
312
+ /**
313
+ * The runtime helper a JS binary arithmetic operator lowers to on every
314
+ * template backend, or `null` when the backend spells the operator itself
315
+ * (#3474). The adapter only spells the call, in its own syntax
316
+ * (`bf.mod(a, b)`, `$bf->mod(a, b)`, `bf_mod a b`), over operands already
317
+ * coerced (`arithmeticOperandCoercion`) and grouped ({@link groupBinaryOperand}).
318
+ *
319
+ * `%` is JS's truncated remainder: the result takes the dividend's sign
320
+ * (`-7 % 2` is `-1`, `7 % -2` is `1`), keeps a fraction (`7.5 % 2` is `1.5`),
321
+ * and is `NaN` for a zero divisor or a `NaN` / infinite dividend. No
322
+ * engine's native operator computes it: Ruby, Python and Perl floor the
323
+ * quotient (`-7 % 2` is `1`), MiniJinja takes the Euclidean remainder, PHP,
324
+ * Perl and Kolon convert the operands to integers first (`NaN % 2` is `0`),
325
+ * and an integer zero divisor raises in Java, PHP and MiniJinja (#3574).
326
+ */
327
+ export function arithmeticHelper(op: string): ArithmeticHelper | null {
328
+ return op === '%' ? 'mod' : null
329
+ }
330
+
308
331
  /**
309
332
  * Wrap an emitted binary/logical/ternary OPERAND in parentheses so the
310
333
  * source grouping the `ParsedExpr` tree encodes survives infix
@@ -325,6 +348,17 @@ export function groupBinaryOperand(operand: ParsedExpr, emitted: string): string
325
348
  : emitted
326
349
  }
327
350
 
351
+ /**
352
+ * Wrap an emitted unary-minus OPERAND in parentheses where the target's
353
+ * prefix `-` would otherwise bind to only part of it (#3474): a compound
354
+ * operand for the reason {@link groupBinaryOperand} gives (`-(a + b)`
355
+ * re-emitted as `-a + b`), and a nested unary operand, since `--x` is a
356
+ * decrement in PHP and Perl. A leaf operand stays unwrapped.
357
+ */
358
+ export function groupUnaryOperand(operand: ParsedExpr, emitted: string): string {
359
+ return operand.kind === 'unary' ? `(${emitted})` : groupBinaryOperand(operand, emitted)
360
+ }
361
+
328
362
  /**
329
363
  * Split an `object-literal`'s (order-preserving) `properties` into rendered
330
364
  * SEGMENTS an adapter's `objectLiteral()` folds with its own merge idiom
@@ -0,0 +1,61 @@
1
+ /**
2
+ * `style={{ … }}` object-literal lowering plan, shared by the template
3
+ * adapters (#3541).
4
+ *
5
+ * Every adapter used to re-parse the attribute text through
6
+ * `parseStyleObjectEntries` (a fresh `ts.createSourceFile`) and then each
7
+ * dynamic value through `parseExpression`. The IR already carries the
8
+ * object-literal tree on `ExpressionAttr.parsed`, so the plan reads that:
9
+ * the CSS keys are decided here once, and an adapter spells only its
10
+ * `style_object` runtime call. Reading the tree also accepts the shorthand
11
+ * `{ color }`, which the text parser refused.
12
+ */
13
+
14
+ import type { ExpressionAttr } from '../types.ts'
15
+ import {
16
+ cssKebabCase,
17
+ isSupported,
18
+ stringifyParsedExpr,
19
+ type ParsedExpr,
20
+ } from '../expression-parser.ts'
21
+
22
+ /** One CSS declaration of a style object: a static string, or a value to lower. */
23
+ export type StyleObjectPlanEntry =
24
+ | { cssKey: string; kind: 'literal'; value: string }
25
+ | { cssKey: string; kind: 'expr'; expr: string; parsed: ParsedExpr }
26
+
27
+ /** The static string a value spells, when it is a string or a substitution-free template literal. */
28
+ function staticString(value: ParsedExpr): string | null {
29
+ if (value.kind === 'literal' && value.literalType === 'string' && typeof value.value === 'string') return value.value
30
+ if (value.kind === 'template-literal' && value.parts.every(p => p.type === 'string')) {
31
+ return value.parts.map(p => (p.type === 'string' ? p.value : '')).join('')
32
+ }
33
+ return null
34
+ }
35
+
36
+ /**
37
+ * The CSS declarations of a `style` attribute's object literal, or `null`
38
+ * when the value is not an object literal every entry of which an adapter
39
+ * can lower: a spread, a numeric key, or a value outside the template
40
+ * subset keeps the attribute on the adapter's refusal path.
41
+ */
42
+ export function planStyleObject(value: Pick<ExpressionAttr, 'expr' | 'parsed'>): StyleObjectPlanEntry[] | null {
43
+ // Phase 1 attaches `parsed` to every expression attribute; without it
44
+ // there is no tree to plan from, and the attribute stays on the refusal path.
45
+ const parsed = value.parsed
46
+ if (parsed?.kind !== 'object-literal' || parsed.properties.length === 0) return null
47
+ const entries: StyleObjectPlanEntry[] = []
48
+ for (const prop of parsed.properties) {
49
+ if (prop.kind !== 'prop' || prop.keyKind === 'numeric') return null
50
+ const cssKey = cssKebabCase(prop.key)
51
+ const literal = staticString(prop.value)
52
+ if (literal !== null) {
53
+ entries.push({ cssKey, kind: 'literal', value: literal })
54
+ } else if (isSupported(prop.value).supported) {
55
+ entries.push({ cssKey, kind: 'expr', expr: stringifyParsedExpr(prop.value), parsed: prop.value })
56
+ } else {
57
+ return null
58
+ }
59
+ }
60
+ return entries
61
+ }