@barefootjs/jsx 0.39.4 → 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.
- package/dist/adapters/array-method.d.ts +93 -0
- package/dist/adapters/array-method.d.ts.map +1 -0
- package/dist/adapters/attr-plan.d.ts +135 -0
- package/dist/adapters/attr-plan.d.ts.map +1 -0
- package/dist/adapters/boolean-result.d.ts +84 -9
- package/dist/adapters/boolean-result.d.ts.map +1 -1
- package/dist/adapters/callback-method.d.ts +126 -0
- package/dist/adapters/callback-method.d.ts.map +1 -0
- package/dist/adapters/component-props.d.ts +99 -0
- package/dist/adapters/component-props.d.ts.map +1 -0
- package/dist/adapters/component-tree.d.ts +25 -0
- package/dist/adapters/component-tree.d.ts.map +1 -0
- package/dist/adapters/filter-capture-collisions.d.ts +17 -0
- package/dist/adapters/filter-capture-collisions.d.ts.map +1 -0
- package/dist/adapters/literal-value.d.ts +22 -0
- package/dist/adapters/literal-value.d.ts.map +1 -0
- package/dist/adapters/loop-plan.d.ts +53 -0
- package/dist/adapters/loop-plan.d.ts.map +1 -0
- package/dist/adapters/parsed-expr-emitter.d.ts +8 -0
- package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
- package/dist/adapters/prop-classes.d.ts +37 -0
- package/dist/adapters/prop-classes.d.ts.map +1 -0
- package/dist/adapters/template-name-collisions.d.ts +21 -0
- package/dist/adapters/template-name-collisions.d.ts.map +1 -0
- package/dist/analyzer-context.d.ts.map +1 -1
- package/dist/expression-parser.d.ts +48 -0
- package/dist/expression-parser.d.ts.map +1 -1
- package/dist/index.d.ts +20 -4
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2077 -1000
- package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +8 -0
- package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts +3 -2
- package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
- package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
- package/dist/ir-to-client-js/utils.d.ts +39 -1
- package/dist/ir-to-client-js/utils.d.ts.map +1 -1
- package/dist/jsx-to-ir.d.ts +465 -1
- package/dist/jsx-to-ir.d.ts.map +1 -1
- package/dist/nullable-signal-attr.d.ts +31 -0
- package/dist/nullable-signal-attr.d.ts.map +1 -1
- package/dist/scope/binding-scope.d.ts +10 -0
- package/dist/scope/binding-scope.d.ts.map +1 -1
- package/dist/types.d.ts +7 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +1 -1
- package/src/__tests__/action-accessor.test.ts +6 -24
- package/src/__tests__/array-method-catalogue.test.ts +99 -0
- package/src/__tests__/attr-plan.test.ts +121 -0
- package/src/__tests__/binding-scope-ratchet.test.ts +13 -13
- package/src/__tests__/binding-scope.test.ts +11 -0
- package/src/__tests__/boolean-result-expr.test.ts +106 -0
- package/src/__tests__/boolean-result.test.ts +34 -1
- package/src/__tests__/callback-method.test.ts +189 -0
- package/src/__tests__/compile-without-node-process.test.ts +78 -0
- package/src/__tests__/component-props.test.ts +148 -0
- package/src/__tests__/delegated-handler-preamble.test.ts +4 -4
- package/src/__tests__/doc-examples.test.ts +1 -0
- package/src/__tests__/dsl-shared-helpers.test.ts +166 -0
- package/src/__tests__/issue-3240-nested-static-map-event-delegation.test.ts +1 -1
- package/src/__tests__/loop-plan.test.ts +104 -0
- package/src/__tests__/map-call-decisions.test.ts +521 -0
- package/src/__tests__/nested-row-shadowing.test.ts +57 -0
- package/src/__tests__/nullable-signal-attr.test.ts +45 -0
- package/src/__tests__/rename-free-identifiers.test.ts +26 -0
- package/src/__tests__/template-name-collisions.test.ts +81 -0
- package/src/adapters/array-method.ts +193 -0
- package/src/adapters/attr-plan.ts +200 -0
- package/src/adapters/boolean-result.ts +208 -12
- package/src/adapters/callback-method.ts +301 -0
- package/src/adapters/component-props.ts +144 -0
- package/src/adapters/component-tree.ts +118 -0
- package/src/adapters/filter-capture-collisions.ts +29 -0
- package/src/adapters/literal-value.ts +36 -0
- package/src/adapters/loop-plan.ts +88 -0
- package/src/adapters/parsed-expr-emitter.ts +18 -0
- package/src/adapters/prop-classes.ts +73 -0
- package/src/adapters/template-name-collisions.ts +120 -0
- package/src/analyzer-context.ts +15 -1
- package/src/expression-parser.ts +569 -374
- package/src/index.ts +58 -3
- package/src/ir-to-client-js/collect-elements.ts +11 -7
- package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +31 -10
- package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +12 -5
- package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +2 -2
- package/src/ir-to-client-js/control-flow/shared.ts +4 -1
- package/src/ir-to-client-js/control-flow/stringify/event-delegation.ts +9 -7
- package/src/ir-to-client-js/html-template.ts +13 -7
- package/src/ir-to-client-js/index.ts +7 -2
- package/src/ir-to-client-js/utils.ts +81 -7
- package/src/jsx-to-ir.ts +1328 -991
- package/src/nullable-signal-attr.ts +116 -6
- package/src/scope/binding-scope.ts +19 -0
- package/src/types.ts +7 -0
package/src/jsx-to-ir.ts
CHANGED
|
@@ -41,7 +41,7 @@ import {
|
|
|
41
41
|
AttrValueOf,
|
|
42
42
|
} from './types.ts'
|
|
43
43
|
import { type AnalyzerContext, type MultiReturnJsxInfo, getSourceLocation, collectReactiveGetterNames, tsTypeToTypeInfo } from './analyzer-context.ts'
|
|
44
|
-
import { parseExpression, isSupported, parseBlockBody, foldBlockToExpr, predicateTernaryToLogical, tsNodeToParsedExpr, sortComparatorFromArrow, stringifyParsedExpr, cssKebabCase, CALLBACK_METHODS, type ParsedExpr } from './expression-parser.ts'
|
|
44
|
+
import { parseExpression, isSupported, parseBlockBody, foldBlockToExpr, predicateTernaryToLogical, tsNodeToParsedExpr, sortComparatorFromArrow, stringifyParsedExpr, cssKebabCase, CALLBACK_METHODS, unboundCallbackParamRead, unboundCallbackParamReason, type ParsedExpr } from './expression-parser.ts'
|
|
45
45
|
import type { IRLoopSort, FunctionInfo, ConstantInfo, ParamInfo } from './types.ts'
|
|
46
46
|
import { formatParamWithType } from './module-exports.ts'
|
|
47
47
|
import { createError, ErrorCodes, internalInvariant } from './errors.ts'
|
|
@@ -85,7 +85,8 @@ interface ReactivityPatterns {
|
|
|
85
85
|
constants: { name: string; value: string | undefined; pattern: RegExp }[]
|
|
86
86
|
}
|
|
87
87
|
|
|
88
|
-
|
|
88
|
+
/** @internal exported for the per-decision loop tests (`map-call-decisions.test.ts`). */
|
|
89
|
+
export interface TransformContext {
|
|
89
90
|
analyzer: AnalyzerContext
|
|
90
91
|
sourceFile: ts.SourceFile
|
|
91
92
|
filePath: string
|
|
@@ -793,7 +794,8 @@ function getDestructuredPropAliases(ctx: TransformContext): Map<string, string>
|
|
|
793
794
|
return ctx._destructuredPropAliases ?? null
|
|
794
795
|
}
|
|
795
796
|
|
|
796
|
-
|
|
797
|
+
/** @internal exported for the per-decision loop tests (`map-call-decisions.test.ts`). */
|
|
798
|
+
export function createTransformContext(analyzer: AnalyzerContext): TransformContext {
|
|
797
799
|
// Shared by `patterns.props` (regex matching) and `boundPropNames`
|
|
798
800
|
// (exact-name binding checks, #2835) so both agree on which prop
|
|
799
801
|
// params are in play — `children` excluded from both the same way.
|
|
@@ -3881,6 +3883,8 @@ function extractFilterPredicate(
|
|
|
3881
3883
|
if (!support.supported) {
|
|
3882
3884
|
return { result: null, unsupportedReason: support.reason }
|
|
3883
3885
|
}
|
|
3886
|
+
const unbound = unboundFilterParamReason(callback, predicate, ctx)
|
|
3887
|
+
if (unbound) return { result: null, unsupportedReason: unbound }
|
|
3884
3888
|
return { result: { param, predicate, raw } }
|
|
3885
3889
|
}
|
|
3886
3890
|
|
|
@@ -3893,10 +3897,28 @@ function extractFilterPredicate(
|
|
|
3893
3897
|
if (!support.supported) {
|
|
3894
3898
|
return { result: null, unsupportedReason: support.reason }
|
|
3895
3899
|
}
|
|
3900
|
+
const unbound = unboundFilterParamReason(callback, predicate, ctx)
|
|
3901
|
+
if (unbound) return { result: null, unsupportedReason: unbound }
|
|
3896
3902
|
|
|
3897
3903
|
return { result: { param, predicate, raw } }
|
|
3898
3904
|
}
|
|
3899
3905
|
|
|
3906
|
+
/**
|
|
3907
|
+
* A loop filter's predicate is evaluated per element with only the element
|
|
3908
|
+
* bound, so `filter((x, i) => i > 0)` cannot lift into `IRLoop.filterPredicate`:
|
|
3909
|
+
* the index would resolve from the enclosing scope instead (see
|
|
3910
|
+
* `unboundCallbackParamRead`).
|
|
3911
|
+
*/
|
|
3912
|
+
function unboundFilterParamReason(
|
|
3913
|
+
callback: ts.ArrowFunction,
|
|
3914
|
+
predicate: ParsedExpr,
|
|
3915
|
+
ctx: TransformContext,
|
|
3916
|
+
): string | undefined {
|
|
3917
|
+
const params = callback.parameters.map(p => p.name.getText(ctx.sourceFile))
|
|
3918
|
+
const unbound = unboundCallbackParamRead('filter', { kind: 'arrow', params, body: predicate })
|
|
3919
|
+
return unbound === null ? undefined : unboundCallbackParamReason('filter', unbound)
|
|
3920
|
+
}
|
|
3921
|
+
|
|
3900
3922
|
/**
|
|
3901
3923
|
* Build the list of destructured bindings for a `.map()` callback parameter.
|
|
3902
3924
|
*
|
|
@@ -4711,1001 +4733,1325 @@ function extractItemConditionalKey(cond: IRConditional): string | null {
|
|
|
4711
4733
|
return a ?? b
|
|
4712
4734
|
}
|
|
4713
4735
|
|
|
4714
|
-
|
|
4715
|
-
|
|
4716
|
-
|
|
4717
|
-
|
|
4718
|
-
|
|
4719
|
-
|
|
4720
|
-
|
|
4721
|
-
|
|
4722
|
-
|
|
4723
|
-
|
|
4724
|
-
|
|
4725
|
-
|
|
4726
|
-
|
|
4727
|
-
|
|
4728
|
-
|
|
4729
|
-
|
|
4730
|
-
|
|
4731
|
-
|
|
4732
|
-
|
|
4733
|
-
|
|
4734
|
-
|
|
4735
|
-
|
|
4736
|
+
// =============================================================================
|
|
4737
|
+
// `.map()` / `.flatMap()` lowering (#3424)
|
|
4738
|
+
//
|
|
4739
|
+
// `transformMapCall` is a coordinator over one function per decision the
|
|
4740
|
+
// loop lowering makes, in the order the IR needs them:
|
|
4741
|
+
//
|
|
4742
|
+
// 1. `resolveLoopSource` — which array is iterated, and what the
|
|
4743
|
+
// receiver chain lifted out of it
|
|
4744
|
+
// 2. `resolveLoopRowParams` — the names a row binds (item / index /
|
|
4745
|
+
// destructure paths)
|
|
4746
|
+
// 3. `transformLoopCallbackBody` — the row's children, preamble and
|
|
4747
|
+
// flatMap carrier, under the row's scope
|
|
4748
|
+
// 4. `refuseUnloweredJsxCallback` — the sound-or-loud structural net
|
|
4749
|
+
// 5. `resolveLoopKey` — the keyFn and the key attribute stamp
|
|
4750
|
+
// 6. `applyPreambleBuilderPasses` / `markPreambleReactivity` — the
|
|
4751
|
+
// preamble's after-the-fact wiring
|
|
4752
|
+
// 7. `classifyLoopArray` — static vs. reconciled rendering
|
|
4753
|
+
//
|
|
4754
|
+
// Every helper keeps the exact statement order of the single function it was
|
|
4755
|
+
// carved from, so diagnostics, slot ids and marker ids are emitted in the
|
|
4756
|
+
// same sequence as before. The helpers are exported for their unit tests
|
|
4757
|
+
// (`__tests__/map-call-decisions.test.ts`) and are not part of the package's
|
|
4758
|
+
// public surface.
|
|
4759
|
+
// =============================================================================
|
|
4736
4760
|
|
|
4737
|
-
|
|
4738
|
-
|
|
4761
|
+
/** The `/* @client *\/` escape every DSL-only refusal below offers, for an expression position. */
|
|
4762
|
+
const CLIENT_ONLY_EXPRESSION_SUGGESTION = 'Add /* @client */ to evaluate this expression on the client only'
|
|
4763
|
+
/** The same escape, worded for a whole loop. */
|
|
4764
|
+
const CLIENT_ONLY_LOOP_SUGGESTION = 'Add /* @client */ to render this loop on the client only'
|
|
4765
|
+
|
|
4766
|
+
/**
|
|
4767
|
+
* The loop's SOURCE after the receiver chain is recognised: the array
|
|
4768
|
+
* expression the loop iterates (`array`, its `_p.`-rewritten `templateArray`
|
|
4769
|
+
* twin, and the AST node it was read from), plus whatever the chain lifted
|
|
4770
|
+
* out of it — the filter predicate, the sort comparator, their order, and
|
|
4771
|
+
* the `.entries()` / `Object.entries()` iteration shape.
|
|
4772
|
+
*/
|
|
4773
|
+
export interface LoopSourcePlan {
|
|
4774
|
+
array: string
|
|
4775
|
+
templateArray: string | undefined
|
|
4776
|
+
/**
|
|
4777
|
+
* AST node `array` was read from, so the static-array decision can run
|
|
4778
|
+
* `exprHasFunctionCalls` on it. Starts as the full map source, which
|
|
4779
|
+
* matches the plain-`.map()` fallback.
|
|
4780
|
+
*/
|
|
4781
|
+
arrayExpr: ts.Expression
|
|
4782
|
+
filterPredicate: FilterPredicateResult | undefined
|
|
4783
|
+
sortComparator: IRLoopSort | undefined
|
|
4784
|
+
chainOrder: 'filter-sort' | 'sort-filter' | undefined
|
|
4785
|
+
iterationShape: 'entries' | 'keys' | undefined
|
|
4786
|
+
objectIteration: 'entries' | 'keys' | 'values' | undefined
|
|
4787
|
+
}
|
|
4739
4788
|
|
|
4740
|
-
|
|
4741
|
-
|
|
4742
|
-
|
|
4743
|
-
|
|
4744
|
-
|
|
4745
|
-
|
|
4746
|
-
|
|
4747
|
-
|
|
4748
|
-
|
|
4749
|
-
|
|
4750
|
-
|
|
4751
|
-
|
|
4752
|
-
|
|
4753
|
-
|
|
4754
|
-
|
|
4755
|
-
|
|
4756
|
-
|
|
4757
|
-
|
|
4758
|
-
|
|
4759
|
-
// JSX-runtime SSR and the declared names (D5 key guard, {out} join).
|
|
4760
|
-
let preamble: MapCallbackPreamble | undefined
|
|
4761
|
-
let iterationShape: 'entries' | 'keys' | undefined
|
|
4762
|
-
let objectIteration: 'entries' | 'keys' | 'values' | undefined
|
|
4763
|
-
|
|
4764
|
-
// Helper to set both array and templateArray
|
|
4765
|
-
const setArray = (node: ts.Expression) => {
|
|
4766
|
-
array = ctx.getJS(node)
|
|
4767
|
-
templateArray = rewriteBarePropRefs(array, node, ctx)
|
|
4768
|
-
arrayExpr = node
|
|
4769
|
-
}
|
|
4770
|
-
|
|
4771
|
-
// Detect `.entries()`, `.keys()`, `.values()` as the outermost wrapper
|
|
4772
|
-
// on the map source. Strip the iterator method and record the shape so
|
|
4773
|
-
// adapters emit the right loop variable bindings. `.values()` is a
|
|
4774
|
-
// no-op (same as plain `.map()`) so it's stripped but not recorded.
|
|
4775
|
-
// The inner expression (after stripping) feeds into the standard
|
|
4776
|
-
// filter/sort chain detection below. Widened to `ts.Expression` (not
|
|
4777
|
-
// narrowed to `mapSource`'s own `LeftHandSideExpression` type) since
|
|
4778
|
-
// `isObjectIteratorCall`'s stripped argument can be any expression
|
|
4779
|
-
// (`x ?? {}`, not just a `LeftHandSideExpression`).
|
|
4780
|
-
let chainSource: ts.Expression = mapSource
|
|
4789
|
+
/**
|
|
4790
|
+
* Strip an iterator wrapper off the map source and record its shape.
|
|
4791
|
+
*
|
|
4792
|
+
* `.entries()` / `.keys()` / `.values()` (the array instance-method form) is
|
|
4793
|
+
* stripped so adapters emit the right loop variable bindings; `.values()` is
|
|
4794
|
+
* a no-op (same as plain `.map()`) so it's stripped but not recorded. The
|
|
4795
|
+
* STATIC `Object.entries(x)` / `.keys(x)` / `.values(x)` form (#2168
|
|
4796
|
+
* object-entries-map) is a SEPARATE shape — see `isObjectIteratorCall`'s and
|
|
4797
|
+
* `IRLoop.objectIteration`'s docstrings — and there `'values'` DOES need
|
|
4798
|
+
* recording (`x` itself isn't iterable as a plain object). The inner
|
|
4799
|
+
* expression feeds the filter/sort chain detection. It is widened to
|
|
4800
|
+
* `ts.Expression` since `isObjectIteratorCall`'s stripped argument can be
|
|
4801
|
+
* any expression (`x ?? {}`, not just a `LeftHandSideExpression`).
|
|
4802
|
+
*/
|
|
4803
|
+
function stripIteratorWrapper(mapSource: ts.LeftHandSideExpression): {
|
|
4804
|
+
chainSource: ts.Expression
|
|
4805
|
+
iterationShape: LoopSourcePlan['iterationShape']
|
|
4806
|
+
objectIteration: LoopSourcePlan['objectIteration']
|
|
4807
|
+
} {
|
|
4781
4808
|
const iteratorInfo = isIteratorShapeCall(mapSource)
|
|
4782
4809
|
if (iteratorInfo) {
|
|
4783
|
-
|
|
4784
|
-
|
|
4785
|
-
|
|
4786
|
-
|
|
4787
|
-
|
|
4788
|
-
}
|
|
4789
|
-
// 'values' is a no-op — same as plain .map()
|
|
4790
|
-
} else {
|
|
4791
|
-
// Detect the STATIC `Object.entries(x)` / `.keys(x)` / `.values(x)`
|
|
4792
|
-
// form (#2168 object-entries-map) — see `isObjectIteratorCall`'s and
|
|
4793
|
-
// `IRLoop.objectIteration`'s docstrings for why this is a SEPARATE
|
|
4794
|
-
// shape from the array-instance-method case above, not a shared one.
|
|
4795
|
-
// Unlike that case, `'values'` DOES need recording here (it isn't a
|
|
4796
|
-
// no-op: `x` itself isn't iterable as a plain object).
|
|
4797
|
-
const objectIteratorInfo = isObjectIteratorCall(mapSource)
|
|
4798
|
-
if (objectIteratorInfo) {
|
|
4799
|
-
chainSource = objectIteratorInfo.object
|
|
4800
|
-
objectIteration = objectIteratorInfo.shape
|
|
4801
|
-
}
|
|
4810
|
+
const iterationShape =
|
|
4811
|
+
iteratorInfo.shape === 'entries' ? 'entries'
|
|
4812
|
+
: iteratorInfo.shape === 'keys' ? 'keys'
|
|
4813
|
+
: undefined
|
|
4814
|
+
return { chainSource: iteratorInfo.array, iterationShape, objectIteration: undefined }
|
|
4802
4815
|
}
|
|
4803
|
-
|
|
4804
|
-
|
|
4805
|
-
|
|
4806
|
-
|
|
4807
|
-
|
|
4808
|
-
|
|
4809
|
-
const innerFilter = isFilterCall(sortInfo.array)
|
|
4810
|
-
|
|
4811
|
-
// Handle sort comparator extraction
|
|
4812
|
-
const sortExtraction = extractSortComparator(sortInfo.callback, sortInfo.method, ctx)
|
|
4813
|
-
if (isClientOnly || !sortExtraction.result) {
|
|
4814
|
-
// Off-subset comparator: keep it in the array string for client / SSR
|
|
4815
|
-
// evaluation. Only raise the diagnostic when the target adapter's runtime
|
|
4816
|
-
// can't run the comparator body verbatim (DSL); a JS-runtime adapter runs
|
|
4817
|
-
// it, so rejecting it would be a universal error for a DSL-only limit.
|
|
4818
|
-
// See spec/callback-fidelity.md.
|
|
4819
|
-
if (!isClientOnly && sortExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.('sort') ?? false)) {
|
|
4820
|
-
ctx.analyzer.errors.push(
|
|
4821
|
-
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
4822
|
-
getSourceLocation(sortInfo.callback, ctx.sourceFile, ctx.filePath),
|
|
4823
|
-
{
|
|
4824
|
-
message: `Expression cannot be compiled to marked template: ${sortExtraction.unsupportedReason}`,
|
|
4825
|
-
suggestion: {
|
|
4826
|
-
message: 'Add /* @client */ to evaluate this expression on the client only',
|
|
4827
|
-
},
|
|
4828
|
-
}
|
|
4829
|
-
)
|
|
4830
|
-
)
|
|
4831
|
-
}
|
|
4832
|
-
// Keep sort (and filter if present) in array string for client evaluation
|
|
4833
|
-
setArray(mapSource)
|
|
4834
|
-
} else {
|
|
4835
|
-
sortComparator = sortExtraction.result
|
|
4836
|
-
|
|
4837
|
-
if (innerFilter) {
|
|
4838
|
-
// filter().sort().map() pattern
|
|
4839
|
-
chainOrder = 'filter-sort'
|
|
4840
|
-
const filterExtraction = extractFilterPredicate(innerFilter.callback, ctx)
|
|
4841
|
-
if (isClientOnly || !filterExtraction.result) {
|
|
4842
|
-
// Off-subset predicate: keep it in the array string for client / SSR
|
|
4843
|
-
// evaluation. Only raise the diagnostic when the target adapter's runtime
|
|
4844
|
-
// can't run the predicate body verbatim (DSL); a JS-runtime adapter runs
|
|
4845
|
-
// it. See spec/callback-fidelity.md.
|
|
4846
|
-
if (!isClientOnly && filterExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.('filter') ?? false)) {
|
|
4847
|
-
ctx.analyzer.errors.push(
|
|
4848
|
-
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
4849
|
-
getSourceLocation(innerFilter.callback, ctx.sourceFile, ctx.filePath),
|
|
4850
|
-
{
|
|
4851
|
-
message: `Expression cannot be compiled to marked template: ${filterExtraction.unsupportedReason}`,
|
|
4852
|
-
suggestion: {
|
|
4853
|
-
message: 'Add /* @client */ to evaluate this expression on the client only',
|
|
4854
|
-
},
|
|
4855
|
-
}
|
|
4856
|
-
)
|
|
4857
|
-
)
|
|
4858
|
-
}
|
|
4859
|
-
// Keep entire chain in array for client evaluation
|
|
4860
|
-
setArray(mapSource)
|
|
4861
|
-
sortComparator = undefined
|
|
4862
|
-
chainOrder = undefined
|
|
4863
|
-
} else {
|
|
4864
|
-
setArray(innerFilter.array)
|
|
4865
|
-
filterPredicate = filterExtraction.result
|
|
4866
|
-
}
|
|
4867
|
-
} else {
|
|
4868
|
-
// Simple sort().map()
|
|
4869
|
-
setArray(sortInfo.array)
|
|
4870
|
-
}
|
|
4871
|
-
}
|
|
4872
|
-
} else if (filterInfo) {
|
|
4873
|
-
// Outermost is filter: could be filter().map() or sort().filter().map()
|
|
4874
|
-
const innerSort = isSortCall(filterInfo.array)
|
|
4875
|
-
|
|
4876
|
-
// Handle filter predicate extraction
|
|
4877
|
-
const filterExtraction = extractFilterPredicate(filterInfo.callback, ctx)
|
|
4878
|
-
|
|
4879
|
-
if (isClientOnly || !filterExtraction.result) {
|
|
4880
|
-
// Off-subset predicate: keep it in the array string for client / SSR
|
|
4881
|
-
// evaluation. Only raise the diagnostic when the target adapter's runtime
|
|
4882
|
-
// can't run the predicate body verbatim (DSL); a JS-runtime adapter runs
|
|
4883
|
-
// it. See spec/callback-fidelity.md.
|
|
4884
|
-
if (!isClientOnly && filterExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.('filter') ?? false)) {
|
|
4885
|
-
ctx.analyzer.errors.push(
|
|
4886
|
-
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
4887
|
-
getSourceLocation(filterInfo.callback, ctx.sourceFile, ctx.filePath),
|
|
4888
|
-
{
|
|
4889
|
-
message: `Expression cannot be compiled to marked template: ${filterExtraction.unsupportedReason}`,
|
|
4890
|
-
suggestion: {
|
|
4891
|
-
message: 'Add /* @client */ to evaluate this expression on the client only',
|
|
4892
|
-
},
|
|
4893
|
-
}
|
|
4894
|
-
)
|
|
4895
|
-
)
|
|
4896
|
-
}
|
|
4897
|
-
// Keep filter (and sort if present) in array for client evaluation
|
|
4898
|
-
setArray(mapSource)
|
|
4899
|
-
} else {
|
|
4900
|
-
filterPredicate = filterExtraction.result
|
|
4901
|
-
|
|
4902
|
-
if (innerSort) {
|
|
4903
|
-
// sort().filter().map() pattern
|
|
4904
|
-
chainOrder = 'sort-filter'
|
|
4905
|
-
const sortExtraction = extractSortComparator(innerSort.callback, innerSort.method, ctx)
|
|
4906
|
-
if (isClientOnly || !sortExtraction.result) {
|
|
4907
|
-
// Off-subset comparator: keep it in the array string for client / SSR
|
|
4908
|
-
// evaluation. Only raise the diagnostic when the target adapter's runtime
|
|
4909
|
-
// can't run the comparator body verbatim (DSL); a JS-runtime adapter runs
|
|
4910
|
-
// it, so rejecting it would be a universal error for a DSL-only limit.
|
|
4911
|
-
// See spec/callback-fidelity.md.
|
|
4912
|
-
if (!isClientOnly && sortExtraction.unsupportedReason && !(ctx.analyzer.acceptsCallbackBody?.('sort') ?? false)) {
|
|
4913
|
-
ctx.analyzer.errors.push(
|
|
4914
|
-
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
4915
|
-
getSourceLocation(innerSort.callback, ctx.sourceFile, ctx.filePath),
|
|
4916
|
-
{
|
|
4917
|
-
message: `Expression cannot be compiled to marked template: ${sortExtraction.unsupportedReason}`,
|
|
4918
|
-
suggestion: {
|
|
4919
|
-
message: 'Add /* @client */ to evaluate this expression on the client only',
|
|
4920
|
-
},
|
|
4921
|
-
}
|
|
4922
|
-
)
|
|
4923
|
-
)
|
|
4924
|
-
}
|
|
4925
|
-
// Keep sort in array for client evaluation, but keep filter extracted
|
|
4926
|
-
setArray(filterInfo.array)
|
|
4927
|
-
} else {
|
|
4928
|
-
sortComparator = sortExtraction.result
|
|
4929
|
-
setArray(innerSort.array)
|
|
4930
|
-
}
|
|
4931
|
-
} else {
|
|
4932
|
-
// Simple filter().map(). `setArray` (not a bare `array =`
|
|
4933
|
-
// assignment) so `templateArray` carries the `_p.`-rewritten form —
|
|
4934
|
-
// the module-scope `template:` lambda can't see init's destructured
|
|
4935
|
-
// prop locals, and a bare destructured name there threw
|
|
4936
|
-
// `ReferenceError` at runtime (#2222).
|
|
4937
|
-
setArray(filterInfo.array)
|
|
4938
|
-
}
|
|
4816
|
+
const objectIteratorInfo = isObjectIteratorCall(mapSource)
|
|
4817
|
+
if (objectIteratorInfo) {
|
|
4818
|
+
return {
|
|
4819
|
+
chainSource: objectIteratorInfo.object,
|
|
4820
|
+
iterationShape: undefined,
|
|
4821
|
+
objectIteration: objectIteratorInfo.shape,
|
|
4939
4822
|
}
|
|
4940
|
-
} else {
|
|
4941
|
-
// Plain `.map()` fallback — same `setArray` requirement as above
|
|
4942
|
-
// (#2222): this is the most common loop shape and was the primary
|
|
4943
|
-
// repro for the bare-destructured-name ReferenceError.
|
|
4944
|
-
setArray(chainSource)
|
|
4945
4823
|
}
|
|
4824
|
+
return { chainSource: mapSource, iterationShape: undefined, objectIteration: undefined }
|
|
4825
|
+
}
|
|
4946
4826
|
|
|
4947
|
-
|
|
4948
|
-
|
|
4949
|
-
|
|
4950
|
-
|
|
4951
|
-
|
|
4952
|
-
|
|
4953
|
-
|
|
4954
|
-
|
|
4955
|
-
|
|
4956
|
-
|
|
4957
|
-
|
|
4958
|
-
|
|
4959
|
-
|
|
4960
|
-
|
|
4961
|
-
|
|
4962
|
-
|
|
4963
|
-
|
|
4964
|
-
|
|
4965
|
-
|
|
4966
|
-
|
|
4967
|
-
|
|
4968
|
-
|
|
4969
|
-
|
|
4970
|
-
|
|
4971
|
-
// residual-object / `.slice(n)` accessor at each reference. Only
|
|
4972
|
-
// computed property keys remain unsupported — those raise `BF025`
|
|
4973
|
-
// and the emitter falls back to the #950 body-entry unwrap.
|
|
4974
|
-
// `.entries()` synthesises `[index, value]` — when the callback
|
|
4975
|
-
// destructures exactly two array elements, extract the names into
|
|
4976
|
-
// `index` and `param` so the loop renders with proper bindings and
|
|
4977
|
-
// the BF104 destructure-param refusal doesn't fire. `Object.entries(x)`
|
|
4978
|
-
// (`objectIteration === 'entries'`) synthesises the SAME `[key,
|
|
4979
|
-
// value]` 2-tuple shape — `index` just holds a string key instead
|
|
4980
|
-
// of a numeric position — so it reuses this exact extraction.
|
|
4981
|
-
const isEntriesShape = iterationShape === 'entries' || objectIteration === 'entries'
|
|
4982
|
-
if (isEntriesShape && ts.isArrayBindingPattern(firstParam.name)) {
|
|
4983
|
-
const elements = firstParam.name.elements.filter(
|
|
4984
|
-
el => !ts.isOmittedExpression(el),
|
|
4985
|
-
)
|
|
4986
|
-
if (elements.length === 2 &&
|
|
4987
|
-
ts.isBindingElement(elements[0]) && ts.isIdentifier(elements[0].name) &&
|
|
4988
|
-
ts.isBindingElement(elements[1]) && ts.isIdentifier(elements[1].name)) {
|
|
4989
|
-
index = elements[0].name.text
|
|
4990
|
-
param = elements[1].name.text
|
|
4991
|
-
itemTypeNode = elements[1].name
|
|
4992
|
-
// Don't populate paramBindings — the destructure is fully
|
|
4993
|
-
// resolved into index + param by the iteration shape.
|
|
4994
|
-
} else {
|
|
4995
|
-
// Non-2-element destructure with .entries() — fall through to
|
|
4996
|
-
// standard destructure handling (will trigger BF104 on
|
|
4997
|
-
// template adapters).
|
|
4998
|
-
const bindingResult = extractLoopParamBindings(firstParam.name)
|
|
4999
|
-
if (bindingResult && !Array.isArray(bindingResult)) {
|
|
5000
|
-
ctx.analyzer.errors.push(
|
|
5001
|
-
createError(ErrorCodes.UNSUPPORTED_DESTRUCTURE_REST,
|
|
5002
|
-
getSourceLocation(firstParam, ctx.sourceFile, ctx.filePath),
|
|
5003
|
-
)
|
|
5004
|
-
)
|
|
5005
|
-
} else if (Array.isArray(bindingResult)) {
|
|
5006
|
-
paramBindings = bindingResult
|
|
5007
|
-
}
|
|
5008
|
-
}
|
|
5009
|
-
} else {
|
|
5010
|
-
const bindingResult = extractLoopParamBindings(firstParam.name)
|
|
5011
|
-
if (bindingResult && !Array.isArray(bindingResult)) {
|
|
5012
|
-
ctx.analyzer.errors.push(
|
|
5013
|
-
createError(ErrorCodes.UNSUPPORTED_DESTRUCTURE_REST,
|
|
5014
|
-
getSourceLocation(firstParam, ctx.sourceFile, ctx.filePath),
|
|
5015
|
-
)
|
|
5016
|
-
)
|
|
5017
|
-
} else if (Array.isArray(bindingResult)) {
|
|
5018
|
-
paramBindings = bindingResult
|
|
5019
|
-
}
|
|
5020
|
-
}
|
|
5021
|
-
}
|
|
5022
|
-
if (callback.parameters.length > 1 && iterationShape !== 'entries' && objectIteration !== 'entries') {
|
|
5023
|
-
const secondParam = callback.parameters[1]
|
|
5024
|
-
index = secondParam.name.getText(ctx.sourceFile)
|
|
5025
|
-
if (secondParam.type) {
|
|
5026
|
-
indexType = secondParam.type.getText(ctx.sourceFile)
|
|
5027
|
-
}
|
|
5028
|
-
}
|
|
5029
|
-
|
|
5030
|
-
// Register loop-bound names so expressions referencing them get slotId,
|
|
5031
|
-
// by entering a new BindingScope frame for this row (#2482 Stage 1a).
|
|
5032
|
-
// For destructured patterns, the frame binds the individual binding
|
|
5033
|
-
// names — `\b${param}\b` never matches a bare name like `cfg` when
|
|
5034
|
-
// `param` is `[, cfg]`, which would otherwise leave reactive-expression
|
|
5035
|
-
// detection silently broken for destructured callbacks.
|
|
5036
|
-
// `savedScope` is restored (not deleted-from) at the matching exit site
|
|
5037
|
-
// below, so a nested loop reusing a param name can never corrupt the
|
|
5038
|
-
// outer scope.
|
|
5039
|
-
const savedScope = ctx.scope
|
|
5040
|
-
ctx.scope = ctx.scope.enterLoopRow({ param, index, paramBindings })
|
|
5041
|
-
ctx.loopDepth++
|
|
5042
|
-
|
|
5043
|
-
// Logical control flow (`cond && <X/>`, `a ?? themeLogo()`) as the map
|
|
5044
|
-
// body. This is not a JSX literal, ternary, or block, so without this
|
|
5045
|
-
// the dispatch below leaves `children` empty and the whole `.map(...)`
|
|
5046
|
-
// falls through to the reactive-text path — emitting the callback
|
|
5047
|
-
// verbatim. That left inline JSX uncompiled and module-level JSX
|
|
5048
|
-
// helpers undeclared (ReferenceError at hydration, #1665). Route the
|
|
5049
|
-
// logical body through the shared JSX expression transformer, which
|
|
5050
|
-
// lowers it into an IRConditional and inlines any JSX helper, exactly
|
|
5051
|
-
// like the ternary form.
|
|
5052
|
-
//
|
|
5053
|
-
// Scoped deliberately to logical operators that actually render JSX
|
|
5054
|
-
// (inline literal or a tracked helper call): a bare call body
|
|
5055
|
-
// (`map(t => renderItem(t))`) stays on the existing reactive-text path
|
|
5056
|
-
// that #546 owns, and a scalar logical body (`t.active && t.label`)
|
|
5057
|
-
// keeps rendering its value.
|
|
5058
|
-
const tryTransformRenderableBody = (expr: ts.Expression): void => {
|
|
5059
|
-
if (!ts.isBinaryExpression(expr)) return
|
|
5060
|
-
const op = expr.operatorToken.kind
|
|
5061
|
-
if (
|
|
5062
|
-
op !== ts.SyntaxKind.AmpersandAmpersandToken &&
|
|
5063
|
-
op !== ts.SyntaxKind.BarBarToken &&
|
|
5064
|
-
op !== ts.SyntaxKind.QuestionQuestionToken
|
|
5065
|
-
) {
|
|
5066
|
-
return
|
|
5067
|
-
}
|
|
5068
|
-
if (!containsJsxInExpression(expr) && !callsJsxHelper(expr, ctx)) return
|
|
5069
|
-
const transformed = transformJsxExpression(expr, ctx, isClientOnly)
|
|
5070
|
-
if (transformed) children = [transformed]
|
|
5071
|
-
}
|
|
5072
|
-
|
|
5073
|
-
// Transform callback body
|
|
5074
|
-
const body = callback.body
|
|
5075
|
-
if (ts.isJsxElement(body) || ts.isJsxSelfClosingElement(body) || ts.isJsxFragment(body)) {
|
|
5076
|
-
const transformed = transformNode(body, ctx)
|
|
5077
|
-
if (transformed) {
|
|
5078
|
-
children = [transformed]
|
|
5079
|
-
}
|
|
5080
|
-
} else if (ts.isConditionalExpression(body)) {
|
|
5081
|
-
// Ternary directly in callback: items.map(item => cond ? <A/> : <B/>)
|
|
5082
|
-
children = [transformConditional(body, ctx)]
|
|
5083
|
-
} else if (ts.isParenthesizedExpression(body)) {
|
|
5084
|
-
let inner = body.expression
|
|
5085
|
-
while (ts.isParenthesizedExpression(inner)) {
|
|
5086
|
-
inner = inner.expression
|
|
5087
|
-
}
|
|
5088
|
-
if (ts.isJsxElement(inner) || ts.isJsxSelfClosingElement(inner) || ts.isJsxFragment(inner)) {
|
|
5089
|
-
const transformed = transformNode(inner, ctx)
|
|
5090
|
-
if (transformed) {
|
|
5091
|
-
children = [transformed]
|
|
5092
|
-
}
|
|
5093
|
-
} else if (ts.isConditionalExpression(inner)) {
|
|
5094
|
-
// Parenthesized ternary: items.map(item => (cond ? <A/> : <B/>))
|
|
5095
|
-
children = [transformConditional(inner, ctx)]
|
|
5096
|
-
} else if (method === 'flatMap' && ts.isArrayLiteralExpression(inner)) {
|
|
5097
|
-
// flatMap arrow with array literal: items.flatMap(item => ([<A/>, <B/>]))
|
|
5098
|
-
children = transformArrayLiteralChildren(inner, ctx)
|
|
5099
|
-
} else {
|
|
5100
|
-
tryTransformRenderableBody(inner)
|
|
5101
|
-
}
|
|
5102
|
-
} else if (method === 'flatMap' && ts.isArrayLiteralExpression(body)) {
|
|
5103
|
-
// flatMap arrow with array literal: items.flatMap(item => [<A/>, <B/>])
|
|
5104
|
-
children = transformArrayLiteralChildren(body, ctx)
|
|
5105
|
-
} else if (ts.isBlock(body)) {
|
|
5106
|
-
// Multi-return JSX block body (if/else-if chain or a `switch`, including
|
|
5107
|
-
// fallthrough case labels, optionally preceded by a `const`/`let`
|
|
5108
|
-
// preamble) — fold to a nested IRConditional so the loop renders each
|
|
5109
|
-
// branch's compiled template. Tried BEFORE the single-return path:
|
|
5110
|
-
// otherwise the trailing `return <fallback/>` would claim the
|
|
5111
|
-
// single-return arm and the leading `if (...) return <A/>` would leak
|
|
5112
|
-
// verbatim into the map preamble (the silent-verbatim-leak this fixes).
|
|
5113
|
-
// Stage 2 of spec/callback-fidelity.md. A branch-local `const` (inside a
|
|
5114
|
-
// branch block/case) or a statement-level nested loop is not folded
|
|
5115
|
-
// (extractMultiReturnJsxBranches returns null) and falls through below.
|
|
5116
|
-
const multiReturn = method !== 'flatMap' ? extractMultiReturnJsxBranches(body, true) : null
|
|
5117
|
-
if (multiReturn && multiReturn.branches.length > 0) {
|
|
5118
|
-
const loc = getSourceLocation(body, ctx.sourceFile, ctx.filePath)
|
|
5119
|
-
children = [foldMultiReturnBranches(multiReturn, ctx, loc, ctx.getJS)]
|
|
5120
|
-
|
|
5121
|
-
const pre = multiReturn.preamble ?? []
|
|
5122
|
-
if (pre.length > 0) {
|
|
5123
|
-
// Emit the leading const/let preamble once per iteration, ahead of
|
|
5124
|
-
// the conditional — the same carrier the single-return path uses. A
|
|
5125
|
-
// JS-runtime adapter (and the browser under /* @client */) runs it
|
|
5126
|
-
// verbatim.
|
|
5127
|
-
preamble = preambleFromValueStatements(pre, ctx, body.statements)
|
|
5128
|
-
|
|
5129
|
-
// Stage 2 of spec/callback-fidelity.md, narrowed by #2447. This used
|
|
5130
|
-
// to refuse EVERY branch preamble on a DSL target, on the premise
|
|
5131
|
-
// that a loop-local can't be carried into a conditional branch
|
|
5132
|
-
// template. That premise stopped holding once `declarations` lower
|
|
5133
|
-
// to a per-row local: the fold emits the conditional INSIDE the loop
|
|
5134
|
-
// body, so a local declared ahead of it is in scope in both arms —
|
|
5135
|
-
// `{{$label := bf_upper .Kind}}{{if .On}}…{{$label}}…{{else}}…`. What
|
|
5136
|
-
// remains true is the original hazard for a preamble that CANNOT be
|
|
5137
|
-
// declared: nothing lowers, both branches read an unassigned name.
|
|
5138
|
-
// So the refusal now keys off the same condition as the single-return
|
|
5139
|
-
// gate below, not off the presence of branches.
|
|
5140
|
-
if (
|
|
5141
|
-
!preamble.declarations &&
|
|
5142
|
-
!isClientOnly &&
|
|
5143
|
-
!(ctx.analyzer.acceptsCallbackBody?.('map') ?? false)
|
|
5144
|
-
) {
|
|
5145
|
-
ctx.analyzer.errors.push(
|
|
5146
|
-
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, loc, {
|
|
5147
|
-
message:
|
|
5148
|
-
'A .map() callback body with a preamble before its branches cannot be ' +
|
|
5149
|
-
'lowered to a template: the preamble is not a sequence of value ' +
|
|
5150
|
-
'declarations, so this backend has no per-row local to carry into the ' +
|
|
5151
|
-
'branches.',
|
|
5152
|
-
suggestion: {
|
|
5153
|
-
message: 'Add /* @client */ to evaluate this expression on the client only',
|
|
5154
|
-
},
|
|
5155
|
-
})
|
|
5156
|
-
)
|
|
5157
|
-
}
|
|
5158
|
-
}
|
|
5159
|
-
}
|
|
5160
|
-
|
|
5161
|
-
// Block body: (item) => { const label = ...; return <div>{label}</div> }
|
|
5162
|
-
const returnStmt = children.length === 0
|
|
5163
|
-
? body.statements.find(
|
|
5164
|
-
(s): s is ts.ReturnStatement => ts.isReturnStatement(s) && s.expression != null
|
|
5165
|
-
)
|
|
5166
|
-
: undefined
|
|
5167
|
-
|
|
5168
|
-
// #2482 Stage 1a Commit 2 — ordering note: the STRUCTURED preamble
|
|
5169
|
-
// (`MapCallbackPreamble`, built further down by
|
|
5170
|
-
// `preambleFromValueStatements` / `buildPreambleSegments`, whichever
|
|
5171
|
-
// branch below the return-expression shape takes) isn't known until
|
|
5172
|
-
// well AFTER this point. But `transformNode(returnExpr, ctx)` just
|
|
5173
|
-
// below walks the return expression's own child expressions RIGHT
|
|
5174
|
-
// NOW — before that happens — so a preamble-declared local shadowing
|
|
5175
|
-
// an outer const/prop must already be bound in `ctx.scope`, or
|
|
5176
|
-
// `tryResolveTemplateSpanFromConst` / `tryResolveIdentifierAsTemplateLiteral`
|
|
5177
|
-
// / `rewriteBarePropRefs` bake the OUTER value into every row instead
|
|
5178
|
-
// of leaving the row-local unresolved (#2222-family, the const/prop-
|
|
5179
|
-
// shadow bug class). Fix: a lightweight declared-names-only pre-scan
|
|
5180
|
-
// — the exact same "statements before the return" shape
|
|
5181
|
-
// `preambleFromValueStatements`/`buildPreambleSegments` scan below —
|
|
5182
|
-
// re-enters the row's `BindingScope` frame (off `savedScope`, the
|
|
5183
|
-
// pre-loop parent, so this REPLACES the param/index-only frame
|
|
5184
|
-
// rather than stacking a second one) with the preamble included, for
|
|
5185
|
-
// the duration of the return-expression transform. Restored back to
|
|
5186
|
-
// the preamble-less row scope right after that window closes (see
|
|
5187
|
-
// `rowScopeBeforePreamble` below) — everything past this window
|
|
5188
|
-
// (the flatMap fallbacks, and the whole rest of `transformMapCall`
|
|
5189
|
-
// after this `if (ts.isBlock(body))` branch) must keep observing
|
|
5190
|
-
// EXACTLY the old (Commit 1) membership, since slotId-allocation
|
|
5191
|
-
// classifiers there read `ctx.scope.valueBoundNames()`, which never
|
|
5192
|
-
// included preamble names to begin with — only shadow guards need
|
|
5193
|
-
// the widened view, and only for this window.
|
|
5194
|
-
let rowScopeBeforePreamble: BindingScope | null = null
|
|
5195
|
-
if (returnStmt) {
|
|
5196
|
-
const preambleNames = new Set<string>()
|
|
5197
|
-
for (const stmt of body.statements) {
|
|
5198
|
-
if (stmt === returnStmt) break
|
|
5199
|
-
collectPreambleDeclaredNames(stmt, preambleNames)
|
|
5200
|
-
}
|
|
5201
|
-
if (preambleNames.size > 0) {
|
|
5202
|
-
rowScopeBeforePreamble = ctx.scope
|
|
5203
|
-
ctx.scope = savedScope.enterLoopRow({
|
|
5204
|
-
param,
|
|
5205
|
-
index,
|
|
5206
|
-
paramBindings,
|
|
5207
|
-
preamble: { declaredNames: [...preambleNames] },
|
|
5208
|
-
})
|
|
5209
|
-
}
|
|
5210
|
-
}
|
|
5211
|
-
|
|
5212
|
-
if (returnStmt && returnStmt.expression) {
|
|
5213
|
-
let returnExpr = returnStmt.expression
|
|
5214
|
-
while (ts.isParenthesizedExpression(returnExpr)) {
|
|
5215
|
-
returnExpr = returnExpr.expression
|
|
5216
|
-
}
|
|
5217
|
-
if (ts.isJsxElement(returnExpr) || ts.isJsxSelfClosingElement(returnExpr) || ts.isJsxFragment(returnExpr)) {
|
|
5218
|
-
const transformed = transformNode(returnExpr, ctx)
|
|
5219
|
-
if (transformed) {
|
|
5220
|
-
children = [transformed]
|
|
5221
|
-
}
|
|
5222
|
-
}
|
|
5223
|
-
// Stage 3 of spec/callback-fidelity.md — an arbitrary `.map()` body that
|
|
5224
|
-
// *constructs* JSX in a statement before its `return` (the classic
|
|
5225
|
-
// `const out = []; for (const c of it.cells) out.push(<td>{c}</td>);
|
|
5226
|
-
// return <tr>{out}</tr>` array-builder) cannot be lowered to a template.
|
|
5227
|
-
// The preamble collector below reconstructs each statement with
|
|
5228
|
-
// `ctx.getJS`, which strips *types* but not JSX, so the raw `<td>{c}</td>`
|
|
5229
|
-
// would splice verbatim into the emitted client bundle — invalid JS, a
|
|
5230
|
-
// silent syntax-error leak with no diagnostic. Refuse loudly instead of
|
|
5231
|
-
// leaking. (A later Stage-3 PR renders such bodies verbatim on JS
|
|
5232
|
-
// runtimes; until then it is a build error on every backend.)
|
|
5233
|
-
// Scan only statements the preamble collector below would reach — i.e.
|
|
5234
|
-
// those *before* `returnStmt` (it `break`s at the return). JSX in
|
|
5235
|
-
// unreachable post-return dead code is never spliced into the preamble,
|
|
5236
|
-
// so it is not part of the leak and must not trip the refusal.
|
|
5237
|
-
let jsxPreambleStmt: ts.Statement | undefined
|
|
5238
|
-
for (const stmt of body.statements) {
|
|
5239
|
-
if (stmt === returnStmt) break
|
|
5240
|
-
if (containsJsxInExpression(stmt)) {
|
|
5241
|
-
jsxPreambleStmt = stmt
|
|
5242
|
-
break
|
|
5243
|
-
}
|
|
5244
|
-
}
|
|
5245
|
-
if (jsxPreambleStmt) {
|
|
5246
|
-
// Stage 3 / D4 (spec/callback-fidelity.md). A JS-runtime adapter runs
|
|
5247
|
-
// the callback body verbatim — each JSX leaf lowers to a template-
|
|
5248
|
-
// literal HTML string, the imperative control flow runs as-is, and the
|
|
5249
|
-
// element-array child ({out}) is joined into the row. A DSL template
|
|
5250
|
-
// runtime can't do this, so it refuses with the /* @client */ escape
|
|
5251
|
-
// (which renders the loop client-only, where the browser — always JS —
|
|
5252
|
-
// runs the same body). Mirrors the const-preamble gate above and the
|
|
5253
|
-
// Stage-1 filter/sort sites (all consult `acceptsCallbackBody`).
|
|
5254
|
-
const jsRuntime = isClientOnly || (ctx.analyzer.acceptsCallbackBody?.('map') ?? false)
|
|
5255
|
-
if (children.length === 0) {
|
|
5256
|
-
// The return shape produced no loop children (a bare identifier
|
|
5257
|
-
// `return out`, a ternary, any non-element return): there is no
|
|
5258
|
-
// single template root to host the built elements, so the loop IR
|
|
5259
|
-
// can't exist and the fallback would splice the raw callback —
|
|
5260
|
-
// JSX included — verbatim into an expression anchor (a silent
|
|
5261
|
-
// leak on EVERY tier, /* @client */ included). Refuse loudly with
|
|
5262
|
-
// restructuring guidance; the return-shape holes pinned by
|
|
5263
|
-
// map-body-no-silent-divergence.test.ts close here.
|
|
5264
|
-
ctx.analyzer.errors.push(
|
|
5265
|
-
createError(
|
|
5266
|
-
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5267
|
-
getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath),
|
|
5268
|
-
{
|
|
5269
|
-
message:
|
|
5270
|
-
'A .map() callback that builds JSX in a statement before its ' +
|
|
5271
|
-
'`return` must return a single JSX element that embeds the ' +
|
|
5272
|
-
'built array — this return shape has no element root to host it.',
|
|
5273
|
-
suggestion: {
|
|
5274
|
-
message:
|
|
5275
|
-
'Wrap the result in one element root, e.g. `return <tr key={item.id}>{out}</tr>`.',
|
|
5276
|
-
},
|
|
5277
|
-
}
|
|
5278
|
-
)
|
|
5279
|
-
)
|
|
5280
|
-
} else if (!jsRuntime) {
|
|
5281
|
-
ctx.analyzer.errors.push(
|
|
5282
|
-
createError(
|
|
5283
|
-
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5284
|
-
getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath),
|
|
5285
|
-
{
|
|
5286
|
-
message:
|
|
5287
|
-
'A .map() callback that builds JSX in a statement before its ' +
|
|
5288
|
-
'`return` (for example pushing elements into an array in a loop) ' +
|
|
5289
|
-
'cannot be lowered to a template on this backend.',
|
|
5290
|
-
suggestion: {
|
|
5291
|
-
message: 'Add /* @client */ to render this loop on the client only',
|
|
5292
|
-
},
|
|
5293
|
-
}
|
|
5294
|
-
)
|
|
5295
|
-
)
|
|
5296
|
-
} else {
|
|
5297
|
-
const collected = buildPreambleSegments(body.statements, returnStmt, ctx)
|
|
5298
|
-
if (collected.refusalNode) {
|
|
5299
|
-
// A leaf carries wiring the verbatim path can't render (event
|
|
5300
|
-
// handler, component, nested loop, reactive slot, spread), or
|
|
5301
|
-
// sits inside a template literal (a segment boundary there would
|
|
5302
|
-
// split the literal's lexical state for downstream text
|
|
5303
|
-
// transforms). Refuse loudly (D-E) rather than emit a
|
|
5304
|
-
// silently-degraded node.
|
|
5305
|
-
ctx.analyzer.errors.push(
|
|
5306
|
-
createError(
|
|
5307
|
-
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5308
|
-
getSourceLocation(collected.refusalNode, ctx.sourceFile, ctx.filePath),
|
|
5309
|
-
{
|
|
5310
|
-
message:
|
|
5311
|
-
'A JSX element built in a .map() callback preamble cannot carry ' +
|
|
5312
|
-
'event handlers, components, nested loops, or reactive expressions, ' +
|
|
5313
|
-
'and cannot sit inside a template literal — the verbatim render ' +
|
|
5314
|
-
'path builds it once, with no reactive wiring.',
|
|
5315
|
-
suggestion: {
|
|
5316
|
-
message:
|
|
5317
|
-
'Return the element directly (not through a preamble variable), ' +
|
|
5318
|
-
'or add /* @client */ to render the loop on the client only.',
|
|
5319
|
-
},
|
|
5320
|
-
}
|
|
5321
|
-
)
|
|
5322
|
-
)
|
|
5323
|
-
} else {
|
|
5324
|
-
preamble = collected.preamble
|
|
5325
|
-
}
|
|
5326
|
-
}
|
|
5327
|
-
} else {
|
|
5328
|
-
const valueStmts: ts.Statement[] = []
|
|
5329
|
-
for (const stmt of body.statements) {
|
|
5330
|
-
if (stmt === returnStmt) break
|
|
5331
|
-
valueStmts.push(stmt)
|
|
5332
|
-
}
|
|
5333
|
-
if (valueStmts.length > 0) {
|
|
5334
|
-
preamble = preambleFromValueStatements(valueStmts, ctx, body.statements)
|
|
5335
|
-
|
|
5336
|
-
// #2447. A DSL adapter cannot execute `preamble.segments` (JS
|
|
5337
|
-
// text), so it lowers `declarations` — one per-row local each —
|
|
5338
|
-
// and the row markup reads them as locals. When the preamble
|
|
5339
|
-
// isn't fully declarable there is nothing to lower, and the
|
|
5340
|
-
// adapter used to emit the row anyway, reading names it never
|
|
5341
|
-
// assigned: the class rendered empty, on every DSL backend, with
|
|
5342
|
-
// no diagnostic. Refuse loudly instead, with the same
|
|
5343
|
-
// `/* @client */` escape as the branch-preamble, array-builder
|
|
5344
|
-
// and flatMap gates above.
|
|
5345
|
-
if (
|
|
5346
|
-
!preamble.declarations &&
|
|
5347
|
-
!isClientOnly &&
|
|
5348
|
-
!(ctx.analyzer.acceptsCallbackBody?.('map') ?? false)
|
|
5349
|
-
) {
|
|
5350
|
-
ctx.analyzer.errors.push(
|
|
5351
|
-
createError(
|
|
5352
|
-
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5353
|
-
getSourceLocation(body, ctx.sourceFile, ctx.filePath),
|
|
5354
|
-
{
|
|
5355
|
-
message:
|
|
5356
|
-
'A .map() callback preamble that is not a sequence of value ' +
|
|
5357
|
-
'declarations cannot be lowered to a template: this backend can ' +
|
|
5358
|
-
'declare a per-row local, but cannot run arbitrary statements per row.',
|
|
5359
|
-
suggestion: {
|
|
5360
|
-
message: 'Add /* @client */ to evaluate this expression on the client only',
|
|
5361
|
-
},
|
|
5362
|
-
},
|
|
5363
|
-
)
|
|
5364
|
-
)
|
|
5365
|
-
}
|
|
5366
|
-
}
|
|
5367
|
-
}
|
|
5368
|
-
}
|
|
5369
|
-
|
|
5370
|
-
// Window closed — restore the preamble-less row scope so every
|
|
5371
|
-
// consumer past this point (the flatMap fallbacks immediately
|
|
5372
|
-
// below, and the rest of `transformMapCall` after this branch)
|
|
5373
|
-
// keeps observing EXACTLY the pre-rework membership.
|
|
5374
|
-
if (rowScopeBeforePreamble) {
|
|
5375
|
-
ctx.scope = rowScopeBeforePreamble
|
|
5376
|
-
}
|
|
5377
|
-
|
|
5378
|
-
// flatMap block body fallback: compile JSX inline when children
|
|
5379
|
-
// couldn't be extracted via the standard single-return path. A pure
|
|
5380
|
-
// single-`return <call>` projection is NOT taken here — it lowers to
|
|
5381
|
-
// neutral IR below (nested-loop child), which DSL adapters templatize.
|
|
5382
|
-
if (method === 'flatMap' && children.length === 0 && !flatMapProjectionCall(body)) {
|
|
5383
|
-
flatMapCallback = buildFlatMapCallback(callback, body, ctx)
|
|
5384
|
-
}
|
|
5385
|
-
} else {
|
|
5386
|
-
tryTransformRenderableBody(body)
|
|
5387
|
-
}
|
|
5388
|
-
|
|
5389
|
-
// flatMap PROJECTION body — the canonical `flatMap(it => it.tags.map(tag
|
|
5390
|
-
// => <li key={...}/>))`, as an expression body or a single-`return` block
|
|
5391
|
-
// (parenthesized or not). This is a pure nested-loop projection, so it
|
|
5392
|
-
// lowers to NEUTRAL IR — an inner IRLoop as the loop's only child — which
|
|
5393
|
-
// every SSR adapter can templatize (nested `{{range}}` on DSL backends),
|
|
5394
|
-
// per spec/callback-fidelity.md's fidelity table ("single expr" row) and
|
|
5395
|
-
// the array-literal flatMap precedent. Only bodies carrying STATEMENTS
|
|
5396
|
-
// (early returns, consts) fall through to the segments carrier below and
|
|
5397
|
-
// its DSL gate. The client reconciles the flattened leaves through the
|
|
5398
|
-
// descriptor mapArray path, synthesized from this same neutral IR
|
|
5399
|
-
// (`renderFlatMapProjectionClientBody`); the leaf `key` renders as the
|
|
5400
|
-
// usual nested-loop `data-key-1` on both the SSR and client string
|
|
5401
|
-
// sides, and the flattened reconciliation identity (`data-key`) is
|
|
5402
|
-
// stamped by mapArray from the inner loop's `key` field.
|
|
5403
|
-
if (method === 'flatMap' && children.length === 0 && !flatMapCallback) {
|
|
5404
|
-
const projection = flatMapProjectionCall(body)
|
|
5405
|
-
if (projection) {
|
|
5406
|
-
const transformed = transformJsxExpression(projection, ctx, isClientOnly)
|
|
5407
|
-
if (transformed && transformed.type === 'loop') {
|
|
5408
|
-
children = [transformed]
|
|
5409
|
-
}
|
|
4827
|
+
/**
|
|
4828
|
+
* An off-subset comparator / predicate stays in the array string for client
|
|
4829
|
+
* / SSR evaluation. The diagnostic is raised only when the target adapter's
|
|
4830
|
+
* runtime can't run the callback body verbatim (DSL); a JS-runtime adapter
|
|
4831
|
+
* runs it, so rejecting it would be a universal error for a DSL-only limit.
|
|
4832
|
+
* See spec/callback-fidelity.md.
|
|
4833
|
+
*/
|
|
4834
|
+
function refuseOffSubsetCallback(
|
|
4835
|
+
kind: 'sort' | 'filter',
|
|
4836
|
+
callback: ts.Expression,
|
|
4837
|
+
unsupportedReason: string | undefined,
|
|
4838
|
+
ctx: TransformContext,
|
|
4839
|
+
isClientOnly: boolean,
|
|
4840
|
+
): void {
|
|
4841
|
+
if (isClientOnly || !unsupportedReason) return
|
|
4842
|
+
if (ctx.analyzer.acceptsCallbackBody?.(kind) ?? false) return
|
|
4843
|
+
ctx.analyzer.errors.push(
|
|
4844
|
+
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
4845
|
+
getSourceLocation(callback, ctx.sourceFile, ctx.filePath),
|
|
4846
|
+
{
|
|
4847
|
+
message: `Expression cannot be compiled to marked template: ${unsupportedReason}`,
|
|
4848
|
+
suggestion: {
|
|
4849
|
+
message: CLIENT_ONLY_EXPRESSION_SUGGESTION,
|
|
4850
|
+
},
|
|
5410
4851
|
}
|
|
5411
|
-
|
|
4852
|
+
)
|
|
4853
|
+
)
|
|
4854
|
+
}
|
|
5412
4855
|
|
|
5413
|
-
|
|
5414
|
-
|
|
5415
|
-
// structured-segments carrier in the isBlock branch above; an unbraced
|
|
5416
|
-
// body is the same shape minus the braces, so route it through the same
|
|
5417
|
-
// door. Without this the dispatch falls to the IRExpression scalar path,
|
|
5418
|
-
// which splices the raw callback — JSX included — verbatim into the
|
|
5419
|
-
// client bundle: a silent SyntaxError that kills the whole component's
|
|
5420
|
-
// hydration.
|
|
5421
|
-
if (method === 'flatMap' && children.length === 0 && !flatMapCallback && !ts.isBlock(body)) {
|
|
5422
|
-
flatMapCallback = buildFlatMapCallback(callback, body, ctx)
|
|
5423
|
-
}
|
|
5424
|
-
|
|
5425
|
-
// A flatMapCallback carries the WHOLE body (statements included) as
|
|
5426
|
-
// structured segments — the generic statements-before-return `preamble`
|
|
5427
|
-
// the block-body path may have collected above is a duplicate carrier.
|
|
5428
|
-
// Worse, it isn't one: spliced into a mapArray renderItem it re-runs the
|
|
5429
|
-
// body's control flow against the wrong binding shape (the audited
|
|
5430
|
-
// `if (t().tags.length > maxTags) return [];` renderItem residue).
|
|
5431
|
-
// The segments carrier is the single door; drop the shadow copy.
|
|
5432
|
-
if (flatMapCallback) preamble = undefined
|
|
5433
|
-
|
|
5434
|
-
// Adapter gate (spec/callback-fidelity.md fidelity model): a flatMap body
|
|
5435
|
-
// carried as structured segments runs verbatim on a JS runtime; a DSL
|
|
5436
|
-
// template runtime cannot execute it at SSR — pre-gate, e.g. the Go
|
|
5437
|
-
// adapter emitted `{{range …}}{{end}}` with an EMPTY body (silent
|
|
5438
|
-
// divergence, the exact failure class the sound-or-loud invariant
|
|
5439
|
-
// forbids). Refuse loudly with the /* @client */ escape, mirroring the
|
|
5440
|
-
// const-preamble and array-builder gates above.
|
|
5441
|
-
if (flatMapCallback && !isClientOnly && !(ctx.analyzer.acceptsCallbackBody?.('flatMap') ?? false)) {
|
|
5442
|
-
ctx.analyzer.errors.push(
|
|
5443
|
-
createError(
|
|
5444
|
-
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5445
|
-
getSourceLocation(body, ctx.sourceFile, ctx.filePath),
|
|
5446
|
-
{
|
|
5447
|
-
message:
|
|
5448
|
-
'A .flatMap() callback body with statements or a nested projection ' +
|
|
5449
|
-
'cannot be lowered to a template on this backend.',
|
|
5450
|
-
suggestion: {
|
|
5451
|
-
message: 'Add /* @client */ to render this loop on the client only',
|
|
5452
|
-
},
|
|
5453
|
-
}
|
|
5454
|
-
)
|
|
5455
|
-
)
|
|
5456
|
-
}
|
|
4856
|
+
/** Binds `array` / `templateArray` / `arrayExpr` on the plan from one AST node. */
|
|
4857
|
+
type SetLoopArray = (expr: ts.Expression) => void
|
|
5457
4858
|
|
|
5458
|
-
|
|
5459
|
-
|
|
5460
|
-
|
|
5461
|
-
|
|
5462
|
-
|
|
4859
|
+
/**
|
|
4860
|
+
* Outermost call is a sort: `sort().map()` or `filter().sort().map()`.
|
|
4861
|
+
* A comparator the catalogue can't model keeps the whole chain (sort and
|
|
4862
|
+
* filter alike) in the array string for client evaluation.
|
|
4863
|
+
*/
|
|
4864
|
+
function resolveSortOuterChain(
|
|
4865
|
+
sortInfo: NonNullable<ReturnType<typeof isSortCall>>,
|
|
4866
|
+
mapSource: ts.Expression,
|
|
4867
|
+
plan: LoopSourcePlan,
|
|
4868
|
+
setArray: SetLoopArray,
|
|
4869
|
+
ctx: TransformContext,
|
|
4870
|
+
isClientOnly: boolean,
|
|
4871
|
+
): void {
|
|
4872
|
+
const innerFilter = isFilterCall(sortInfo.array)
|
|
4873
|
+
const sortExtraction = extractSortComparator(sortInfo.callback, sortInfo.method, ctx)
|
|
4874
|
+
if (isClientOnly || !sortExtraction.result) {
|
|
4875
|
+
refuseOffSubsetCallback('sort', sortInfo.callback, sortExtraction.unsupportedReason, ctx, isClientOnly)
|
|
4876
|
+
// Keep sort (and filter if present) in array string for client evaluation
|
|
4877
|
+
setArray(mapSource)
|
|
4878
|
+
return
|
|
5463
4879
|
}
|
|
5464
|
-
|
|
5465
|
-
|
|
5466
|
-
|
|
5467
|
-
|
|
5468
|
-
|
|
5469
|
-
// Structural net (sound-or-loud, spec/callback-fidelity.md): a callback
|
|
5470
|
-
// body that carries an INLINE JSX literal but produced no loop lowering
|
|
5471
|
-
// must never fall through to the IRExpression scalar path — `ctx.getJS`
|
|
5472
|
-
// strips types, not JSX, so the raw `<li …>` would splice verbatim into
|
|
5473
|
-
// the emitted client bundle as a silent SyntaxError. Any recognizer gap
|
|
5474
|
-
// for a JSX-bearing shape becomes a loud diagnostic here instead of a
|
|
5475
|
-
// leak. (A JSX-helper CALL — `map(t => renderItem(t))` — carries no
|
|
5476
|
-
// inline JSX literal and legitimately stays on the reactive-text path.)
|
|
5477
|
-
const cb = node.arguments[0]
|
|
5478
|
-
const cbBody = cb && (ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) ? cb.body : undefined
|
|
5479
|
-
// Entry-count gate: a more specific refusal already fired for THIS call
|
|
5480
|
-
// (e.g. the flatMap leaf-wiring check) — don't stack the generic message
|
|
5481
|
-
// on top of it. Comparing against the count captured at entry (not
|
|
5482
|
-
// `=== 0`) keeps the net armed when an unrelated diagnostic was recorded
|
|
5483
|
-
// earlier in the file — a warning elsewhere must never silence the leak
|
|
5484
|
-
// guard for this callback.
|
|
5485
|
-
if (cbBody && containsJsxInExpression(cbBody) && ctx.analyzer.errors.length === diagCountAtEntry) {
|
|
5486
|
-
ctx.analyzer.errors.push(
|
|
5487
|
-
createError(
|
|
5488
|
-
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5489
|
-
getSourceLocation(cbBody, ctx.sourceFile, ctx.filePath),
|
|
5490
|
-
{
|
|
5491
|
-
message:
|
|
5492
|
-
`A .${method}() callback that builds JSX in this shape cannot be ` +
|
|
5493
|
-
'compiled — the JSX would leak verbatim into the client bundle. ' +
|
|
5494
|
-
'Recognized bodies: a JSX element/fragment, a ternary or ' +
|
|
5495
|
-
'&& / || / ?? expression, an array literal (flatMap), or a block ' +
|
|
5496
|
-
'body whose return the compiler can lower.',
|
|
5497
|
-
suggestion: {
|
|
5498
|
-
message:
|
|
5499
|
-
'Restructure the callback to return the JSX element directly ' +
|
|
5500
|
-
'(or via a block body with a plain `return`).',
|
|
5501
|
-
},
|
|
5502
|
-
}
|
|
5503
|
-
)
|
|
5504
|
-
)
|
|
5505
|
-
}
|
|
5506
|
-
return null
|
|
4880
|
+
plan.sortComparator = sortExtraction.result
|
|
4881
|
+
if (!innerFilter) {
|
|
4882
|
+
// Simple sort().map()
|
|
4883
|
+
setArray(sortInfo.array)
|
|
4884
|
+
return
|
|
5507
4885
|
}
|
|
5508
|
-
|
|
5509
|
-
|
|
5510
|
-
|
|
5511
|
-
if (
|
|
5512
|
-
|
|
4886
|
+
// filter().sort().map() pattern
|
|
4887
|
+
plan.chainOrder = 'filter-sort'
|
|
4888
|
+
const filterExtraction = extractFilterPredicate(innerFilter.callback, ctx)
|
|
4889
|
+
if (isClientOnly || !filterExtraction.result) {
|
|
4890
|
+
refuseOffSubsetCallback('filter', innerFilter.callback, filterExtraction.unsupportedReason, ctx, isClientOnly)
|
|
4891
|
+
// Keep entire chain in array for client evaluation
|
|
4892
|
+
setArray(mapSource)
|
|
4893
|
+
plan.sortComparator = undefined
|
|
4894
|
+
plan.chainOrder = undefined
|
|
4895
|
+
return
|
|
5513
4896
|
}
|
|
4897
|
+
setArray(innerFilter.array)
|
|
4898
|
+
plan.filterPredicate = filterExtraction.result
|
|
4899
|
+
}
|
|
5514
4900
|
|
|
5515
|
-
|
|
5516
|
-
|
|
5517
|
-
|
|
5518
|
-
|
|
5519
|
-
|
|
5520
|
-
|
|
5521
|
-
|
|
5522
|
-
|
|
5523
|
-
|
|
5524
|
-
|
|
5525
|
-
|
|
5526
|
-
|
|
5527
|
-
|
|
5528
|
-
|
|
5529
|
-
|
|
5530
|
-
|
|
5531
|
-
|
|
5532
|
-
|
|
5533
|
-
|
|
5534
|
-
|
|
5535
|
-
// gate. See `IRElement.keyAttr` / `applyLoopKeyAttr`'s docstrings.
|
|
5536
|
-
if (key !== null) {
|
|
5537
|
-
const resolvedKeyAttrName = keyAttrName(depth)
|
|
5538
|
-
if (bodyIsItemConditional) {
|
|
5539
|
-
applyLoopKeyAttr(itemConditional!, resolvedKeyAttrName, key)
|
|
5540
|
-
} else if (children.length > 0) {
|
|
5541
|
-
applyLoopKeyAttr(children[0], resolvedKeyAttrName, key)
|
|
5542
|
-
}
|
|
4901
|
+
/**
|
|
4902
|
+
* Outermost call is a filter: `filter().map()` or `sort().filter().map()`.
|
|
4903
|
+
* An off-subset predicate keeps the whole chain in the array string; an
|
|
4904
|
+
* off-subset INNER sort keeps only the sort there and still lifts the filter.
|
|
4905
|
+
*/
|
|
4906
|
+
function resolveFilterOuterChain(
|
|
4907
|
+
filterInfo: NonNullable<ReturnType<typeof isFilterCall>>,
|
|
4908
|
+
mapSource: ts.Expression,
|
|
4909
|
+
plan: LoopSourcePlan,
|
|
4910
|
+
setArray: SetLoopArray,
|
|
4911
|
+
ctx: TransformContext,
|
|
4912
|
+
isClientOnly: boolean,
|
|
4913
|
+
): void {
|
|
4914
|
+
const innerSort = isSortCall(filterInfo.array)
|
|
4915
|
+
const filterExtraction = extractFilterPredicate(filterInfo.callback, ctx)
|
|
4916
|
+
if (isClientOnly || !filterExtraction.result) {
|
|
4917
|
+
refuseOffSubsetCallback('filter', filterInfo.callback, filterExtraction.unsupportedReason, ctx, isClientOnly)
|
|
4918
|
+
// Keep filter (and sort if present) in array for client evaluation
|
|
4919
|
+
setArray(mapSource)
|
|
4920
|
+
return
|
|
5543
4921
|
}
|
|
5544
|
-
|
|
5545
|
-
|
|
5546
|
-
|
|
5547
|
-
|
|
5548
|
-
|
|
5549
|
-
|
|
5550
|
-
|
|
5551
|
-
|
|
5552
|
-
? new Set(preamble.declaredNames)
|
|
5553
|
-
: undefined
|
|
5554
|
-
if (key && declaredNameSet) {
|
|
5555
|
-
const keyRefs = extractFreeIdentifiersFromText(key)
|
|
5556
|
-
const usesLocal = [...keyRefs].some((r) => declaredNameSet.has(r))
|
|
5557
|
-
if (usesLocal) {
|
|
5558
|
-
ctx.analyzer.errors.push(
|
|
5559
|
-
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(node, ctx.sourceFile, ctx.filePath), {
|
|
5560
|
-
message:
|
|
5561
|
-
'A .map() loop key must be derivable from the loop item — it is ' +
|
|
5562
|
-
'evaluated before the callback body runs, so it cannot reference a ' +
|
|
5563
|
-
'value computed in the callback preamble.',
|
|
5564
|
-
suggestion: {
|
|
5565
|
-
message: 'Derive the key directly from the loop item (e.g. key={item.id}).',
|
|
5566
|
-
},
|
|
5567
|
-
})
|
|
5568
|
-
)
|
|
5569
|
-
}
|
|
4922
|
+
plan.filterPredicate = filterExtraction.result
|
|
4923
|
+
if (!innerSort) {
|
|
4924
|
+
// Simple filter().map(). `setArray` (not a bare `array =` assignment) so
|
|
4925
|
+
// `templateArray` carries the `_p.`-rewritten form — the module-scope
|
|
4926
|
+
// `template:` lambda can't see init's destructured prop locals, and a
|
|
4927
|
+
// bare destructured name there threw `ReferenceError` at runtime (#2222).
|
|
4928
|
+
setArray(filterInfo.array)
|
|
4929
|
+
return
|
|
5570
4930
|
}
|
|
4931
|
+
// sort().filter().map() pattern
|
|
4932
|
+
plan.chainOrder = 'sort-filter'
|
|
4933
|
+
const sortExtraction = extractSortComparator(innerSort.callback, innerSort.method, ctx)
|
|
4934
|
+
if (isClientOnly || !sortExtraction.result) {
|
|
4935
|
+
refuseOffSubsetCallback('sort', innerSort.callback, sortExtraction.unsupportedReason, ctx, isClientOnly)
|
|
4936
|
+
// Keep sort in array for client evaluation, but keep filter extracted
|
|
4937
|
+
setArray(filterInfo.array)
|
|
4938
|
+
return
|
|
4939
|
+
}
|
|
4940
|
+
plan.sortComparator = sortExtraction.result
|
|
4941
|
+
setArray(innerSort.array)
|
|
4942
|
+
}
|
|
5571
4943
|
|
|
5572
|
-
|
|
5573
|
-
|
|
5574
|
-
|
|
5575
|
-
|
|
5576
|
-
|
|
5577
|
-
|
|
4944
|
+
/**
|
|
4945
|
+
* Decision 1 — recognise the receiver of `.map()` and decide what the loop
|
|
4946
|
+
* iterates. Chaining patterns on the map source:
|
|
4947
|
+
*
|
|
4948
|
+
* 1. `sort().map()` / `toSorted().map()`
|
|
4949
|
+
* 2. `filter().map()`
|
|
4950
|
+
* 3. `filter().sort().map()` (outermost = sort, inner = filter)
|
|
4951
|
+
* 4. `sort().filter().map()` (outermost = filter, inner = sort)
|
|
4952
|
+
* 5. `entries().map()` / `keys().map()` / `values().map()`, and the static
|
|
4953
|
+
* `Object.entries(x).map()` family
|
|
4954
|
+
*
|
|
4955
|
+
* Every branch binds the array through `setArray` so `templateArray`
|
|
4956
|
+
* carries the `_p.`-rewritten form (#2222): the plain `.map()` fallback is
|
|
4957
|
+
* the most common loop shape and was the primary repro for the
|
|
4958
|
+
* bare-destructured-name ReferenceError.
|
|
4959
|
+
*
|
|
4960
|
+
* @internal exported for unit tests
|
|
4961
|
+
*/
|
|
4962
|
+
export function resolveLoopSource(
|
|
4963
|
+
node: ts.CallExpression,
|
|
4964
|
+
ctx: TransformContext,
|
|
4965
|
+
isClientOnly: boolean,
|
|
4966
|
+
): LoopSourcePlan {
|
|
4967
|
+
const propAccess = node.expression as ts.PropertyAccessExpression
|
|
4968
|
+
const mapSource = propAccess.expression
|
|
4969
|
+
const iteration = stripIteratorWrapper(mapSource)
|
|
4970
|
+
const plan: LoopSourcePlan = {
|
|
4971
|
+
array: '',
|
|
4972
|
+
templateArray: undefined,
|
|
4973
|
+
arrayExpr: mapSource,
|
|
4974
|
+
filterPredicate: undefined,
|
|
4975
|
+
sortComparator: undefined,
|
|
4976
|
+
chainOrder: undefined,
|
|
4977
|
+
iterationShape: iteration.iterationShape,
|
|
4978
|
+
objectIteration: iteration.objectIteration,
|
|
4979
|
+
}
|
|
4980
|
+
const setArray: SetLoopArray = (expr) => {
|
|
4981
|
+
plan.array = ctx.getJS(expr)
|
|
4982
|
+
plan.templateArray = rewriteBarePropRefs(plan.array, expr, ctx)
|
|
4983
|
+
plan.arrayExpr = expr
|
|
4984
|
+
}
|
|
4985
|
+
|
|
4986
|
+
const filterInfo = isFilterCall(iteration.chainSource)
|
|
4987
|
+
const sortInfo = isSortCall(iteration.chainSource)
|
|
4988
|
+
if (sortInfo) {
|
|
4989
|
+
resolveSortOuterChain(sortInfo, mapSource, plan, setArray, ctx, isClientOnly)
|
|
4990
|
+
} else if (filterInfo) {
|
|
4991
|
+
resolveFilterOuterChain(filterInfo, mapSource, plan, setArray, ctx, isClientOnly)
|
|
4992
|
+
} else {
|
|
4993
|
+
setArray(iteration.chainSource)
|
|
5578
4994
|
}
|
|
4995
|
+
return plan
|
|
4996
|
+
}
|
|
5579
4997
|
|
|
5580
|
-
|
|
5581
|
-
|
|
5582
|
-
|
|
5583
|
-
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5588
|
-
|
|
5589
|
-
|
|
4998
|
+
/** The names one loop row binds, read off the callback's parameter list. */
|
|
4999
|
+
export interface LoopRowParams {
|
|
5000
|
+
param: string
|
|
5001
|
+
paramType: string | undefined
|
|
5002
|
+
index: string | null
|
|
5003
|
+
indexType: string | undefined
|
|
5004
|
+
paramBindings: LoopParamBinding[] | undefined
|
|
5005
|
+
/** Node whose checker type is the scalar item-type evidence (`IRLoop.itemType`). */
|
|
5006
|
+
itemTypeNode: ts.Node | undefined
|
|
5007
|
+
}
|
|
5008
|
+
|
|
5009
|
+
/**
|
|
5010
|
+
* `.entries()` synthesises `[index, value]` — when the callback destructures
|
|
5011
|
+
* exactly two array elements, the names go straight into `index` and
|
|
5012
|
+
* `param` so the loop renders with proper bindings and the BF104
|
|
5013
|
+
* destructure-param refusal doesn't fire. `Object.entries(x)` synthesises
|
|
5014
|
+
* the SAME `[key, value]` 2-tuple shape (`index` just holds a string key
|
|
5015
|
+
* instead of a numeric position), so it reuses this exact extraction.
|
|
5016
|
+
* Returns `null` for any other pattern, which falls through to the standard
|
|
5017
|
+
* destructure handling (and BF104 on template adapters).
|
|
5018
|
+
*/
|
|
5019
|
+
function entriesTupleBindings(
|
|
5020
|
+
pattern: ts.ArrayBindingPattern,
|
|
5021
|
+
): { index: string; param: string; itemTypeNode: ts.Node } | null {
|
|
5022
|
+
const elements = pattern.elements.filter(el => !ts.isOmittedExpression(el))
|
|
5023
|
+
if (elements.length !== 2) return null
|
|
5024
|
+
const [first, second] = elements
|
|
5025
|
+
if (!ts.isBindingElement(first) || !ts.isIdentifier(first.name)) return null
|
|
5026
|
+
if (!ts.isBindingElement(second) || !ts.isIdentifier(second.name)) return null
|
|
5027
|
+
return { index: first.name.text, param: second.name.text, itemTypeNode: second.name }
|
|
5028
|
+
}
|
|
5029
|
+
|
|
5030
|
+
/**
|
|
5031
|
+
* Destructured param (`([, cfg]) => ...`, `({ x, y }) => ...`): walk the
|
|
5032
|
+
* binding pattern into per-binding accessor paths so the client JS emitter
|
|
5033
|
+
* can rewrite references to `__bfItem().path` (#951). Rest elements
|
|
5034
|
+
* (`{ a, ...rest }`, `[first, ...tail]`) lower into a residual-object /
|
|
5035
|
+
* `.slice(n)` accessor at each reference. Only computed property keys remain
|
|
5036
|
+
* unsupported — those raise `BF025` and the emitter falls back to the #950
|
|
5037
|
+
* body-entry unwrap.
|
|
5038
|
+
*/
|
|
5039
|
+
function loopParamBindingsOrRefuse(
|
|
5040
|
+
firstParam: ts.ParameterDeclaration,
|
|
5041
|
+
ctx: TransformContext,
|
|
5042
|
+
): LoopParamBinding[] | undefined {
|
|
5043
|
+
const bindingResult = extractLoopParamBindings(firstParam.name)
|
|
5044
|
+
if (bindingResult && !Array.isArray(bindingResult)) {
|
|
5590
5045
|
ctx.analyzer.errors.push(
|
|
5591
|
-
createError(ErrorCodes.
|
|
5592
|
-
|
|
5593
|
-
|
|
5594
|
-
'component: the built elements would reach the component as raw HTML ' +
|
|
5595
|
-
'strings on the client but as JSX elements at SSR (a silent divergence).',
|
|
5596
|
-
suggestion: {
|
|
5597
|
-
message:
|
|
5598
|
-
'Return a plain element root that embeds the array, or move the ' +
|
|
5599
|
-
'building logic inside the component.',
|
|
5600
|
-
},
|
|
5601
|
-
})
|
|
5046
|
+
createError(ErrorCodes.UNSUPPORTED_DESTRUCTURE_REST,
|
|
5047
|
+
getSourceLocation(firstParam, ctx.sourceFile, ctx.filePath),
|
|
5048
|
+
)
|
|
5602
5049
|
)
|
|
5603
|
-
|
|
5604
|
-
// still runs on an errored compile, and the dom-ops backstop invariant
|
|
5605
|
-
// must stay a FUTURE-variant tripwire, not re-fire on shapes Phase 1
|
|
5606
|
-
// already refused loudly.
|
|
5607
|
-
preamble = undefined
|
|
5050
|
+
return undefined
|
|
5608
5051
|
}
|
|
5052
|
+
return Array.isArray(bindingResult) ? bindingResult : undefined
|
|
5053
|
+
}
|
|
5609
5054
|
|
|
5610
|
-
|
|
5611
|
-
|
|
5612
|
-
|
|
5613
|
-
|
|
5614
|
-
|
|
5615
|
-
|
|
5616
|
-
|
|
5617
|
-
|
|
5618
|
-
|
|
5619
|
-
|
|
5620
|
-
|
|
5621
|
-
|
|
5622
|
-
|
|
5623
|
-
|
|
5624
|
-
|
|
5625
|
-
|
|
5626
|
-
|
|
5627
|
-
|
|
5628
|
-
|
|
5629
|
-
|
|
5630
|
-
|
|
5631
|
-
|
|
5632
|
-
|
|
5633
|
-
|
|
5634
|
-
|
|
5055
|
+
/**
|
|
5056
|
+
* Decision 2 — the names a row binds: the item param (and its type text),
|
|
5057
|
+
* the index param, and the destructure accessor paths. An `.entries()`
|
|
5058
|
+
* shape takes its index from the 2-tuple destructure instead of a second
|
|
5059
|
+
* parameter.
|
|
5060
|
+
*
|
|
5061
|
+
* @internal exported for unit tests
|
|
5062
|
+
*/
|
|
5063
|
+
export function resolveLoopRowParams(
|
|
5064
|
+
callback: ts.ArrowFunction,
|
|
5065
|
+
source: Pick<LoopSourcePlan, 'iterationShape' | 'objectIteration'>,
|
|
5066
|
+
ctx: TransformContext,
|
|
5067
|
+
): LoopRowParams {
|
|
5068
|
+
const row: LoopRowParams = {
|
|
5069
|
+
param: 'item',
|
|
5070
|
+
paramType: undefined,
|
|
5071
|
+
index: null,
|
|
5072
|
+
indexType: undefined,
|
|
5073
|
+
paramBindings: undefined,
|
|
5074
|
+
itemTypeNode: undefined,
|
|
5075
|
+
}
|
|
5076
|
+
const isEntriesShape = source.iterationShape === 'entries' || source.objectIteration === 'entries'
|
|
5077
|
+
if (callback.parameters.length > 0) {
|
|
5078
|
+
const firstParam = callback.parameters[0]
|
|
5079
|
+
row.itemTypeNode = firstParam
|
|
5080
|
+
row.param = firstParam.name.getText(ctx.sourceFile)
|
|
5081
|
+
if (firstParam.type) {
|
|
5082
|
+
row.paramType = firstParam.type.getText(ctx.sourceFile)
|
|
5083
|
+
}
|
|
5084
|
+
const tuple = isEntriesShape && ts.isArrayBindingPattern(firstParam.name)
|
|
5085
|
+
? entriesTupleBindings(firstParam.name)
|
|
5086
|
+
: null
|
|
5087
|
+
if (tuple) {
|
|
5088
|
+
// Fully resolved into index + param by the iteration shape — no
|
|
5089
|
+
// paramBindings.
|
|
5090
|
+
row.index = tuple.index
|
|
5091
|
+
row.param = tuple.param
|
|
5092
|
+
row.itemTypeNode = tuple.itemTypeNode
|
|
5093
|
+
} else {
|
|
5094
|
+
row.paramBindings = loopParamBindingsOrRefuse(firstParam, ctx)
|
|
5635
5095
|
}
|
|
5636
5096
|
}
|
|
5097
|
+
if (callback.parameters.length > 1 && !isEntriesShape) {
|
|
5098
|
+
const secondParam = callback.parameters[1]
|
|
5099
|
+
row.index = secondParam.name.getText(ctx.sourceFile)
|
|
5100
|
+
if (secondParam.type) {
|
|
5101
|
+
row.indexType = secondParam.type.getText(ctx.sourceFile)
|
|
5102
|
+
}
|
|
5103
|
+
}
|
|
5104
|
+
return row
|
|
5105
|
+
}
|
|
5637
5106
|
|
|
5638
|
-
|
|
5107
|
+
/** What one `.map()` callback body lowers to. */
|
|
5108
|
+
export interface LoopBodyLowering {
|
|
5109
|
+
children: IRNode[]
|
|
5110
|
+
/**
|
|
5111
|
+
* Structured pre-return statements of a block-body callback (Stage 3 root
|
|
5112
|
+
* cure): JS text + compiled JSX leaves as segments, plus the raw TSX for
|
|
5113
|
+
* JSX-runtime SSR and the declared names (D5 key guard, {out} join).
|
|
5114
|
+
*/
|
|
5115
|
+
preamble: MapCallbackPreamble | undefined
|
|
5116
|
+
flatMapCallback: FlatMapCallback | undefined
|
|
5117
|
+
}
|
|
5639
5118
|
|
|
5640
|
-
|
|
5641
|
-
|
|
5642
|
-
|
|
5643
|
-
|
|
5644
|
-
|
|
5645
|
-
|
|
5646
|
-
|
|
5647
|
-
|
|
5648
|
-
|
|
5649
|
-
|
|
5650
|
-
|
|
5651
|
-
|
|
5652
|
-
|
|
5653
|
-
|
|
5654
|
-
|
|
5655
|
-
|
|
5656
|
-
|
|
5657
|
-
|
|
5658
|
-
|
|
5659
|
-
|
|
5660
|
-
|
|
5661
|
-
|
|
5662
|
-
const
|
|
5119
|
+
/**
|
|
5120
|
+
* Logical control flow (`cond && <X/>`, `a ?? themeLogo()`) as the map
|
|
5121
|
+
* body. This is not a JSX literal, ternary, or block, so without this the
|
|
5122
|
+
* dispatch would leave `children` empty and the whole `.map(...)` would fall
|
|
5123
|
+
* through to the reactive-text path — emitting the callback verbatim. That
|
|
5124
|
+
* left inline JSX uncompiled and module-level JSX helpers undeclared
|
|
5125
|
+
* (ReferenceError at hydration, #1665). Route the logical body through the
|
|
5126
|
+
* shared JSX expression transformer, which lowers it into an IRConditional
|
|
5127
|
+
* and inlines any JSX helper, exactly like the ternary form.
|
|
5128
|
+
*
|
|
5129
|
+
* Scoped deliberately to logical operators that actually render JSX (inline
|
|
5130
|
+
* literal or a tracked helper call): a bare call body (`map(t =>
|
|
5131
|
+
* renderItem(t))`) stays on the existing reactive-text path that #546 owns,
|
|
5132
|
+
* and a scalar logical body (`t.active && t.label`) keeps rendering its
|
|
5133
|
+
* value.
|
|
5134
|
+
*/
|
|
5135
|
+
function transformRenderableLogicalBody(
|
|
5136
|
+
expr: ts.Expression,
|
|
5137
|
+
ctx: TransformContext,
|
|
5138
|
+
isClientOnly: boolean,
|
|
5139
|
+
): IRNode[] {
|
|
5140
|
+
if (!ts.isBinaryExpression(expr)) return []
|
|
5141
|
+
const op = expr.operatorToken.kind
|
|
5142
|
+
if (
|
|
5143
|
+
op !== ts.SyntaxKind.AmpersandAmpersandToken &&
|
|
5144
|
+
op !== ts.SyntaxKind.BarBarToken &&
|
|
5145
|
+
op !== ts.SyntaxKind.QuestionQuestionToken
|
|
5146
|
+
) {
|
|
5147
|
+
return []
|
|
5148
|
+
}
|
|
5149
|
+
if (!containsJsxInExpression(expr) && !callsJsxHelper(expr, ctx)) return []
|
|
5150
|
+
const transformed = transformJsxExpression(expr, ctx, isClientOnly)
|
|
5151
|
+
return transformed ? [transformed] : []
|
|
5152
|
+
}
|
|
5153
|
+
|
|
5154
|
+
/**
|
|
5155
|
+
* An expression-bodied callback (parentheses stripped): a JSX literal, a
|
|
5156
|
+
* ternary (`items.map(item => cond ? <A/> : <B/>)`), a flatMap array
|
|
5157
|
+
* literal (`items.flatMap(item => [<A/>, <B/>])`), or a renderable logical
|
|
5158
|
+
* expression.
|
|
5159
|
+
*/
|
|
5160
|
+
function transformLoopExpressionBody(
|
|
5161
|
+
body: ts.Expression,
|
|
5162
|
+
ctx: TransformContext,
|
|
5163
|
+
isClientOnly: boolean,
|
|
5164
|
+
method: 'map' | 'flatMap',
|
|
5165
|
+
): IRNode[] {
|
|
5166
|
+
let inner = body
|
|
5167
|
+
while (ts.isParenthesizedExpression(inner)) {
|
|
5168
|
+
inner = inner.expression
|
|
5169
|
+
}
|
|
5170
|
+
if (ts.isJsxElement(inner) || ts.isJsxSelfClosingElement(inner) || ts.isJsxFragment(inner)) {
|
|
5171
|
+
const transformed = transformNode(inner, ctx)
|
|
5172
|
+
return transformed ? [transformed] : []
|
|
5173
|
+
}
|
|
5174
|
+
if (ts.isConditionalExpression(inner)) {
|
|
5175
|
+
return [transformConditional(inner, ctx)]
|
|
5176
|
+
}
|
|
5177
|
+
if (method === 'flatMap' && ts.isArrayLiteralExpression(inner)) {
|
|
5178
|
+
return transformArrayLiteralChildren(inner, ctx)
|
|
5179
|
+
}
|
|
5180
|
+
return transformRenderableLogicalBody(inner, ctx, isClientOnly)
|
|
5181
|
+
}
|
|
5182
|
+
|
|
5183
|
+
/**
|
|
5184
|
+
* #2447 — a DSL adapter cannot execute `preamble.segments` (JS text), so it
|
|
5185
|
+
* lowers `declarations` (one per-row local each) and the row markup reads
|
|
5186
|
+
* them as locals. When the preamble isn't fully declarable there is nothing
|
|
5187
|
+
* to lower, and the adapter used to emit the row anyway, reading names it
|
|
5188
|
+
* never assigned: the class rendered empty, on every DSL backend, with no
|
|
5189
|
+
* diagnostic. Refuse loudly instead, with the same `/* @client *\/` escape as
|
|
5190
|
+
* the array-builder and flatMap gates.
|
|
5191
|
+
*/
|
|
5192
|
+
function refuseUndeclarablePreamble(
|
|
5193
|
+
preamble: MapCallbackPreamble,
|
|
5194
|
+
loc: SourceLocation,
|
|
5195
|
+
message: string,
|
|
5196
|
+
ctx: TransformContext,
|
|
5197
|
+
isClientOnly: boolean,
|
|
5198
|
+
): void {
|
|
5199
|
+
if (preamble.declarations) return
|
|
5200
|
+
if (isClientOnly) return
|
|
5201
|
+
if (ctx.analyzer.acceptsCallbackBody?.('map') ?? false) return
|
|
5202
|
+
ctx.analyzer.errors.push(
|
|
5203
|
+
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, loc, {
|
|
5204
|
+
message,
|
|
5205
|
+
suggestion: {
|
|
5206
|
+
message: CLIENT_ONLY_EXPRESSION_SUGGESTION,
|
|
5207
|
+
},
|
|
5208
|
+
})
|
|
5209
|
+
)
|
|
5210
|
+
}
|
|
5211
|
+
|
|
5212
|
+
/**
|
|
5213
|
+
* Multi-return JSX block body (if/else-if chain or a `switch`, including
|
|
5214
|
+
* fallthrough case labels, optionally preceded by a `const`/`let` preamble)
|
|
5215
|
+
* — fold to a nested IRConditional so the loop renders each branch's
|
|
5216
|
+
* compiled template. Tried BEFORE the single-return path: otherwise the
|
|
5217
|
+
* trailing `return <fallback/>` would claim the single-return arm and the
|
|
5218
|
+
* leading `if (...) return <A/>` would leak verbatim into the map preamble
|
|
5219
|
+
* (the silent-verbatim-leak this fixes). Stage 2 of
|
|
5220
|
+
* spec/callback-fidelity.md. A branch-local `const` (inside a branch
|
|
5221
|
+
* block/case) or a statement-level nested loop is not folded
|
|
5222
|
+
* (`extractMultiReturnJsxBranches` returns null) and falls through to the
|
|
5223
|
+
* single-return path.
|
|
5224
|
+
*
|
|
5225
|
+
* The leading const/let preamble is emitted once per iteration, ahead of
|
|
5226
|
+
* the conditional — the same carrier the single-return path uses. A
|
|
5227
|
+
* JS-runtime adapter (and the browser under /* @client *\/) runs it
|
|
5228
|
+
* verbatim. The DSL refusal was narrowed by #2447: it used to refuse EVERY
|
|
5229
|
+
* branch preamble on a DSL target, on the premise that a loop-local can't
|
|
5230
|
+
* be carried into a conditional branch template. That premise stopped
|
|
5231
|
+
* holding once `declarations` lower to a per-row local — the fold emits the
|
|
5232
|
+
* conditional INSIDE the loop body, so a local declared ahead of it is in
|
|
5233
|
+
* scope in both arms (`{{$label := bf_upper .Kind}}{{if .On}}…{{$label}}…
|
|
5234
|
+
* {{else}}…`). What remains is the hazard for a preamble that CANNOT be
|
|
5235
|
+
* declared: nothing lowers, both branches read an unassigned name. So the
|
|
5236
|
+
* refusal keys off the same condition as the single-return gate.
|
|
5237
|
+
*/
|
|
5238
|
+
function lowerMultiReturnLoopBody(
|
|
5239
|
+
body: ts.Block,
|
|
5240
|
+
ctx: TransformContext,
|
|
5241
|
+
isClientOnly: boolean,
|
|
5242
|
+
): Pick<LoopBodyLowering, 'children' | 'preamble'> | null {
|
|
5243
|
+
const multiReturn = extractMultiReturnJsxBranches(body, true)
|
|
5244
|
+
if (!multiReturn || multiReturn.branches.length === 0) return null
|
|
5245
|
+
const loc = getSourceLocation(body, ctx.sourceFile, ctx.filePath)
|
|
5246
|
+
const children = [foldMultiReturnBranches(multiReturn, ctx, loc, ctx.getJS)]
|
|
5247
|
+
const pre = multiReturn.preamble ?? []
|
|
5248
|
+
if (pre.length === 0) return { children, preamble: undefined }
|
|
5249
|
+
const preamble = preambleFromValueStatements(pre, ctx, body.statements)
|
|
5250
|
+
refuseUndeclarablePreamble(
|
|
5251
|
+
preamble,
|
|
5252
|
+
loc,
|
|
5253
|
+
'A .map() callback body with a preamble before its branches cannot be ' +
|
|
5254
|
+
'lowered to a template: the preamble is not a sequence of value ' +
|
|
5255
|
+
'declarations, so this backend has no per-row local to carry into the ' +
|
|
5256
|
+
'branches.',
|
|
5257
|
+
ctx,
|
|
5258
|
+
isClientOnly,
|
|
5259
|
+
)
|
|
5260
|
+
return { children, preamble }
|
|
5261
|
+
}
|
|
5262
|
+
|
|
5263
|
+
/**
|
|
5264
|
+
* #2482 Stage 1a Commit 2 — the preamble-shadow scope window. The STRUCTURED
|
|
5265
|
+
* preamble (`MapCallbackPreamble`, built by `preambleFromValueStatements` /
|
|
5266
|
+
* `buildPreambleSegments` inside `run`) isn't known until well after the
|
|
5267
|
+
* return expression is transformed. But `transformNode(returnExpr, ctx)`
|
|
5268
|
+
* walks the return expression's own child expressions RIGHT THEN, so a
|
|
5269
|
+
* preamble-declared local shadowing an outer const/prop must already be
|
|
5270
|
+
* bound in `ctx.scope`, or `tryResolveTemplateSpanFromConst` /
|
|
5271
|
+
* `tryResolveIdentifierAsTemplateLiteral` / `rewriteBarePropRefs` bake the
|
|
5272
|
+
* OUTER value into every row instead of leaving the row-local unresolved
|
|
5273
|
+
* (#2222-family, the const/prop-shadow bug class).
|
|
5274
|
+
*
|
|
5275
|
+
* Fix: a lightweight declared-names-only pre-scan — the exact same
|
|
5276
|
+
* "statements before the return" shape the preamble collectors scan —
|
|
5277
|
+
* re-enters the row's `BindingScope` frame (off `savedScope`, the pre-loop
|
|
5278
|
+
* parent, so this REPLACES the param/index-only frame rather than stacking
|
|
5279
|
+
* a second one) with the preamble included, for the duration of `run`.
|
|
5280
|
+
* Restored to the preamble-less row scope right after: everything past this
|
|
5281
|
+
* window (the flatMap fallbacks and the rest of the loop lowering) must keep
|
|
5282
|
+
* observing EXACTLY the old (Commit 1) membership, since slotId-allocation
|
|
5283
|
+
* classifiers there read `ctx.scope.valueBoundNames()`, which never included
|
|
5284
|
+
* preamble names to begin with — only shadow guards need the widened view,
|
|
5285
|
+
* and only for this window.
|
|
5286
|
+
*/
|
|
5287
|
+
function withPreambleRowScope<T>(
|
|
5288
|
+
ctx: TransformContext,
|
|
5289
|
+
savedScope: BindingScope,
|
|
5290
|
+
row: LoopRowParams,
|
|
5291
|
+
body: ts.Block,
|
|
5292
|
+
returnStmt: ts.ReturnStatement,
|
|
5293
|
+
run: () => T,
|
|
5294
|
+
): T {
|
|
5295
|
+
const preambleNames = new Set<string>()
|
|
5296
|
+
for (const stmt of body.statements) {
|
|
5297
|
+
if (stmt === returnStmt) break
|
|
5298
|
+
collectPreambleDeclaredNames(stmt, preambleNames)
|
|
5299
|
+
}
|
|
5300
|
+
if (preambleNames.size === 0) return run()
|
|
5301
|
+
const rowScopeBeforePreamble = ctx.scope
|
|
5302
|
+
ctx.scope = savedScope.enterLoopRow({
|
|
5303
|
+
param: row.param,
|
|
5304
|
+
index: row.index,
|
|
5305
|
+
paramBindings: row.paramBindings,
|
|
5306
|
+
preamble: { declaredNames: [...preambleNames] },
|
|
5307
|
+
})
|
|
5308
|
+
try {
|
|
5309
|
+
return run()
|
|
5310
|
+
} finally {
|
|
5311
|
+
// Window closed — restore the preamble-less row scope.
|
|
5312
|
+
ctx.scope = rowScopeBeforePreamble
|
|
5313
|
+
}
|
|
5314
|
+
}
|
|
5315
|
+
|
|
5316
|
+
/**
|
|
5317
|
+
* Stage 3 of spec/callback-fidelity.md — the first statement before the
|
|
5318
|
+
* `return` that *constructs* JSX (the classic `const out = []; for (const c
|
|
5319
|
+
* of it.cells) out.push(<td>{c}</td>); return <tr>{out}</tr>` array-builder).
|
|
5320
|
+
* Scans only statements the preamble collector would reach — those *before*
|
|
5321
|
+
* `returnStmt` (it `break`s at the return). JSX in unreachable post-return
|
|
5322
|
+
* dead code is never spliced into the preamble, so it is not part of the
|
|
5323
|
+
* leak and must not trip the refusal.
|
|
5324
|
+
*/
|
|
5325
|
+
function findJsxBuildingPreambleStatement(
|
|
5326
|
+
body: ts.Block,
|
|
5327
|
+
returnStmt: ts.ReturnStatement,
|
|
5328
|
+
): ts.Statement | undefined {
|
|
5329
|
+
for (const stmt of body.statements) {
|
|
5330
|
+
if (stmt === returnStmt) break
|
|
5331
|
+
if (containsJsxInExpression(stmt)) return stmt
|
|
5332
|
+
}
|
|
5333
|
+
return undefined
|
|
5334
|
+
}
|
|
5335
|
+
|
|
5336
|
+
/**
|
|
5337
|
+
* Stage 3 / D4 (spec/callback-fidelity.md) — a `.map()` body that builds
|
|
5338
|
+
* JSX in a statement before its `return`. The preamble collector
|
|
5339
|
+
* reconstructs each statement with `ctx.getJS`, which strips *types* but not
|
|
5340
|
+
* JSX, so the raw `<td>{c}</td>` would splice verbatim into the emitted
|
|
5341
|
+
* client bundle — invalid JS, a silent syntax-error leak with no diagnostic.
|
|
5342
|
+
*
|
|
5343
|
+
* A JS-runtime adapter runs the callback body verbatim — each JSX leaf
|
|
5344
|
+
* lowers to a template-literal HTML string, the imperative control flow runs
|
|
5345
|
+
* as-is, and the element-array child ({out}) is joined into the row. A DSL
|
|
5346
|
+
* template runtime can't do this, so it refuses with the /* @client *\/
|
|
5347
|
+
* escape (which renders the loop client-only, where the browser — always JS
|
|
5348
|
+
* — runs the same body). Mirrors the const-preamble gate and the Stage-1
|
|
5349
|
+
* filter/sort sites (all consult `acceptsCallbackBody`).
|
|
5350
|
+
*/
|
|
5351
|
+
function lowerJsxBuildingPreamble(
|
|
5352
|
+
body: ts.Block,
|
|
5353
|
+
returnStmt: ts.ReturnStatement,
|
|
5354
|
+
jsxPreambleStmt: ts.Statement,
|
|
5355
|
+
children: IRNode[],
|
|
5356
|
+
ctx: TransformContext,
|
|
5357
|
+
isClientOnly: boolean,
|
|
5358
|
+
): MapCallbackPreamble | undefined {
|
|
5359
|
+
const jsRuntime = isClientOnly || (ctx.analyzer.acceptsCallbackBody?.('map') ?? false)
|
|
5360
|
+
if (children.length === 0) {
|
|
5361
|
+
// The return shape produced no loop children (a bare identifier `return
|
|
5362
|
+
// out`, a ternary, any non-element return): there is no single template
|
|
5363
|
+
// root to host the built elements, so the loop IR can't exist and the
|
|
5364
|
+
// fallback would splice the raw callback — JSX included — verbatim into
|
|
5365
|
+
// an expression anchor (a silent leak on EVERY tier, /* @client */
|
|
5366
|
+
// included). Refuse loudly with restructuring guidance; the return-shape
|
|
5367
|
+
// holes pinned by map-body-no-silent-divergence.test.ts close here.
|
|
5368
|
+
ctx.analyzer.errors.push(
|
|
5369
|
+
createError(
|
|
5370
|
+
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5371
|
+
getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath),
|
|
5372
|
+
{
|
|
5373
|
+
message:
|
|
5374
|
+
'A .map() callback that builds JSX in a statement before its ' +
|
|
5375
|
+
'`return` must return a single JSX element that embeds the ' +
|
|
5376
|
+
'built array — this return shape has no element root to host it.',
|
|
5377
|
+
suggestion: {
|
|
5378
|
+
message:
|
|
5379
|
+
'Wrap the result in one element root, e.g. `return <tr key={item.id}>{out}</tr>`.',
|
|
5380
|
+
},
|
|
5381
|
+
}
|
|
5382
|
+
)
|
|
5383
|
+
)
|
|
5384
|
+
return undefined
|
|
5385
|
+
}
|
|
5386
|
+
if (!jsRuntime) {
|
|
5387
|
+
ctx.analyzer.errors.push(
|
|
5388
|
+
createError(
|
|
5389
|
+
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5390
|
+
getSourceLocation(jsxPreambleStmt, ctx.sourceFile, ctx.filePath),
|
|
5391
|
+
{
|
|
5392
|
+
message:
|
|
5393
|
+
'A .map() callback that builds JSX in a statement before its ' +
|
|
5394
|
+
'`return` (for example pushing elements into an array in a loop) ' +
|
|
5395
|
+
'cannot be lowered to a template on this backend.',
|
|
5396
|
+
suggestion: {
|
|
5397
|
+
message: CLIENT_ONLY_LOOP_SUGGESTION,
|
|
5398
|
+
},
|
|
5399
|
+
}
|
|
5400
|
+
)
|
|
5401
|
+
)
|
|
5402
|
+
return undefined
|
|
5403
|
+
}
|
|
5404
|
+
const collected = buildPreambleSegments(body.statements, returnStmt, ctx)
|
|
5405
|
+
if (collected.refusalNode) {
|
|
5406
|
+
// A leaf carries wiring the verbatim path can't render (event handler,
|
|
5407
|
+
// component, nested loop, reactive slot, spread), or sits inside a
|
|
5408
|
+
// template literal (a segment boundary there would split the literal's
|
|
5409
|
+
// lexical state for downstream text transforms). Refuse loudly (D-E)
|
|
5410
|
+
// rather than emit a silently-degraded node.
|
|
5411
|
+
ctx.analyzer.errors.push(
|
|
5412
|
+
createError(
|
|
5413
|
+
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5414
|
+
getSourceLocation(collected.refusalNode, ctx.sourceFile, ctx.filePath),
|
|
5415
|
+
{
|
|
5416
|
+
message:
|
|
5417
|
+
'A JSX element built in a .map() callback preamble cannot carry ' +
|
|
5418
|
+
'event handlers, components, nested loops, or reactive expressions, ' +
|
|
5419
|
+
'and cannot sit inside a template literal — the verbatim render ' +
|
|
5420
|
+
'path builds it once, with no reactive wiring.',
|
|
5421
|
+
suggestion: {
|
|
5422
|
+
message:
|
|
5423
|
+
'Return the element directly (not through a preamble variable), ' +
|
|
5424
|
+
'or add /* @client */ to render the loop on the client only.',
|
|
5425
|
+
},
|
|
5426
|
+
}
|
|
5427
|
+
)
|
|
5428
|
+
)
|
|
5429
|
+
return undefined
|
|
5430
|
+
}
|
|
5431
|
+
return collected.preamble
|
|
5432
|
+
}
|
|
5433
|
+
|
|
5434
|
+
/**
|
|
5435
|
+
* A value-only preamble (`(item) => { const label = ...; return <div>{label}
|
|
5436
|
+
* </div> }`): every statement before the `return`, carried as value
|
|
5437
|
+
* declarations, with the #2447 DSL gate.
|
|
5438
|
+
*/
|
|
5439
|
+
function lowerValuePreamble(
|
|
5440
|
+
body: ts.Block,
|
|
5441
|
+
returnStmt: ts.ReturnStatement,
|
|
5442
|
+
ctx: TransformContext,
|
|
5443
|
+
isClientOnly: boolean,
|
|
5444
|
+
): MapCallbackPreamble | undefined {
|
|
5445
|
+
const valueStmts: ts.Statement[] = []
|
|
5446
|
+
for (const stmt of body.statements) {
|
|
5447
|
+
if (stmt === returnStmt) break
|
|
5448
|
+
valueStmts.push(stmt)
|
|
5449
|
+
}
|
|
5450
|
+
if (valueStmts.length === 0) return undefined
|
|
5451
|
+
const preamble = preambleFromValueStatements(valueStmts, ctx, body.statements)
|
|
5452
|
+
refuseUndeclarablePreamble(
|
|
5453
|
+
preamble,
|
|
5454
|
+
getSourceLocation(body, ctx.sourceFile, ctx.filePath),
|
|
5455
|
+
'A .map() callback preamble that is not a sequence of value ' +
|
|
5456
|
+
'declarations cannot be lowered to a template: this backend can ' +
|
|
5457
|
+
'declare a per-row local, but cannot run arbitrary statements per row.',
|
|
5458
|
+
ctx,
|
|
5459
|
+
isClientOnly,
|
|
5460
|
+
)
|
|
5461
|
+
return preamble
|
|
5462
|
+
}
|
|
5463
|
+
|
|
5464
|
+
/**
|
|
5465
|
+
* Single-return block body: the returned JSX element (parentheses stripped)
|
|
5466
|
+
* becomes the row, and the statements before the `return` become the
|
|
5467
|
+
* preamble — the JSX-building carrier when one of them constructs JSX, the
|
|
5468
|
+
* value-declaration carrier otherwise.
|
|
5469
|
+
*/
|
|
5470
|
+
function lowerSingleReturnLoopBody(
|
|
5471
|
+
body: ts.Block,
|
|
5472
|
+
returnStmt: ts.ReturnStatement,
|
|
5473
|
+
ctx: TransformContext,
|
|
5474
|
+
isClientOnly: boolean,
|
|
5475
|
+
): Pick<LoopBodyLowering, 'children' | 'preamble'> {
|
|
5476
|
+
let returnExpr = returnStmt.expression as ts.Expression
|
|
5477
|
+
while (ts.isParenthesizedExpression(returnExpr)) {
|
|
5478
|
+
returnExpr = returnExpr.expression
|
|
5479
|
+
}
|
|
5480
|
+
let children: IRNode[] = []
|
|
5481
|
+
if (ts.isJsxElement(returnExpr) || ts.isJsxSelfClosingElement(returnExpr) || ts.isJsxFragment(returnExpr)) {
|
|
5482
|
+
const transformed = transformNode(returnExpr, ctx)
|
|
5483
|
+
if (transformed) {
|
|
5484
|
+
children = [transformed]
|
|
5485
|
+
}
|
|
5486
|
+
}
|
|
5487
|
+
const jsxPreambleStmt = findJsxBuildingPreambleStatement(body, returnStmt)
|
|
5488
|
+
const preamble = jsxPreambleStmt
|
|
5489
|
+
? lowerJsxBuildingPreamble(body, returnStmt, jsxPreambleStmt, children, ctx, isClientOnly)
|
|
5490
|
+
: lowerValuePreamble(body, returnStmt, ctx, isClientOnly)
|
|
5491
|
+
return { children, preamble }
|
|
5492
|
+
}
|
|
5493
|
+
|
|
5494
|
+
/**
|
|
5495
|
+
* A block-bodied callback: the multi-return fold first, then the
|
|
5496
|
+
* single-return path (under the preamble-shadow scope window), then the
|
|
5497
|
+
* flatMap block fallback. A pure single-`return <call>` projection is NOT
|
|
5498
|
+
* taken by that fallback — it lowers to neutral IR in
|
|
5499
|
+
* `applyFlatMapFallbacks` (nested-loop child), which DSL adapters
|
|
5500
|
+
* templatize.
|
|
5501
|
+
*/
|
|
5502
|
+
function transformLoopBlockBody(
|
|
5503
|
+
body: ts.Block,
|
|
5504
|
+
callback: ts.ArrowFunction,
|
|
5505
|
+
row: LoopRowParams,
|
|
5506
|
+
savedScope: BindingScope,
|
|
5507
|
+
ctx: TransformContext,
|
|
5508
|
+
isClientOnly: boolean,
|
|
5509
|
+
method: 'map' | 'flatMap',
|
|
5510
|
+
): LoopBodyLowering {
|
|
5511
|
+
const out: LoopBodyLowering = { children: [], preamble: undefined, flatMapCallback: undefined }
|
|
5512
|
+
const multi = method !== 'flatMap' ? lowerMultiReturnLoopBody(body, ctx, isClientOnly) : null
|
|
5513
|
+
if (multi) {
|
|
5514
|
+
out.children = multi.children
|
|
5515
|
+
out.preamble = multi.preamble
|
|
5516
|
+
}
|
|
5517
|
+
const returnStmt = out.children.length === 0
|
|
5518
|
+
? body.statements.find(
|
|
5519
|
+
(s): s is ts.ReturnStatement => ts.isReturnStatement(s) && s.expression != null
|
|
5520
|
+
)
|
|
5521
|
+
: undefined
|
|
5522
|
+
if (returnStmt) {
|
|
5523
|
+
const single = withPreambleRowScope(ctx, savedScope, row, body, returnStmt, () =>
|
|
5524
|
+
lowerSingleReturnLoopBody(body, returnStmt, ctx, isClientOnly),
|
|
5525
|
+
)
|
|
5526
|
+
out.children = single.children
|
|
5527
|
+
out.preamble = single.preamble
|
|
5528
|
+
}
|
|
5529
|
+
// flatMap block body fallback: compile JSX inline when children couldn't
|
|
5530
|
+
// be extracted via the standard single-return path.
|
|
5531
|
+
if (method === 'flatMap' && out.children.length === 0 && !flatMapProjectionCall(body)) {
|
|
5532
|
+
out.flatMapCallback = buildFlatMapCallback(callback, body, ctx)
|
|
5533
|
+
}
|
|
5534
|
+
return out
|
|
5535
|
+
}
|
|
5536
|
+
|
|
5537
|
+
/**
|
|
5538
|
+
* The flatMap-only fallbacks, in order:
|
|
5539
|
+
*
|
|
5540
|
+
* - PROJECTION body — the canonical `flatMap(it => it.tags.map(tag => <li
|
|
5541
|
+
* key={...}/>))`, as an expression body or a single-`return` block. This is
|
|
5542
|
+
* a pure nested-loop projection, so it lowers to NEUTRAL IR — an inner
|
|
5543
|
+
* IRLoop as the loop's only child — which every SSR adapter can templatize
|
|
5544
|
+
* (nested `{{range}}` on DSL backends), per spec/callback-fidelity.md's
|
|
5545
|
+
* fidelity table ("single expr" row) and the array-literal flatMap
|
|
5546
|
+
* precedent. Only bodies carrying STATEMENTS (early returns, consts) fall
|
|
5547
|
+
* through to the segments carrier and its DSL gate. The client reconciles
|
|
5548
|
+
* the flattened leaves through the descriptor mapArray path, synthesized
|
|
5549
|
+
* from this same neutral IR (`renderFlatMapProjectionClientBody`); the
|
|
5550
|
+
* leaf `key` renders as the usual nested-loop `data-key-1` on both the SSR
|
|
5551
|
+
* and client string sides, and the flattened reconciliation identity
|
|
5552
|
+
* (`data-key`) is stamped by mapArray from the inner loop's `key` field.
|
|
5553
|
+
* - EXPRESSION body containing JSX in a non-projection shape — e.g. a call
|
|
5554
|
+
* wrapping JSX. The block-body form already rides the structured-segments
|
|
5555
|
+
* carrier; an unbraced body is the same shape minus the braces, so it goes
|
|
5556
|
+
* through the same door. Without this the dispatch falls to the
|
|
5557
|
+
* IRExpression scalar path, which splices the raw callback — JSX included
|
|
5558
|
+
* — verbatim into the client bundle: a silent SyntaxError that kills the
|
|
5559
|
+
* whole component's hydration.
|
|
5560
|
+
* - A flatMapCallback carries the WHOLE body (statements included) as
|
|
5561
|
+
* structured segments — the generic statements-before-return `preamble`
|
|
5562
|
+
* the block-body path may have collected is a duplicate carrier. Worse, it
|
|
5563
|
+
* isn't one: spliced into a mapArray renderItem it re-runs the body's
|
|
5564
|
+
* control flow against the wrong binding shape (the audited `if
|
|
5565
|
+
* (t().tags.length > maxTags) return [];` renderItem residue). The
|
|
5566
|
+
* segments carrier is the single door; the shadow copy is dropped.
|
|
5567
|
+
* - Adapter gate (spec/callback-fidelity.md fidelity model): a flatMap body
|
|
5568
|
+
* carried as structured segments runs verbatim on a JS runtime; a DSL
|
|
5569
|
+
* template runtime cannot execute it at SSR — pre-gate, e.g. the Go
|
|
5570
|
+
* adapter emitted `{{range …}}{{end}}` with an EMPTY body (silent
|
|
5571
|
+
* divergence, the exact failure class the sound-or-loud invariant
|
|
5572
|
+
* forbids). Refuse loudly with the /* @client *\/ escape, mirroring the
|
|
5573
|
+
* const-preamble and array-builder gates.
|
|
5574
|
+
*/
|
|
5575
|
+
function applyFlatMapFallbacks(
|
|
5576
|
+
out: LoopBodyLowering,
|
|
5577
|
+
callback: ts.ArrowFunction,
|
|
5578
|
+
ctx: TransformContext,
|
|
5579
|
+
isClientOnly: boolean,
|
|
5580
|
+
method: 'map' | 'flatMap',
|
|
5581
|
+
): void {
|
|
5582
|
+
if (method !== 'flatMap') return
|
|
5583
|
+
const body = callback.body
|
|
5584
|
+
if (out.children.length === 0 && !out.flatMapCallback) {
|
|
5585
|
+
const projection = flatMapProjectionCall(body)
|
|
5586
|
+
if (projection) {
|
|
5587
|
+
const transformed = transformJsxExpression(projection, ctx, isClientOnly)
|
|
5588
|
+
if (transformed && transformed.type === 'loop') {
|
|
5589
|
+
out.children = [transformed]
|
|
5590
|
+
}
|
|
5591
|
+
}
|
|
5592
|
+
}
|
|
5593
|
+
if (out.children.length === 0 && !out.flatMapCallback && !ts.isBlock(body)) {
|
|
5594
|
+
out.flatMapCallback = buildFlatMapCallback(callback, body, ctx)
|
|
5595
|
+
}
|
|
5596
|
+
if (!out.flatMapCallback) return
|
|
5597
|
+
out.preamble = undefined
|
|
5598
|
+
if (isClientOnly || (ctx.analyzer.acceptsCallbackBody?.('flatMap') ?? false)) return
|
|
5599
|
+
ctx.analyzer.errors.push(
|
|
5600
|
+
createError(
|
|
5601
|
+
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5602
|
+
getSourceLocation(body, ctx.sourceFile, ctx.filePath),
|
|
5603
|
+
{
|
|
5604
|
+
message:
|
|
5605
|
+
'A .flatMap() callback body with statements or a nested projection ' +
|
|
5606
|
+
'cannot be lowered to a template on this backend.',
|
|
5607
|
+
suggestion: {
|
|
5608
|
+
message: CLIENT_ONLY_LOOP_SUGGESTION,
|
|
5609
|
+
},
|
|
5610
|
+
}
|
|
5611
|
+
)
|
|
5612
|
+
)
|
|
5613
|
+
}
|
|
5614
|
+
|
|
5615
|
+
/**
|
|
5616
|
+
* Run `fn` under the row's `BindingScope` frame. Registers the loop-bound
|
|
5617
|
+
* names so expressions referencing them get a slotId (#2482 Stage 1a): for
|
|
5618
|
+
* destructured patterns the frame binds the individual binding names —
|
|
5619
|
+
* `\b${param}\b` never matches a bare name like `cfg` when `param` is
|
|
5620
|
+
* `[, cfg]`, which would otherwise leave reactive-expression detection
|
|
5621
|
+
* silently broken for destructured callbacks. `fn` receives the pre-loop
|
|
5622
|
+
* parent scope (the frame the preamble-shadow window re-enters from). The
|
|
5623
|
+
* parent is restored by reference, not deleted-from, so a nested loop
|
|
5624
|
+
* reusing a param name can never corrupt the outer scope — the BindingScope
|
|
5625
|
+
* twin of the old "unregister loop params" delete block, which can never
|
|
5626
|
+
* miss an entry the add-site added.
|
|
5627
|
+
*
|
|
5628
|
+
* @internal exported for unit tests
|
|
5629
|
+
*/
|
|
5630
|
+
export function withLoopRowScope<T>(
|
|
5631
|
+
ctx: TransformContext,
|
|
5632
|
+
row: Pick<LoopRowParams, 'param' | 'index' | 'paramBindings'>,
|
|
5633
|
+
fn: (savedScope: BindingScope) => T,
|
|
5634
|
+
): T {
|
|
5635
|
+
const savedScope = ctx.scope
|
|
5636
|
+
ctx.scope = ctx.scope.enterLoopRow({ param: row.param, index: row.index, paramBindings: row.paramBindings })
|
|
5637
|
+
ctx.loopDepth++
|
|
5638
|
+
try {
|
|
5639
|
+
return fn(savedScope)
|
|
5640
|
+
} finally {
|
|
5641
|
+
ctx.scope = savedScope
|
|
5642
|
+
ctx.loopDepth--
|
|
5643
|
+
}
|
|
5644
|
+
}
|
|
5645
|
+
|
|
5646
|
+
/**
|
|
5647
|
+
* Decision 3 — lower the callback body into the row's children, preamble
|
|
5648
|
+
* and flatMap carrier. The caller has already entered the row's
|
|
5649
|
+
* `BindingScope` frame (`ctx.scope`, see `withLoopRowScope`) and bumped
|
|
5650
|
+
* `ctx.loopDepth`; `savedScope` is the pre-loop parent the preamble-shadow
|
|
5651
|
+
* window re-enters from.
|
|
5652
|
+
*
|
|
5653
|
+
* @internal exported for unit tests
|
|
5654
|
+
*/
|
|
5655
|
+
export function transformLoopCallbackBody(
|
|
5656
|
+
callback: ts.ArrowFunction,
|
|
5657
|
+
row: LoopRowParams,
|
|
5658
|
+
savedScope: BindingScope,
|
|
5659
|
+
ctx: TransformContext,
|
|
5660
|
+
isClientOnly: boolean,
|
|
5661
|
+
method: 'map' | 'flatMap',
|
|
5662
|
+
): LoopBodyLowering {
|
|
5663
|
+
const body = callback.body
|
|
5664
|
+
const out: LoopBodyLowering = ts.isBlock(body)
|
|
5665
|
+
? transformLoopBlockBody(body, callback, row, savedScope, ctx, isClientOnly, method)
|
|
5666
|
+
: { children: transformLoopExpressionBody(body, ctx, isClientOnly, method), preamble: undefined, flatMapCallback: undefined }
|
|
5667
|
+
applyFlatMapFallbacks(out, callback, ctx, isClientOnly, method)
|
|
5668
|
+
return out
|
|
5669
|
+
}
|
|
5670
|
+
|
|
5671
|
+
/**
|
|
5672
|
+
* Decision 4 — the structural net (sound-or-loud, spec/callback-fidelity.md):
|
|
5673
|
+
* a callback body that carries an INLINE JSX literal but produced no loop
|
|
5674
|
+
* lowering must never fall through to the IRExpression scalar path —
|
|
5675
|
+
* `ctx.getJS` strips types, not JSX, so the raw `<li …>` would splice
|
|
5676
|
+
* verbatim into the emitted client bundle as a silent SyntaxError. Any
|
|
5677
|
+
* recognizer gap for a JSX-bearing shape becomes a loud diagnostic here
|
|
5678
|
+
* instead of a leak. (A JSX-helper CALL — `map(t => renderItem(t))` —
|
|
5679
|
+
* carries no inline JSX literal and legitimately stays on the reactive-text
|
|
5680
|
+
* path.)
|
|
5681
|
+
*
|
|
5682
|
+
* Entry-count gate: a more specific refusal already fired for THIS call
|
|
5683
|
+
* (e.g. the flatMap leaf-wiring check) — don't stack the generic message on
|
|
5684
|
+
* top of it. Comparing against the count captured at entry (not `=== 0`)
|
|
5685
|
+
* keeps the net armed when an unrelated diagnostic was recorded earlier in
|
|
5686
|
+
* the file — a warning elsewhere must never silence the leak guard for this
|
|
5687
|
+
* callback.
|
|
5688
|
+
*
|
|
5689
|
+
* @internal exported for unit tests
|
|
5690
|
+
*/
|
|
5691
|
+
export function refuseUnloweredJsxCallback(
|
|
5692
|
+
node: ts.CallExpression,
|
|
5693
|
+
ctx: TransformContext,
|
|
5694
|
+
method: 'map' | 'flatMap',
|
|
5695
|
+
diagCountAtEntry: number,
|
|
5696
|
+
): void {
|
|
5697
|
+
const cb = node.arguments[0]
|
|
5698
|
+
const cbBody = cb && (ts.isArrowFunction(cb) || ts.isFunctionExpression(cb)) ? cb.body : undefined
|
|
5699
|
+
if (!cbBody || !containsJsxInExpression(cbBody)) return
|
|
5700
|
+
if (ctx.analyzer.errors.length !== diagCountAtEntry) return
|
|
5701
|
+
ctx.analyzer.errors.push(
|
|
5702
|
+
createError(
|
|
5703
|
+
ErrorCodes.UNSUPPORTED_JSX_PATTERN,
|
|
5704
|
+
getSourceLocation(cbBody, ctx.sourceFile, ctx.filePath),
|
|
5705
|
+
{
|
|
5706
|
+
message:
|
|
5707
|
+
`A .${method}() callback that builds JSX in this shape cannot be ` +
|
|
5708
|
+
'compiled — the JSX would leak verbatim into the client bundle. ' +
|
|
5709
|
+
'Recognized bodies: a JSX element/fragment, a ternary or ' +
|
|
5710
|
+
'&& / || / ?? expression, an array literal (flatMap), or a block ' +
|
|
5711
|
+
'body whose return the compiler can lower.',
|
|
5712
|
+
suggestion: {
|
|
5713
|
+
message:
|
|
5714
|
+
'Restructure the callback to return the JSX element directly ' +
|
|
5715
|
+
'(or via a block body with a plain `return`).',
|
|
5716
|
+
},
|
|
5717
|
+
}
|
|
5718
|
+
)
|
|
5719
|
+
)
|
|
5720
|
+
}
|
|
5721
|
+
|
|
5722
|
+
/** The loop's keyFn source and whether the body is a whole-item conditional. */
|
|
5723
|
+
export interface LoopKeyPlan {
|
|
5724
|
+
key: string | null
|
|
5725
|
+
bodyIsItemConditional: boolean
|
|
5726
|
+
}
|
|
5727
|
+
|
|
5728
|
+
/**
|
|
5729
|
+
* Decision 5 — the row key. Emits BF023 / BF024 if the loop root element
|
|
5730
|
+
* lacks a valid key attribute, then looks for the loop's keyFn source on the
|
|
5731
|
+
* first child. `extractLoopKey` handles direct elements, child components,
|
|
5732
|
+
* and — crucially — ternary bodies (#1098): when every branch of an
|
|
5733
|
+
* `IRConditional` declares the same `key={EXPR}`, that EXPR is lifted out to
|
|
5734
|
+
* mapArray's keyFn so a shape change (e.g. `<polygon>` ↔ `<circle>`)
|
|
5735
|
+
* replaces the DOM node instead of mutating attributes on the wrong tag.
|
|
5736
|
+
* Whole-item conditional bodies (#1665): the loop item is a single
|
|
5737
|
+
* conditional whose at-least-one branch renders nothing, so an item shows
|
|
5738
|
+
* 0-or-1 element. The key lives inside the rendering branch, so it is
|
|
5739
|
+
* hoisted from there; the flag routes the loop through anchored emission
|
|
5740
|
+
* downstream.
|
|
5741
|
+
*
|
|
5742
|
+
* #2753: the row's key ATTRIBUTE (name + value) is resolved here, once, and
|
|
5743
|
+
* stamped onto the element(s) that render it — `null` (unkeyed) means no
|
|
5744
|
+
* `IRElement.keyAttr` at all, which is the correct final answer for every
|
|
5745
|
+
* adapter and the client runtime alike, not a hint they still have to gate.
|
|
5746
|
+
* See `IRElement.keyAttr` / `applyLoopKeyAttr`'s docstrings.
|
|
5747
|
+
*
|
|
5748
|
+
* @internal exported for unit tests
|
|
5749
|
+
*/
|
|
5750
|
+
export function resolveLoopKey(
|
|
5751
|
+
callback: ts.ArrowFunction,
|
|
5752
|
+
children: IRNode[],
|
|
5753
|
+
ctx: TransformContext,
|
|
5754
|
+
isNested: boolean,
|
|
5755
|
+
depth: number,
|
|
5756
|
+
): LoopKeyPlan {
|
|
5757
|
+
if (children.length > 0) {
|
|
5758
|
+
checkLoopKey(callback, ctx, isNested)
|
|
5759
|
+
}
|
|
5760
|
+
const itemConditional = children.length > 0 ? loopBodyItemConditional(children) : null
|
|
5761
|
+
const bodyIsItemConditional = itemConditional !== null
|
|
5762
|
+
const key = itemConditional
|
|
5763
|
+
? extractItemConditionalKey(itemConditional)
|
|
5764
|
+
: (children.length > 0 ? extractLoopKey(children[0]) : null)
|
|
5765
|
+
if (key !== null) {
|
|
5766
|
+
const resolvedKeyAttrName = keyAttrName(depth)
|
|
5767
|
+
if (itemConditional) {
|
|
5768
|
+
applyLoopKeyAttr(itemConditional, resolvedKeyAttrName, key)
|
|
5769
|
+
} else if (children.length > 0) {
|
|
5770
|
+
applyLoopKeyAttr(children[0], resolvedKeyAttrName, key)
|
|
5771
|
+
}
|
|
5772
|
+
}
|
|
5773
|
+
applyRowPortalKeyAttrs(children, key, depth, ctx)
|
|
5774
|
+
return { key, bodyIsItemConditional }
|
|
5775
|
+
}
|
|
5776
|
+
|
|
5777
|
+
/**
|
|
5778
|
+
* Stage 3 / D5 (spec/callback-fidelity.md) — the keyFn is hoisted: `mapArray`
|
|
5779
|
+
* computes it from the raw item BEFORE the callback body runs, so the key
|
|
5780
|
+
* must be derivable from the item (and index), never from a value the
|
|
5781
|
+
* preamble computes. A key that reads a preamble-declared local would
|
|
5782
|
+
* compile to an unbound keyFn; refuse instead.
|
|
5783
|
+
*/
|
|
5784
|
+
function refusePreambleDerivedKey(
|
|
5785
|
+
node: ts.CallExpression,
|
|
5786
|
+
key: string | null,
|
|
5787
|
+
preamble: MapCallbackPreamble | undefined,
|
|
5788
|
+
ctx: TransformContext,
|
|
5789
|
+
): void {
|
|
5790
|
+
if (!key || !preamble || preamble.declaredNames.length === 0) return
|
|
5791
|
+
const declaredNameSet = new Set(preamble.declaredNames)
|
|
5792
|
+
const keyRefs = extractFreeIdentifiersFromText(key)
|
|
5793
|
+
const usesLocal = [...keyRefs].some((r) => declaredNameSet.has(r))
|
|
5794
|
+
if (!usesLocal) return
|
|
5795
|
+
ctx.analyzer.errors.push(
|
|
5796
|
+
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(node, ctx.sourceFile, ctx.filePath), {
|
|
5797
|
+
message:
|
|
5798
|
+
'A .map() loop key must be derivable from the loop item — it is ' +
|
|
5799
|
+
'evaluated before the callback body runs, so it cannot reference a ' +
|
|
5800
|
+
'value computed in the callback preamble.',
|
|
5801
|
+
suggestion: {
|
|
5802
|
+
message: 'Derive the key directly from the loop item (e.g. key={item.id}).',
|
|
5803
|
+
},
|
|
5804
|
+
})
|
|
5805
|
+
)
|
|
5806
|
+
}
|
|
5807
|
+
|
|
5808
|
+
/**
|
|
5809
|
+
* Decision 6a — the JSX-building preamble's element-array children.
|
|
5810
|
+
*
|
|
5811
|
+
* Stage 3 / D4 — flag element-array children ({out}) built by the preamble
|
|
5812
|
+
* so Phase-2 string emission joins them instead of `String([])`-collapsing
|
|
5813
|
+
* them. Scoped to builderNames (leaf accumulators), NOT all declared locals
|
|
5814
|
+
* — a value-only `{label}` keeps its historical plain interpolation.
|
|
5815
|
+
*
|
|
5816
|
+
* Stage 3 root cure — a JSX-building preamble feeding a COMPONENT root is
|
|
5817
|
+
* refused: the component loop's rows are createComponent-driven ('dom-ops'
|
|
5818
|
+
* row construction), and a lowered HTML-string leaf passed as a prop would
|
|
5819
|
+
* silently diverge from SSR, where the same prop is a real JSX element.
|
|
5820
|
+
* Refused = not carried (the old "do NOT collect" principle): codegen still
|
|
5821
|
+
* runs on an errored compile, and the dom-ops backstop invariant must stay
|
|
5822
|
+
* a FUTURE-variant tripwire, not re-fire on shapes Phase 1 already refused
|
|
5823
|
+
* loudly. Returns the preamble to carry (`undefined` once refused).
|
|
5824
|
+
*
|
|
5825
|
+
* @internal exported for unit tests
|
|
5826
|
+
*/
|
|
5827
|
+
export function applyPreambleBuilderPasses(
|
|
5828
|
+
node: ts.CallExpression,
|
|
5829
|
+
children: IRNode[],
|
|
5830
|
+
preamble: MapCallbackPreamble | undefined,
|
|
5831
|
+
ctx: TransformContext,
|
|
5832
|
+
): MapCallbackPreamble | undefined {
|
|
5833
|
+
if (!preamble || preamble.builderNames.length === 0) return preamble
|
|
5834
|
+
flagArrayChildExpressions(children, new Set(preamble.builderNames))
|
|
5835
|
+
if (children.length !== 1 || children[0].type !== 'component') return preamble
|
|
5836
|
+
ctx.analyzer.errors.push(
|
|
5837
|
+
createError(ErrorCodes.UNSUPPORTED_JSX_PATTERN, getSourceLocation(node, ctx.sourceFile, ctx.filePath), {
|
|
5838
|
+
message:
|
|
5839
|
+
'A .map() callback that builds JSX in its preamble cannot return a ' +
|
|
5840
|
+
'component: the built elements would reach the component as raw HTML ' +
|
|
5841
|
+
'strings on the client but as JSX elements at SSR (a silent divergence).',
|
|
5842
|
+
suggestion: {
|
|
5843
|
+
message:
|
|
5844
|
+
'Return a plain element root that embeds the array, or move the ' +
|
|
5845
|
+
'building logic inside the component.',
|
|
5846
|
+
},
|
|
5847
|
+
})
|
|
5848
|
+
)
|
|
5849
|
+
return undefined
|
|
5850
|
+
}
|
|
5851
|
+
|
|
5852
|
+
/**
|
|
5853
|
+
* Extract childComponent info if the loop body is a single component. This
|
|
5854
|
+
* enables createComponent-based rendering with proper prop passing.
|
|
5855
|
+
*/
|
|
5856
|
+
function loopChildComponentOf(children: IRNode[]): IRLoopChildComponent | undefined {
|
|
5857
|
+
if (children.length !== 1 || children[0].type !== 'component') return undefined
|
|
5858
|
+
const comp = children[0] as IRComponent
|
|
5859
|
+
return {
|
|
5860
|
+
name: comp.name,
|
|
5861
|
+
slotId: comp.slotId,
|
|
5862
|
+
props: comp.props
|
|
5863
|
+
.filter((p) => p.name !== 'key') // key is handled separately
|
|
5864
|
+
.map((p) => ({
|
|
5865
|
+
name: p.name,
|
|
5866
|
+
value: p.value,
|
|
5867
|
+
isEventHandler: isEventHandlerName(p.name),
|
|
5868
|
+
})),
|
|
5869
|
+
children: comp.children,
|
|
5870
|
+
}
|
|
5871
|
+
}
|
|
5872
|
+
|
|
5873
|
+
/** How the loop's array renders: static (prop) or reconciled (signal/memo/call). */
|
|
5874
|
+
export interface LoopArrayClassification {
|
|
5875
|
+
callsReactive: boolean
|
|
5876
|
+
hasCalls: boolean
|
|
5877
|
+
isDirectPropArray: boolean
|
|
5878
|
+
isStaticArray: boolean
|
|
5879
|
+
}
|
|
5880
|
+
|
|
5881
|
+
/**
|
|
5882
|
+
* Decision 7 — is the array static (prop) or dynamic (signal/memo)? Static
|
|
5883
|
+
* arrays don't need mapArray/mapArrayAnchored — SSR elements are hydrated
|
|
5884
|
+
* directly. Signal / memo arrays need mapArray for dynamic DOM updates.
|
|
5885
|
+
*
|
|
5886
|
+
* Solid-style wrap-by-default fallback (#943, follow-up to
|
|
5887
|
+
* #937/#939/#940/#941/#942): if the array expression AST contains a function
|
|
5888
|
+
* call but the analyzer can't recognise the callee as a signal / memo, we
|
|
5889
|
+
* still force reconciliation. `getItems().map(...)` where `getItems` is an
|
|
5890
|
+
* imported helper previously silent-dropped into the static-render path,
|
|
5891
|
+
* freezing the SSR-time list on the client. Over-reconciling an array that
|
|
5892
|
+
* happens to contain a pure call costs one extra `mapArray` per loop;
|
|
5893
|
+
* under-reconciling is the silent-drop bug this closes.
|
|
5894
|
+
*
|
|
5895
|
+
* Destructured map params (`([, cfg]) => ...`, `({ a, b }) => ...`, typed
|
|
5896
|
+
* forms) used to be excluded from the widening to avoid a latent crash in
|
|
5897
|
+
* the `mapArray` renderItem emitter — see #949 and the emitter-side
|
|
5898
|
+
* `destructureLoopParam` helper, which now unwraps the signal accessor at
|
|
5899
|
+
* renderItem body entry. No more skip.
|
|
5900
|
+
*
|
|
5901
|
+
* `objectIteration` (#2168 object-entries-map): `array` here is the STRIPPED
|
|
5902
|
+
* object expression (`Object.entries(x)`'s `x`), which can itself be a
|
|
5903
|
+
* static module-scope const object literal and would otherwise satisfy
|
|
5904
|
+
* every check — but a plain OBJECT has no `.forEach()`/`.map()` (the
|
|
5905
|
+
* static-array client codegen's own methods), unlike an actual array
|
|
5906
|
+
* literal. Force the dynamic `mapArray()` path instead, which this shape's
|
|
5907
|
+
* client-JS array-expr reconstruction (`applyObjectIterationWrap`,
|
|
5908
|
+
* `ir-to-client-js/utils.ts`) already handles correctly.
|
|
5909
|
+
*
|
|
5910
|
+
* @internal exported for unit tests
|
|
5911
|
+
*/
|
|
5912
|
+
export function classifyLoopArray(
|
|
5913
|
+
source: Pick<LoopSourcePlan, 'array' | 'arrayExpr' | 'objectIteration'>,
|
|
5914
|
+
method: 'map' | 'flatMap',
|
|
5915
|
+
ctx: TransformContext,
|
|
5916
|
+
): LoopArrayClassification {
|
|
5917
|
+
const callsReactive = exprCallsReactiveGetters(source.arrayExpr, ctx)
|
|
5918
|
+
const hasCalls = exprHasFunctionCalls(source.arrayExpr)
|
|
5919
|
+
const isDirectPropArray = method !== 'flatMap' && isArrayExprDirectPropRef(source.arrayExpr, ctx)
|
|
5663
5920
|
const isStaticArray =
|
|
5664
|
-
!isSignalOrMemoArray(array, ctx)
|
|
5921
|
+
!isSignalOrMemoArray(source.array, ctx)
|
|
5665
5922
|
&& !isDirectPropArray
|
|
5666
5923
|
&& !hasCalls
|
|
5667
|
-
|
|
5668
|
-
|
|
5669
|
-
|
|
5670
|
-
// otherwise satisfy every check above — but a plain OBJECT has no
|
|
5671
|
-
// `.forEach()`/`.map()` (the static-array client codegen's own
|
|
5672
|
-
// methods), unlike an actual array literal. Force the dynamic
|
|
5673
|
-
// `mapArray()` path instead, which this shape's client-JS array-expr
|
|
5674
|
-
// reconstruction (`applyObjectIterationWrap`, `ir-to-client-js/utils.ts`)
|
|
5675
|
-
// already handles correctly.
|
|
5676
|
-
&& !objectIteration
|
|
5677
|
-
|
|
5678
|
-
// #2389 patch-on-update — a signal-backed (non-static) loop whose body has
|
|
5679
|
-
// a preamble may reference a preamble-declared local directly as a child
|
|
5680
|
-
// expression (`{cells}`, `{stateLabel}`). `mapArray` reuses the same DOM
|
|
5681
|
-
// node on a same-key update, re-running only the wired text/attr slots —
|
|
5682
|
-
// this child has neither, so without a dedicated region-patch effect it
|
|
5683
|
-
// freezes at its mount-time value. Static arrays are never recreated via
|
|
5684
|
-
// signals, so there is nothing to patch; skip them entirely.
|
|
5685
|
-
const preambleRegions = preamble && !isStaticArray
|
|
5686
|
-
? collectPreambleRegions(children, new Set(preamble.declaredNames), ctx)
|
|
5687
|
-
: undefined
|
|
5924
|
+
&& !source.objectIteration
|
|
5925
|
+
return { callsReactive, hasCalls, isDirectPropArray, isStaticArray }
|
|
5926
|
+
}
|
|
5688
5927
|
|
|
5689
|
-
|
|
5690
|
-
|
|
5691
|
-
|
|
5692
|
-
|
|
5693
|
-
|
|
5694
|
-
|
|
5695
|
-
|
|
5696
|
-
|
|
5697
|
-
|
|
5698
|
-
|
|
5699
|
-
|
|
5700
|
-
|
|
5701
|
-
|
|
5702
|
-
|
|
5703
|
-
|
|
5704
|
-
|
|
5705
|
-
|
|
5706
|
-
|
|
5928
|
+
/**
|
|
5929
|
+
* Decision 6b — the preamble's after-the-fact reactivity wiring on a
|
|
5930
|
+
* signal-backed (non-static) loop. Static arrays are never recreated via
|
|
5931
|
+
* signals, so there is nothing to patch; they are skipped entirely.
|
|
5932
|
+
*
|
|
5933
|
+
* #2389 patch-on-update — a loop body with a preamble may reference a
|
|
5934
|
+
* preamble-declared local directly as a child expression (`{cells}`,
|
|
5935
|
+
* `{stateLabel}`). `mapArray` reuses the same DOM node on a same-key update,
|
|
5936
|
+
* re-running only the wired text/attr slots — this child has neither, so
|
|
5937
|
+
* without a dedicated region-patch effect it freezes at its mount-time
|
|
5938
|
+
* value.
|
|
5939
|
+
*
|
|
5940
|
+
* #2447 follow-up — the ATTRIBUTE twin of the regions. `class={cls}` where
|
|
5941
|
+
* the preamble declares `cls` froze at its row-construction value for the
|
|
5942
|
+
* same reason `{cells}` did, and for one extra reason on top: an attribute
|
|
5943
|
+
* only gets wired at all if its element carries a slot id, and
|
|
5944
|
+
* `hasReactiveAttributes` (which decides that at element-build time, before
|
|
5945
|
+
* any loop preamble is known) scores a bare local as non-reactive. So the
|
|
5946
|
+
* slot has to be granted HERE, in the same after-the-fact pass the regions
|
|
5947
|
+
* use — after which `collectLoopChildReactiveAttrs` classifies the attr and
|
|
5948
|
+
* the row effect re-runs the preamble ahead of the write.
|
|
5949
|
+
*
|
|
5950
|
+
* #2596 — the CONDITION-position twin. See
|
|
5951
|
+
* `markPreambleConditionalReactivity`'s docstring for why that one is gated
|
|
5952
|
+
* on `reactiveNames` (genuinely signal-derived) rather than the blanket
|
|
5953
|
+
* `declaredNames` the region/attr passes use.
|
|
5954
|
+
*
|
|
5955
|
+
* @internal exported for unit tests
|
|
5956
|
+
*/
|
|
5957
|
+
export function markPreambleReactivity(
|
|
5958
|
+
children: IRNode[],
|
|
5959
|
+
preamble: MapCallbackPreamble | undefined,
|
|
5960
|
+
isStaticArray: boolean,
|
|
5961
|
+
ctx: TransformContext,
|
|
5962
|
+
): PreambleRegionSource[] | undefined {
|
|
5963
|
+
if (!preamble || isStaticArray) return undefined
|
|
5964
|
+
const declared = new Set(preamble.declaredNames)
|
|
5965
|
+
const preambleRegions = collectPreambleRegions(children, declared, ctx)
|
|
5966
|
+
markPreambleAttrSlots(children, declared, ctx)
|
|
5967
|
+
if (preamble.reactiveNames && preamble.reactiveNames.length > 0) {
|
|
5968
|
+
markPreambleConditionalReactivity(children, new Set(preamble.reactiveNames), ctx)
|
|
5969
|
+
}
|
|
5970
|
+
return preambleRegions
|
|
5971
|
+
}
|
|
5972
|
+
|
|
5973
|
+
/**
|
|
5974
|
+
* Scalar operand evidence only. Inferring object rows here would bypass
|
|
5975
|
+
* adapters' existing row-structure capability checks and their diagnostics.
|
|
5976
|
+
*/
|
|
5977
|
+
function scalarLoopItemType(itemTypeNode: ts.Node | undefined, ctx: TransformContext): TypeInfo | null {
|
|
5978
|
+
const callbackType = itemTypeNode && ctx.analyzer.checker
|
|
5979
|
+
? tsTypeToTypeInfo(ctx.analyzer.checker.getTypeAtLocation(itemTypeNode), ctx.analyzer.checker)
|
|
5980
|
+
: null
|
|
5981
|
+
if (!callbackType) return null
|
|
5982
|
+
if (callbackType.kind === 'primitive') return callbackType
|
|
5983
|
+
if (callbackType.kind === 'union' && callbackType.unionTypes?.every(t => t.kind === 'primitive')) {
|
|
5984
|
+
return callbackType
|
|
5985
|
+
}
|
|
5986
|
+
return null
|
|
5987
|
+
}
|
|
5988
|
+
|
|
5989
|
+
function transformMapCall(
|
|
5990
|
+
node: ts.CallExpression,
|
|
5991
|
+
ctx: TransformContext,
|
|
5992
|
+
isClientOnly = false,
|
|
5993
|
+
method: 'map' | 'flatMap' = 'map'
|
|
5994
|
+
): IRLoop | null {
|
|
5995
|
+
// Capture nesting depth before we register this map's own params.
|
|
5996
|
+
// ctx.scope is populated by the *outer* map; if any VALUE names (item/
|
|
5997
|
+
// index/destructure) are bound we are inside one. Reads
|
|
5998
|
+
// `valueBoundNames()`, not `boundNames()`, for consistency with the
|
|
5999
|
+
// other structural/reactivity consumers (#2482 Stage 1a Commit 2) —
|
|
6000
|
+
// though a bound outer-loop row always carries at least one value
|
|
6001
|
+
// binding regardless, so this can't actually change the answer.
|
|
6002
|
+
const isNested = ctx.scope.valueBoundNames().size > 0
|
|
6003
|
+
// Diagnostic count at entry — the structural net at the scalar fallthrough
|
|
6004
|
+
// de-dups against refusals fired DURING this call (leaf-wiring, DSL gates),
|
|
6005
|
+
// never against unrelated diagnostics recorded before it.
|
|
6006
|
+
const diagCountAtEntry = ctx.analyzer.errors.length
|
|
6007
|
+
// This loop's own depth (0 = outermost) is however many enclosing
|
|
6008
|
+
// loops are already active, captured before `ctx.loopDepth` below is
|
|
6009
|
+
// bumped for THIS loop's own descendants.
|
|
6010
|
+
const depth = ctx.loopDepth
|
|
6011
|
+
|
|
6012
|
+
const source = resolveLoopSource(node, ctx, isClientOnly)
|
|
6013
|
+
|
|
6014
|
+
// Only an arrow callback lowers to a loop; anything else (a function
|
|
6015
|
+
// reference, a function expression) falls through to the structural net
|
|
6016
|
+
// and the IRExpression scalar path.
|
|
6017
|
+
const callback = node.arguments[0]
|
|
6018
|
+
if (!ts.isArrowFunction(callback)) {
|
|
6019
|
+
refuseUnloweredJsxCallback(node, ctx, method, diagCountAtEntry)
|
|
6020
|
+
return null
|
|
5707
6021
|
}
|
|
5708
6022
|
|
|
6023
|
+
const row = resolveLoopRowParams(callback, source, ctx)
|
|
6024
|
+
const body = withLoopRowScope(ctx, row, (savedScope) =>
|
|
6025
|
+
transformLoopCallbackBody(callback, row, savedScope, ctx, isClientOnly, method),
|
|
6026
|
+
)
|
|
6027
|
+
|
|
6028
|
+
const { children, flatMapCallback } = body
|
|
6029
|
+
// If no JSX children were found (e.g., callback returns a function call),
|
|
6030
|
+
// fall back to treating the entire expression as an IRExpression — unless
|
|
6031
|
+
// flatMap already built a compiled callback (flatMapCallback).
|
|
6032
|
+
if (children.length === 0 && !flatMapCallback) {
|
|
6033
|
+
refuseUnloweredJsxCallback(node, ctx, method, diagCountAtEntry)
|
|
6034
|
+
return null
|
|
6035
|
+
}
|
|
6036
|
+
|
|
6037
|
+
const { key, bodyIsItemConditional } = resolveLoopKey(callback, children, ctx, isNested, depth)
|
|
6038
|
+
refusePreambleDerivedKey(node, key, body.preamble, ctx)
|
|
6039
|
+
const preamble = applyPreambleBuilderPasses(node, children, body.preamble, ctx)
|
|
6040
|
+
|
|
6041
|
+
// A component that is a DIRECT member of the loop body (the row root, or
|
|
6042
|
+
// one of several flatMap-sibling roots) owns its own per-row identity and
|
|
6043
|
+
// gets a freshly randomized `bf-s` rather than deriving one from parent
|
|
6044
|
+
// scope + slot. Tag it here — the single place that knows which nodes are
|
|
6045
|
+
// direct loop-body members — so every backend can consult
|
|
6046
|
+
// `derivesScopeFromSlot()` instead of re-deriving this fact from a mutable
|
|
6047
|
+
// "am I inside a loop" flag.
|
|
6048
|
+
tagLoopItemRootComponents(children)
|
|
6049
|
+
|
|
6050
|
+
const childComponent = loopChildComponentOf(children)
|
|
6051
|
+
const bodyIsMultiRoot = loopBodyIsMultiRoot(children)
|
|
6052
|
+
const arrayKind = classifyLoopArray(source, method, ctx)
|
|
6053
|
+
const preambleRegions = markPreambleReactivity(children, preamble, arrayKind.isStaticArray, ctx)
|
|
6054
|
+
|
|
5709
6055
|
// Collect nested components for both static and dynamic arrays.
|
|
5710
6056
|
// Static arrays: needed for initChild hydration.
|
|
5711
6057
|
// Dynamic arrays with native root + component descendants: enables
|
|
@@ -5713,24 +6059,15 @@ function transformMapCall(
|
|
|
5713
6059
|
// createComponent replacement).
|
|
5714
6060
|
const nestedComponents = collectNestedComponents(children).filter(c => c.name !== childComponent?.name)
|
|
5715
6061
|
|
|
5716
|
-
// Scalar operand evidence only. Inferring object rows here would bypass
|
|
5717
|
-
// adapters' existing row-structure capability checks and their diagnostics.
|
|
5718
|
-
const callbackType = itemTypeNode && ctx.analyzer.checker
|
|
5719
|
-
? tsTypeToTypeInfo(ctx.analyzer.checker.getTypeAtLocation(itemTypeNode), ctx.analyzer.checker)
|
|
5720
|
-
: null
|
|
5721
|
-
const scalarItemType = callbackType?.kind === 'primitive' ||
|
|
5722
|
-
(callbackType?.kind === 'union' && callbackType.unionTypes?.every(t => t.kind === 'primitive'))
|
|
5723
|
-
? callbackType : null
|
|
5724
|
-
|
|
5725
6062
|
return {
|
|
5726
6063
|
type: 'loop',
|
|
5727
6064
|
method: method === 'flatMap' ? 'flatMap' : undefined,
|
|
5728
|
-
array,
|
|
5729
|
-
templateArray,
|
|
6065
|
+
array: source.array,
|
|
6066
|
+
templateArray: source.templateArray,
|
|
5730
6067
|
arrayType: null,
|
|
5731
|
-
itemType:
|
|
5732
|
-
param,
|
|
5733
|
-
index,
|
|
6068
|
+
itemType: scalarLoopItemType(row.itemTypeNode, ctx),
|
|
6069
|
+
param: row.param,
|
|
6070
|
+
index: row.index,
|
|
5734
6071
|
key,
|
|
5735
6072
|
children,
|
|
5736
6073
|
// Loops don't generate their own slotId; they inherit from parent element
|
|
@@ -5742,27 +6079,27 @@ function transformMapCall(
|
|
|
5742
6079
|
// `l1`, ...) so element bf="sN" numbering stays stable across versions
|
|
5743
6080
|
// and ssr-hydration-contract assertions don't shift when loops are added.
|
|
5744
6081
|
markerId: `l${ctx.loopMarkerCounter++}`,
|
|
5745
|
-
isStaticArray,
|
|
5746
|
-
isPropDerivedArray: isDirectPropArray || undefined,
|
|
5747
|
-
callsReactiveGetters: callsReactive || undefined,
|
|
5748
|
-
hasFunctionCalls: hasCalls || undefined,
|
|
6082
|
+
isStaticArray: arrayKind.isStaticArray,
|
|
6083
|
+
isPropDerivedArray: arrayKind.isDirectPropArray || undefined,
|
|
6084
|
+
callsReactiveGetters: arrayKind.callsReactive || undefined,
|
|
6085
|
+
hasFunctionCalls: arrayKind.hasCalls || undefined,
|
|
5749
6086
|
bodyIsMultiRoot: bodyIsMultiRoot || undefined,
|
|
5750
6087
|
bodyIsItemConditional: bodyIsItemConditional || undefined,
|
|
5751
6088
|
childComponent,
|
|
5752
6089
|
nestedComponents,
|
|
5753
|
-
filterPredicate,
|
|
5754
|
-
sortComparator,
|
|
5755
|
-
chainOrder,
|
|
5756
|
-
iterationShape,
|
|
5757
|
-
objectIteration,
|
|
6090
|
+
filterPredicate: source.filterPredicate,
|
|
6091
|
+
sortComparator: source.sortComparator,
|
|
6092
|
+
chainOrder: source.chainOrder,
|
|
6093
|
+
iterationShape: source.iterationShape,
|
|
6094
|
+
objectIteration: source.objectIteration,
|
|
5758
6095
|
depth,
|
|
5759
6096
|
clientOnly: isClientOnly || undefined,
|
|
5760
6097
|
preamble,
|
|
5761
6098
|
preambleRegions: preambleRegions && preambleRegions.length > 0 ? preambleRegions : undefined,
|
|
5762
|
-
paramType,
|
|
5763
|
-
indexType,
|
|
5764
|
-
paramBindings,
|
|
5765
|
-
arrayFreeIdentifiers: extractFreeIdentifiersFromNode(arrayExpr),
|
|
6099
|
+
paramType: row.paramType,
|
|
6100
|
+
indexType: row.indexType,
|
|
6101
|
+
paramBindings: row.paramBindings,
|
|
6102
|
+
arrayFreeIdentifiers: extractFreeIdentifiersFromNode(source.arrayExpr),
|
|
5766
6103
|
flatMapCallback,
|
|
5767
6104
|
loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
|
|
5768
6105
|
}
|