@barefootjs/jsx 0.39.5 → 0.39.6

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 (57) hide show
  1. package/dist/adapters/array-method.d.ts +93 -0
  2. package/dist/adapters/array-method.d.ts.map +1 -0
  3. package/dist/adapters/attr-plan.d.ts +135 -0
  4. package/dist/adapters/attr-plan.d.ts.map +1 -0
  5. package/dist/adapters/boolean-result.d.ts +84 -9
  6. package/dist/adapters/boolean-result.d.ts.map +1 -1
  7. package/dist/adapters/callback-method.d.ts +126 -0
  8. package/dist/adapters/callback-method.d.ts.map +1 -0
  9. package/dist/adapters/component-props.d.ts +99 -0
  10. package/dist/adapters/component-props.d.ts.map +1 -0
  11. package/dist/adapters/component-tree.d.ts +25 -0
  12. package/dist/adapters/component-tree.d.ts.map +1 -0
  13. package/dist/adapters/literal-value.d.ts +22 -0
  14. package/dist/adapters/literal-value.d.ts.map +1 -0
  15. package/dist/adapters/loop-plan.d.ts +53 -0
  16. package/dist/adapters/loop-plan.d.ts.map +1 -0
  17. package/dist/adapters/prop-classes.d.ts +37 -0
  18. package/dist/adapters/prop-classes.d.ts.map +1 -0
  19. package/dist/expression-parser.d.ts +38 -0
  20. package/dist/expression-parser.d.ts.map +1 -1
  21. package/dist/index.d.ts +17 -3
  22. package/dist/index.d.ts.map +1 -1
  23. package/dist/index.js +1765 -914
  24. package/dist/jsx-to-ir.d.ts +465 -1
  25. package/dist/jsx-to-ir.d.ts.map +1 -1
  26. package/dist/nullable-signal-attr.d.ts +19 -0
  27. package/dist/nullable-signal-attr.d.ts.map +1 -1
  28. package/package.json +2 -2
  29. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
  30. package/src/__tests__/action-accessor.test.ts +6 -24
  31. package/src/__tests__/array-method-catalogue.test.ts +99 -0
  32. package/src/__tests__/attr-plan.test.ts +121 -0
  33. package/src/__tests__/binding-scope-ratchet.test.ts +12 -12
  34. package/src/__tests__/boolean-result-expr.test.ts +106 -0
  35. package/src/__tests__/boolean-result.test.ts +34 -1
  36. package/src/__tests__/callback-method.test.ts +189 -0
  37. package/src/__tests__/component-props.test.ts +148 -0
  38. package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
  39. package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
  40. package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
  41. package/src/__tests__/loop-plan.test.ts +104 -0
  42. package/src/__tests__/map-call-decisions.test.ts +521 -0
  43. package/src/__tests__/nullable-signal-attr.test.ts +45 -0
  44. package/src/adapters/array-method.ts +193 -0
  45. package/src/adapters/attr-plan.ts +200 -0
  46. package/src/adapters/boolean-result.ts +208 -12
  47. package/src/adapters/callback-method.ts +301 -0
  48. package/src/adapters/component-props.ts +144 -0
  49. package/src/adapters/component-tree.ts +118 -0
  50. package/src/adapters/literal-value.ts +36 -0
  51. package/src/adapters/loop-plan.ts +88 -0
  52. package/src/adapters/prop-classes.ts +73 -0
  53. package/src/expression-parser.ts +537 -374
  54. package/src/index.ts +53 -2
  55. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
  56. package/src/jsx-to-ir.ts +1328 -991
  57. package/src/nullable-signal-attr.ts +78 -0
@@ -0,0 +1,193 @@
1
+ /**
2
+ * The array / string method catalogue shared by the DSL adapters (#3476).
3
+ *
4
+ * Each DSL adapter lowers `xs.join(sep)`, `s.padStart(n, c)` and the rest of
5
+ * {@link ArrayMethod} to one call of its template runtime's helper. What the
6
+ * call means is the same in all of them: which helper, which arguments, and
7
+ * what fills an argument the source left out (`join` → `','`, `at` → `0`,
8
+ * `slice` end → "to length"). This module owns that meaning as data. An
9
+ * adapter only spells the call: its helper prefix (`bf.`, `$bf->`, `bf->`,
10
+ * `$bf.`), its undefined literal (`none`, `nil`, `null`, `undef`), and the
11
+ * odd helper it lowers to a native operator instead (ERB's `.downcase`).
12
+ *
13
+ * The `Record<ArrayMethod, …>` type is the exhaustiveness guard: a new
14
+ * `ArrayMethod` member fails to compile here, once, instead of in each
15
+ * adapter's `switch`.
16
+ */
17
+
18
+ import type { ParsedExpr } from '../expression-parser.ts'
19
+ import type { ArrayMethod } from './parsed-expr-emitter.ts'
20
+
21
+ /**
22
+ * Runtime helper ids. Every DSL runtime names the helper by this id; only the
23
+ * receiver syntax around it differs.
24
+ */
25
+ export type ArrayMethodHelper =
26
+ | 'join'
27
+ | 'includes'
28
+ | 'index_of'
29
+ | 'last_index_of'
30
+ | 'at'
31
+ | 'concat'
32
+ | 'slice'
33
+ | 'reverse'
34
+ | 'lc'
35
+ | 'uc'
36
+ | 'trim'
37
+ | 'trim_start'
38
+ | 'trim_end'
39
+ | 'to_fixed'
40
+ | 'split'
41
+ | 'starts_with'
42
+ | 'ends_with'
43
+ | 'replace'
44
+ | 'replace_all'
45
+ | 'repeat'
46
+ | 'pad_start'
47
+ | 'pad_end'
48
+
49
+ /** A literal that fills an argument the source call left out. */
50
+ export type ArrayMethodDefault =
51
+ | { kind: 'number'; value: number }
52
+ | { kind: 'string'; value: string }
53
+ /** The backend's undefined literal; the runtime reads it as "not given". */
54
+ | { kind: 'undefined' }
55
+
56
+ /** How one argument after the receiver is passed. */
57
+ export type ArrayMethodParam =
58
+ /** Always present. The parser refuses the call without it. */
59
+ | { kind: 'required' }
60
+ /** Filled with `value` when the source left it out. */
61
+ | { kind: 'default'; value: ArrayMethodDefault }
62
+ /** Dropped when the source left it out; the helper call is shorter. */
63
+ | { kind: 'optional' }
64
+
65
+ export interface ArrayMethodEntry {
66
+ helper: ArrayMethodHelper
67
+ /** The arguments after the receiver, in order. Extra source arguments are dropped. */
68
+ params: readonly ArrayMethodParam[]
69
+ /** `xs.concat()` is the receiver itself, not a helper call. */
70
+ receiverWhenNoArgs?: true
71
+ }
72
+
73
+ const required: ArrayMethodParam = { kind: 'required' }
74
+ const optional: ArrayMethodParam = { kind: 'optional' }
75
+ const zero: ArrayMethodParam = { kind: 'default', value: { kind: 'number', value: 0 } }
76
+
77
+ export const ARRAY_METHOD_CATALOGUE: Readonly<Record<ArrayMethod, ArrayMethodEntry>> = {
78
+ // `bf.join` rather than a template builtin, so the JS element handling
79
+ // (undefined → empty, default separator) is the runtime's, everywhere.
80
+ join: { helper: 'join', params: [{ kind: 'default', value: { kind: 'string', value: ',' } }] },
81
+ includes: { helper: 'includes', params: [required] },
82
+ // JS's `fromIndex` second argument is not lowered.
83
+ indexOf: { helper: 'index_of', params: [required] },
84
+ lastIndexOf: { helper: 'last_index_of', params: [required] },
85
+ at: { helper: 'at', params: [zero] },
86
+ concat: { helper: 'concat', params: [required], receiverWhenNoArgs: true },
87
+ // The undefined end reads as "to length" in every runtime's `slice`.
88
+ slice: { helper: 'slice', params: [zero, { kind: 'default', value: { kind: 'undefined' } }] },
89
+ reverse: { helper: 'reverse', params: [] },
90
+ toReversed: { helper: 'reverse', params: [] },
91
+ // The runtime coerces a non-string receiver the JS way first; a bare
92
+ // template `lower` filter would not.
93
+ toLowerCase: { helper: 'lc', params: [] },
94
+ toUpperCase: { helper: 'uc', params: [] },
95
+ trim: { helper: 'trim', params: [] },
96
+ // The one-sided siblings of `.trim()` (#2183) have their own helpers.
97
+ trimStart: { helper: 'trim_start', params: [] },
98
+ trimEnd: { helper: 'trim_end', params: [] },
99
+ // `bf.to_fixed` mirrors JS rounding and zero-padding (#1897).
100
+ toFixed: { helper: 'to_fixed', params: [zero] },
101
+ split: { helper: 'split', params: [optional, optional] },
102
+ startsWith: { helper: 'starts_with', params: [required, optional] },
103
+ endsWith: { helper: 'ends_with', params: [required, optional] },
104
+ // String patterns only; the parser refuses a regex pattern (#2182).
105
+ replace: { helper: 'replace', params: [required, required] },
106
+ replaceAll: { helper: 'replace_all', params: [required, required] },
107
+ repeat: { helper: 'repeat', params: [zero] },
108
+ padStart: { helper: 'pad_start', params: [zero, optional] },
109
+ padEnd: { helper: 'pad_end', params: [zero, optional] },
110
+ }
111
+
112
+ /** One argument of a lowered call after the receiver. */
113
+ export type ArrayMethodArg =
114
+ | { kind: 'expr'; expr: ParsedExpr }
115
+ | { kind: 'default'; value: ArrayMethodDefault }
116
+
117
+ /** A lowered array / string method call, as data. */
118
+ export type ArrayMethodPlan =
119
+ | { kind: 'receiver'; object: ParsedExpr }
120
+ | { kind: 'call'; helper: ArrayMethodHelper; object: ParsedExpr; args: ArrayMethodArg[] }
121
+
122
+ /** Lower `object.method(...args)` through {@link ARRAY_METHOD_CATALOGUE}. */
123
+ export function lowerArrayMethod(
124
+ method: ArrayMethod,
125
+ object: ParsedExpr,
126
+ args: readonly ParsedExpr[],
127
+ ): ArrayMethodPlan {
128
+ const entry = ARRAY_METHOD_CATALOGUE[method]
129
+ if (entry.receiverWhenNoArgs && args.length === 0) return { kind: 'receiver', object }
130
+ const out: ArrayMethodArg[] = []
131
+ for (const [i, param] of entry.params.entries()) {
132
+ const arg = args[i]
133
+ if (arg) {
134
+ out.push({ kind: 'expr', expr: arg })
135
+ } else if (param.kind === 'default') {
136
+ out.push({ kind: 'default', value: param.value })
137
+ } else if (param.kind === 'optional') {
138
+ break
139
+ } else {
140
+ throw new Error(`lowerArrayMethod: '.${method}()' needs argument ${i + 1}`)
141
+ }
142
+ }
143
+ return { kind: 'call', helper: entry.helper, object, args: out }
144
+ }
145
+
146
+ /** How one DSL backend spells a lowered call. */
147
+ export interface ArrayMethodSpelling {
148
+ /** Spell `helper(receiver, ...args)` from already-emitted operands. */
149
+ call(helper: ArrayMethodHelper, operands: readonly string[]): string
150
+ /** The backend's undefined literal (`none`, `nil`, `null`, `undef`). */
151
+ undefinedLiteral: string
152
+ }
153
+
154
+ /**
155
+ * Emit a plan with `emit` for the operands and `spelling` for the call. The
156
+ * receiver is emitted first, then the arguments in order.
157
+ */
158
+ export function emitArrayMethod(
159
+ plan: ArrayMethodPlan,
160
+ emit: (e: ParsedExpr) => string,
161
+ spelling: ArrayMethodSpelling,
162
+ ): string {
163
+ if (plan.kind === 'receiver') return emit(plan.object)
164
+ const operands = [emit(plan.object)]
165
+ for (const arg of plan.args) {
166
+ operands.push(arg.kind === 'expr' ? emit(arg.expr) : defaultLiteral(arg.value, spelling))
167
+ }
168
+ return spelling.call(plan.helper, operands)
169
+ }
170
+
171
+ /**
172
+ * The text of a default. A string default is written single-quoted, which
173
+ * every DSL backend reads the same way as long as the value has no quote or
174
+ * backslash; the catalogue's only string default is `','`.
175
+ */
176
+ function defaultLiteral(value: ArrayMethodDefault, spelling: ArrayMethodSpelling): string {
177
+ switch (value.kind) {
178
+ case 'number':
179
+ return String(value.value)
180
+ case 'string':
181
+ return `'${value.value}'`
182
+ case 'undefined':
183
+ return spelling.undefinedLiteral
184
+ }
185
+ }
186
+
187
+ /** The usual spelling: `<prefix><helper>(operands)`, e.g. `bf.` or `$bf->`. */
188
+ export function prefixedArrayMethodSpelling(prefix: string, undefinedLiteral: string): ArrayMethodSpelling {
189
+ return {
190
+ call: (helper, operands) => `${prefix}${helper}(${operands.join(', ')})`,
191
+ undefinedLiteral,
192
+ }
193
+ }
@@ -0,0 +1,200 @@
1
+ /**
2
+ * How a DSL adapter emits an intrinsic element's attribute (#3478), as data.
3
+ *
4
+ * Every DSL adapter's `elementAttrEmitter` makes the same decisions for an
5
+ * `{expr}` attribute value and a `{...spread}`; only the spelling differs.
6
+ * {@link planAttrExpression} and {@link planSpreadAttr} make them once. The
7
+ * adapter keeps what is its own: the style-object lowering and the refusal
8
+ * gate before the plan, and, per plan kind, the escape call (`bf.string`,
9
+ * `bf.h`, `e(...)`), the nil and truthy tests, the temporary binding and the
10
+ * hash literal.
11
+ */
12
+
13
+ import { exprToString, isSupported, parseExpression, type ParsedExpr } from '../expression-parser.ts'
14
+ import type { LoweringMatcher } from '../lowering-registry.ts'
15
+ import { attrValueMayBeNullish, nullableSignalAttrGetter, type NullishAttrContext } from '../nullable-signal-attr.ts'
16
+ import type { ConstantInfo, ExpressionAttr, SpreadAttr } from '../types.ts'
17
+ import { isBooleanAttr } from '../html-constants.ts'
18
+
19
+ const IDENTIFIER = /^[A-Za-z_$][\w$]*$/
20
+
21
+ /**
22
+ * Whether an attribute value is a shape no template lowers: a JS object
23
+ * literal (`style={{…}}` aside, which the adapter lowers first) or a
24
+ * tagged template literal (`cn\`base ${tone()}\``). Returns the refusal, with
25
+ * the support gate's reason when it gives one, or `null` when the value
26
+ * goes on to {@link planAttrExpression}. The adapter reports BF101 in its own
27
+ * words. A value starting with neither shape is never parsed here.
28
+ */
29
+ export function unsupportedAttrExpression(
30
+ expr: string,
31
+ loweringMatchers: readonly LoweringMatcher[],
32
+ ): { reason: string | undefined } | null {
33
+ let probe = expr.trim()
34
+ while (probe.startsWith('(')) probe = probe.slice(1).trimStart()
35
+ const startsAsObjectLiteral = probe.startsWith('{')
36
+ const hasTaggedTemplate = /[A-Za-z_$][\w$]*\s*`/.test(probe)
37
+ if (!startsAsObjectLiteral && !hasTaggedTemplate) return null
38
+ const parsed = parseExpression(expr.trim())
39
+ const support = isSupported(parsed, { loweringMatchers })
40
+ if (parsed.kind !== 'unsupported' && support.supported) return null
41
+ return { reason: support.reason ?? (parsed.kind === 'unsupported' ? parsed.reason : undefined) }
42
+ }
43
+
44
+ /**
45
+ * The emission of an `{expr}` attribute value.
46
+ *
47
+ * - `omit-nullable`: a bare read of an optional, no-default prop or of a
48
+ * nullable signal (#2248, #3304). The attribute is guarded by a nil test
49
+ * on the value itself, as Hono drops an `undefined` attribute.
50
+ * `restKey` marks a closed-type rest-expanded key (`rest.tag`, #3057).
51
+ * - `boolean-attr`: an HTML boolean attribute (`disabled`), present when
52
+ * the value is truthy.
53
+ * - `presence`: `attr={expr || undefined}` (#1897). The value is bound to a
54
+ * temporary once and rendered when truthy.
55
+ * - `undefined-alternate`: `attr={cond ? value : undefined}` (or `: null`).
56
+ * The attribute is rendered when `cond` holds.
57
+ * - `omit-nil`: a value that may reach `null` / `undefined` through a memo,
58
+ * an optional member read or a ternary branch (#3322). The value is bound
59
+ * to a temporary once and rendered when not nil.
60
+ * - `plain`: always rendered.
61
+ *
62
+ * `boolStr`: the value is boolean-shaped and goes through `bool_str`, so the
63
+ * bytes match JS `String(boolean)`.
64
+ */
65
+ export type AttrExpressionPlan =
66
+ | { kind: 'omit-nullable'; boolStr: boolean; restKey: boolean }
67
+ | { kind: 'boolean-attr' }
68
+ | { kind: 'presence'; boolStr: boolean }
69
+ | { kind: 'undefined-alternate'; ternary: UndefinedAlternateTernary }
70
+ | { kind: 'omit-nil'; boolStr: boolean }
71
+ | { kind: 'plain'; boolStr: boolean }
72
+
73
+ export interface AttrPlanContext {
74
+ /** The SolidJS-style props identifier (`function C(props: P)`), if any. */
75
+ propsObjectName: string | null
76
+ /** The destructured `...rest` binding (`function C({ ...rest })`), if any. */
77
+ restPropsName: string | null
78
+ /** Optional, no-default props, by bare name (`collectNullableOptionalProps`). */
79
+ nullableOptionalProps: ReadonlySet<string>
80
+ /** Signal getters whose SSR value may be `undefined` (`collectNullableSignalGetters`). */
81
+ nullableSignalGetters: ReadonlySet<string>
82
+ nullishAttrCtx: NullishAttrContext
83
+ /** A loop binding at the attribute site shadows `name`. */
84
+ isLoopBound(name: string): boolean
85
+ /** The adapter routes this value through `bool_str`. */
86
+ boolStr(expr: string, name: string): boolean
87
+ }
88
+
89
+ /** Plan an `{expr}` attribute value. */
90
+ export function planAttrExpression(value: ExpressionAttr, name: string, ctx: AttrPlanContext): AttrExpressionPlan {
91
+ const booleanAttr = isBooleanAttr(name)
92
+ if (!booleanAttr && !value.presenceOrUndefined) {
93
+ const nullable = nullableBareRead(value, ctx)
94
+ if (nullable !== null) return { kind: 'omit-nullable', boolStr: ctx.boolStr(value.expr, name), restKey: nullable.restKey }
95
+ }
96
+ if (booleanAttr) return { kind: 'boolean-attr' }
97
+ if (value.presenceOrUndefined) return { kind: 'presence', boolStr: ctx.boolStr(value.expr, name) }
98
+ const ternary = parseUndefinedAlternateTernary(value.expr)
99
+ if (ternary) return { kind: 'undefined-alternate', ternary }
100
+ const boolStr = ctx.boolStr(value.expr, name)
101
+ if (attrValueMayBeNullish(value.parsed, ctx.nullishAttrCtx, (n) => ctx.isLoopBound(n))) return { kind: 'omit-nil', boolStr }
102
+ return { kind: 'plain', boolStr }
103
+ }
104
+
105
+ /**
106
+ * Whether the value is a bare read of a nullable optional prop (`id`,
107
+ * `props.id`, `rest.id`) or of a nullable signal (`title()`) that no loop
108
+ * binding shadows (#2488). `restKey`: the read names a rest-expanded key.
109
+ */
110
+ function nullableBareRead(value: ExpressionAttr, ctx: AttrPlanContext): { restKey: boolean } | null {
111
+ const bare = value.expr.trim()
112
+ const restKey = ctx.restPropsName !== null && bare.startsWith(`${ctx.restPropsName}.`)
113
+ let normalized = bare
114
+ if (ctx.propsObjectName && bare.startsWith(`${ctx.propsObjectName}.`)) normalized = bare.slice(ctx.propsObjectName.length + 1)
115
+ else if (restKey) normalized = bare.slice(ctx.restPropsName!.length + 1)
116
+ const prop = IDENTIFIER.test(normalized) && ctx.nullableOptionalProps.has(normalized) && !ctx.isLoopBound(normalized)
117
+ const signal = nullableSignalAttrGetter(value.parsed, ctx.nullableSignalGetters)
118
+ if (prop || (signal !== null && !ctx.isLoopBound(signal))) return { restKey }
119
+ return null
120
+ }
121
+
122
+ /**
123
+ * `cond ? value : undefined` (or `: null`), whose falsy branch drops the
124
+ * attribute (#1897).
125
+ *
126
+ * `testParsed` / `consequentParsed` are the parsed sub-trees, for the caller
127
+ * to lower directly (#2843 review). `condition` / `consequent` are
128
+ * `exprToString` output, a debug formatter that renders a nested object
129
+ * literal as a non-reparseable `[UNSUPPORTED: …]` placeholder: re-parsing it
130
+ * would corrupt a call like `queryHref(base, { tag })` before the lowering
131
+ * registry sees it. They are serialised from the parsed tree rather than
132
+ * sliced from the text, which would mis-split `cond ? 'a:b' : undefined`.
133
+ */
134
+ export interface UndefinedAlternateTernary {
135
+ condition: string
136
+ consequent: string
137
+ testParsed: ParsedExpr
138
+ consequentParsed: ParsedExpr
139
+ }
140
+
141
+ /** Parse `cond ? value : undefined` (or `: null`), or `null` for any other shape. */
142
+ export function parseUndefinedAlternateTernary(expr: string): UndefinedAlternateTernary | null {
143
+ const parsed = parseExpression(expr.trim())
144
+ if (parsed?.kind !== 'conditional') return null
145
+ const alt = parsed.alternate
146
+ const isUndef =
147
+ (alt.kind === 'identifier' && (alt.name === 'undefined' || alt.name === 'null')) ||
148
+ (alt.kind === 'literal' && (alt.value === null || alt.value === undefined))
149
+ if (!isUndef) return null
150
+ return {
151
+ condition: exprToString(parsed.test),
152
+ consequent: exprToString(parsed.consequent),
153
+ testParsed: parsed.test,
154
+ consequentParsed: parsed.consequent,
155
+ }
156
+ }
157
+
158
+ /**
159
+ * The emission of a `{...spread}` attribute.
160
+ *
161
+ * - `props-object`: `{...props}`, the component's own props object, which no
162
+ * template scope holds as one value. The adapter enumerates `params` into
163
+ * a hash literal.
164
+ * - `value`: any other spread. The adapter tries its conditional-spread
165
+ * lowering (`{...(cond ? {…} : {})}`) on each of `candidates` in order:
166
+ * the spread's own tree, then the initializer of the function-scope
167
+ * `const` it names (`const sizeAttrs = size ? {…} : {}`), unless a loop
168
+ * binding shadows that name (#2489). If none lowers, it spreads the
169
+ * expression itself.
170
+ */
171
+ export type SpreadAttrPlan =
172
+ | { kind: 'props-object'; params: string[] }
173
+ | { kind: 'value'; candidates: Array<ParsedExpr | undefined> }
174
+
175
+ export interface SpreadPlanContext {
176
+ propsObjectName: string | null
177
+ propsParams: ReadonlyArray<{ name: string }>
178
+ localConstants: readonly ConstantInfo[]
179
+ /** A binding at the spread site shadows `name`. */
180
+ isBound(name: string): boolean
181
+ }
182
+
183
+ /** Plan a `{...spread}` attribute. */
184
+ export function planSpreadAttr(value: SpreadAttr, ctx: SpreadPlanContext): SpreadAttrPlan {
185
+ const trimmed = value.expr.trim()
186
+ if (ctx.propsObjectName && ctx.propsObjectName === trimmed) {
187
+ return { kind: 'props-object', params: ctx.propsParams.map((p) => p.name) }
188
+ }
189
+ const candidates: Array<ParsedExpr | undefined> = [value.parsed]
190
+ const init = localConstInitializer(trimmed, ctx)
191
+ if (init !== null) candidates.push(parseExpression(init))
192
+ return { kind: 'value', candidates }
193
+ }
194
+
195
+ /** The initializer text of the function-scope `const` a bare spread names, unless it is itself a bare name. */
196
+ function localConstInitializer(name: string, ctx: SpreadPlanContext): string | null {
197
+ if (!IDENTIFIER.test(name) || ctx.isBound(name)) return null
198
+ const init = ctx.localConstants.find((c) => c.name === name && !c.isModule)?.value?.trim()
199
+ return init !== undefined && !IDENTIFIER.test(init) ? init : null
200
+ }
@@ -1,10 +1,26 @@
1
1
  /**
2
- * Backend-neutral boolean-result classification shared by the adapters whose
3
- * host language has no boolean type (Mojolicious, Xslate: Perl renders a
4
- * comparison as `''` / `1` and the literal `false` as `0`). Both adapters
5
- * route a boolean-shaped attribute value through their `bool_str` runtime
6
- * helper; this module decides which `ParsedExpr` shapes are boolean-shaped
7
- * and rewrites a ternary that only PARTLY is (#3349).
2
+ * Backend-neutral boolean-result classification shared by every DSL
3
+ * template adapter (Blade, ERB, Jinja, MiniJinja, Mojolicious, Pebble, Twig,
4
+ * Xslate; #3475 lifted the per-adapter copies here). It decides which
5
+ * `ParsedExpr` shapes evaluate to a JS boolean, rewrites a ternary that only
6
+ * PARTLY does (#3349), and names the ARIA attributes whose binding is
7
+ * boolean by definition. The adapters use it for two decisions:
8
+ *
9
+ * 1. **Stringification.** A boolean-shaped attribute / text binding is routed
10
+ * through the runtime's `bool_str` helper so it serialises as JS
11
+ * `String(boolean)` ("true" / "false"). No host language gets this for
12
+ * free: Perl renders a comparison as `''` / `1` and `false` as `0`;
13
+ * Python's `str(True)` is `"True"`; PHP's `(string) true` is `"1"` and
14
+ * `(string) false` is `""`; Java's `Boolean.toString()` happens to match,
15
+ * but Pebble still routes explicitly so `bf.string` handles every JS value
16
+ * shape the same way.
17
+ * 2. **Condition-position truthiness** (Blade, Jinja, MiniJinja, Pebble,
18
+ * Twig). A condition that is already boolean-shaped is emitted as is;
19
+ * anything else is wrapped in the runtime's JS-faithful `truthy` before it
20
+ * becomes an `if` / ternary test, because those hosts disagree with JS on
21
+ * empty containers (`[]` / `{}` are JS-truthy, falsy in Python, PHP and
22
+ * Pebble) and PHP also on the string `'0'`. Perl never needed this: an
23
+ * array / hash reference is always true there.
8
24
  *
9
25
  * Detected boolean-result shapes:
10
26
  * - `binary` with a comparison operator (`<`, `>`, `<=`, `>=`, `==`,
@@ -12,10 +28,18 @@
12
28
  * - `unary` with logical `!`
13
29
  * - `literal` with `literalType: 'boolean'`
14
30
  * - `logical` (`&&` / `||` / `??`) when both sides are boolean-result
31
+ * (`x > 0 && y < 10`, not `x() || 'fallback'`)
15
32
  * - `conditional` (`?:`) when both branches are boolean-result
33
+ * - with a caller's `isBooleanName`, a getter call, `props.X` or bare
34
+ * name declared `boolean`
35
+ *
36
+ * Anything else is not boolean-result, including a bare identifier
37
+ * (`accepted`) or call (`accepted()`) without a witness: its type is not
38
+ * recoverable from source text.
16
39
  */
17
40
 
18
- import type { ParsedExpr } from '../expression-parser.ts'
41
+ import { parseExpression, type ParsedExpr } from '../expression-parser.ts'
42
+ import type { IRMetadata, TypeInfo } from '../types.ts'
19
43
 
20
44
  const COMPARISON_OPS = new Set([
21
45
  '<',
@@ -28,8 +52,18 @@ const COMPARISON_OPS = new Set([
28
52
  '!==',
29
53
  ])
30
54
 
31
- /** Whether `node` structurally evaluates to a JS boolean. */
32
- export function isBooleanResultParsed(node: ParsedExpr): boolean {
55
+ /**
56
+ * Whether `node` evaluates to a JS boolean: structurally, or, when the
57
+ * caller passes `isBooleanName`, through a leaf declared `boolean` — a
58
+ * zero-arg getter call (`on()`), `props.on`, or a bare name — the same
59
+ * witness shape `isStringTypedOperand` takes for strings. A logical
60
+ * expression mixing a boolean prop with a comparison (`props.on &&
61
+ * !props.off`) then classifies as boolean (#3443).
62
+ */
63
+ export function isBooleanResultParsed(
64
+ node: ParsedExpr,
65
+ isBooleanName?: (name: string, componentProperty?: boolean) => boolean,
66
+ ): boolean {
33
67
  switch (node.kind) {
34
68
  case 'literal':
35
69
  return node.literalType === 'boolean'
@@ -41,14 +75,21 @@ export function isBooleanResultParsed(node: ParsedExpr): boolean {
41
75
  // `x > 0 && y < 10` is boolean; `x() || 'fallback'` is not.
42
76
  // Only both-sides-boolean qualifies.
43
77
  return (
44
- isBooleanResultParsed(node.left) && isBooleanResultParsed(node.right)
78
+ isBooleanResultParsed(node.left, isBooleanName) && isBooleanResultParsed(node.right, isBooleanName)
45
79
  )
46
80
  case 'conditional':
47
81
  // `cond ? bool : bool` is boolean; `cond ? 'a' : 'b'` is not.
48
82
  return (
49
- isBooleanResultParsed(node.consequent) &&
50
- isBooleanResultParsed(node.alternate)
83
+ isBooleanResultParsed(node.consequent, isBooleanName) &&
84
+ isBooleanResultParsed(node.alternate, isBooleanName)
51
85
  )
86
+ case 'call':
87
+ return !!isBooleanName && node.callee.kind === 'identifier' && node.args.length === 0 && isBooleanName(node.callee.name)
88
+ case 'member':
89
+ return !!isBooleanName && !node.computed && node.object.kind === 'identifier' && node.object.name === 'props' &&
90
+ isBooleanName(node.property, true)
91
+ case 'identifier':
92
+ return !!isBooleanName && isBooleanName(node.name)
52
93
  default:
53
94
  return false
54
95
  }
@@ -87,3 +128,158 @@ function stringifyBooleanBranch(branch: ParsedExpr): ParsedExpr {
87
128
  }
88
129
  }
89
130
 
131
+
132
+ /**
133
+ * Names whose value is always a JS boolean, for {@link isBooleanResultParsed}'s
134
+ * `isBooleanName` (#3443):
135
+ *
136
+ * - `names`, read as a bare identifier or getter call: signals and memos
137
+ * typed `boolean` (or, untyped, seeded with a boolean literal), local
138
+ * constants typed or seeded so, and — only when the props are
139
+ * destructured — the `boolean` props. A local constant of another type
140
+ * shadows a same-named prop: with a props object (`props.enabled`) a bare
141
+ * `enabled` is never the prop.
142
+ * - `props`, read as `props.X`: the `boolean` props by their source key.
143
+ *
144
+ * A prop counts only when it can't be `undefined` (required, or carrying a
145
+ * default proven boolean); an omitted one stringifies as `undefined`, not
146
+ * `false`, and so does one defaulted to `undefined` or any other non-boolean
147
+ * expression. A loop
148
+ * or callback binding of the same name shadows a bare name, which the
149
+ * caller's scope decides.
150
+ */
151
+ export function collectBooleanValueNames(
152
+ metadata: Pick<IRMetadata, 'signals' | 'memos' | 'propsParams' | 'localConstants' | 'propsObjectName'>,
153
+ ): { names: Set<string>; props: Set<string> } {
154
+ const isBoolean = (type: TypeInfo | null | undefined): boolean =>
155
+ type?.kind === 'primitive' && type.primitive === 'boolean'
156
+ const isBooleanSeed = (type: TypeInfo | null | undefined, seed: string | undefined): boolean => {
157
+ const text = seed?.trim()
158
+ return isBoolean(type) || ((!type || type.kind === 'unknown') && (text === 'true' || text === 'false'))
159
+ }
160
+ const names = new Set<string>()
161
+ const props = new Set<string>()
162
+ for (const signal of metadata.signals) {
163
+ if (isBooleanSeed(signal.type, signal.initialValue)) names.add(signal.getter)
164
+ }
165
+ for (const memo of metadata.memos ?? []) {
166
+ if (isBoolean(memo.type)) names.add(memo.name)
167
+ }
168
+ // A destructure default sees only the bindings before it, so one that
169
+ // reads an earlier proven-boolean param (`{ off = false, on = off }`) is
170
+ // boolean too.
171
+ const provenParams = new Set<string>()
172
+ for (const param of metadata.propsParams) {
173
+ if (!isBoolean(param.type)) continue
174
+ if (param.optional && !(param.parsed && isBooleanResultParsed(param.parsed, (n, member) => !member && provenParams.has(n)))) continue
175
+ provenParams.add(param.name)
176
+ props.add(param.sourceName ?? param.name)
177
+ if (!metadata.propsObjectName) names.add(param.name)
178
+ }
179
+ // A body destructure of a boolean prop (`const { on } = props` →
180
+ // `props.on`), or one defaulted to a boolean (`const { on = false } =
181
+ // props` → `props.on ?? false`), is boolean whatever the prop's
182
+ // optionality: the default covers the absent case.
183
+ const propsObject = metadata.propsObjectName
184
+ const booleanTyped = new Set(
185
+ metadata.propsParams.filter(p => isBoolean(p.type)).map(p => p.sourceName ?? p.name),
186
+ )
187
+ const readsBooleanProp = (e: ParsedExpr | undefined): boolean => {
188
+ if (!e) return false
189
+ if (e.kind === 'member') {
190
+ return !e.computed && !!propsObject && e.object.kind === 'identifier' && e.object.name === propsObject &&
191
+ props.has(e.property)
192
+ }
193
+ if (e.kind === 'logical' && (e.op === '??' || e.op === '||')) {
194
+ const left = e.left
195
+ return left.kind === 'member' && !left.computed && !!propsObject && left.object.kind === 'identifier' &&
196
+ left.object.name === propsObject && booleanTyped.has(left.property) &&
197
+ e.right.kind === 'literal' && e.right.literalType === 'boolean'
198
+ }
199
+ return false
200
+ }
201
+ for (const constant of metadata.localConstants ?? []) {
202
+ if (readsBooleanProp(constant.parsed) || isBooleanSeed(constant.type ?? undefined, constant.value)) names.add(constant.name)
203
+ else names.delete(constant.name)
204
+ }
205
+ return { names, props }
206
+ }
207
+
208
+ /**
209
+ * {@link isBooleanResultParsed} over expression source text: parses `expr`
210
+ * and classifies the tree structurally (no `isBooleanName` witness). An
211
+ * unparseable expression is not boolean-result.
212
+ */
213
+ export function isBooleanResultExpr(expr: string): boolean {
214
+ const parsed = parseExpression(expr.trim())
215
+ if (!parsed) return false
216
+ return isBooleanResultParsed(parsed)
217
+ }
218
+
219
+ /**
220
+ * True when `expr`'s top-level shape is an explicit one-argument JS
221
+ * `String(x)` call (the `EVAL_BUILTIN_IDENTS` builtin the compiler
222
+ * recognizes structurally; each DSL adapter lowers it to its runtime's
223
+ * `string` helper).
224
+ *
225
+ * Guards the {@link isAriaBooleanAttr}-driven `bool_str` override in the DSL
226
+ * adapters' attribute emitters: an author who wrote `String(...)` has opted
227
+ * into JS `String()` semantics, and `bool_str` over that already-stringified
228
+ * value is a truthiness test of a string (`"false"` is a non-empty, truthy
229
+ * string in Python, Ruby, PHP and Java), so it must not run on top.
230
+ */
231
+ export function isExplicitStringCall(expr: string): boolean {
232
+ const parsed = parseExpression(expr.trim())
233
+ return (
234
+ !!parsed &&
235
+ parsed.kind === 'call' &&
236
+ parsed.callee.kind === 'identifier' &&
237
+ parsed.callee.name === 'String' &&
238
+ parsed.args.length === 1
239
+ )
240
+ }
241
+
242
+ /**
243
+ * ARIA attributes whose spec values are `"true"`, `"false"`, and (for
244
+ * tri-state members) `"mixed"`. When a fixture binds one of these to an
245
+ * arbitrary JS expression (`aria-checked={accepted()}`), the expression's
246
+ * type isn't recoverable from source text, but the attribute name witnesses
247
+ * that the binding is boolean-shaped, so the DSL adapters route it through
248
+ * their `bool_str` runtime helper for the spec-canonical `"true"` /
249
+ * `"false"`.
250
+ *
251
+ * Deliberately conservative: only attributes whose spec value set is exactly
252
+ * `true | false` or `true | false | mixed`. Tokenised ARIA attributes
253
+ * (`aria-current` is `page | step | …`, `aria-sort` is `ascending | …`) are
254
+ * excluded so a string-valued binding is never coerced to `"true"` /
255
+ * `"false"`.
256
+ */
257
+ const ARIA_BOOLEAN_ATTRS = new Set([
258
+ // Strict boolean state (true | false; some allow `undefined` = attribute
259
+ // absent, which the runtime emits as no-attr regardless).
260
+ 'aria-atomic',
261
+ 'aria-busy',
262
+ 'aria-disabled',
263
+ 'aria-hidden',
264
+ 'aria-modal',
265
+ 'aria-multiline',
266
+ 'aria-multiselectable',
267
+ 'aria-readonly',
268
+ 'aria-required',
269
+ // true | false | undefined (absent): selection / disclosure state (#1897:
270
+ // tabs' `aria-selected={props.selected ?? false}` rendered Perl's `1` /
271
+ // `0` without this).
272
+ 'aria-selected',
273
+ 'aria-expanded',
274
+ // Tri-state (true | false | mixed). `bool_str` only maps truthy / falsy to
275
+ // true / false; a fixture that wants the literal "mixed" binds a
276
+ // string-valued JSX attr (`aria-checked="mixed"`), which lowers through
277
+ // the `literal` emit path and never reaches this set.
278
+ 'aria-checked',
279
+ 'aria-pressed',
280
+ ])
281
+
282
+ /** Whether `name` is one of {@link ARIA_BOOLEAN_ATTRS}. */
283
+ export function isAriaBooleanAttr(name: string): boolean {
284
+ return ARIA_BOOLEAN_ATTRS.has(name)
285
+ }