@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
@@ -11,6 +11,9 @@
11
11
  * issue #1021 Stage B for the rationale.
12
12
  */
13
13
 
14
+ import ts from 'typescript'
15
+ import { isIdentifierLikeToken, isTriviaKind, iterateJsTokens } from '../scanner/js-scanner.ts'
16
+
14
17
  /** JavaScript keywords and common globals to skip during identifier extraction. */
15
18
  const KEYWORDS_AND_GLOBALS = new Set([
16
19
  'true',
@@ -56,46 +59,94 @@ const KEYWORDS_AND_GLOBALS = new Set([
56
59
  ])
57
60
 
58
61
  /**
59
- * Extract identifiers from an expression string.
62
+ * Words that can never name a binding in module (strict) code. Every other
63
+ * identifier-or-keyword token, contextual keywords included (`type`, `of`,
64
+ * `get`, …), can.
60
65
  */
61
- export function extractIdentifiers(expr: string, set: Set<string>): void {
62
- const matches = expr.match(/\b[a-zA-Z_][a-zA-Z0-9_]*\b/g)
63
- if (matches) {
64
- for (const id of matches) {
65
- if (!isKeywordOrGlobal(id)) {
66
- set.add(id)
67
- }
66
+ const RESERVED_WORDS = new Set([
67
+ 'await', 'break', 'case', 'catch', 'class', 'const', 'continue', 'debugger', 'default', 'delete', 'do',
68
+ 'else', 'enum', 'export', 'extends', 'false', 'finally', 'for', 'function', 'if', 'implements', 'import',
69
+ 'in', 'instanceof', 'interface', 'let', 'new', 'null', 'package', 'private', 'protected', 'public',
70
+ 'return', 'static', 'super', 'switch', 'this', 'throw', 'true', 'try', 'typeof', 'var', 'void', 'while',
71
+ 'with', 'yield',
72
+ ])
73
+
74
+ /**
75
+ * Walk the tokens of `text` (`iterateJsTokens`, the shared JS lexer, which
76
+ * reads a regex literal as one token and closes template substitutions at
77
+ * their own `}`), calling `onName` for every identifier, member names
78
+ * included (`props.value` yields both: the reference graph reads a
79
+ * props-object member as a use of that prop), and `onSubstitution` with the
80
+ * source span of every outermost `${…}` body. String, regex and comment
81
+ * contents produce no names, and `$` is an identifier character, so
82
+ * `step$` / `$step` are found (#3536).
83
+ *
84
+ * A contextual keyword (`type`, `of`, `get`, …) is a legal binding name, so
85
+ * it is reported like an identifier; a reserved word is reported only as a
86
+ * member name (`props.default`).
87
+ */
88
+ function scanNames(
89
+ text: string,
90
+ onName: (name: string) => void,
91
+ onSubstitution?: (start: number, end: number) => void,
92
+ ): void {
93
+ // The source offset where each open template's current `${` body starts.
94
+ const bodyStarts: number[] = []
95
+ let prev: ts.SyntaxKind | undefined
96
+ for (const token of iterateJsTokens(text)) {
97
+ if (isTriviaKind(token.kind)) continue
98
+ if (token.kind === ts.SyntaxKind.TemplateHead) {
99
+ bodyStarts.push(token.end)
100
+ } else if (token.kind === ts.SyntaxKind.TemplateMiddle || token.kind === ts.SyntaxKind.TemplateTail) {
101
+ const bodyStart = bodyStarts.pop()
102
+ // Only an outermost body: a nested template stays inside its parent's.
103
+ if (bodyStart !== undefined && bodyStarts.length === 0) onSubstitution?.(bodyStart, token.pos)
104
+ if (token.kind === ts.SyntaxKind.TemplateMiddle) bodyStarts.push(token.end)
105
+ } else if (isIdentifierLikeToken(token.kind)) {
106
+ const name = text.slice(token.pos, token.end)
107
+ const isMemberName = prev === ts.SyntaxKind.DotToken || prev === ts.SyntaxKind.QuestionDotToken
108
+ if (isMemberName || !RESERVED_WORDS.has(name)) onName(name)
68
109
  }
110
+ prev = token.kind
69
111
  }
70
112
  }
71
113
 
114
+ /** `text` as a template literal: already backtick-quoted, or quoted here. */
115
+ function asTemplateLiteral(text: string): string {
116
+ return text.startsWith('`') && text.endsWith('`') && text.length >= 2 ? text : `\`${text}\``
117
+ }
118
+
72
119
  /**
73
- * Yield each `${...}` substitution body inside a template-style string.
74
- * Returns the inner expressions — the surrounding HTML / static text is
75
- * stripped. Empty array when no substitutions are present.
76
- *
77
- * Uses a `[^}]+` character class rather than a balance-aware scanner —
78
- * cheap and matches the legacy reach. Object literals inside `${...}`
79
- * are not supported (they would split prematurely on the inner `}`).
120
+ * Extract identifiers from an expression string.
121
+ */
122
+ export function extractIdentifiers(expr: string, set: Set<string>): void {
123
+ scanNames(expr, name => {
124
+ if (!isKeywordOrGlobal(name)) set.add(name)
125
+ })
126
+ }
127
+
128
+ /**
129
+ * Yield each `${...}` substitution body inside a template-style string
130
+ * (backtick-quoted or not). Returns the inner expressions — the
131
+ * surrounding HTML / static text is stripped. Empty array when no
132
+ * substitutions are present. Nested braces and template literals inside a
133
+ * body are kept whole.
80
134
  */
81
135
  export function extractTemplateExpressions(template: string): string[] {
82
- const re = /\$\{([^}]+)\}/g
136
+ const literal = asTemplateLiteral(template)
83
137
  const out: string[] = []
84
- let match
85
- while ((match = re.exec(template)) !== null) {
86
- out.push(match[1])
87
- }
138
+ scanNames(literal, () => {}, (start, end) => out.push(literal.slice(start, end)))
88
139
  return out
89
140
  }
90
141
 
91
142
  /**
92
143
  * Extract identifiers from template literal expressions.
93
- * Finds ${...} patterns and extracts identifiers from inside.
144
+ * Only `${...}` substitutions are scanned; static text is not code.
94
145
  */
95
146
  export function extractTemplateIdentifiers(template: string, set: Set<string>): void {
96
- for (const expr of extractTemplateExpressions(template)) {
97
- extractIdentifiers(expr, set)
98
- }
147
+ scanNames(asTemplateLiteral(template), name => {
148
+ if (!isKeywordOrGlobal(name)) set.add(name)
149
+ })
99
150
  }
100
151
 
101
152
  /**
@@ -3,9 +3,10 @@
3
3
  */
4
4
 
5
5
  import ts from 'typescript'
6
- import type { ComponentIR, IRNode } from '../types.ts'
6
+ import type { CompilerError, ComponentIR, ImportInfo, IRNode, SourceLocation } from '../types.ts'
7
+ import { createError, ErrorCodes } from '../errors.ts'
7
8
  import { isClientBuiltinName } from '../builtins.ts'
8
- import { collectValueReferencedNames } from '../value-references.ts'
9
+ import { analyzeEmittedReferences, collectValueReferencedNames } from '../value-references.ts'
9
10
  import { identifierCallPattern } from '../identifier-pattern.ts'
10
11
 
11
12
  // All exports from @barefootjs/client/runtime that may be used in generated code
@@ -84,32 +85,68 @@ export const RUNTIME_MODULE = '@barefootjs/client/runtime'
84
85
  export const IMPORT_PLACEHOLDER = '/* __BAREFOOTJS_DOM_IMPORTS__ */'
85
86
  export const MODULE_CONSTANTS_PLACEHOLDER = '/* __MODULE_LEVEL_CONSTANTS__ */'
86
87
 
88
+ /** Runtime names `detectUsedImports` can report: the candidates plus the slot finders. */
89
+ const RUNTIME_IMPORT_NAMES: ReadonlySet<string> = new Set<string>([...RUNTIME_IMPORT_CANDIDATES, '$', '$c', '$t'])
90
+
87
91
  /**
88
- * Detect which @barefootjs/client/runtime functions are actually used in the generated code
92
+ * Detect which @barefootjs/client/runtime functions the generated code uses:
93
+ * the runtime names it references without binding them itself (#3537). A
94
+ * module-level user helper emitted as `var insert = …`, or a parameter that
95
+ * happens to be called `qsa`, binds its name, so it neither pulls in the
96
+ * runtime import nor collides with it as a duplicate declaration.
97
+ *
98
+ * Falls back to the per-name call scan only when the code does not parse
99
+ * cleanly, where narrowing on a partial parse could drop a needed import.
89
100
  */
90
101
  export function detectUsedImports(code: string): Set<string> {
102
+ const refs = analyzeEmittedReferences(code)
103
+ if (refs) return new Set([...refs.free].filter(name => RUNTIME_IMPORT_NAMES.has(name)))
91
104
  const used = new Set<string>()
92
105
  for (const name of RUNTIME_IMPORT_CANDIDATES) {
93
- // Match function calls: name(
94
- if (identifierCallPattern(name).test(code)) {
95
- used.add(name)
96
- }
97
- }
98
- // Shorthand finders need special detection ($ is not a word character)
99
- if (/\$c\s*\(/.test(code)) {
100
- used.add('$c')
101
- }
102
- // Match $t( for text node finders
103
- if (/\$t\s*\(/.test(code)) {
104
- used.add('$t')
105
- }
106
- // Match $( but not $c( or $t( - use negative lookahead
107
- if (/\$\s*\(/.test(code)) {
108
- used.add('$')
106
+ if (identifierCallPattern(name).test(code)) used.add(name)
109
107
  }
108
+ if (/\$c\s*\(/.test(code)) used.add('$c')
109
+ if (/\$t\s*\(/.test(code)) used.add('$t')
110
+ if (/\$\s*\(/.test(code)) used.add('$')
110
111
  return used
111
112
  }
112
113
 
114
+ /**
115
+ * BF057 for each module-level binding of the user's that takes a runtime
116
+ * helper's name (#3537): a module-level declaration the client JS re-emits,
117
+ * or a value import from anything but the runtime itself, whose name the
118
+ * emitted `code` also calls. That call may be the compiler's own, which the
119
+ * user's binding would capture, so it is refused rather than guessed at.
120
+ * This is exactly the case that used to emit both the binding and a runtime
121
+ * import of the same name, a duplicate-declaration SyntaxError. A binding
122
+ * the code never calls (`const qsa = {…}` read as `qsa.step`) stays legal.
123
+ */
124
+ export function runtimeNameCollisions(
125
+ declarations: readonly { name: string; loc: SourceLocation }[],
126
+ imports: readonly ImportInfo[],
127
+ code: string,
128
+ ): CompilerError[] {
129
+ const runtimeSources = new Set([RUNTIME_MODULE, '@barefootjs/client'])
130
+ const bound = [...declarations]
131
+ for (const imp of imports) {
132
+ if (imp.isTypeOnly || runtimeSources.has(imp.source)) continue
133
+ for (const spec of imp.specifiers) {
134
+ if (!spec.isTypeOnly) bound.push({ name: spec.alias ?? spec.name, loc: imp.loc })
135
+ }
136
+ }
137
+ const colliding = bound.filter(b => RUNTIME_IMPORT_NAMES.has(b.name))
138
+ if (colliding.length === 0) return []
139
+ const called = analyzeEmittedReferences(code)?.called
140
+ return colliding
141
+ .filter(b => called?.has(b.name) ?? true)
142
+ .map(b =>
143
+ createError(ErrorCodes.RUNTIME_HELPER_NAME_COLLISION, b.loc, {
144
+ message: `'${b.name}' is also a BarefootJS runtime helper, and the compiled client JS calls '${b.name}(…)'. ` +
145
+ 'Rename the declaration, or import it under an alias.',
146
+ }),
147
+ )
148
+ }
149
+
113
150
  /**
114
151
  * Collect user-defined imports from @barefootjs/client (or the
115
152
  * compiler-emitted /runtime subpath).
@@ -22,7 +22,7 @@ import { buildInlinableConstants, csrInlinableConstantsFromCtx } from './emit-re
22
22
  import { buildEnvFromCtx } from './compute-inlinability.ts'
23
23
  import { nameForRegistryRef, buildImportAliasMap, setActiveImportAliases } from './component-scope.ts'
24
24
  import { resolveRestSpreadNames } from './prop-handling.ts'
25
- import { IMPORT_PLACEHOLDER, RUNTIME_MODULE, detectUsedImports, collectExternalImports } from './imports.ts'
25
+ import { IMPORT_PLACEHOLDER, RUNTIME_MODULE, detectUsedImports, collectExternalImports, runtimeNameCollisions } from './imports.ts'
26
26
  import { isInlinableInTemplate } from '../relocate.ts'
27
27
  import { buildSourceMapFromIR, type SourceMapV3 } from './source-map.ts'
28
28
  import { resolvePropDeclaredType, baseTypeName } from '../rich-type-evidence.ts'
@@ -391,6 +391,7 @@ function generateTemplateOnlyMount(ir: ComponentIR, ctx: ClientJsContext): strin
391
391
  // same — without it, a constant whose value got inlined into the
392
392
  // template (e.g. `useYjs(_p.x)`) leaves the template referencing a
393
393
  // bare module-import name that's no longer imported (#1138 / #1133).
394
+ ctx.warnings.push(...runtimeNameCollisions([], ir.metadata.imports, generatedCode))
394
395
  const externalImports = collectExternalImports(ir, generatedCode)
395
396
  const allImports = externalImports.length > 0
396
397
  ? `${importLine}\n${externalImports.join('\n')}`
@@ -17,7 +17,7 @@
17
17
  */
18
18
 
19
19
  import type { ClientJsContext } from '../types.ts'
20
- import { toDomEventName, varSlotId, wrapHandlerInBlock, wrapHandlerForTurn } from '../utils.ts'
20
+ import { toDomEventName, varSlotId, wrapHandlerForTurn } from '../utils.ts'
21
21
  import type { LoopDelegationIndex } from '../control-flow/plan/loop-delegation-index.ts'
22
22
 
23
23
  export function emitEventHandlers(
@@ -35,7 +35,7 @@ export function emitEventHandlers(
35
35
  // profiling run attributes the reactive work it triggers to this turn.
36
36
  const wrappedHandler = ctx.profile
37
37
  ? wrapHandlerForTurn(event.handler, `${ctx.componentName}#handler:${elem.slotId}:${event.name}`)
38
- : wrapHandlerInBlock(event.handler)
38
+ : event.handler.trim()
39
39
  if (elem.slotId === '__scope') {
40
40
  lines.push(` if (__scope) __scope.addEventListener('${eventName}', ${wrappedHandler})`)
41
41
  } else {
@@ -1,6 +1,7 @@
1
1
  /**
2
2
  * `props-extraction` phase — emit the one surviving one-time prop
3
- * extraction, `const children = _p.children [?? <default>]`.
3
+ * extraction, `const children = _p.children [?? <default>]` (or
4
+ * `const kids = _p.children` for a renamed `{ children: kids }`).
4
5
  *
5
6
  * `children` must stay a ONE-TIME read: a prop's slot-children value is a
6
7
  * getter that INSTANTIATES child components when read (see
@@ -18,13 +19,10 @@
18
19
  * downstream code there reads `_p.X` directly via the late-stage rename.
19
20
  */
20
21
 
21
- import type { PropUsage } from '../../types.ts'
22
+ import { type PropUsage, isChildrenPropParam } from '../../types.ts'
22
23
  import { computePropsUsedAsConditions } from '../compute-prop-usage.ts'
23
24
  import { propReadBase, propReadFallback } from '../../props-binding.ts'
24
25
  import type { ClientJsContext } from '../types.ts'
25
- import { PROPS_PARAM } from '../utils.ts'
26
-
27
- const CHILDREN = 'children'
28
26
 
29
27
  export function emitPropsExtraction(
30
28
  lines: string[],
@@ -33,16 +31,19 @@ export function emitPropsExtraction(
33
31
  propUsage: Map<string, PropUsage>,
34
32
  ): void {
35
33
  if (ctx.propsObjectName) return
36
- if (!neededProps.has(CHILDREN)) return
37
-
38
- const prop = ctx.propsParams.find(p => p.name === CHILDREN)
39
- if (!prop) {
40
- lines.push(` const ${CHILDREN} = ${PROPS_PARAM}.${CHILDREN}`, '')
41
- return
42
- }
34
+ // The children prop's local binding: `children`, or the renamed local of
35
+ // `{ children: kids }` (`isChildrenPropParam`, #3572), which reads
36
+ // `_p.children` the same one-time way. A local named `children` that binds
37
+ // another prop (`{ items: children }`) is an ordinary prop, read live.
38
+ // `neededProps` holds only props-param locals, so a component with no
39
+ // children param has nothing to extract.
40
+ const prop = ctx.propsParams.find(isChildrenPropParam)
41
+ if (!prop) return
42
+ const local = prop.name
43
+ if (!neededProps.has(local)) return
43
44
 
44
- const usedAsCondition = computePropsUsedAsConditions(ctx, neededProps).has(CHILDREN)
45
- const fallback = propReadFallback(prop, propUsage.get(CHILDREN), usedAsCondition)
45
+ const usedAsCondition = computePropsUsedAsConditions(ctx, neededProps).has(local)
46
+ const fallback = propReadFallback(prop, propUsage.get(local), usedAsCondition)
46
47
  const read = propReadBase(prop) + (fallback === null ? '' : ` ?? ${fallback}`)
47
- lines.push(` const ${CHILDREN} = ${read}`, '')
48
+ lines.push(` const ${local} = ${read}`, '')
48
49
  }
@@ -13,7 +13,7 @@ import type { Declaration } from '../declaration-sort.ts'
13
13
  import type { ClientJsContext } from '../types.ts'
14
14
  import type { ParamInfo, SignalInfo } from '../../types.ts'
15
15
  import { inferDefaultValue, PROPS_PARAM, readsBareProp } from '../utils.ts'
16
- import { livePropReadExpr } from '../../props-binding.ts'
16
+ import { livePropReadExpr, propDefaultText } from '../../props-binding.ts'
17
17
  import { signalFactoryInitializer, signalSecondBinding } from '../../signal-initializer.ts'
18
18
  import type {
19
19
  ControlledSignalEffectPlan,
@@ -138,7 +138,7 @@ function resolveSignalInitialValue(signal: SignalInfo, lookups: DeclarationEmitL
138
138
  const controlled = lookups.controlledBySignal.get(signal)
139
139
  if (controlled) {
140
140
  const prop = lookups.propByName.get(controlled.propName)
141
- const defaultVal = prop?.defaultValue ?? inferDefaultValue(signal.type)
141
+ const defaultVal = (prop && propDefaultText(prop)) ?? inferDefaultValue(signal.type)
142
142
  // `_p` is always keyed by the caller-facing name (#2524 CSR half).
143
143
  return `${PROPS_PARAM}.${prop?.sourceName ?? controlled.propName} ?? ${defaultVal}`
144
144
  }
@@ -40,7 +40,7 @@ import { PROPS_PARAM } from './utils.ts'
40
40
  * Does `init` read `<objectName>.<key>` or `<objectName>.<key> ?? <fallback>`?
41
41
  * The one recognizer for "a prop read initializer", shared by
42
42
  * `propExtractionName` below (which additionally requires the bound name to
43
- * equal `key`, and always reads off `_p`), `rewriteBodyAliasReads`
43
+ * equal `key` unless `key` is `children`, and always reads off `_p`), `rewriteBodyAliasReads`
44
44
  * (`rewrite-destructured-props.ts`, which does not require the name match —
45
45
  * a renamed alias's bound name differs from `key` by definition, but also
46
46
  * always reads off `_p`), and `resolveBodyPropAliases` (`props-binding.ts`,
@@ -66,8 +66,11 @@ export function parsePropReadInitializer(
66
66
  }
67
67
 
68
68
  /** Is `stmt` a single-declarator `const X = _p.X…` prop extraction whose
69
- * initializer is `_p.X` or `_p.X ?? <default>`? Returns the bound name, or
70
- * null when the statement is anything else. */
69
+ * initializer is `_p.X` or `_p.X ?? <default>`? The children prop's
70
+ * extraction may bind another name (`const kids = _p.children`, a renamed
71
+ * `{ children: kids }`, #3572): its eager read is the hazard this pass
72
+ * removes, so it matches under any name. Returns the bound name, or null
73
+ * when the statement is anything else. */
71
74
  function propExtractionName(stmt: ts.Statement): string | null {
72
75
  if (!ts.isVariableStatement(stmt)) return null
73
76
  const decls = stmt.declarationList.declarations
@@ -76,7 +79,7 @@ function propExtractionName(stmt: ts.Statement): string | null {
76
79
  if (!ts.isIdentifier(decl.name) || !decl.initializer) return null
77
80
 
78
81
  const parsed = parsePropReadInitializer(decl.initializer)
79
- if (parsed === null || parsed.key !== decl.name.text) return null
82
+ if (parsed === null || (parsed.key !== decl.name.text && parsed.key !== 'children')) return null
80
83
  return decl.name.text
81
84
  }
82
85
 
@@ -2,7 +2,7 @@
2
2
  * Reactivity detection: reactive expression checking, event/ref collection.
3
3
  */
4
4
 
5
- import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin } from '../types.ts'
5
+ import { type IRNode, type IRElement, type IRComponent, type IRLoop, type IRProp, type LoopParamBinding, type OriginInfo, pickAttrMetaFromIR, isReactiveOrigin, isChildrenPropParam } from '../types.ts'
6
6
  import type {
7
7
  ClientJsContext,
8
8
  ConditionalBranchEvent,
@@ -237,7 +237,7 @@ function needsEffectWrapperCore(
237
237
  // Check individual prop names (excluding children which is server-rendered
238
238
  // and should not trigger effect wrapping on the client)
239
239
  for (const prop of ctx.propsParams) {
240
- if (prop.name === 'children') continue
240
+ if (isChildrenPropParam(prop)) continue
241
241
  if (freeIdentifiers ? freeIdentifiers.has(prop.name) : tokenContainsIdent(expr, prop.name)) {
242
242
  return true
243
243
  }
@@ -25,7 +25,7 @@
25
25
  */
26
26
 
27
27
  import ts from 'typescript'
28
- import type { PropUsage } from '../types.ts'
28
+ import { type PropUsage, isChildrenPropParam } from '../types.ts'
29
29
  import { computePropsUsedAsConditions } from './compute-prop-usage.ts'
30
30
  import { boundPropLocalNames, livePropReadExpr, resolveBodyPropAliases, type LivePropReadInfo } from '../props-binding.ts'
31
31
  import { parsePropReadInitializer } from './prune-unused-prop-extractions.ts'
@@ -54,7 +54,8 @@ export function rewriteDestructuredPropReads(
54
54
  * handler-local `const title = 'local'` keep their own binding even when
55
55
  * `title` is also a prop name.
56
56
  *
57
- * Excluding `children`: reading `_p.children` live re-invokes a getter that
57
+ * Excluding the children prop (`isChildrenPropParam`, renamed or not):
58
+ * reading `_p.children` live re-invokes a getter that
58
59
  * instantiates child components (see `emitPropsExtraction`) — `children`
59
60
  * must stay a captured-once read, by design.
60
61
  *
@@ -74,7 +75,7 @@ function rewriteParamDestructuredReads(
74
75
  propUsage: ReadonlyMap<string, PropUsage>,
75
76
  ): string {
76
77
  const names = new Set(boundPropLocalNames(ctx))
77
- names.delete('children')
78
+ for (const p of ctx.propsParams) if (isChildrenPropParam(p)) names.delete(p.name)
78
79
  if (names.size === 0) return code
79
80
 
80
81
  const propsUsedAsConditions = computePropsUsedAsConditions(ctx, names)
@@ -102,6 +103,16 @@ function rewriteParamDestructuredReads(
102
103
  return result
103
104
  }
104
105
 
106
+ /**
107
+ * The `defaultParts` the analyzer recorded on a body-destructured local's
108
+ * props param (`ParamInfo.defaultParts`), when its default reads an earlier
109
+ * binding of the same pattern.
110
+ */
111
+ function bodyAliasDefaultParts(ctx: ClientJsContext, local: string, key: string): Pick<LivePropReadInfo, 'defaultParts'> {
112
+ const param = ctx.propsParams.find(p => !p.isRest && p.name === local && (p.sourceName ?? p.name) === key)
113
+ return param?.defaultParts ? { defaultParts: param.defaultParts } : {}
114
+ }
115
+
105
116
  /**
106
117
  * Rewrite every bare value-position read of a BODY-destructured (or
107
118
  * bare-member-alias) prop local in `code` to a live `_p.<key>` read, for a
@@ -150,7 +161,7 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
150
161
  const sourceFile = ts.createSourceFile('init-body.ts', code, ts.ScriptTarget.Latest, /*setParentNodes*/ true, ts.ScriptKind.TS)
151
162
 
152
163
  const spans: Array<readonly [number, number]> = []
153
- const located = new Map<string, { key: string; defaultValue?: string; defaultContainsArrow?: boolean }>()
164
+ const located = new Map<string, Pick<LivePropReadInfo, 'defaultValue' | 'defaultContainsArrow' | 'defaultParts'> & { key: string }>()
154
165
  for (const stmt of sourceFile.statements) {
155
166
  if (!ts.isFunctionDeclaration(stmt) || !stmt.name?.text.startsWith('init') || !stmt.body) continue
156
167
  for (const inner of stmt.body.statements) {
@@ -181,6 +192,11 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
181
192
  defaultContainsArrow: alias.defaultContainsArrow && !(
182
193
  parsedInit.fallback && ts.isParenthesizedExpression(parsedInit.fallback)
183
194
  ),
195
+ // A default reading an earlier binding of the same destructure
196
+ // (`const { off = false, on = off } = props`, #3531): the analyzer
197
+ // split it on the binding's props param, and the earlier binding's
198
+ // declaration is gone from this body, so the read renders live.
199
+ ...bodyAliasDefaultParts(ctx, decl.name.text, alias.key),
184
200
  })
185
201
  spans.push([inner.getFullStart(), inner.getEnd()])
186
202
  }
@@ -205,6 +221,7 @@ function rewriteBodyAliasReads(code: string, ctx: ClientJsContext): string {
205
221
  sourceName: info.key,
206
222
  defaultValue: info.defaultValue,
207
223
  defaultContainsArrow: info.defaultContainsArrow,
224
+ ...(info.defaultParts && { defaultParts: info.defaultParts }),
208
225
  }
209
226
  return livePropReadExpr(prop, undefined, false)
210
227
  }
@@ -37,7 +37,7 @@
37
37
  */
38
38
 
39
39
  import type { IRExpression } from '../types.ts'
40
- import { parseExpression, type ParsedExpr } from '../expression-parser.ts'
40
+ import { PROPS_PARAM } from './utils.ts'
41
41
 
42
42
  /**
43
43
  * A JS expression string that evaluates, in the client template, to HTML
@@ -110,6 +110,27 @@ export function childrenMarkup(expr: string): SafeHtml {
110
110
  return safeHtml(`markupOrEmpty(${expr})`)
111
111
  }
112
112
 
113
+ /**
114
+ * `_p.children == null ? escapeText(expr) : markupOrEmpty(_p.children)` — a
115
+ * read of the children prop with a text fallback: `children ?? 'x'`,
116
+ * `(children ?? '<b>x</b>') ?? ''` (`absentWhen: 'nullish'`), or
117
+ * `children || 'x'` (`absentWhen: 'falsy'`, tested as `!_p.children`); #3554.
118
+ * Phase 1 decided from the binding that the chain's head is the component's
119
+ * own `children` prop (`IRExpression.childrenRead`), so the head is read where
120
+ * every client template finds that prop, `_p.children` (the same place the
121
+ * Phase 1 `templateExpr` rewrite and the alias inlining resolve a destructured
122
+ * or aliased `children` to). Present children are the HTML string
123
+ * `materializeComponent` joined, spliced as `childrenMarkup` does; otherwise
124
+ * `expr` (the whole lowered chain) evaluates to its fallback, which is text
125
+ * and escaped. `expr` is not split: when the head is absent,
126
+ * `(c ?? x) ?? y` and `c ?? (x ?? y)` both evaluate to `x ?? y`.
127
+ */
128
+ export function childrenMarkupOrEscapedFallback(expr: string, absentWhen: 'nullish' | 'falsy'): SafeHtml {
129
+ const children = `${PROPS_PARAM}.children`
130
+ const absent = absentWhen === 'nullish' ? `${children} == null` : `!${children}`
131
+ return safeHtml(`${absent} ? escapeText(${expr}) : markupOrEmpty(${children})`)
132
+ }
133
+
113
134
  /**
114
135
  * Stage 3 / D4 — an element-array child (`{out}`) built by an arbitrary
115
136
  * `.map()` preamble is an array of compiled-leaf HTML strings; join it
@@ -179,37 +200,6 @@ export const EMPTY_MARKUP: SafeHtml = safeHtml("''")
179
200
  // The door for a child-position expression node.
180
201
  // ---------------------------------------------------------------------------
181
202
 
182
- /**
183
- * Recognizes a JSX child-position expression that is exactly a reference to
184
- * the reserved `children` prop, optionally with `?? ''`: bare `children` (destructured) or
185
- * `<receiver>.children` for any single-identifier receiver (`props.children`,
186
- * a custom props-param name, a loop-scoped alias closing over props, ...).
187
- *
188
- * Deliberately LOOSER than `isTransparentFragment` (`jsx-to-ir.ts`), which
189
- * runs on the TS AST with the analyzer-resolved props name in hand. This
190
- * layer parses IR expressions without analyzer context, so any single-identifier receiver
191
- * is the available approximation. The looseness costs nothing measurable: an
192
- * unrelated `.children` member (a tree node's own `children` array, say) is a
193
- * reactive member expression that gets a `slotId` and takes the slotted arm
194
- * of `spliceChildValue` before this predicate is consulted.
195
- */
196
- function isChildrenPassthroughExpr(expr: string): boolean {
197
- return isChildrenPassthrough(parseExpression(expr))
198
- }
199
-
200
- function isChildrenPassthrough(expr: ParsedExpr): boolean {
201
- if (expr.kind === 'identifier') return expr.name === 'children'
202
- if (expr.kind === 'member') {
203
- return expr.object.kind === 'identifier' && expr.property === 'children'
204
- && !expr.computed && !expr.optional
205
- }
206
- // An empty fallback adds no untrusted text to the compiler-built markup.
207
- // Other fallbacks still take the escape-by-default path.
208
- return expr.kind === 'logical' && expr.op === '??'
209
- && expr.right.kind === 'literal' && expr.right.value === ''
210
- && isChildrenPassthrough(expr.left)
211
- }
212
-
213
203
  export interface ChildSpliceContext {
214
204
  /**
215
205
  * Set while emitting inside a conditional-branch `template()` arrow
@@ -241,7 +231,9 @@ export interface ChildSpliceContext {
241
231
  * 3. `slotId` ∈ markupSlotIds → `escapedTextOrMarkup`
242
232
  * 4. `slotId` → `escapedText`
243
233
  * 5. `{children}` passthrough → `childrenMarkup` (bare splice only, #2775/#2786)
244
- * 6. otherwise → `escapedText`
234
+ * 6. `children ?? fallback`, → `childrenMarkupOrEscapedFallback` (#3554)
235
+ * `children || fallback`
236
+ * 7. otherwise → `escapedText`
245
237
  *
246
238
  * Arm 5 tests BOTH `node.expr` (the original source text, stable across
247
239
  * builders) and the caller's resolved form (with parentheses handled structurally): a
@@ -250,7 +242,7 @@ export interface ChildSpliceContext {
250
242
  * either alone misses one of the two shapes (#2786).
251
243
  */
252
244
  export function spliceChildValue(
253
- node: Pick<IRExpression, 'expr' | 'slotId' | 'joinArrayChild'>,
245
+ node: Pick<IRExpression, 'expr' | 'slotId' | 'joinArrayChild' | 'childrenRead'>,
254
246
  valueExpr: string,
255
247
  cx: ChildSpliceContext,
256
248
  ): SafeHtml {
@@ -259,8 +251,10 @@ export function spliceChildValue(
259
251
  if (node.slotId) {
260
252
  return cx.markupSlotIds?.has(node.slotId) ? escapedTextOrMarkup(valueExpr) : escapedText(valueExpr)
261
253
  }
262
- if (isChildrenPassthroughExpr(node.expr) || isChildrenPassthroughExpr(valueExpr)) {
254
+ if (node.childrenRead === 'bare' || node.childrenRead === 'nullish-empty') {
263
255
  return childrenMarkup(valueExpr)
264
256
  }
257
+ if (node.childrenRead === 'nullish-fallback') return childrenMarkupOrEscapedFallback(valueExpr, 'nullish')
258
+ if (node.childrenRead === 'or-fallback') return childrenMarkupOrEscapedFallback(valueExpr, 'falsy')
265
259
  return escapedText(valueExpr)
266
260
  }
@@ -24,6 +24,7 @@ import type {
24
24
  TypeDefinition,
25
25
  MapCallbackPreamble,
26
26
  PreambleRegionSource,
27
+ JsSourceText,
27
28
  } from '../types.ts'
28
29
  import type { CsrInlinabilityMap } from './csr-substitute.ts'
29
30
  import type { SkeletonSlotPaths } from './html-template.ts'
@@ -197,7 +198,7 @@ export interface DynamicElement {
197
198
  export interface ConditionalBranchEvent {
198
199
  slotId: string
199
200
  eventName: string
200
- handler: string
201
+ handler: JsSourceText
201
202
  }
202
203
 
203
204
  export interface ConditionalBranchRef {
@@ -528,7 +529,7 @@ export interface NestedLoop extends LoopCore {
528
529
  export interface LoopChildEvent {
529
530
  eventName: string // 'click', 'submit', etc.
530
531
  childSlotId: string // bf slot ID of the element with the event
531
- handler: string // Handler expression (may reference loop param)
532
+ handler: JsSourceText // Handler expression (may reference loop param)
532
533
  /** Nesting info for events inside nested inner loops. Empty = direct child. */
533
534
  nestedLoops: NestedLoop[]
534
535
  /** DOM nesting depth (0 = loop body root). Deepest-first sorting for event delegation (#774). */
@@ -4,7 +4,7 @@
4
4
  */
5
5
 
6
6
  import ts from 'typescript'
7
- import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR } from '../types.ts'
7
+ import type { AttrValue, IRTemplatePart, LoopParamBinding, FreeReference, IRNode, IRFragment, ComponentIR, JsSourceText } from '../types.ts'
8
8
  import type { TopLevelLoop, BranchLoop, LoopOffset } from './types.ts'
9
9
  import { isNonReferenceIdentifierPosition } from '../analyzer.ts'
10
10
  import { BindingScope, type LoopBindingSource } from '../scope/binding-scope.ts'
@@ -387,30 +387,6 @@ export function quotePropName(name: string): string {
387
387
  // toHtmlAttrName is now re-exported from @barefootjs/shared (classifyDOMProp's
388
388
  // toHTMLAttrName), keeping the same public name for downstream consumers.
389
389
 
390
- /**
391
- * Wrap arrow function handler in block to prevent accidental return false.
392
- * Returning false from a DOM event handler prevents default behavior.
393
- *
394
- * Example:
395
- * Input: (e) => e.key === 'Enter' && handleAdd()
396
- * Output: (e) => { e.key === 'Enter' && handleAdd() }
397
- */
398
- export function wrapHandlerInBlock(handler: string): string {
399
- const trimmed = handler.trim()
400
-
401
- if (trimmed.startsWith('(') && trimmed.includes('=>')) {
402
- const arrowIndex = trimmed.indexOf('=>')
403
- const params = trimmed.substring(0, arrowIndex + 2)
404
- const body = trimmed.substring(arrowIndex + 2).trim()
405
-
406
- if (!body.startsWith('{')) {
407
- return `${params} { ${body} }`
408
- }
409
- }
410
-
411
- return trimmed
412
- }
413
-
414
390
  /**
415
391
  * Profile mode (#1690, SR3): wrap an event handler so a profiling run can
416
392
  * attribute the reactive work it triggers to one turn. The original handler
@@ -424,7 +400,7 @@ export function wrapHandlerInBlock(handler: string): string {
424
400
  * emitted while it runs. Used at every handler emit site in profile mode so
425
401
  * no path is left unattributed.
426
402
  */
427
- export function wrapHandlerForTurn(handler: string, handlerId: string, loc?: string): string {
403
+ export function wrapHandlerForTurn(handler: JsSourceText, handlerId: string, loc?: string): string {
428
404
  const idArg = loc ? `${JSON.stringify(handlerId)}, ${JSON.stringify(loc)}` : JSON.stringify(handlerId)
429
405
  return `(...__bfa) => { beginTurn(${idArg}); try { return (${handler.trim()})(...__bfa) } finally { endTurn() } }`
430
406
  }