@barefootjs/jsx 0.35.4 → 0.35.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 (113) hide show
  1. package/dist/analyzer-context.d.ts +5 -4
  2. package/dist/analyzer-context.d.ts.map +1 -1
  3. package/dist/analyzer.d.ts.map +1 -1
  4. package/dist/errors.d.ts +0 -1
  5. package/dist/errors.d.ts.map +1 -1
  6. package/dist/index.js +5306 -4949
  7. package/dist/ir-to-client-js/compute-inlinability.d.ts +8 -0
  8. package/dist/ir-to-client-js/compute-inlinability.d.ts.map +1 -1
  9. package/dist/ir-to-client-js/compute-prop-usage.d.ts +6 -0
  10. package/dist/ir-to-client-js/compute-prop-usage.d.ts.map +1 -1
  11. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts +3 -2
  12. package/dist/ir-to-client-js/control-flow/plan/build-event-delegation.d.ts.map +1 -1
  13. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts +12 -2
  14. package/dist/ir-to-client-js/control-flow/plan/build-loop.d.ts.map +1 -1
  15. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts +40 -0
  16. package/dist/ir-to-client-js/control-flow/plan/event-collision.d.ts.map +1 -0
  17. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts +13 -0
  18. package/dist/ir-to-client-js/control-flow/plan/event-delegation.d.ts.map +1 -1
  19. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts +45 -0
  20. package/dist/ir-to-client-js/control-flow/plan/loop-delegation-index.d.ts.map +1 -0
  21. package/dist/ir-to-client-js/control-flow/plan/types.d.ts +2 -0
  22. package/dist/ir-to-client-js/control-flow/plan/types.d.ts.map +1 -1
  23. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts +12 -0
  24. package/dist/ir-to-client-js/control-flow/stringify/event-delegation.d.ts.map +1 -1
  25. package/dist/ir-to-client-js/control-flow.d.ts +2 -1
  26. package/dist/ir-to-client-js/control-flow.d.ts.map +1 -1
  27. package/dist/ir-to-client-js/emit-reactive.d.ts +7 -3
  28. package/dist/ir-to-client-js/emit-reactive.d.ts.map +1 -1
  29. package/dist/ir-to-client-js/generate-init.d.ts.map +1 -1
  30. package/dist/ir-to-client-js/imports.d.ts +2 -2
  31. package/dist/ir-to-client-js/imports.d.ts.map +1 -1
  32. package/dist/ir-to-client-js/index.d.ts +1 -0
  33. package/dist/ir-to-client-js/index.d.ts.map +1 -1
  34. package/dist/ir-to-client-js/phases/event-handlers.d.ts +9 -1
  35. package/dist/ir-to-client-js/phases/event-handlers.d.ts.map +1 -1
  36. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts +5 -0
  37. package/dist/ir-to-client-js/phases/props-event-handlers.d.ts.map +1 -1
  38. package/dist/ir-to-client-js/phases/props-extraction.d.ts +15 -13
  39. package/dist/ir-to-client-js/phases/props-extraction.d.ts.map +1 -1
  40. package/dist/ir-to-client-js/phases.d.ts +12 -1
  41. package/dist/ir-to-client-js/phases.d.ts.map +1 -1
  42. package/dist/ir-to-client-js/plan/build-declaration-emit.d.ts.map +1 -1
  43. package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
  44. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts +50 -0
  45. package/dist/ir-to-client-js/prune-unused-prop-extractions.d.ts.map +1 -1
  46. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts +29 -0
  47. package/dist/ir-to-client-js/rewrite-destructured-props.d.ts.map +1 -0
  48. package/dist/ir-to-client-js/utils.d.ts +21 -1
  49. package/dist/ir-to-client-js/utils.d.ts.map +1 -1
  50. package/dist/jsx-to-ir.d.ts.map +1 -1
  51. package/dist/prop-rewrite.d.ts.map +1 -1
  52. package/dist/props-binding.d.ts +112 -1
  53. package/dist/props-binding.d.ts.map +1 -1
  54. package/dist/ssr-defaults.d.ts.map +1 -1
  55. package/dist/static-literal.d.ts +20 -8
  56. package/dist/static-literal.d.ts.map +1 -1
  57. package/dist/types.d.ts +38 -0
  58. package/dist/types.d.ts.map +1 -1
  59. package/package.json +2 -2
  60. package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +31 -35
  61. package/src/__tests__/aliased-destructured-prop-csr.test.ts +19 -7
  62. package/src/__tests__/body-destructured-prop-default-propsparams.test.ts +153 -0
  63. package/src/__tests__/body-destructured-props-live.test.ts +245 -0
  64. package/src/__tests__/client-js-generation.test.ts +11 -4
  65. package/src/__tests__/client-only-date-lowering.test.ts +5 -2
  66. package/src/__tests__/destructured-from-props-localconst-value.test.ts +17 -6
  67. package/src/__tests__/destructured-props-live.test.ts +167 -0
  68. package/src/__tests__/doc-examples.test.ts +2 -4
  69. package/src/__tests__/event-delegation-container-collision-2930.test.ts +197 -0
  70. package/src/__tests__/format-error.test.ts +5 -3
  71. package/src/__tests__/issue-2910-mutated-const-not-inlined.test.ts +118 -0
  72. package/src/__tests__/issue-2910-own-scope-id-emission.test.ts +64 -0
  73. package/src/__tests__/live-only-props.test.ts +160 -0
  74. package/src/__tests__/prop-references.test.ts +26 -17
  75. package/src/__tests__/props-destructuring.test.ts +6 -275
  76. package/src/__tests__/prune-unused-prop-extractions.test.ts +11 -5
  77. package/src/__tests__/signal-getter-not-called.test.ts +5 -0
  78. package/src/__tests__/ssr-defaults.test.ts +83 -0
  79. package/src/__tests__/staged-ir/02-shadow-guards.test.ts +12 -5
  80. package/src/__tests__/static-literal.test.ts +39 -4
  81. package/src/analyzer-context.ts +8 -7
  82. package/src/analyzer.ts +233 -106
  83. package/src/errors.ts +7 -8
  84. package/src/ir-to-client-js/compute-inlinability.ts +8 -1
  85. package/src/ir-to-client-js/compute-prop-usage.ts +19 -0
  86. package/src/ir-to-client-js/control-flow/plan/build-event-delegation.ts +5 -0
  87. package/src/ir-to-client-js/control-flow/plan/build-loop.ts +27 -11
  88. package/src/ir-to-client-js/control-flow/plan/event-collision.ts +55 -0
  89. package/src/ir-to-client-js/control-flow/plan/event-delegation.ts +13 -0
  90. package/src/ir-to-client-js/control-flow/plan/loop-delegation-index.ts +79 -0
  91. package/src/ir-to-client-js/control-flow/plan/types.ts +2 -0
  92. package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +50 -10
  93. package/src/ir-to-client-js/control-flow.ts +68 -31
  94. package/src/ir-to-client-js/emit-reactive.ts +12 -8
  95. package/src/ir-to-client-js/emit-registration.ts +2 -2
  96. package/src/ir-to-client-js/generate-init.ts +22 -2
  97. package/src/ir-to-client-js/imports.ts +6 -0
  98. package/src/ir-to-client-js/index.ts +51 -3
  99. package/src/ir-to-client-js/phases/event-handlers.ts +10 -0
  100. package/src/ir-to-client-js/phases/props-event-handlers.ts +6 -0
  101. package/src/ir-to-client-js/phases/props-extraction.ts +29 -48
  102. package/src/ir-to-client-js/phases.ts +17 -3
  103. package/src/ir-to-client-js/plan/build-declaration-emit.ts +6 -5
  104. package/src/ir-to-client-js/prop-handling.ts +9 -0
  105. package/src/ir-to-client-js/prune-unused-prop-extractions.ts +31 -10
  106. package/src/ir-to-client-js/rewrite-destructured-props.ts +210 -0
  107. package/src/ir-to-client-js/utils.ts +29 -1
  108. package/src/jsx-to-ir.ts +110 -48
  109. package/src/prop-rewrite.ts +11 -0
  110. package/src/props-binding.ts +171 -6
  111. package/src/ssr-defaults.ts +10 -5
  112. package/src/static-literal.ts +21 -9
  113. package/src/types.ts +38 -0
package/src/analyzer.ts CHANGED
@@ -25,7 +25,7 @@ import {
25
25
  isArrowComponentFunction,
26
26
  collectReactiveGetterNames,
27
27
  } from './analyzer-context.ts'
28
- import { createError, createWarning, ErrorCodes, type ErrorCode } from './errors.ts'
28
+ import { createError, ErrorCodes, type ErrorCode } from './errors.ts'
29
29
  import { baseTypeName } from './rich-type-evidence.ts'
30
30
  import { CATALOGUED_RICH_TYPE_NAMES } from './date-lowering.ts'
31
31
  import path from 'node:path'
@@ -1806,6 +1806,7 @@ function collectInitStatement(node: ts.Statement, ctx: AnalyzerContext): void {
1806
1806
  loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
1807
1807
  freeIdentifiers: extractFreeIdentifiersFromNode(node),
1808
1808
  assignedIdentifiers: extractAssignedIdentifiersFromNode(node),
1809
+ mutatedIdentifiers: extractMutatedIdentifiersFromNode(node),
1809
1810
  // Init statements run inside the component's init function, so they
1810
1811
  // belong to `init` scope. Phase is conservatively `hydrate` (run-once
1811
1812
  // at hydration). relocate() can refine this when consuming the field.
@@ -1896,28 +1897,8 @@ function extractAssignedIdentifiersFromNode(node: ts.Node): Set<string> {
1896
1897
  ) {
1897
1898
  return
1898
1899
  }
1899
- if (ts.isBinaryExpression(n)) {
1900
- const op = n.operatorToken.kind
1901
- if (
1902
- op === ts.SyntaxKind.EqualsToken ||
1903
- op === ts.SyntaxKind.PlusEqualsToken ||
1904
- op === ts.SyntaxKind.MinusEqualsToken ||
1905
- op === ts.SyntaxKind.AsteriskEqualsToken ||
1906
- op === ts.SyntaxKind.SlashEqualsToken ||
1907
- op === ts.SyntaxKind.PercentEqualsToken ||
1908
- op === ts.SyntaxKind.AsteriskAsteriskEqualsToken ||
1909
- op === ts.SyntaxKind.AmpersandEqualsToken ||
1910
- op === ts.SyntaxKind.BarEqualsToken ||
1911
- op === ts.SyntaxKind.CaretEqualsToken ||
1912
- op === ts.SyntaxKind.LessThanLessThanEqualsToken ||
1913
- op === ts.SyntaxKind.GreaterThanGreaterThanEqualsToken ||
1914
- op === ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken ||
1915
- op === ts.SyntaxKind.AmpersandAmpersandEqualsToken ||
1916
- op === ts.SyntaxKind.BarBarEqualsToken ||
1917
- op === ts.SyntaxKind.QuestionQuestionEqualsToken
1918
- ) {
1919
- addFromTarget(n.left)
1920
- }
1900
+ if (ts.isBinaryExpression(n) && isAssignmentOperator(n.operatorToken.kind)) {
1901
+ addFromTarget(n.left)
1921
1902
  }
1922
1903
  if (ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) {
1923
1904
  if (
@@ -1940,6 +1921,126 @@ function extractAssignedIdentifiersFromNode(node: ts.Node): Set<string> {
1940
1921
  return ids
1941
1922
  }
1942
1923
 
1924
+ /**
1925
+ * Method names that mutate their receiver in place. Used only to recognise
1926
+ * `<root>.<method>(...)` calls as mutating the root identifier (#2910) —
1927
+ * NOT to model array/collection semantics generally, so this stays a small,
1928
+ * explicit catalogue rather than a heuristic over every possible method.
1929
+ */
1930
+ const MUTATING_METHOD_NAMES: ReadonlySet<string> = new Set([
1931
+ 'push', 'pop', 'shift', 'unshift', 'splice', 'sort', 'reverse', 'fill', 'copyWithin',
1932
+ 'set', 'add', 'delete', 'clear',
1933
+ ])
1934
+
1935
+ /**
1936
+ * Collect identifiers mutated IN PLACE by a statement — a property/element
1937
+ * write (`config[k] = …`, `config.a.b += 1`), an `Object.assign(config, …)`
1938
+ * call, or a call to a known mutating method on the receiver
1939
+ * (`items.push(...)`) — as opposed to `extractAssignedIdentifiersFromNode`,
1940
+ * which only tracks reassignment of the BINDING itself (#2910).
1941
+ *
1942
+ * This distinction matters because `expandDynamicPropValue` /
1943
+ * `expandConstantForReactivity` (`ir-to-client-js/prop-handling.ts`) inline
1944
+ * a `localConstants` entry's DECLARATION-TIME initializer text wherever the
1945
+ * bare identifier is referenced. A `const config = {}` later populated by
1946
+ * `for (const s of series) config[s.key] = {...}` never reassigns `config`
1947
+ * itself — `extractAssignedIdentifiersFromNode` (correctly) reports no
1948
+ * assigned identifiers, since `config[s.key] = …` doesn't create an
1949
+ * implicit global — but the compiler must still know `config`'s value is
1950
+ * no longer just `{}` by the time this statement has run, so a consumer
1951
+ * that inlines the stale literal (instead of referencing the live `config`
1952
+ * binding) silently drops everything the mutation was supposed to do. See
1953
+ * `ConstantInfo.mutatedAfterDeclaration` for where this is consumed.
1954
+ */
1955
+ function extractMutatedIdentifiersFromNode(node: ts.Node): Set<string> {
1956
+ const ids = new Set<string>()
1957
+
1958
+ function rootIdentifierOf(expr: ts.Expression): string | null {
1959
+ let current: ts.Expression = expr
1960
+ while (true) {
1961
+ if (ts.isIdentifier(current)) return current.text
1962
+ if (ts.isParenthesizedExpression(current)) { current = current.expression; continue }
1963
+ if (ts.isNonNullExpression(current)) { current = current.expression; continue }
1964
+ if (ts.isPropertyAccessExpression(current)) { current = current.expression; continue }
1965
+ if (ts.isElementAccessExpression(current)) { current = current.expression; continue }
1966
+ return null
1967
+ }
1968
+ }
1969
+
1970
+ function visit(n: ts.Node): void {
1971
+ // Same init/sub-init boundary as `extractAssignedIdentifiersFromNode`:
1972
+ // a mutation inside a nested function literal doesn't run at init time.
1973
+ if (
1974
+ ts.isArrowFunction(n) ||
1975
+ ts.isFunctionExpression(n) ||
1976
+ ts.isFunctionDeclaration(n) ||
1977
+ ts.isMethodDeclaration(n) ||
1978
+ ts.isGetAccessorDeclaration(n) ||
1979
+ ts.isSetAccessorDeclaration(n) ||
1980
+ ts.isConstructorDeclaration(n)
1981
+ ) {
1982
+ return
1983
+ }
1984
+
1985
+ if (ts.isBinaryExpression(n) && isAssignmentOperator(n.operatorToken.kind)) {
1986
+ if (ts.isPropertyAccessExpression(n.left) || ts.isElementAccessExpression(n.left)) {
1987
+ const root = rootIdentifierOf(n.left)
1988
+ if (root) ids.add(root)
1989
+ }
1990
+ } else if (ts.isPrefixUnaryExpression(n) || ts.isPostfixUnaryExpression(n)) {
1991
+ const isIncDec = n.operator === ts.SyntaxKind.PlusPlusToken || n.operator === ts.SyntaxKind.MinusMinusToken
1992
+ if (isIncDec && (ts.isPropertyAccessExpression(n.operand) || ts.isElementAccessExpression(n.operand))) {
1993
+ const root = rootIdentifierOf(n.operand)
1994
+ if (root) ids.add(root)
1995
+ }
1996
+ } else if (ts.isCallExpression(n)) {
1997
+ const callee = n.expression
1998
+ if (ts.isPropertyAccessExpression(callee)) {
1999
+ const methodName = callee.name.text
2000
+ if (MUTATING_METHOD_NAMES.has(methodName)) {
2001
+ const root = rootIdentifierOf(callee.expression)
2002
+ if (root) ids.add(root)
2003
+ } else if (
2004
+ methodName === 'assign' &&
2005
+ ts.isIdentifier(callee.expression) &&
2006
+ callee.expression.text === 'Object' &&
2007
+ n.arguments.length > 0
2008
+ ) {
2009
+ // `Object.assign(target, ...)` mutates `target` in place.
2010
+ const root = rootIdentifierOf(n.arguments[0])
2011
+ if (root) ids.add(root)
2012
+ }
2013
+ }
2014
+ }
2015
+
2016
+ ts.forEachChild(n, visit)
2017
+ }
2018
+
2019
+ visit(node)
2020
+ return ids
2021
+ }
2022
+
2023
+ function isAssignmentOperator(kind: ts.SyntaxKind): boolean {
2024
+ return (
2025
+ kind === ts.SyntaxKind.EqualsToken ||
2026
+ kind === ts.SyntaxKind.PlusEqualsToken ||
2027
+ kind === ts.SyntaxKind.MinusEqualsToken ||
2028
+ kind === ts.SyntaxKind.AsteriskEqualsToken ||
2029
+ kind === ts.SyntaxKind.SlashEqualsToken ||
2030
+ kind === ts.SyntaxKind.PercentEqualsToken ||
2031
+ kind === ts.SyntaxKind.AsteriskAsteriskEqualsToken ||
2032
+ kind === ts.SyntaxKind.AmpersandEqualsToken ||
2033
+ kind === ts.SyntaxKind.BarEqualsToken ||
2034
+ kind === ts.SyntaxKind.CaretEqualsToken ||
2035
+ kind === ts.SyntaxKind.LessThanLessThanEqualsToken ||
2036
+ kind === ts.SyntaxKind.GreaterThanGreaterThanEqualsToken ||
2037
+ kind === ts.SyntaxKind.GreaterThanGreaterThanGreaterThanEqualsToken ||
2038
+ kind === ts.SyntaxKind.AmpersandAmpersandEqualsToken ||
2039
+ kind === ts.SyntaxKind.BarBarEqualsToken ||
2040
+ kind === ts.SyntaxKind.QuestionQuestionEqualsToken
2041
+ )
2042
+ }
2043
+
1943
2044
  /**
1944
2045
  * Collect all variable names declared within a statement tree (for-loop
1945
2046
  * initializers, for-in/of bindings, nested `let`/`const`/`var` blocks).
@@ -3029,6 +3130,30 @@ function getSystemConstructKind(node: ts.Node): 'createContext' | 'weakMap' | un
3029
3130
  return undefined
3030
3131
  }
3031
3132
 
3133
+ /**
3134
+ * The default-value-shaped fields a binding element's own `initializer`
3135
+ * contributes to a `ParamInfo` — `defaultValue`'s source text, `parsed`'s
3136
+ * structured mirror (from the initializer's OWN AST node, no re-parse),
3137
+ * and `defaultContainsArrow`. Shared by the parameter-destructured path
3138
+ * (`extractProps`'s Pattern 1, below) and the BODY-destructure-from-props
3139
+ * path (`collectConstant`'s object-binding-pattern branch, #2943) so "what
3140
+ * does this default look like structurally" has one implementation, not
3141
+ * two independently-drifting ones.
3142
+ */
3143
+ function bindingElementDefaultFields(
3144
+ initializer: ts.Expression | undefined,
3145
+ ctx: AnalyzerContext,
3146
+ ): Pick<ParamInfo, 'defaultValue' | 'parsed' | 'defaultContainsArrow'> {
3147
+ const defaultValue = initializer ? ctx.getJS(initializer) : undefined
3148
+ const defaultContainsArrow = initializer ? nodeContainsArrow(initializer) : false
3149
+ const parsedDefault = initializer ? tsNodeToParsedExpr(initializer) : undefined
3150
+ return {
3151
+ defaultValue,
3152
+ ...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
3153
+ defaultContainsArrow: defaultContainsArrow || undefined,
3154
+ }
3155
+ }
3156
+
3032
3157
  function collectConstant(
3033
3158
  node: ts.VariableDeclaration,
3034
3159
  ctx: AnalyzerContext,
@@ -3090,6 +3215,55 @@ function collectConstant(
3090
3215
  // _isModule === false; binding lives in init scope.
3091
3216
  origin: { phase: 'hydrate', scope: 'init', effect: 'pure' },
3092
3217
  })
3218
+
3219
+ // #2943: a BODY destructure's default (`const { label = 'none' } =
3220
+ // props`) has no other way to reach `ParamInfo.defaultValue` —
3221
+ // `extractPropsFromTypeMembers` builds `propsParams` purely from the
3222
+ // TYPE annotation, which has no notion of a body-level default. Every
3223
+ // downstream consumer that reads `ParamInfo.defaultValue`/`.optional`
3224
+ // (each adapter's "does this attribute need a presence guard"
3225
+ // classification, `extractSsrDefaults`'s SSR-stash seed, the
3226
+ // CSR-fresh-mount `template:` lambda) needs the default visible here,
3227
+ // on the SAME shared `ParamInfo` the parameter-destructured form
3228
+ // already populates via `bindingElementDefaultFields` above — not on
3229
+ // a second, parallel structure only the CSR lambda used to consult.
3230
+ //
3231
+ // A `let` binding or one `markMutatedConstants` later flags as
3232
+ // mutated is still a perfectly valid default AT its declaration —
3233
+ // this is a static, compile-time fact about the source, not a
3234
+ // liveness question, so (unlike `resolveBodyPropAliases`'s
3235
+ // `requireLiveRewriteSafe` gate) nothing here excludes them.
3236
+ if (el.initializer) {
3237
+ const defaultFields = bindingElementDefaultFields(el.initializer, ctx)
3238
+ const existing = ctx.propsParams.find(p => !p.isRest && p.sourceName === undefined && p.name === sourceKey)
3239
+ if (localName === sourceKey) {
3240
+ // Unrenamed: overlay onto the type-member entry `sourceKey`
3241
+ // already has (or synthesize one for an untyped `props` param,
3242
+ // matching the parameter-destructured form's own `unknown`
3243
+ // fallback for an unannotated `{ x = 1 }`). Never clobber a
3244
+ // default some earlier binding element already established.
3245
+ if (existing) {
3246
+ if (existing.defaultValue === undefined) Object.assign(existing, { optional: true, ...defaultFields })
3247
+ } else {
3248
+ ctx.propsParams.push({ name: localName, type: { kind: 'unknown', raw: 'unknown' }, optional: true, ...defaultFields })
3249
+ }
3250
+ } else if (!ctx.propsParams.some(p => p.name === localName)) {
3251
+ // Renamed (`const { label: text = 'none' } = props`): ADD a
3252
+ // second entry rather than replacing `sourceKey`'s — a bare
3253
+ // `props.label` read elsewhere in the same component is still a
3254
+ // real, separately-classified binding (no default, needs its own
3255
+ // presence guard / stash entry), and `text` needs `sourceName` so
3256
+ // every `sourceName ?? name` consumer resolves the caller-facing
3257
+ // key correctly.
3258
+ ctx.propsParams.push({
3259
+ name: localName,
3260
+ type: existing?.type ?? { kind: 'unknown', raw: 'unknown' },
3261
+ optional: true,
3262
+ sourceName: sourceKey,
3263
+ ...defaultFields,
3264
+ })
3265
+ }
3266
+ }
3093
3267
  }
3094
3268
  return
3095
3269
  }
@@ -3330,57 +3504,6 @@ function collectConstant(
3330
3504
  })
3331
3505
  }
3332
3506
 
3333
- // =============================================================================
3334
- // Ignore Directive Detection
3335
- // =============================================================================
3336
-
3337
- /**
3338
- * Check if a node has an ignore directive comment for the specified rule.
3339
- * Supports: // @bf-ignore rule-id
3340
- *
3341
- * For arrow function components, also checks the parent VariableStatement.
3342
- */
3343
- function hasIgnoreDirective(
3344
- node: ts.Node,
3345
- sourceFile: ts.SourceFile,
3346
- ruleId: string
3347
- ): boolean {
3348
- const checkComments = (targetNode: ts.Node): boolean => {
3349
- const fullStart = targetNode.getFullStart()
3350
- const leadingComments = ts.getLeadingCommentRanges(
3351
- sourceFile.getFullText(),
3352
- fullStart
3353
- )
3354
- if (!leadingComments) return false
3355
-
3356
- for (const range of leadingComments) {
3357
- const text = sourceFile.getFullText().slice(range.pos, range.end)
3358
- if (text.includes(`@bf-ignore ${ruleId}`)) {
3359
- return true
3360
- }
3361
- }
3362
- return false
3363
- }
3364
-
3365
- // Check the node itself
3366
- if (checkComments(node)) return true
3367
-
3368
- // For arrow functions, check the parent VariableStatement
3369
- // AST structure: VariableStatement > VariableDeclarationList > VariableDeclaration > ArrowFunction
3370
- if (ts.isArrowFunction(node)) {
3371
- let current: ts.Node | undefined = node.parent
3372
- while (current) {
3373
- if (ts.isVariableStatement(current)) {
3374
- if (checkComments(current)) return true
3375
- break
3376
- }
3377
- current = current.parent
3378
- }
3379
- }
3380
-
3381
- return false
3382
- }
3383
-
3384
3507
  // =============================================================================
3385
3508
  // Props Extraction
3386
3509
  // =============================================================================
@@ -3388,13 +3511,7 @@ function hasIgnoreDirective(
3388
3511
  function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): void {
3389
3512
  // Pattern 1: Destructured props - { prop1, prop2 }
3390
3513
  if (ts.isObjectBindingPattern(param.name)) {
3391
- // Record destructuring info for deferred BF043 emission (stateful components only)
3392
- const componentNode = ctx.componentNode
3393
- const ignored = !!(componentNode && hasIgnoreDirective(componentNode, ctx.sourceFile, 'props-destructuring'))
3394
- ctx.propsDestructuring = {
3395
- loc: getSourceLocation(param, ctx.sourceFile, ctx.filePath),
3396
- hasIgnoreDirective: ignored,
3397
- }
3514
+ ctx.propsDestructuring = { loc: getSourceLocation(param, ctx.sourceFile, ctx.filePath) }
3398
3515
 
3399
3516
  // Resolve each destructured binding's declared type from the param's type
3400
3517
  // annotation, so `{ value }: Props` keeps the same per-prop TypeInfo as the
@@ -3405,7 +3522,6 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
3405
3522
  for (const element of param.name.elements) {
3406
3523
  if (ts.isBindingElement(element) && ts.isIdentifier(element.name)) {
3407
3524
  const localName = element.name.text
3408
- const defaultValue = element.initializer ? ctx.getJS(element.initializer) : undefined
3409
3525
 
3410
3526
  // Handle rest props: { ...props }
3411
3527
  if (element.dotDotDotToken) {
@@ -3422,22 +3538,13 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
3422
3538
  const member = memberTypes?.get(sourcePropName)
3423
3539
  const resolvedType: TypeInfo = member?.type ?? { kind: 'unknown', raw: 'unknown' }
3424
3540
 
3425
- const defaultContainsArrow = element.initializer ? nodeContainsArrow(element.initializer) : false
3426
- // Structured mirror of `defaultValue`, from the binding element's OWN
3427
- // `initializer` node — `tsNodeToParsedExpr` converts the already-parsed
3428
- // AST directly, no re-parse of the `defaultValue` text (same convention
3429
- // as `SignalInfo.parsed`). An unsupported shape leaves `parsed` unset;
3430
- // consumers fall back to `defaultValue` text.
3431
- const parsedDefault = element.initializer ? tsNodeToParsedExpr(element.initializer) : undefined
3432
3541
  ctx.propsParams.push({
3433
3542
  name: localName,
3434
3543
  type: resolvedType,
3435
3544
  // The type's `?` and a destructure default (`{ x = 1 }`) both mean
3436
3545
  // the caller may omit the prop.
3437
3546
  optional: !!member?.optional || !!element.initializer,
3438
- defaultValue,
3439
- ...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
3440
- defaultContainsArrow: defaultContainsArrow || undefined,
3547
+ ...bindingElementDefaultFields(element.initializer, ctx),
3441
3548
  // Only aliased bindings carry the source key — see ParamInfo.sourceName.
3442
3549
  ...(sourcePropName !== localName && { sourceName: sourcePropName }),
3443
3550
  })
@@ -3864,20 +3971,6 @@ function extractDependencies(code: string, ctx: AnalyzerContext): string[] {
3864
3971
  // =============================================================================
3865
3972
 
3866
3973
  function validateContext(ctx: AnalyzerContext): void {
3867
- // BF043: Emit props destructuring warning only for stateful components.
3868
- // Stateless components can safely destructure props since values are static.
3869
- const isStateful = ctx.signals.length > 0 || ctx.memos.length > 0 ||
3870
- ctx.effects.length > 0 || ctx.onMounts.length > 0
3871
- if (ctx.propsDestructuring && isStateful && !ctx.propsDestructuring.hasIgnoreDirective) {
3872
- ctx.errors.push(
3873
- createWarning(ErrorCodes.PROPS_DESTRUCTURING, ctx.propsDestructuring.loc, {
3874
- suggestion: {
3875
- message: 'Use props object directly: function Component(props: Props) { ... props.checked ... }',
3876
- },
3877
- })
3878
- )
3879
- }
3880
-
3881
3974
  // Check for 'use client' directive if any browser-only API is used.
3882
3975
  // Browser-only APIs include signals AND context/portal runtime hooks:
3883
3976
  // their implementations live in `@barefootjs/client/runtime` and require
@@ -3899,6 +3992,11 @@ function validateContext(ctx: AnalyzerContext): void {
3899
3992
  }
3900
3993
  }
3901
3994
 
3995
+ // A same-scope statement (typically a `for`/`while` loop) may mutate a
3996
+ // `localConstants` binding after its declaration — flag those bindings so
3997
+ // downstream inlining never re-embeds their stale initializer text (#2910).
3998
+ markMutatedConstants(ctx)
3999
+
3902
4000
  // BF052: init statements that write to an identifier with no visible
3903
4001
  // declaration cause a ReferenceError in ESM strict mode. Flag them
3904
4002
  // at compile time instead of shipping broken client JS. (#933)
@@ -4162,6 +4260,35 @@ function fileHasUseClientDirective(filePath: string): boolean {
4162
4260
  return found
4163
4261
  }
4164
4262
 
4263
+ /**
4264
+ * Flag every `localConstants` entry a same-scope init statement mutates
4265
+ * after its declaration (#2910) — see `ConstantInfo.mutatedAfterDeclaration`
4266
+ * for why this matters and who reads it. Runs once, after the whole
4267
+ * component (and module-level) body has been walked, since the mutating
4268
+ * statement is a SEPARATE statement from the declaration and may follow it
4269
+ * by any number of lines.
4270
+ *
4271
+ * Deliberately keyed off BOTH `mutatedIdentifiers` (in-place writes) and
4272
+ * `assignedIdentifiers` (whole-binding reassignment, e.g. a `let` later
4273
+ * written to): both leave `ConstantInfo.value` stale, and
4274
+ * `expandDynamicPropValue` inlines `value` for `let` bindings exactly the
4275
+ * same way it does for `const`.
4276
+ */
4277
+ function markMutatedConstants(ctx: AnalyzerContext): void {
4278
+ if (ctx.initStatements.length === 0 || ctx.localConstants.length === 0) return
4279
+
4280
+ const mutatedNames = new Set<string>()
4281
+ for (const stmt of ctx.initStatements) {
4282
+ if (stmt.mutatedIdentifiers) for (const name of stmt.mutatedIdentifiers) mutatedNames.add(name)
4283
+ if (stmt.assignedIdentifiers) for (const name of stmt.assignedIdentifiers) mutatedNames.add(name)
4284
+ }
4285
+ if (mutatedNames.size === 0) return
4286
+
4287
+ for (const constant of ctx.localConstants) {
4288
+ if (mutatedNames.has(constant.name)) constant.mutatedAfterDeclaration = true
4289
+ }
4290
+ }
4291
+
4165
4292
  function validateInitStatementReferences(ctx: AnalyzerContext): void {
4166
4293
  if (ctx.initStatements.length === 0) return
4167
4294
 
package/src/errors.ts CHANGED
@@ -51,8 +51,9 @@ export const ErrorCodes = {
51
51
  // to resolve the identifier at return position too.
52
52
  RETURN_VALUE_NOT_JSX: 'BF027',
53
53
 
54
- // Component errors (BF043-BF049)
55
- PROPS_DESTRUCTURING: 'BF043',
54
+ // Component errors (BF043-BF049). BF043 is retired (it warned that props
55
+ // destructuring broke reactivity, which it no longer does) and is the next
56
+ // free slot.
56
57
  SIGNAL_GETTER_NOT_CALLED: 'BF044',
57
58
  JSX_IN_LOCAL_FUNCTION: 'BF045',
58
59
  COMPONENT_REQUIRED_PROP_MISSING: 'BF046',
@@ -181,8 +182,6 @@ const errorMessages: Record<ErrorCode, string> = {
181
182
  [ErrorCodes.RETURN_VALUE_NOT_JSX]:
182
183
  "Component's return value is not recognized as JSX — return the JSX expression directly instead of binding it to a local variable first.",
183
184
 
184
- [ErrorCodes.PROPS_DESTRUCTURING]:
185
- 'Props destructuring in function parameters breaks reactivity. Use props object directly.',
186
185
  [ErrorCodes.SIGNAL_GETTER_NOT_CALLED]:
187
186
  'Signal/memo getter passed without calling it. Use getter() to read the value.',
188
187
  [ErrorCodes.JSX_IN_LOCAL_FUNCTION]:
@@ -382,10 +381,10 @@ export function formatError(
382
381
  options?: { projectDir?: string },
383
382
  ): string {
384
383
  // Lowercase severity matches the prose convention in
385
- // `docs/core/advanced/error-codes.md` (`error[BF001]:`,
386
- // `warning[BF043]:`) — that doc IS the rendering contract referenced
387
- // by `bf guide advanced/error-codes`, so keep the wire format aligned
388
- // with the reference rather than the function's old uppercase shape.
384
+ // `docs/core/advanced/error-codes.md` (`error[BF001]:`) — that doc IS the
385
+ // rendering contract referenced by `bf guide advanced/error-codes`, so
386
+ // keep the wire format aligned with the reference rather than the
387
+ // function's old uppercase shape.
389
388
  const severityLabel = error.severity
390
389
  const lines: string[] = []
391
390
 
@@ -113,6 +113,12 @@ export type ConstantInlinability =
113
113
  /** After chained-ref resolution, the inlined value still mentions
114
114
  * a name classified unsafe above. Transitive demotion. */
115
115
  | { kind: 'depends-on-unsafe' }
116
+ /** A same-scope statement mutates this binding's value after its
117
+ * declaration (`ConstantInfo.mutatedAfterDeclaration`, #2910) — e.g.
118
+ * `const config = {}; for (...) config[k] = ...`. `value` is a
119
+ * pre-mutation snapshot; inlining it anywhere would silently drop
120
+ * the mutation, so this is unsafe exactly like an init-local. */
121
+ | { kind: 'mutated-after-declaration' }
116
122
 
117
123
  export type FunctionInlinability =
118
124
  /** Module-scope function that does NOT touch component internals —
@@ -339,7 +345,7 @@ function populateCsrInlinable(ctx: ClientJsContext, relocateEnv: RelocateEnv, ge
339
345
  // call-kind entry (`buildEnvWithConsts`'s Map spread puts `constSubs`
340
346
  // last) — the literal `(undefined)()` this issue is about (#2778).
341
347
  for (const c of ctx.localConstants) {
342
- if (c.isJsx || !c.value || c.containsArrow || c.systemConstructKind || getterAliases.has(c.name)) {
348
+ if (c.isJsx || !c.value || c.containsArrow || c.systemConstructKind || c.mutatedAfterDeclaration || getterAliases.has(c.name)) {
343
349
  ctx.csrInlinable.set(c.name, null)
344
350
  finalised.add(c.name)
345
351
  }
@@ -626,6 +632,7 @@ function classifyConstantInitial(
626
632
  ): { status: ConstantInlinability; decisions: RelocateDecision[] } {
627
633
  if (c.isJsx) return { status: { kind: 'jsx-inline' }, decisions: [] }
628
634
  if (!c.value) return { status: { kind: 'placeholder-let' }, decisions: [] }
635
+ if (c.mutatedAfterDeclaration) return { status: { kind: 'mutated-after-declaration' }, decisions: [] }
629
636
  if (c.containsArrow) return { status: { kind: 'arrow-literal' }, decisions: [] }
630
637
  if (c.systemConstructKind) return { status: { kind: 'system-construct' }, decisions: [] }
631
638
  // A multi-hop alias chain to a getter (`const a = items; const b = a`)
@@ -67,3 +67,22 @@ export function propHasPropertyAccess(u: PropUsage | undefined): boolean {
67
67
  if (!u) return false
68
68
  return u.accessKinds.has('property') || u.accessKinds.has('index')
69
69
  }
70
+
71
+ /**
72
+ * Which of `propNames` guard a conditional branch. A prop in this set must
73
+ * NOT get a `{}` fallback even when it has property access — `{}` is truthy,
74
+ * so the branch would always render when the caller omits the prop.
75
+ */
76
+ export function computePropsUsedAsConditions(
77
+ ctx: Pick<ClientJsContext, 'conditionalElements' | 'clientOnlyConditionals'>,
78
+ propNames: ReadonlySet<string>,
79
+ ): Set<string> {
80
+ const result = new Set<string>()
81
+ for (const cond of ctx.conditionalElements) {
82
+ if (propNames.has(cond.condition)) result.add(cond.condition)
83
+ }
84
+ for (const cond of ctx.clientOnlyConditionals) {
85
+ if (propNames.has(cond.condition)) result.add(cond.condition)
86
+ }
87
+ return result
88
+ }
@@ -17,16 +17,19 @@ import type {
17
17
  EventDelegationPlan,
18
18
  ItemLookup,
19
19
  } from './types.ts'
20
+ import type { ContainerOwnHandler } from './event-collision.ts'
20
21
 
21
22
  export function buildDynamicLoopDelegationPlan(
22
23
  elem: TopLevelLoop,
23
24
  profileComponentName?: string,
25
+ ownHandlers?: Map<string, ContainerOwnHandler>,
24
26
  ): EventDelegationPlan {
25
27
  return {
26
28
  kind: 'event-delegation',
27
29
  containerVar: `_${varSlotId(elem.slotId)}`,
28
30
  events: elem.bindings.events,
29
31
  profileComponentName,
32
+ ownHandlers,
30
33
  itemLookup: buildKeyedOrIndexLookup({
31
34
  // Chain `.filter()` / `.toSorted()` so the index-based lookup walks
32
35
  // the same array shape mapArray reconciled into the DOM (#1434).
@@ -93,12 +96,14 @@ export function buildBranchLoopDelegationPlan(
93
96
  export function buildStaticArrayDelegationPlan(
94
97
  elem: TopLevelLoop,
95
98
  profileComponentName?: string,
99
+ ownHandlers?: Map<string, ContainerOwnHandler>,
96
100
  ): EventDelegationPlan {
97
101
  return {
98
102
  kind: 'event-delegation',
99
103
  containerVar: `_${varSlotId(elem.slotId)}`,
100
104
  events: elem.bindings.events,
101
105
  profileComponentName,
106
+ ownHandlers,
102
107
  itemLookup: {
103
108
  kind: 'static-index',
104
109
  // Static arrays render through the same `.filter()`/`.toSorted()`
@@ -62,29 +62,45 @@ export interface BuildLoopPlanOptions {
62
62
  lazyScope?: LazyRowScopeInfo
63
63
  }
64
64
 
65
+ /** Which `LoopPlan` variant `buildLoopPlan` would build for a given loop. */
66
+ export type LoopVariantKind = 'plain' | 'static' | 'composite' | 'component'
67
+
65
68
  /**
66
- * The single public builder. Selects the variant via the decision tree
67
- * described above and returns the discriminated `LoopPlan`.
69
+ * Classify which variant `buildLoopPlan` would build for `elem`, without
70
+ * building it. Mirrors the decision tree below exactly — pulled out so a
71
+ * caller that only needs the classification (e.g. the event-delegation
72
+ * eligibility precompute, #2930) doesn't have to duplicate these predicates
73
+ * or pay for building the full `LoopPlan`.
68
74
  */
69
- export function buildLoopPlan(elem: TopLevelLoop, opts: BuildLoopPlanOptions): LoopPlan {
75
+ export function classifyLoopKind(elem: TopLevelLoop): LoopVariantKind {
70
76
  // Whole-item conditional bodies (#1665) render 0-or-1 element per item, so
71
77
  // they need anchored `mapArrayAnchored` emission regardless of whether the
72
78
  // array is static or dynamic. Routing both through the plain (anchored)
73
79
  // path keeps `const arr` and `signal()` behaviour identical — a static
74
80
  // array's per-item conditional still toggles reactively instead of freezing
75
81
  // in the SSR-time `forEach` (which has no conditional handling at all).
76
- if (elem.bodyIsItemConditional) {
77
- return buildPlainLoopPlan(elem, opts.profileComponentName, opts.lazyScope)
78
- }
79
- if (elem.isStaticArray) {
80
- return buildStaticLoopPlan(elem, opts.unsafeLocalNames, opts.profileComponentName)
81
- }
82
+ if (elem.bodyIsItemConditional) return 'plain'
83
+ if (elem.isStaticArray) return 'static'
82
84
  const hasInnerStructure = (elem.nestedComponents?.length ?? 0) > 0
83
85
  || (elem.innerLoops?.length ?? 0) > 0
84
- if (elem.useElementReconciliation && hasInnerStructure) {
86
+ if (elem.useElementReconciliation && hasInnerStructure) return 'composite'
87
+ if (elem.childComponent) return 'component'
88
+ return 'plain'
89
+ }
90
+
91
+ /**
92
+ * The single public builder. Dispatches via `classifyLoopKind` and returns
93
+ * the discriminated `LoopPlan`.
94
+ */
95
+ export function buildLoopPlan(elem: TopLevelLoop, opts: BuildLoopPlanOptions): LoopPlan {
96
+ const kind = classifyLoopKind(elem)
97
+ if (kind === 'static') {
98
+ return buildStaticLoopPlan(elem, opts.unsafeLocalNames, opts.profileComponentName)
99
+ }
100
+ if (kind === 'composite') {
85
101
  return buildTopLevelCompositePlan(elem, opts.profileComponentName)
86
102
  }
87
- if (elem.childComponent) {
103
+ if (kind === 'component') {
88
104
  return buildComponentLoopPlan(elem, opts.profileComponentName)
89
105
  }
90
106
  return buildPlainLoopPlan(elem, opts.profileComponentName, opts.lazyScope)
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Find a container's own directly-authored event handler that collides with
3
+ * a `.map()` row's delegated dispatcher for the same DOM event (#2930).
4
+ *
5
+ * `.map()` rows compiled via delegation share their delegated listener's
6
+ * node with the loop's static container — the compiler registers ONE
7
+ * `addEventListener` on the container, resolving `event.target` back to a
8
+ * row. When the container ALSO carries its own handler for the same event,
9
+ * both end up as separate `addEventListener` calls on the identical DOM
10
+ * node, so a row's `stopPropagation()` can't stop the container's own
11
+ * handler: native DOM `stopPropagation()` only blocks bubbling to *other
12
+ * nodes*, never other listeners already registered on the *same* node.
13
+ *
14
+ * This is the one place that answers "does this container slot have its own
15
+ * handler for this event" — both `phases/event-handlers.ts` (which must
16
+ * suppress the direct listener when the answer is yes) and
17
+ * `control-flow.ts` (which must fold that handler into the delegated
18
+ * dispatcher instead) call it, rather than answering the question twice.
19
+ */
20
+
21
+ import type { InteractiveElement } from '../../types.ts'
22
+ import { toDomEventName, NON_BUBBLING_EVENTS } from '../../utils.ts'
23
+
24
+ export interface ContainerOwnHandler {
25
+ /** The container element's own slot id (used for profile-mode turn ids). */
26
+ slotId: string
27
+ /** Original (pre-DOM-mapped) event name, e.g. 'contextmenu'. */
28
+ eventName: string
29
+ handler: string
30
+ }
31
+
32
+ /**
33
+ * Find the container's own handler for `domEventName`, if any.
34
+ *
35
+ * Returns `null` for a non-bubbling event (focus/blur/…) — those delegate
36
+ * in capture mode, and a container's own bubble-phase handler there only
37
+ * ever fires when the container itself is the event target, never for a
38
+ * descendant row, so there is no collision to resolve. Also returns `null`
39
+ * when `containerSlotId` lives inside a conditional branch — that slot's
40
+ * own handler (if any) is bound by `insert()`'s `bindEvents` in a separate
41
+ * scope this check doesn't cover.
42
+ */
43
+ export function findContainerOwnHandler(
44
+ interactiveElements: InteractiveElement[],
45
+ conditionalSlotIds: Set<string>,
46
+ containerSlotId: string,
47
+ domEventName: string,
48
+ ): ContainerOwnHandler | null {
49
+ if (NON_BUBBLING_EVENTS.has(domEventName)) return null
50
+ if (conditionalSlotIds.has(containerSlotId)) return null
51
+ const elem = interactiveElements.find(e => e.slotId === containerSlotId)
52
+ if (!elem) return null
53
+ const match = elem.events.find(event => toDomEventName(event.name) === domEventName)
54
+ return match ? { slotId: containerSlotId, eventName: match.name, handler: match.handler } : null
55
+ }