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