@barefootjs/jsx 0.40.0 → 0.40.2
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/ambiguous-nil-arithmetic.d.ts +42 -0
- package/dist/adapters/ambiguous-nil-arithmetic.d.ts.map +1 -0
- package/dist/adapters/attr-plan.d.ts.map +1 -1
- package/dist/adapters/boolean-carrier.d.ts +31 -0
- package/dist/adapters/boolean-carrier.d.ts.map +1 -0
- package/dist/adapters/boolean-result.d.ts +32 -10
- package/dist/adapters/boolean-result.d.ts.map +1 -1
- package/dist/adapters/brace-delimiter-text.d.ts +18 -0
- package/dist/adapters/brace-delimiter-text.d.ts.map +1 -0
- package/dist/adapters/callback-method.d.ts +38 -5
- package/dist/adapters/callback-method.d.ts.map +1 -1
- package/dist/adapters/component-props.d.ts +22 -7
- package/dist/adapters/component-props.d.ts.map +1 -1
- package/dist/adapters/computed-const.d.ts +28 -1
- package/dist/adapters/computed-const.d.ts.map +1 -1
- package/dist/adapters/dsl-template-adapter.d.ts +39 -1
- package/dist/adapters/dsl-template-adapter.d.ts.map +1 -1
- package/dist/adapters/loop-bound-names.d.ts +9 -1
- package/dist/adapters/loop-bound-names.d.ts.map +1 -1
- package/dist/adapters/loop-row-type.d.ts +52 -0
- package/dist/adapters/loop-row-type.d.ts.map +1 -0
- package/dist/adapters/nil-reading.d.ts +68 -0
- package/dist/adapters/nil-reading.d.ts.map +1 -0
- package/dist/adapters/non-primitive-equality.d.ts +33 -0
- package/dist/adapters/non-primitive-equality.d.ts.map +1 -0
- package/dist/adapters/number-value.d.ts +45 -0
- package/dist/adapters/number-value.d.ts.map +1 -0
- package/dist/adapters/operand-typing.d.ts +126 -0
- package/dist/adapters/operand-typing.d.ts.map +1 -0
- package/dist/adapters/parsed-expr-emitter.d.ts +70 -12
- package/dist/adapters/parsed-expr-emitter.d.ts.map +1 -1
- package/dist/adapters/primitive-plan.d.ts +291 -0
- package/dist/adapters/primitive-plan.d.ts.map +1 -0
- package/dist/analyzer-context.d.ts +11 -0
- package/dist/analyzer-context.d.ts.map +1 -1
- package/dist/analyzer.d.ts +34 -0
- package/dist/analyzer.d.ts.map +1 -1
- package/dist/augment-inherited-props.d.ts +63 -8
- package/dist/augment-inherited-props.d.ts.map +1 -1
- package/dist/compiler.d.ts.map +1 -1
- package/dist/event-handler-name.d.ts +12 -0
- package/dist/event-handler-name.d.ts.map +1 -1
- package/dist/expression-parser.d.ts +8 -0
- package/dist/expression-parser.d.ts.map +1 -1
- package/dist/index.d.ts +24 -11
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5671 -2586
- package/dist/ir-to-client-js/build-references.d.ts.map +1 -1
- package/dist/ir-to-client-js/child-props-object.d.ts +64 -0
- package/dist/ir-to-client-js/child-props-object.d.ts.map +1 -0
- package/dist/ir-to-client-js/collect-elements.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-component-loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts +29 -0
- package/dist/ir-to-client-js/control-flow/plan/build-inner-loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-lazy-row.d.ts +2 -0
- package/dist/ir-to-client-js/control-flow/plan/build-lazy-row.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-loop-child-arm.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/build-reactive-effects.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/inner-loop.d.ts +5 -4
- package/dist/ir-to-client-js/control-flow/plan/inner-loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/loop-child-arm.d.ts +2 -0
- package/dist/ir-to-client-js/control-flow/plan/loop-child-arm.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/loop.d.ts +15 -0
- package/dist/ir-to-client-js/control-flow/plan/loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/plan/reactive-effects.d.ts +2 -0
- package/dist/ir-to-client-js/control-flow/plan/reactive-effects.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/shared.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts +22 -0
- package/dist/ir-to-client-js/control-flow/stringify/claim-plan.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/component-loop.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/event-listener.d.ts.map +1 -1
- package/dist/ir-to-client-js/control-flow/stringify/lazy-row.d.ts.map +1 -1
- package/dist/ir-to-client-js/html-template.d.ts +3 -2
- package/dist/ir-to-client-js/html-template.d.ts.map +1 -1
- package/dist/ir-to-client-js/imports.d.ts +2 -2
- package/dist/ir-to-client-js/imports.d.ts.map +1 -1
- package/dist/ir-to-client-js/index.d.ts +2 -6
- package/dist/ir-to-client-js/index.d.ts.map +1 -1
- package/dist/ir-to-client-js/plan/build-static-array-child-init.d.ts.map +1 -1
- package/dist/ir-to-client-js/plan/static-array-child-init.d.ts +37 -19
- package/dist/ir-to-client-js/plan/static-array-child-init.d.ts.map +1 -1
- package/dist/ir-to-client-js/prop-handling.d.ts.map +1 -1
- package/dist/ir-to-client-js/reactivity.d.ts.map +1 -1
- package/dist/ir-to-client-js/safe-html.d.ts +9 -3
- package/dist/ir-to-client-js/safe-html.d.ts.map +1 -1
- package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts +3 -2
- package/dist/ir-to-client-js/stringify/static-array-child-init.d.ts.map +1 -1
- package/dist/ir-to-client-js/types.d.ts +30 -0
- package/dist/ir-to-client-js/types.d.ts.map +1 -1
- package/dist/ir-to-client-js/utils.d.ts +8 -0
- package/dist/ir-to-client-js/utils.d.ts.map +1 -1
- package/dist/jsx-to-ir.d.ts +1 -0
- package/dist/jsx-to-ir.d.ts.map +1 -1
- package/dist/nullable-signal-attr.d.ts +95 -10
- package/dist/nullable-signal-attr.d.ts.map +1 -1
- package/dist/prop-rewrite.d.ts +7 -0
- package/dist/prop-rewrite.d.ts.map +1 -1
- package/dist/props-binding.d.ts +27 -3
- package/dist/props-binding.d.ts.map +1 -1
- package/dist/props-object-whole-read.d.ts +15 -0
- package/dist/props-object-whole-read.d.ts.map +1 -0
- package/dist/rich-type-refusal.d.ts.map +1 -1
- package/dist/scope/binding-scope.d.ts +100 -4
- package/dist/scope/binding-scope.d.ts.map +1 -1
- package/dist/scope/lexical-scope-walk.d.ts +3 -2
- package/dist/scope/lexical-scope-walk.d.ts.map +1 -1
- package/dist/scope/root-prop-alias.d.ts +16 -0
- package/dist/scope/root-prop-alias.d.ts.map +1 -1
- package/dist/signal-prop-name-collision.d.ts.map +1 -1
- package/dist/ssr-defaults.d.ts +4 -2
- package/dist/ssr-defaults.d.ts.map +1 -1
- package/dist/ssr-seed-plan.d.ts +14 -0
- package/dist/ssr-seed-plan.d.ts.map +1 -1
- package/dist/strip-types.d.ts +13 -0
- package/dist/strip-types.d.ts.map +1 -1
- package/dist/template-parts.d.ts.map +1 -1
- package/dist/template-position-walk.d.ts +21 -3
- package/dist/template-position-walk.d.ts.map +1 -1
- package/dist/types.d.ts +120 -0
- package/dist/types.d.ts.map +1 -1
- package/package.json +2 -2
- package/src/__tests__/__snapshots__/doc-examples.test.ts.snap +3 -3
- package/src/__tests__/binding-scope-ratchet.test.ts +12 -2
- package/src/__tests__/binding-scope.test.ts +89 -1
- package/src/__tests__/body-destructure-props-object-alias.test.ts +123 -0
- package/src/__tests__/boolean-carrier.test.ts +74 -0
- package/src/__tests__/boolean-result.test.ts +22 -5
- package/src/__tests__/brace-delimiter-text.test.ts +26 -0
- package/src/__tests__/callback-method.test.ts +62 -2
- package/src/__tests__/child-components-in-map.test.ts +1 -1
- package/src/__tests__/component-props.test.ts +14 -0
- package/src/__tests__/computed-const.test.ts +188 -0
- package/src/__tests__/emit-to-string-call.test.ts +2 -1
- package/src/__tests__/expression-parser.test.ts +24 -0
- package/src/__tests__/hydration-payload-analysis.test.ts +166 -0
- package/src/__tests__/issue-2724-prop-alias-loop-not-static.test.ts +7 -7
- package/src/__tests__/issue-2754-rest-spread-needs-slot.test.ts +5 -2
- package/src/__tests__/issue-2798-static-nested-loop-bindings.test.ts +1 -1
- package/src/__tests__/issue-2835-props-type-member-name-collision.test.ts +4 -4
- package/src/__tests__/issue-3044-nested-prop-object-array-not-static.test.ts +1 -1
- package/src/__tests__/issue-3688-props-spread-child-csr.test.ts +143 -0
- package/src/__tests__/issue-3713-props-spread-loop-row.test.ts +65 -0
- package/src/__tests__/lookup-literal-const.test.ts +9 -3
- package/src/__tests__/loop-index-reactivity.test.ts +2 -2
- package/src/__tests__/loop-param-accessor-key-member-safety.test.ts +1 -1
- package/src/__tests__/loop-plan.test.ts +1 -1
- package/src/__tests__/loop-row-const-initializer-shadow.test.ts +146 -0
- package/src/__tests__/loop-row-prop-read.test.ts +111 -0
- package/src/__tests__/loop-row-type.test.ts +64 -0
- package/src/__tests__/lowering-value-position.test.ts +4 -0
- package/src/__tests__/memo-body-expr.test.ts +137 -0
- package/src/__tests__/module-const-destructure-default.test.ts +156 -0
- package/src/__tests__/nested-loop-index-param.test.ts +1 -1
- package/src/__tests__/nested-loop-reactive-attrs.test.ts +2 -2
- package/src/__tests__/nested-row-shadowing.test.ts +2 -2
- package/src/__tests__/nil-reading.test.ts +77 -0
- package/src/__tests__/nullable-signal-attr.test.ts +231 -2
- package/src/__tests__/primitive-plan.test.ts +416 -0
- package/src/__tests__/profile-binding-ids.test.ts +14 -0
- package/src/__tests__/profile-loop-binding-ids.test.ts +2 -2
- package/src/__tests__/profile-nested-binding-ids.test.ts +2 -2
- package/src/__tests__/props-object-whole-read.test.ts +40 -0
- package/src/__tests__/reactive-attrs-in-map.test.ts +1 -1
- package/src/__tests__/reactive-factory-inlining.test.ts +4 -1
- package/src/__tests__/rest-binding-gaps.test.ts +192 -0
- package/src/__tests__/root-prop-alias.test.ts +79 -1
- package/src/__tests__/signal-prop-name-collision.test.ts +102 -2
- package/src/__tests__/source-file-cache.test.ts +105 -0
- package/src/__tests__/ssr-seed-plan.test.ts +43 -0
- package/src/__tests__/static-loop-csr-materialize.test.ts +2 -2
- package/src/__tests__/static-record-literal-array.test.ts +171 -0
- package/src/__tests__/string-concat-identifier.test.ts +40 -1
- package/src/__tests__/template-parts-literal-boundary.test.ts +19 -0
- package/src/adapters/ambiguous-nil-arithmetic.ts +103 -0
- package/src/adapters/attr-plan.ts +6 -2
- package/src/adapters/boolean-carrier.ts +76 -0
- package/src/adapters/boolean-result.ts +72 -66
- package/src/adapters/brace-delimiter-text.ts +25 -0
- package/src/adapters/callback-method.ts +151 -27
- package/src/adapters/component-props.ts +28 -8
- package/src/adapters/computed-const.ts +443 -10
- package/src/adapters/dsl-template-adapter.ts +79 -2
- package/src/adapters/loop-bound-names.ts +9 -1
- package/src/adapters/loop-plan.ts +1 -1
- package/src/adapters/loop-row-type.ts +139 -0
- package/src/adapters/nil-reading.ts +297 -0
- package/src/adapters/non-primitive-equality.ts +92 -0
- package/src/adapters/number-value.ts +108 -0
- package/src/adapters/operand-typing.ts +522 -0
- package/src/adapters/parsed-expr-emitter.ts +154 -19
- package/src/adapters/primitive-plan.ts +696 -0
- package/src/analyzer-context.ts +14 -0
- package/src/analyzer.ts +692 -85
- package/src/augment-inherited-props.ts +108 -10
- package/src/compiler.ts +17 -0
- package/src/event-handler-name.ts +15 -0
- package/src/expression-parser.ts +74 -2
- package/src/index.ts +45 -9
- package/src/ir-to-client-js/build-references.ts +69 -0
- package/src/ir-to-client-js/child-props-object.ts +106 -0
- package/src/ir-to-client-js/collect-elements.ts +100 -67
- package/src/ir-to-client-js/compute-inlinability.ts +1 -1
- package/src/ir-to-client-js/control-flow/plan/build-component-loop.ts +15 -1
- package/src/ir-to-client-js/control-flow/plan/build-inner-loop.ts +85 -5
- package/src/ir-to-client-js/control-flow/plan/build-lazy-row.ts +3 -0
- package/src/ir-to-client-js/control-flow/plan/build-loop-child-arm.ts +30 -28
- package/src/ir-to-client-js/control-flow/plan/build-reactive-effects.ts +1 -0
- package/src/ir-to-client-js/control-flow/plan/inner-loop.ts +5 -4
- package/src/ir-to-client-js/control-flow/plan/loop-child-arm.ts +2 -0
- package/src/ir-to-client-js/control-flow/plan/loop.ts +12 -0
- package/src/ir-to-client-js/control-flow/plan/reactive-effects.ts +2 -0
- package/src/ir-to-client-js/control-flow/shared.ts +23 -24
- package/src/ir-to-client-js/control-flow/stringify/claim-plan.ts +29 -0
- package/src/ir-to-client-js/control-flow/stringify/component-loop.ts +8 -2
- package/src/ir-to-client-js/control-flow/stringify/event-listener.ts +8 -1
- package/src/ir-to-client-js/control-flow/stringify/inner-loop.ts +8 -7
- package/src/ir-to-client-js/control-flow/stringify/lazy-row.ts +8 -7
- package/src/ir-to-client-js/control-flow/stringify/loop-child-arm.ts +4 -4
- package/src/ir-to-client-js/control-flow/stringify/loop.ts +3 -3
- package/src/ir-to-client-js/control-flow/stringify/reactive-effects.ts +6 -6
- package/src/ir-to-client-js/emit-reactive.ts +1 -1
- package/src/ir-to-client-js/html-template.ts +95 -38
- package/src/ir-to-client-js/imports.ts +1 -1
- package/src/ir-to-client-js/index.ts +53 -11
- package/src/ir-to-client-js/plan/build-static-array-child-init.ts +42 -15
- package/src/ir-to-client-js/plan/static-array-child-init.ts +34 -19
- package/src/ir-to-client-js/prop-handling.ts +22 -3
- package/src/ir-to-client-js/reactivity.ts +14 -0
- package/src/ir-to-client-js/safe-html.ts +11 -4
- package/src/ir-to-client-js/stringify/static-array-child-init.ts +30 -12
- package/src/ir-to-client-js/types.ts +23 -0
- package/src/ir-to-client-js/utils.ts +15 -1
- package/src/jsx-to-ir.ts +510 -58
- package/src/nullable-signal-attr.ts +366 -28
- package/src/prop-rewrite.ts +30 -6
- package/src/props-binding.ts +54 -3
- package/src/props-object-whole-read.ts +87 -0
- package/src/rich-type-refusal.ts +2 -1
- package/src/scope/binding-scope.ts +203 -11
- package/src/scope/lexical-scope-walk.ts +4 -3
- package/src/scope/root-prop-alias.ts +23 -0
- package/src/signal-prop-name-collision.ts +113 -22
- package/src/ssr-defaults.ts +10 -4
- package/src/ssr-seed-plan.ts +82 -17
- package/src/strip-types.ts +31 -3
- package/src/template-parts.ts +21 -1
- package/src/template-position-walk.ts +57 -28
- package/src/types.ts +117 -0
package/src/analyzer.ts
CHANGED
|
@@ -9,12 +9,12 @@
|
|
|
9
9
|
import ts from 'typescript'
|
|
10
10
|
import { foldRenderReassignmentsInSource } from './fold-render-reassignments.ts'
|
|
11
11
|
import { CLIENT_DIRECTIVE_INTERIOR_RE, USE_CLIENT_DIRECTIVE, isUseClientDirectiveText } from './directives.ts'
|
|
12
|
-
import type { ImportSpecifier, TypeInfo, ParamInfo, PropDefaultPart, PropDefaultRead, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation, SignalFactoryCall, MemoInfo } from './types.ts'
|
|
12
|
+
import type { ImportSpecifier, TypeInfo, ParamInfo, PropDefaultPart, PropDefaultRead, ReactiveFactoryInfo, DeclinedReactiveFactory, RequiredFactoryImport, FactoryRenameSite, SourceLocation, SignalFactoryCall, MemoInfo, SignalInfo } from './types.ts'
|
|
13
13
|
import { CALLBACK_METHODS, parseExpression, parseBlockBodyTolerant, foldBlockToExpr, tsNodeToParsedExpr, stringifyParsedExpr, type ParsedExpr } from './expression-parser.ts'
|
|
14
14
|
import type { CallbackBodyAcceptor } from './adapters/interface.ts'
|
|
15
15
|
import { collectAssignmentTargets, rewriteBarePropRefs, splitScopedValueRefs } from './prop-rewrite.ts'
|
|
16
16
|
import { isEventHandlerName } from './event-handler-name.ts'
|
|
17
|
-
import { buildPropAliasMap, coalesceDefaultText, livePropReadExpr, signalPropSeed } from './props-binding.ts'
|
|
17
|
+
import { buildPropAliasMap, coalesceDefaultText, livePropReadExpr, signalPropSeed, templatePropReadParams } from './props-binding.ts'
|
|
18
18
|
import { incrementCounter } from './instrumentation.ts'
|
|
19
19
|
import {
|
|
20
20
|
type AnalyzerContext,
|
|
@@ -34,7 +34,11 @@ import { CATALOGUED_RICH_TYPE_NAMES } from './date-lowering.ts'
|
|
|
34
34
|
import path from 'node:path'
|
|
35
35
|
import fs from 'node:fs'
|
|
36
36
|
import { signalSecondBinding } from './signal-initializer.ts'
|
|
37
|
+
import { observesWholePropsObject } from './props-object-whole-read.ts'
|
|
37
38
|
import { separateSignalPropBindings, programWithSeparatedSource } from './signal-prop-name-collision.ts'
|
|
39
|
+
import { isAssignmentTargetIdentifier } from './assignment-target.ts'
|
|
40
|
+
import { addSourceReplacement } from './strip-types.ts'
|
|
41
|
+
import { walkWithScope } from './scope/lexical-scope-walk.ts'
|
|
38
42
|
|
|
39
43
|
// =============================================================================
|
|
40
44
|
// TypeScript Program Creation
|
|
@@ -150,10 +154,26 @@ export function createProgramForFile(
|
|
|
150
154
|
source: string,
|
|
151
155
|
filePath: string,
|
|
152
156
|
hostOptions: { currentDirectory?: string } = {}
|
|
157
|
+
): { program: ts.Program; sourceFile: ts.SourceFile; checker: ts.TypeChecker } | null {
|
|
158
|
+
return buildProgramForFile(source, filePath, hostOptions)
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
/**
|
|
162
|
+
* `createProgramForFile`, plus `sourceFiles`: Programs built one after
|
|
163
|
+
* another share parsed (and bound) SourceFiles through it. Every file the
|
|
164
|
+
* host serves, `source` included, is parsed once per distinct text. Not
|
|
165
|
+
* exported from the package: every Program built here has the same compiler
|
|
166
|
+
* options, which is what makes sharing bound SourceFiles between them safe
|
|
167
|
+
* (see `SourceFileCache`).
|
|
168
|
+
*/
|
|
169
|
+
function buildProgramForFile(
|
|
170
|
+
source: string,
|
|
171
|
+
filePath: string,
|
|
172
|
+
hostOptions: { currentDirectory?: string; sourceFiles?: SourceFileCache },
|
|
153
173
|
): { program: ts.Program; sourceFile: ts.SourceFile; checker: ts.TypeChecker } | null {
|
|
154
174
|
incrementCounter('programCreations')
|
|
155
175
|
try {
|
|
156
|
-
const { currentDirectory } = hostOptions
|
|
176
|
+
const { currentDirectory, sourceFiles } = hostOptions
|
|
157
177
|
const resolveFrom = (fileName: string): string =>
|
|
158
178
|
currentDirectory === undefined ? path.resolve(fileName) : path.resolve(currentDirectory, fileName)
|
|
159
179
|
const normalizedPath = resolveFrom(filePath)
|
|
@@ -176,8 +196,13 @@ export function createProgramForFile(
|
|
|
176
196
|
...(currentDirectory === undefined ? {} : { getCurrentDirectory: () => currentDirectory }),
|
|
177
197
|
getSourceFile(fileName, languageVersion) {
|
|
178
198
|
if (resolveFrom(fileName) === normalizedPath) {
|
|
199
|
+
if (sourceFiles) return sourceFiles.get(fileName, languageVersion, source, VIRTUAL_SOURCE_PARSE)
|
|
179
200
|
return ts.createSourceFile(fileName, source, languageVersion, true, ts.ScriptKind.TSX)
|
|
180
201
|
}
|
|
202
|
+
if (sourceFiles) {
|
|
203
|
+
const text = defaultHost.readFile(fileName)
|
|
204
|
+
return text === undefined ? undefined : sourceFiles.get(fileName, languageVersion, text, DISK_FILE_PARSE)
|
|
205
|
+
}
|
|
181
206
|
return defaultHost.getSourceFile(fileName, languageVersion)
|
|
182
207
|
},
|
|
183
208
|
fileExists(fileName) {
|
|
@@ -232,12 +257,79 @@ function rewriteSourceForAnalysis(
|
|
|
232
257
|
* implementation for every harness that compiles under relative names:
|
|
233
258
|
* the conformance harness (`packages/adapter-tests/src/harness-program.ts`)
|
|
234
259
|
* and the docs-example suite (`doc-examples.test.ts`).
|
|
260
|
+
*
|
|
261
|
+
* Every Program it builds draws on one process-wide `SourceFileCache` that
|
|
262
|
+
* is never evicted, so it suits a test process over a fixed corpus. Do not
|
|
263
|
+
* call it from a long-running watcher.
|
|
235
264
|
*/
|
|
236
265
|
export function createAnchoredProgram(source: string, filename: string, anchorDir: string): ts.Program | undefined {
|
|
237
266
|
if (!needsTypeBasedDetection(source)) return undefined
|
|
238
|
-
return
|
|
267
|
+
return buildProgramForFile(source, filename, { currentDirectory: anchorDir, sourceFiles: anchoredSourceFiles })?.program
|
|
268
|
+
}
|
|
269
|
+
|
|
270
|
+
/**
|
|
271
|
+
* Parsed SourceFiles shared by consecutive Programs, keyed by file name, the
|
|
272
|
+
* parse options the Program asks for, and the text. A file is parsed once per
|
|
273
|
+
* distinct text: a file that changed on disk (a rebuilt `@barefootjs/client`
|
|
274
|
+
* `dist`) is parsed again, never served stale, and the many different sources
|
|
275
|
+
* a harness compiles under one virtual name (`component.tsx`) each keep their
|
|
276
|
+
* own entry.
|
|
277
|
+
*
|
|
278
|
+
* A reused SourceFile also keeps its binding, so a Program built from cached
|
|
279
|
+
* files costs module resolution and checker setup, not a parse of
|
|
280
|
+
* `lib.*.d.ts` and every imported declaration (~430 ms → ~30 ms per Program
|
|
281
|
+
* in the conformance harness, #3666). Sharing SourceFiles between Programs
|
|
282
|
+
* with the same compiler options is how TypeScript's own DocumentRegistry
|
|
283
|
+
* serves language services. The Programs themselves are not shared: a
|
|
284
|
+
* checker assigns type ids in the order it is queried, so one reused across
|
|
285
|
+
* compiles could make a compile's output depend on what ran before it.
|
|
286
|
+
*
|
|
287
|
+
* Only for Programs built with the same compiler options: the cache does not
|
|
288
|
+
* key on them. Entries are never evicted, which suits a test process over a
|
|
289
|
+
* fixed corpus, not a long-running watcher.
|
|
290
|
+
*/
|
|
291
|
+
export class SourceFileCache {
|
|
292
|
+
private readonly files = new Map<string, Map<string, ts.SourceFile>>()
|
|
293
|
+
|
|
294
|
+
get(
|
|
295
|
+
fileName: string,
|
|
296
|
+
languageVersion: ts.ScriptTarget | ts.CreateSourceFileOptions,
|
|
297
|
+
text: string,
|
|
298
|
+
parse: SourceFileParse,
|
|
299
|
+
): ts.SourceFile {
|
|
300
|
+
const key = `${fileName}\0${parseOptionsKey(languageVersion)}\0${parse.scriptKind ?? ''}\0${parse.setParentNodes}`
|
|
301
|
+
let byText = this.files.get(key)
|
|
302
|
+
if (!byText) {
|
|
303
|
+
byText = new Map()
|
|
304
|
+
this.files.set(key, byText)
|
|
305
|
+
}
|
|
306
|
+
const cached = byText.get(text)
|
|
307
|
+
if (cached) return cached
|
|
308
|
+
const parsed = ts.createSourceFile(fileName, text, languageVersion, parse.setParentNodes, parse.scriptKind)
|
|
309
|
+
byText.set(text, parsed)
|
|
310
|
+
return parsed
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
/** How `SourceFileCache` parses a file; part of its key. */
|
|
315
|
+
export interface SourceFileParse {
|
|
316
|
+
scriptKind?: ts.ScriptKind
|
|
317
|
+
setParentNodes: boolean
|
|
318
|
+
}
|
|
319
|
+
|
|
320
|
+
/** The virtual source, parsed as `createProgramForFile` always parsed it. */
|
|
321
|
+
const VIRTUAL_SOURCE_PARSE: SourceFileParse = { scriptKind: ts.ScriptKind.TSX, setParentNodes: true }
|
|
322
|
+
/** A file read from disk, parsed the way the default compiler host parses it. */
|
|
323
|
+
const DISK_FILE_PARSE: SourceFileParse = { setParentNodes: false }
|
|
324
|
+
|
|
325
|
+
function parseOptionsKey(languageVersion: ts.ScriptTarget | ts.CreateSourceFileOptions): string {
|
|
326
|
+
if (typeof languageVersion === 'number') return String(languageVersion)
|
|
327
|
+
return `${languageVersion.languageVersion}:${languageVersion.impliedNodeFormat ?? ''}:${languageVersion.jsDocParsingMode ?? ''}`
|
|
239
328
|
}
|
|
240
329
|
|
|
330
|
+
/** The cache behind every `createAnchoredProgram` Program in this process. */
|
|
331
|
+
const anchoredSourceFiles = new SourceFileCache()
|
|
332
|
+
|
|
241
333
|
/**
|
|
242
334
|
* Parse a signal's initializer into the IR, and record which prop it seeds
|
|
243
335
|
* from and with what fallback (#3508).
|
|
@@ -767,6 +859,7 @@ function analyzeComponentBody(
|
|
|
767
859
|
if (node.parameters.length > 0) {
|
|
768
860
|
extractProps(node.parameters[0], ctx)
|
|
769
861
|
}
|
|
862
|
+
if (ctx.propsObjectName) ctx.propsObjectObservedWhole = observesWholePropsObject(node, ctx.propsObjectName)
|
|
770
863
|
|
|
771
864
|
// Visit component body
|
|
772
865
|
const body = ts.isFunctionDeclaration(node) ? node.body : getArrowFunctionBody(node)
|
|
@@ -848,16 +941,8 @@ function visitComponentBody(node: ts.Node, ctx: AnalyzerContext): void {
|
|
|
848
941
|
if (ts.isIdentifier(decl.name)) {
|
|
849
942
|
const isLet = (node.declarationList.flags & ts.NodeFlags.Let) !== 0
|
|
850
943
|
collectConstant(decl, ctx, false, isLet ? 'let' : 'const')
|
|
851
|
-
} else if (
|
|
852
|
-
|
|
853
|
-
decl.initializer &&
|
|
854
|
-
ts.isIdentifier(decl.initializer) &&
|
|
855
|
-
ctx.propsObjectName === decl.initializer.text
|
|
856
|
-
) {
|
|
857
|
-
// Body-level destructure from `props` — `collectConstant` handles
|
|
858
|
-
// the expansion into one entry per destructured name.
|
|
859
|
-
const isLet = (node.declarationList.flags & ts.NodeFlags.Let) !== 0
|
|
860
|
-
collectConstant(decl, ctx, false, isLet ? 'let' : 'const')
|
|
944
|
+
} else if (ts.isObjectBindingPattern(decl.name)) {
|
|
945
|
+
collectBodyDestructure(decl, node.declarationList.flags, isTopLevel, ctx)
|
|
861
946
|
}
|
|
862
947
|
}
|
|
863
948
|
}
|
|
@@ -1527,37 +1612,29 @@ function collectSignal(node: ts.VariableDeclaration, ctx: AnalyzerContext): void
|
|
|
1527
1612
|
// the binding actually in scope rather than a hardcoded canonical name (#2057).
|
|
1528
1613
|
const envFactory = envReader ? callExpr.expression.getText(ctx.sourceFile) : undefined
|
|
1529
1614
|
|
|
1530
|
-
//
|
|
1531
|
-
//
|
|
1532
|
-
//
|
|
1533
|
-
// `template:` arrow's module-scope SSR fallback —
|
|
1534
|
-
// closure over `initXxx`'s `const size = _p.size`
|
|
1535
|
-
//
|
|
1536
|
-
|
|
1537
|
-
|
|
1538
|
-
if (!ctx.propsObjectName && callExpr.arguments[0]) {
|
|
1539
|
-
const propNames = new Set(ctx.propsParams.map(p => p.name))
|
|
1540
|
-
if (propNames.size > 0) {
|
|
1541
|
-
const propAliases = buildPropAliasMap(ctx.propsParams)
|
|
1542
|
-
templateInitialValue = rewriteBarePropRefs(initialValue, callExpr.arguments[0], propNames, undefined, propAliases, destructuredPropTemplateRead(ctx))
|
|
1543
|
-
}
|
|
1544
|
-
}
|
|
1545
|
-
|
|
1546
|
-
ctx.signals.push({
|
|
1615
|
+
// A signal's initial value referencing a bare destructured prop
|
|
1616
|
+
// (`createSignal(size ?? 1)` with `{ size }: { size?: number }`, #2265,
|
|
1617
|
+
// or a `(props)`-arg component's body destructure binding) needs
|
|
1618
|
+
// `_p.size` for the CSR `template:` arrow's module-scope SSR fallback —
|
|
1619
|
+
// that arrow isn't a closure over `initXxx`'s `const size = _p.size`
|
|
1620
|
+
// extraction (`deferTemplatePropRead`).
|
|
1621
|
+
const seedNode = callExpr.arguments[0]
|
|
1622
|
+
const signal: SignalInfo = {
|
|
1547
1623
|
getter,
|
|
1548
1624
|
setter,
|
|
1549
1625
|
getterElided: getterElided || undefined,
|
|
1550
1626
|
initialValue,
|
|
1551
1627
|
typedInitialValue: typedInitialValue !== initialValue ? typedInitialValue : undefined,
|
|
1552
|
-
templateInitialValue,
|
|
1553
1628
|
type,
|
|
1554
1629
|
loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
|
|
1555
|
-
initialFreeIdentifiers:
|
|
1556
|
-
? extractFreeIdentifiersFromNode(
|
|
1630
|
+
initialFreeIdentifiers: seedNode
|
|
1631
|
+
? extractFreeIdentifiersFromNode(seedNode)
|
|
1557
1632
|
: new Set(),
|
|
1558
1633
|
envReader,
|
|
1559
1634
|
envFactory,
|
|
1560
|
-
}
|
|
1635
|
+
}
|
|
1636
|
+
ctx.signals.push(signal)
|
|
1637
|
+
if (seedNode) deferTemplatePropRead(initialValue, seedNode, ctx, text => { signal.templateInitialValue = text })
|
|
1561
1638
|
}
|
|
1562
1639
|
|
|
1563
1640
|
/**
|
|
@@ -1623,28 +1700,15 @@ function collectFactorySignal(
|
|
|
1623
1700
|
type = inferTypeFromValue(initialValue)
|
|
1624
1701
|
}
|
|
1625
1702
|
|
|
1626
|
-
// Destructured-arg components (#2265): the CSR `template:` arrow's
|
|
1627
|
-
// module-scope fallback needs `_p.<name>` for a bare destructured prop in
|
|
1628
|
-
// `initial`, same as a `createSignal` initial value.
|
|
1629
|
-
let templateInitialValue: string | undefined
|
|
1630
|
-
if (!ctx.propsObjectName && initialNode.kind === 'expression') {
|
|
1631
|
-
const propNames = new Set(ctx.propsParams.map(p => p.name))
|
|
1632
|
-
if (propNames.size > 0) {
|
|
1633
|
-
const propAliases = buildPropAliasMap(ctx.propsParams)
|
|
1634
|
-
templateInitialValue = rewriteBarePropRefs(initialValue, initialNode.node, propNames, undefined, propAliases, destructuredPropTemplateRead(ctx))
|
|
1635
|
-
}
|
|
1636
|
-
}
|
|
1637
|
-
|
|
1638
1703
|
const argTexts = callExpr.arguments.map(arg => ctx.getJS(arg))
|
|
1639
1704
|
const requestArg = callExpr.arguments[0]
|
|
1640
1705
|
|
|
1641
|
-
|
|
1706
|
+
const signal: SignalInfo = {
|
|
1642
1707
|
getter: valueName ?? `__bfGet_${action}`,
|
|
1643
1708
|
setter: null,
|
|
1644
1709
|
getterElided: getterElided || undefined,
|
|
1645
1710
|
initialValue,
|
|
1646
1711
|
typedInitialValue: typedInitialValue !== undefined && typedInitialValue !== initialValue ? typedInitialValue : undefined,
|
|
1647
|
-
templateInitialValue,
|
|
1648
1712
|
type,
|
|
1649
1713
|
loc: getSourceLocation(node, ctx.sourceFile, ctx.filePath),
|
|
1650
1714
|
initialFreeIdentifiers,
|
|
@@ -1656,7 +1720,14 @@ function collectFactorySignal(
|
|
|
1656
1720
|
requestFreeIdentifiers: requestArg ? extractFreeIdentifiersFromNode(requestArg) : new Set(),
|
|
1657
1721
|
action,
|
|
1658
1722
|
},
|
|
1659
|
-
}
|
|
1723
|
+
}
|
|
1724
|
+
ctx.signals.push(signal)
|
|
1725
|
+
// The CSR `template:` arrow's module-scope fallback needs `_p.<name>` for
|
|
1726
|
+
// a bare destructured prop in `initial`, same as a `createSignal` initial
|
|
1727
|
+
// value (#2265).
|
|
1728
|
+
if (initialNode.kind === 'expression') {
|
|
1729
|
+
deferTemplatePropRead(initialValue, initialNode.node, ctx, text => { signal.templateInitialValue = text })
|
|
1730
|
+
}
|
|
1660
1731
|
}
|
|
1661
1732
|
|
|
1662
1733
|
/**
|
|
@@ -2062,33 +2133,33 @@ function memoStructuredBody(
|
|
|
2062
2133
|
}
|
|
2063
2134
|
|
|
2064
2135
|
/**
|
|
2065
|
-
* `MemoInfo.bodyExpr` / `bodyExprIsCall`
|
|
2066
|
-
*
|
|
2136
|
+
* `MemoInfo.bodyExpr` / `bodyExprIsCall` from the callback's body node
|
|
2137
|
+
* (#3510).
|
|
2067
2138
|
*/
|
|
2068
2139
|
function memoBodyFields(
|
|
2069
2140
|
body: { node: ts.Node; call: boolean },
|
|
2070
2141
|
ctx: AnalyzerContext,
|
|
2071
|
-
): Pick<MemoInfo, 'bodyExpr' | 'bodyExprIsCall'
|
|
2072
|
-
|
|
2073
|
-
|
|
2074
|
-
|
|
2075
|
-
|
|
2076
|
-
|
|
2077
|
-
|
|
2078
|
-
|
|
2079
|
-
|
|
2080
|
-
|
|
2081
|
-
|
|
2082
|
-
|
|
2083
|
-
|
|
2084
|
-
|
|
2085
|
-
|
|
2086
|
-
|
|
2087
|
-
|
|
2088
|
-
|
|
2089
|
-
|
|
2090
|
-
|
|
2091
|
-
|
|
2142
|
+
): Pick<MemoInfo, 'bodyExpr' | 'bodyExprIsCall'> {
|
|
2143
|
+
return { bodyExpr: asMemoBodyExpr(ctx.getJS(body.node), body.call), bodyExprIsCall: body.call || undefined }
|
|
2144
|
+
}
|
|
2145
|
+
|
|
2146
|
+
function asMemoBodyExpr(text: string, call: boolean): string {
|
|
2147
|
+
return call ? `(${text})()` : text
|
|
2148
|
+
}
|
|
2149
|
+
|
|
2150
|
+
/**
|
|
2151
|
+
* `MemoInfo.templateBodyExpr`: the memo twin of the signal
|
|
2152
|
+
* `templateInitialValue` rewrite (#2265). A memo body referencing a bare
|
|
2153
|
+
* destructured prop (`createMemo(() => value * 10)` with
|
|
2154
|
+
* `{ value }: { value: number }`) is inlined into the CSR `template:` arrow
|
|
2155
|
+
* by `buildSignalMemoEnv`, and that arrow runs at module scope — it is not a
|
|
2156
|
+
* closure over `initXxx`'s `const value = _p.value` extraction, so the bare
|
|
2157
|
+
* ref must become `_p.value` (adapter-tests scope-gate, #2468 sweep).
|
|
2158
|
+
*/
|
|
2159
|
+
function deferMemoTemplateBody(memo: MemoInfo, body: { node: ts.Node; call: boolean }, ctx: AnalyzerContext): void {
|
|
2160
|
+
deferTemplatePropRead(ctx.getJS(body.node), body.node, ctx, text => {
|
|
2161
|
+
memo.templateBodyExpr = text === undefined ? undefined : asMemoBodyExpr(text, body.call)
|
|
2162
|
+
})
|
|
2092
2163
|
}
|
|
2093
2164
|
|
|
2094
2165
|
function collectMemo(node: ts.VariableDeclaration, ctx: AnalyzerContext): void {
|
|
@@ -2169,6 +2240,7 @@ function collectMemo(node: ts.VariableDeclaration, ctx: AnalyzerContext): void {
|
|
|
2169
2240
|
: new Set(),
|
|
2170
2241
|
}
|
|
2171
2242
|
ctx.memos.push(memo)
|
|
2243
|
+
if (body) deferMemoTemplateBody(memo, body, ctx)
|
|
2172
2244
|
markBlockMemo(memo, blockTyped, body?.node, ctx)
|
|
2173
2245
|
}
|
|
2174
2246
|
|
|
@@ -3676,6 +3748,32 @@ function destructuredPropTemplateRead(ctx: AnalyzerContext): (localName: string,
|
|
|
3676
3748
|
return (localName, callerKey) => livePropReadExpr(byName.get(localName) ?? { name: localName, sourceName: callerKey }, undefined, false)
|
|
3677
3749
|
}
|
|
3678
3750
|
|
|
3751
|
+
/**
|
|
3752
|
+
* Queue the client template text of a signal seed or memo body: `text` (the
|
|
3753
|
+
* source of `node`) with each read of a props binding the template reads live
|
|
3754
|
+
* (`templatePropReadParams`) rewritten to that read, or undefined when it
|
|
3755
|
+
* reads none, handed to `write` by `writeTemplatePropReads`. In a
|
|
3756
|
+
* `(props)`-arg component such a binding is a body destructure binding holding
|
|
3757
|
+
* its prop (`const { b: local = d } = props`), so a memo over it reads the
|
|
3758
|
+
* default just as markup does. The set is decided once the whole body is
|
|
3759
|
+
* walked: a binding written later no longer holds its prop, and a local
|
|
3760
|
+
* function or constant declared later keeps its own meaning.
|
|
3761
|
+
*/
|
|
3762
|
+
function deferTemplatePropRead(text: string, node: ts.Node, ctx: AnalyzerContext, write: (text: string | undefined) => void): void {
|
|
3763
|
+
ctx.templatePropReadWriters.push(() => {
|
|
3764
|
+
const readable = templatePropReadParams(ctx)
|
|
3765
|
+
if (readable.length === 0) return
|
|
3766
|
+
const propNames = new Set(readable.map(p => p.name))
|
|
3767
|
+
write(rewriteBarePropRefs(text, node, propNames, undefined, buildPropAliasMap(readable), destructuredPropTemplateRead(ctx)))
|
|
3768
|
+
})
|
|
3769
|
+
}
|
|
3770
|
+
|
|
3771
|
+
/** Run the writers `deferTemplatePropRead` queued, against the walked body. */
|
|
3772
|
+
function writeTemplatePropReads(ctx: AnalyzerContext): void {
|
|
3773
|
+
for (const write of ctx.templatePropReadWriters) write()
|
|
3774
|
+
ctx.templatePropReadWriters.length = 0
|
|
3775
|
+
}
|
|
3776
|
+
|
|
3679
3777
|
/**
|
|
3680
3778
|
* The default-value-shaped fields a binding element's own `initializer`
|
|
3681
3779
|
* contributes to a `ParamInfo` — `defaultValue`'s source text, `parsed`'s
|
|
@@ -3690,10 +3788,11 @@ function bindingElementDefaultFields(
|
|
|
3690
3788
|
initializer: ts.Expression | undefined,
|
|
3691
3789
|
ctx: AnalyzerContext,
|
|
3692
3790
|
earlier: ReadonlyMap<string, PropDefaultRead> = new Map(),
|
|
3693
|
-
): Pick<ParamInfo, 'defaultValue' | 'parsed' | 'defaultContainsArrow' | 'defaultParts'> {
|
|
3791
|
+
): Pick<ParamInfo, 'defaultValue' | 'parsed' | 'defaultContainsArrow' | 'defaultFreeIdentifiers' | 'defaultParts'> {
|
|
3694
3792
|
const defaultValue = initializer ? ctx.getJS(initializer) : undefined
|
|
3695
3793
|
const defaultContainsArrow = initializer ? nodeContainsArrow(initializer) : false
|
|
3696
3794
|
const parsedDefault = initializer ? tsNodeToParsedExpr(initializer) : undefined
|
|
3795
|
+
const defaultFreeIdentifiers = initializer ? [...extractFreeIdentifiersFromNode(initializer)] : []
|
|
3697
3796
|
const defaultParts = initializer && defaultValue !== undefined
|
|
3698
3797
|
? defaultPartsReadingEarlierBindings(initializer, defaultValue, earlier)
|
|
3699
3798
|
: undefined
|
|
@@ -3701,6 +3800,7 @@ function bindingElementDefaultFields(
|
|
|
3701
3800
|
defaultValue,
|
|
3702
3801
|
...(parsedDefault && parsedDefault.kind !== 'unsupported' && { parsed: parsedDefault }),
|
|
3703
3802
|
defaultContainsArrow: defaultContainsArrow || undefined,
|
|
3803
|
+
...(defaultFreeIdentifiers.length > 0 && { defaultFreeIdentifiers }),
|
|
3704
3804
|
...(defaultParts && { defaultParts }),
|
|
3705
3805
|
}
|
|
3706
3806
|
}
|
|
@@ -3732,6 +3832,418 @@ function defaultPartsReadingEarlierBindings(
|
|
|
3732
3832
|
)
|
|
3733
3833
|
}
|
|
3734
3834
|
|
|
3835
|
+
/**
|
|
3836
|
+
* Whether `decl` is a component-body object destructure of the props object
|
|
3837
|
+
* (`const { x } = props`) — the one decision both `visitComponentBody` and
|
|
3838
|
+
* `collectConstant` use to expand it into per-name prop reads.
|
|
3839
|
+
*
|
|
3840
|
+
* The initializer may also be a component-scope `const` alias of the props
|
|
3841
|
+
* object (`const p = props; const { x } = p`, transitively). Anything else
|
|
3842
|
+
* is NOT the props object. The alias is resolved from real bindings: the
|
|
3843
|
+
* alias declaration and the destructure must both be direct statements of
|
|
3844
|
+
* the component body (no nested block can shadow the alias between them),
|
|
3845
|
+
* and the alias must be declared before the destructure. A `let` alias is
|
|
3846
|
+
* refused, since a reassignment can make it name another object. Any alias
|
|
3847
|
+
* is refused when the props parameter itself is assigned anywhere in the
|
|
3848
|
+
* body (`props = …`): the alias keeps the object it captured, so it may no
|
|
3849
|
+
* longer be what `props` names.
|
|
3850
|
+
*/
|
|
3851
|
+
function destructuresPropsObject(
|
|
3852
|
+
decl: ts.VariableDeclaration,
|
|
3853
|
+
ctx: AnalyzerContext,
|
|
3854
|
+
): decl is ts.VariableDeclaration & { name: ts.ObjectBindingPattern; initializer: ts.Expression } {
|
|
3855
|
+
if (!ts.isObjectBindingPattern(decl.name) || !decl.initializer || ctx.propsObjectName === null) return false
|
|
3856
|
+
return isPropsObjectReference(decl.initializer, decl, ctx, new Set())
|
|
3857
|
+
}
|
|
3858
|
+
|
|
3859
|
+
function isPropsObjectReference(
|
|
3860
|
+
expr: ts.Expression,
|
|
3861
|
+
use: ts.VariableDeclaration,
|
|
3862
|
+
ctx: AnalyzerContext,
|
|
3863
|
+
visiting: Set<ts.VariableDeclaration>,
|
|
3864
|
+
): boolean {
|
|
3865
|
+
if (!ts.isIdentifier(expr)) return false
|
|
3866
|
+
if (expr.text === ctx.propsObjectName) return true
|
|
3867
|
+
const body = ctx.componentBodyBlock
|
|
3868
|
+
if (body === null || !isComponentBodyStatementDeclaration(use, body)) return false
|
|
3869
|
+
// A const alias keeps the object it captured, but the props parameter can
|
|
3870
|
+
// be reassigned after the capture. Then the alias is not the props object.
|
|
3871
|
+
if (assignsIdentifier(body, ctx.propsObjectName)) return false
|
|
3872
|
+
const alias = componentConstDeclaration(expr.text, body)
|
|
3873
|
+
if (alias === null || alias.pos >= use.pos || visiting.has(alias) || !alias.initializer) return false
|
|
3874
|
+
visiting.add(alias)
|
|
3875
|
+
return isPropsObjectReference(alias.initializer, alias, ctx, visiting)
|
|
3876
|
+
}
|
|
3877
|
+
|
|
3878
|
+
/**
|
|
3879
|
+
* Whether anything under `root` writes the identifier `name`, by the shared
|
|
3880
|
+
* assignment-target rule (`isAssignmentTargetIdentifier`): an assignment or
|
|
3881
|
+
* compound assignment, `++` / `--`, a destructuring-assignment target or a
|
|
3882
|
+
* `for (… of / in …)` head. Conservative: a nested binding that shadows
|
|
3883
|
+
* `name` counts too.
|
|
3884
|
+
*/
|
|
3885
|
+
function assignsIdentifier(root: ts.Node, name: string | null): boolean {
|
|
3886
|
+
if (name === null) return false
|
|
3887
|
+
let found = false
|
|
3888
|
+
const visit = (node: ts.Node): void => {
|
|
3889
|
+
if (found) return
|
|
3890
|
+
if (ts.isIdentifier(node) && node.text === name && isAssignmentTargetIdentifier(node)) {
|
|
3891
|
+
found = true
|
|
3892
|
+
return
|
|
3893
|
+
}
|
|
3894
|
+
ts.forEachChild(node, visit)
|
|
3895
|
+
}
|
|
3896
|
+
visit(root)
|
|
3897
|
+
return found
|
|
3898
|
+
}
|
|
3899
|
+
|
|
3900
|
+
/** Whether `decl` belongs to a variable statement that is a direct child of `body`. */
|
|
3901
|
+
function isComponentBodyStatementDeclaration(decl: ts.VariableDeclaration, body: ts.Block): boolean {
|
|
3902
|
+
const statement = decl.parent?.parent
|
|
3903
|
+
return statement !== undefined && ts.isVariableStatement(statement) && statement.parent === body
|
|
3904
|
+
}
|
|
3905
|
+
|
|
3906
|
+
/** The `const <name> = …` declaration among `body`'s direct statements, or null. */
|
|
3907
|
+
function componentConstDeclaration(name: string, body: ts.Block): ts.VariableDeclaration | null {
|
|
3908
|
+
for (const stmt of body.statements) {
|
|
3909
|
+
if (!ts.isVariableStatement(stmt)) continue
|
|
3910
|
+
for (const d of stmt.declarationList.declarations) {
|
|
3911
|
+
if (!ts.isIdentifier(d.name) || d.name.text !== name) continue
|
|
3912
|
+
return (stmt.declarationList.flags & ts.NodeFlags.Const) !== 0 ? d : null
|
|
3913
|
+
}
|
|
3914
|
+
}
|
|
3915
|
+
return null
|
|
3916
|
+
}
|
|
3917
|
+
|
|
3918
|
+
/**
|
|
3919
|
+
* The rest element of a component-body destructure of the props object
|
|
3920
|
+
* (`const { label, ...rest } = props`): it binds the component's rest props
|
|
3921
|
+
* exactly as a signature rest (`({ label, ...rest })`) does, so it is
|
|
3922
|
+
* recorded the same way: `restPropsName`, and the closed-type keys it
|
|
3923
|
+
* holds (`restPropsExpandedKeys`), which are the props type's keys minus the
|
|
3924
|
+
* ones the destructure takes. `restPropsOmittedKeys` records those taken
|
|
3925
|
+
* keys for a backend that runs the body as JS. A component already holding
|
|
3926
|
+
* a rest binding keeps it.
|
|
3927
|
+
*/
|
|
3928
|
+
function collectBodyRestBinding(pattern: ts.ObjectBindingPattern, ctx: AnalyzerContext): void {
|
|
3929
|
+
const restElement = pattern.elements.find(el => el.dotDotDotToken)
|
|
3930
|
+
if (!restElement || !ts.isIdentifier(restElement.name) || ctx.restPropsName !== null) return
|
|
3931
|
+
const restName = restElement.name.text
|
|
3932
|
+
const taken: string[] = []
|
|
3933
|
+
for (const el of pattern.elements) {
|
|
3934
|
+
if (el.dotDotDotToken) continue
|
|
3935
|
+
const key = bindingElementKey(el)
|
|
3936
|
+
if (key !== null) taken.push(key)
|
|
3937
|
+
}
|
|
3938
|
+
ctx.restPropsName = restName
|
|
3939
|
+
ctx.restPropsOmittedKeys = taken
|
|
3940
|
+
const param = ctx.componentNode?.parameters[0]
|
|
3941
|
+
const allKeys = param?.type ? collectTypeKeys(param.type, ctx) : null
|
|
3942
|
+
if (allKeys) ctx.restPropsExpandedKeys = allKeys.filter(k => !taken.includes(k))
|
|
3943
|
+
respellBodyRestMemberReads(restName, taken, ctx)
|
|
3944
|
+
}
|
|
3945
|
+
|
|
3946
|
+
/**
|
|
3947
|
+
* Respell each member read of a props-object body rest (`const { label,
|
|
3948
|
+
* ...rest } = props`, `rest.id`) as the read of the props object it is
|
|
3949
|
+
* (#3854): the rest holds the props object's keys minus the ones the
|
|
3950
|
+
* destructure takes, so `rest.id` reads `props.id`; a read of a taken key
|
|
3951
|
+
* (`rest.label`) is refused ({@link refuseTakenKeyRestRead}). Every backend
|
|
3952
|
+
* then reads it as it reads the props object: a template binds each
|
|
3953
|
+
* declared prop as its own variable, while its rest bag holds only the keys
|
|
3954
|
+
* the props type does not declare, so the read can't go to the bag.
|
|
3955
|
+
*
|
|
3956
|
+
* Decided here, where the rest is recorded, and spelled through `getJS`
|
|
3957
|
+
* (`addSourceReplacement`): every expression, const and handler built from
|
|
3958
|
+
* the source afterwards carries the respelled read. Only a read the rest
|
|
3959
|
+
* binding reaches is respelled: not one a nested binding of the same name
|
|
3960
|
+
* shadows (`items.map(rest => rest.id)`, `walkWithScope`), not an
|
|
3961
|
+
* assignment target, and not a key the props type does not declare (that
|
|
3962
|
+
* one stays a read of the rest bag, which holds it). A read where a nested
|
|
3963
|
+
* binding shadows the props object's name is refused
|
|
3964
|
+
* ({@link refuseRestReadUnderShadowedProps}).
|
|
3965
|
+
*/
|
|
3966
|
+
function respellBodyRestMemberReads(restName: string, taken: readonly string[], ctx: AnalyzerContext): void {
|
|
3967
|
+
const body = ctx.componentBodyBlock
|
|
3968
|
+
const propsName = ctx.propsObjectName
|
|
3969
|
+
if (body === null || propsName === null) return
|
|
3970
|
+
const declared = new Set([...ctx.restPropsExpandedKeys, ...taken])
|
|
3971
|
+
for (const stmt of body.statements) {
|
|
3972
|
+
walkWithScope(stmt, (ident, parent, shadowed, isShadowed) => {
|
|
3973
|
+
if (shadowed || ident.text !== restName || parent === undefined) return
|
|
3974
|
+
const key = restMemberReadKey(ident, parent)
|
|
3975
|
+
if (key === null || !declared.has(key) || isWrittenAccess(parent)) return
|
|
3976
|
+
if (taken.includes(key)) {
|
|
3977
|
+
refuseTakenKeyRestRead(parent, restName, key, ctx)
|
|
3978
|
+
return
|
|
3979
|
+
}
|
|
3980
|
+
if (isShadowed(propsName)) {
|
|
3981
|
+
refuseRestReadUnderShadowedProps(parent, propsName, ctx)
|
|
3982
|
+
return
|
|
3983
|
+
}
|
|
3984
|
+
addSourceReplacement(ctx.typeExcludeRanges, { start: parent.getStart(ctx.sourceFile), end: parent.getEnd(), replacement: propsMemberRead(propsName, key) })
|
|
3985
|
+
})
|
|
3986
|
+
}
|
|
3987
|
+
}
|
|
3988
|
+
|
|
3989
|
+
/**
|
|
3990
|
+
* BF101 for a read through a props-object body rest of a key the same
|
|
3991
|
+
* destructure takes (`const { label, ...rest } = props`, `rest.label`):
|
|
3992
|
+
* the rest never holds it, so the read is always `undefined`. No backend
|
|
3993
|
+
* spells a bare `undefined` read the way JS renders it, so the read is
|
|
3994
|
+
* refused rather than respelled ({@link respellBodyRestMemberReads}).
|
|
3995
|
+
*/
|
|
3996
|
+
function refuseTakenKeyRestRead(access: ts.Node, restName: string, key: string, ctx: AnalyzerContext): void {
|
|
3997
|
+
ctx.errors.push({
|
|
3998
|
+
code: 'BF101',
|
|
3999
|
+
severity: 'error',
|
|
4000
|
+
message: `\`${access.getText(ctx.sourceFile)}\` reads '${key}' through the rest \`${restName}\`, but the same destructure takes '${key}', so the rest never holds it and the read is always undefined.`,
|
|
4001
|
+
loc: getSourceLocation(access, ctx.sourceFile, ctx.filePath),
|
|
4002
|
+
suggestion: { message: `Read the destructured '${key}' binding instead, or drop the read.` },
|
|
4003
|
+
})
|
|
4004
|
+
}
|
|
4005
|
+
|
|
4006
|
+
/**
|
|
4007
|
+
* BF101 for a read through a props-object body rest where a nested binding
|
|
4008
|
+
* shadows the props object's name (`rows.map(props => rest.id)`): the read
|
|
4009
|
+
* would be respelled `props.id`, which there names the nested binding, and
|
|
4010
|
+
* no other spelling reaches the component's prop on every backend
|
|
4011
|
+
* ({@link respellBodyRestMemberReads}).
|
|
4012
|
+
*/
|
|
4013
|
+
function refuseRestReadUnderShadowedProps(access: ts.Node, propsName: string, ctx: AnalyzerContext): void {
|
|
4014
|
+
ctx.errors.push({
|
|
4015
|
+
code: 'BF101',
|
|
4016
|
+
severity: 'error',
|
|
4017
|
+
message: `\`${access.getText(ctx.sourceFile)}\` reads the component's props through a rest, inside a binding that shadows the props object's name \`${propsName}\`, so the read has no spelling that reaches the component's prop.`,
|
|
4018
|
+
loc: getSourceLocation(access, ctx.sourceFile, ctx.filePath),
|
|
4019
|
+
suggestion: { message: `Rename the inner \`${propsName}\` binding, or read the value into a const outside it.` },
|
|
4020
|
+
})
|
|
4021
|
+
}
|
|
4022
|
+
|
|
4023
|
+
/** The key `parent` reads off `ident` (`ident.key`, `ident?.key`, `ident['key']`), or null when `parent` is no such read. */
|
|
4024
|
+
function restMemberReadKey(ident: ts.Identifier, parent: ts.Node): string | null {
|
|
4025
|
+
if (ts.isPropertyAccessExpression(parent) && parent.expression === ident && ts.isIdentifier(parent.name)) return parent.name.text
|
|
4026
|
+
if (ts.isElementAccessExpression(parent) && parent.expression === ident && ts.isStringLiteralLike(parent.argumentExpression)) {
|
|
4027
|
+
return parent.argumentExpression.text
|
|
4028
|
+
}
|
|
4029
|
+
return null
|
|
4030
|
+
}
|
|
4031
|
+
|
|
4032
|
+
/** Whether the member access `access` is written (`a.b = 1`, `a.b += 1`, `a.b++`, `delete a.b`) rather than read. */
|
|
4033
|
+
function isWrittenAccess(access: ts.Node): boolean {
|
|
4034
|
+
const parent = access.parent
|
|
4035
|
+
if (ts.isBinaryExpression(parent)) {
|
|
4036
|
+
const op = parent.operatorToken.kind
|
|
4037
|
+
return parent.left === access && op >= ts.SyntaxKind.FirstAssignment && op <= ts.SyntaxKind.LastAssignment
|
|
4038
|
+
}
|
|
4039
|
+
if (ts.isPrefixUnaryExpression(parent) || ts.isPostfixUnaryExpression(parent)) {
|
|
4040
|
+
return parent.operator === ts.SyntaxKind.PlusPlusToken || parent.operator === ts.SyntaxKind.MinusMinusToken
|
|
4041
|
+
}
|
|
4042
|
+
return ts.isDeleteExpression(parent)
|
|
4043
|
+
}
|
|
4044
|
+
|
|
4045
|
+
/** `props.key`, or `props["key"]` for a key that is not an identifier. */
|
|
4046
|
+
function propsMemberRead(propsName: string, key: string): string {
|
|
4047
|
+
return isIdentifierName(key) ? `${propsName}.${key}` : `${propsName}[${JSON.stringify(key)}]`
|
|
4048
|
+
}
|
|
4049
|
+
|
|
4050
|
+
/** The property key a binding element reads (`{ a }`, `{ a: b }`, `{ 'a-b': c }`), or null for a computed key. */
|
|
4051
|
+
function bindingElementKey(el: ts.BindingElement): string | null {
|
|
4052
|
+
const name = el.propertyName ?? el.name
|
|
4053
|
+
if (ts.isIdentifier(name) || ts.isStringLiteral(name)) return name.text
|
|
4054
|
+
return null
|
|
4055
|
+
}
|
|
4056
|
+
|
|
4057
|
+
/**
|
|
4058
|
+
* A component-body object destructure. One of the props object (or a
|
|
4059
|
+
* component-scope `const` alias of it) — `collectConstant` expands it into
|
|
4060
|
+
* one entry per destructured name. A top-level `const` one of another const
|
|
4061
|
+
* object — {@link collectConstDestructure}. Any other top-level one binds
|
|
4062
|
+
* names nothing declares, so it is refused ({@link refuseBodyDestructure}).
|
|
4063
|
+
*/
|
|
4064
|
+
function collectBodyDestructure(decl: ts.VariableDeclaration, flags: ts.NodeFlags, isTopLevel: boolean, ctx: AnalyzerContext): void {
|
|
4065
|
+
if (destructuresPropsObject(decl, ctx)) {
|
|
4066
|
+
collectConstant(decl, ctx, false, (flags & ts.NodeFlags.Let) !== 0 ? 'let' : 'const')
|
|
4067
|
+
} else if (isTopLevel && !((flags & ts.NodeFlags.Const) !== 0 && collectConstDestructure(decl, ctx))) {
|
|
4068
|
+
refuseBodyDestructure(decl, flags, ctx)
|
|
4069
|
+
}
|
|
4070
|
+
}
|
|
4071
|
+
|
|
4072
|
+
/**
|
|
4073
|
+
* BF101 for a component-body object destructure no backend binds (#3854):
|
|
4074
|
+
* a `let` one, one whose source is not an identifier naming a const object
|
|
4075
|
+
* (`getConf()`, `props.nested`, an imported name), or one with an element
|
|
4076
|
+
* that has no const form (a rest element, a non-literal default, a computed
|
|
4077
|
+
* key). The compiler rebuilds the body from what it collects, so such a
|
|
4078
|
+
* statement used to be dropped, leaving its names unbound in every output.
|
|
4079
|
+
*/
|
|
4080
|
+
function refuseBodyDestructure(decl: ts.VariableDeclaration, flags: ts.NodeFlags, ctx: AnalyzerContext): void {
|
|
4081
|
+
ctx.errors.push({
|
|
4082
|
+
code: 'BF101',
|
|
4083
|
+
severity: 'error',
|
|
4084
|
+
message: `The destructure \`${decl.getText(ctx.sourceFile)}\` has no compiled form: ${bodyDestructureRefusalReason(decl, flags, ctx)}.`,
|
|
4085
|
+
loc: getSourceLocation(decl, ctx.sourceFile, ctx.filePath),
|
|
4086
|
+
suggestion: {
|
|
4087
|
+
message:
|
|
4088
|
+
'Destructure the props object or a `const` object declared before it, with plain or literal-defaulted elements; or read the values directly (`const a = getConf().a`).',
|
|
4089
|
+
},
|
|
4090
|
+
})
|
|
4091
|
+
}
|
|
4092
|
+
|
|
4093
|
+
/** Why {@link refuseBodyDestructure} refuses `decl`, for its message. */
|
|
4094
|
+
function bodyDestructureRefusalReason(decl: ts.VariableDeclaration, flags: ts.NodeFlags, ctx: AnalyzerContext): string {
|
|
4095
|
+
if ((flags & ts.NodeFlags.Const) === 0) return 'only a `const` destructure is collected'
|
|
4096
|
+
let source: ts.Expression | undefined = decl.initializer
|
|
4097
|
+
while (source && ts.isParenthesizedExpression(source)) source = source.expression
|
|
4098
|
+
if (!source || !ts.isIdentifier(source)) return 'its source is not a plain name'
|
|
4099
|
+
if (!isConstObjectSource(source.text, decl, ctx)) return `\`${source.text}\` is not the props object or a \`const\` object declared before it`
|
|
4100
|
+
return 'an element is a rest element, has a non-literal default, or has a computed key'
|
|
4101
|
+
}
|
|
4102
|
+
|
|
4103
|
+
/**
|
|
4104
|
+
* A component-body `const` object destructure of a const object or of the
|
|
4105
|
+
* rest props (`const conf = { tone: 'info' }; const { tone } = conf`,
|
|
4106
|
+
* `const { tone } = rest`, `const { a: { b } } = MODULE_CONF`). It binds
|
|
4107
|
+
* each name to the path it reads off the source, so it is collected as one
|
|
4108
|
+
* const per binding, exactly as if the source had written
|
|
4109
|
+
* `const tone = conf.tone`: every backend then reads it through the same
|
|
4110
|
+
* const handling as any other computed const, instead of reading a name
|
|
4111
|
+
* nothing declares.
|
|
4112
|
+
*
|
|
4113
|
+
* The source is an identifier the destructure statement sees as a const
|
|
4114
|
+
* object: the rest props binding, a component-body `const` declared before
|
|
4115
|
+
* the statement, or a module `const` no component binding shadows. A binding
|
|
4116
|
+
* element may rename (`{ tone: t }`), nest an object pattern, or default to
|
|
4117
|
+
* a literal (`{ tone = 'x' }` reads `conf.tone === undefined ? 'x' :
|
|
4118
|
+
* conf.tone`). False, collecting nothing, for any other source or a
|
|
4119
|
+
* statement with any other element (a rest element, a computed key, an
|
|
4120
|
+
* array pattern, a non-literal default); the caller refuses it.
|
|
4121
|
+
*/
|
|
4122
|
+
function collectConstDestructure(decl: ts.VariableDeclaration, ctx: AnalyzerContext): boolean {
|
|
4123
|
+
if (!ts.isObjectBindingPattern(decl.name) || !decl.initializer) return false
|
|
4124
|
+
let source: ts.Expression = decl.initializer
|
|
4125
|
+
while (ts.isParenthesizedExpression(source)) source = source.expression
|
|
4126
|
+
if (!ts.isIdentifier(source) || !isConstObjectSource(source.text, decl, ctx)) return false
|
|
4127
|
+
// A rest a body destructure of the props object binds holds the props
|
|
4128
|
+
// object's keys minus the ones that destructure takes: its key reads are
|
|
4129
|
+
// the props object's, and a taken key reads `undefined`.
|
|
4130
|
+
const bodyRest = source.text === ctx.restPropsName && ctx.restPropsOmittedKeys && ctx.propsObjectName
|
|
4131
|
+
const path = bodyRest ? ctx.propsObjectName! : source.text
|
|
4132
|
+
const bindings: ConstDestructureBinding[] = []
|
|
4133
|
+
if (!collectConstDestructureBindings(decl.name, path, bindings)) return false
|
|
4134
|
+
const loc = getSourceLocation(decl, ctx.sourceFile, ctx.filePath)
|
|
4135
|
+
for (const { name, key, value: read, fallback } of bindings) {
|
|
4136
|
+
const value = bodyRest && ctx.restPropsOmittedKeys!.includes(key) ? (fallback ?? 'undefined') : read
|
|
4137
|
+
ctx.localConstants.push({
|
|
4138
|
+
name,
|
|
4139
|
+
value,
|
|
4140
|
+
parsed: parseExpression(`(${value})`),
|
|
4141
|
+
declarationKind: 'const',
|
|
4142
|
+
isExported: false,
|
|
4143
|
+
type: null,
|
|
4144
|
+
loc,
|
|
4145
|
+
freeIdentifiers: new Set([path]),
|
|
4146
|
+
origin: { phase: 'hydrate', scope: 'init', effect: 'pure' },
|
|
4147
|
+
})
|
|
4148
|
+
}
|
|
4149
|
+
return true
|
|
4150
|
+
}
|
|
4151
|
+
|
|
4152
|
+
/**
|
|
4153
|
+
* Whether `name`, read by the destructure `use`, names a const object (see
|
|
4154
|
+
* {@link collectConstDestructure}): the rest props, a component-body `const`
|
|
4155
|
+
* declared before `use`, or a module `const` that no component binding
|
|
4156
|
+
* shadows.
|
|
4157
|
+
*/
|
|
4158
|
+
function isConstObjectSource(name: string, use: ts.VariableDeclaration, ctx: AnalyzerContext): boolean {
|
|
4159
|
+
if (name === ctx.restPropsName) return true
|
|
4160
|
+
const body = ctx.componentBodyBlock
|
|
4161
|
+
if (body === null || !isComponentBodyStatementDeclaration(use, body)) return false
|
|
4162
|
+
const local = componentConstDeclaration(name, body)
|
|
4163
|
+
if (local !== null) return local.pos < use.pos && ts.isIdentifier(local.name)
|
|
4164
|
+
if (componentBodyBindsName(name, body) || ctx.propsObjectName === name) return false
|
|
4165
|
+
if (ctx.propsObjectName === null && ctx.propsParams.some(p => p.name === name)) return false
|
|
4166
|
+
return ctx.localConstants.some(c => c.isModule && c.name === name && (c.declarationKind ?? 'const') === 'const')
|
|
4167
|
+
}
|
|
4168
|
+
|
|
4169
|
+
/** Whether a direct statement of `body` declares `name` (any binding form, `let` included). */
|
|
4170
|
+
function componentBodyBindsName(name: string, body: ts.Block): boolean {
|
|
4171
|
+
for (const stmt of body.statements) {
|
|
4172
|
+
if (ts.isFunctionDeclaration(stmt) && stmt.name?.text === name) return true
|
|
4173
|
+
if (!ts.isVariableStatement(stmt)) continue
|
|
4174
|
+
for (const d of stmt.declarationList.declarations) {
|
|
4175
|
+
if (bindingNameDeclares(d.name, name)) return true
|
|
4176
|
+
}
|
|
4177
|
+
}
|
|
4178
|
+
return false
|
|
4179
|
+
}
|
|
4180
|
+
|
|
4181
|
+
function bindingNameDeclares(binding: ts.BindingName, name: string): boolean {
|
|
4182
|
+
if (ts.isIdentifier(binding)) return binding.text === name
|
|
4183
|
+
return binding.elements.some(el => !ts.isOmittedExpression(el) && bindingNameDeclares(el.name, name))
|
|
4184
|
+
}
|
|
4185
|
+
|
|
4186
|
+
/** One const a {@link collectConstDestructure} binding element binds. */
|
|
4187
|
+
interface ConstDestructureBinding {
|
|
4188
|
+
name: string
|
|
4189
|
+
/** What it reads off the source path. */
|
|
4190
|
+
value: string
|
|
4191
|
+
/** The key of the destructure's own element it sits under. */
|
|
4192
|
+
key: string
|
|
4193
|
+
/** The source text of its literal default, if any. */
|
|
4194
|
+
fallback?: string
|
|
4195
|
+
}
|
|
4196
|
+
|
|
4197
|
+
/**
|
|
4198
|
+
* The `{ name, value }` const each element of `pattern` binds, read off
|
|
4199
|
+
* `path` (see {@link collectConstDestructure}), with the key of `pattern`'s
|
|
4200
|
+
* own element it sits under. False when an element has no such const form.
|
|
4201
|
+
*/
|
|
4202
|
+
function collectConstDestructureBindings(
|
|
4203
|
+
pattern: ts.ObjectBindingPattern,
|
|
4204
|
+
path: string,
|
|
4205
|
+
out: ConstDestructureBinding[],
|
|
4206
|
+
topKey?: string,
|
|
4207
|
+
): boolean {
|
|
4208
|
+
for (const el of pattern.elements) {
|
|
4209
|
+
const key = el.dotDotDotToken ? null : bindingElementKey(el)
|
|
4210
|
+
if (key === null) return false
|
|
4211
|
+
const access = isIdentifierName(key) ? `${path}.${key}` : `${path}[${JSON.stringify(key)}]`
|
|
4212
|
+
if (ts.isObjectBindingPattern(el.name) && !el.initializer) {
|
|
4213
|
+
if (!collectConstDestructureBindings(el.name, access, out, topKey ?? key)) return false
|
|
4214
|
+
continue
|
|
4215
|
+
}
|
|
4216
|
+
if (!ts.isIdentifier(el.name)) return false
|
|
4217
|
+
const fallback = el.initializer ? literalDefaultText(el.initializer) : undefined
|
|
4218
|
+
if (fallback === null) return false
|
|
4219
|
+
const value = fallback === undefined ? access : `${access} === undefined ? ${fallback} : ${access}`
|
|
4220
|
+
out.push({ name: el.name.text, value, key: topKey ?? key, ...(fallback !== undefined && { fallback }) })
|
|
4221
|
+
}
|
|
4222
|
+
return true
|
|
4223
|
+
}
|
|
4224
|
+
|
|
4225
|
+
/** Whether `key` is spelled as an identifier, so `obj.key` reads it. */
|
|
4226
|
+
function isIdentifierName(key: string): boolean {
|
|
4227
|
+
const chars = [...key]
|
|
4228
|
+
return chars.length > 0 && chars.every((ch, i) => {
|
|
4229
|
+
const code = ch.codePointAt(0)!
|
|
4230
|
+
return i === 0 ? ts.isIdentifierStart(code, ts.ScriptTarget.Latest) : ts.isIdentifierPart(code, ts.ScriptTarget.Latest)
|
|
4231
|
+
})
|
|
4232
|
+
}
|
|
4233
|
+
|
|
4234
|
+
/** The source text of a literal default (`'x'`, `1`, `-1`, `true`, `null`), or null for any other one. */
|
|
4235
|
+
function literalDefaultText(node: ts.Expression): string | null {
|
|
4236
|
+
if (ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node)) return JSON.stringify(node.text)
|
|
4237
|
+
if (ts.isNumericLiteral(node)) return node.text
|
|
4238
|
+
if (ts.isPrefixUnaryExpression(node) && node.operator === ts.SyntaxKind.MinusToken && ts.isNumericLiteral(node.operand)) {
|
|
4239
|
+
return `-${node.operand.text}`
|
|
4240
|
+
}
|
|
4241
|
+
if (node.kind === ts.SyntaxKind.TrueKeyword) return 'true'
|
|
4242
|
+
if (node.kind === ts.SyntaxKind.FalseKeyword) return 'false'
|
|
4243
|
+
if (node.kind === ts.SyntaxKind.NullKeyword) return 'null'
|
|
4244
|
+
return null
|
|
4245
|
+
}
|
|
4246
|
+
|
|
3735
4247
|
/** {@link propDefaultReadOf} for a body destructure's binding (`const { label: text = 'x' } = props`). */
|
|
3736
4248
|
function bodyBindingRead(
|
|
3737
4249
|
localName: string,
|
|
@@ -3771,17 +4283,15 @@ function collectConstant(
|
|
|
3771
4283
|
// declarations from `localConstants`). Expand into one `localConstants`
|
|
3772
4284
|
// entry per destructured name, valued `props.X`, so the late-stage
|
|
3773
4285
|
// props-object rename turns them into `const X = _p.X` in the init body.
|
|
3774
|
-
if (
|
|
3775
|
-
|
|
3776
|
-
|
|
3777
|
-
|
|
3778
|
-
|
|
3779
|
-
ctx.propsObjectName === node.initializer.text
|
|
3780
|
-
) {
|
|
3781
|
-
const propsName = node.initializer.text
|
|
4286
|
+
if (!_isModule && ctx.propsObjectName !== null && destructuresPropsObject(node, ctx)) {
|
|
4287
|
+
// Always the props object's own name, even when the destructure reads
|
|
4288
|
+
// it through a `const` alias (`const p = props; const { x } = p`), so
|
|
4289
|
+
// every downstream `props.X` recognizer sees one spelling.
|
|
4290
|
+
const propsName = ctx.propsObjectName
|
|
3782
4291
|
// Bindings already destructured by this pattern, by local name: a later
|
|
3783
4292
|
// default reads them (`const { off = false, on = off } = props`, #3531).
|
|
3784
4293
|
const earlier = new Map<string, PropDefaultRead>()
|
|
4294
|
+
collectBodyRestBinding(node.name, ctx)
|
|
3785
4295
|
for (const el of node.name.elements) {
|
|
3786
4296
|
if (!ts.isBindingElement(el) || !ts.isIdentifier(el.name) || el.dotDotDotToken) continue
|
|
3787
4297
|
const localName = el.name.text
|
|
@@ -4166,6 +4676,8 @@ function extractProps(param: ts.ParameterDeclaration, ctx: AnalyzerContext): voi
|
|
|
4166
4676
|
const info: ParamInfo = {
|
|
4167
4677
|
name: localName,
|
|
4168
4678
|
type: resolvedType,
|
|
4679
|
+
...unresolvedDeclaredType(member),
|
|
4680
|
+
...propLiteralKeys(param.type, sourcePropName, ctx),
|
|
4169
4681
|
// The type's `?` and a destructure default (`{ x = 1 }`) both mean
|
|
4170
4682
|
// the caller may omit the prop.
|
|
4171
4683
|
optional: !!member?.optional || !!element.initializer,
|
|
@@ -4423,20 +4935,112 @@ function localObjectMemberTypesFor(ctx: AnalyzerContext): LocalObjectMemberTypes
|
|
|
4423
4935
|
* `isResolvableMemberType`'s own docstring for why the structural cases
|
|
4424
4936
|
* are safe to admit and why those three still are not.
|
|
4425
4937
|
*/
|
|
4938
|
+
/**
|
|
4939
|
+
* A destructured binding's member type: `type` when it resolves to a
|
|
4940
|
+
* concrete representation (`isResolvableMemberType`), and the declared
|
|
4941
|
+
* type as written (`declared`), which `ParamInfo.declaredType` carries when
|
|
4942
|
+
* `type` does not resolve.
|
|
4943
|
+
*/
|
|
4944
|
+
interface DestructuredMemberType {
|
|
4945
|
+
type: TypeInfo | null
|
|
4946
|
+
declared: TypeInfo | null
|
|
4947
|
+
optional: boolean
|
|
4948
|
+
}
|
|
4949
|
+
|
|
4950
|
+
/** `ParamInfo.declaredType` for a member whose declared type did not resolve to `type`. */
|
|
4951
|
+
function unresolvedDeclaredType(member: DestructuredMemberType | undefined): Pick<ParamInfo, 'declaredType'> {
|
|
4952
|
+
return member && !member.type && member.declared ? { declaredType: member.declared } : {}
|
|
4953
|
+
}
|
|
4954
|
+
|
|
4955
|
+
/** Upper bound on alias / intersection hops a type walk follows, a guard against a cycle. */
|
|
4956
|
+
const MAX_TYPE_HOPS = 8
|
|
4957
|
+
|
|
4958
|
+
/**
|
|
4959
|
+
* `ParamInfo.literalKeys` for the member `name` of a props type node: the
|
|
4960
|
+
* member's declared type node, found through a type literal, a same-file
|
|
4961
|
+
* interface or type alias, or an intersection of those (`{ name: N } &
|
|
4962
|
+
* IconProps`), read by {@link literalKeyDomain}. Empty when the member is
|
|
4963
|
+
* not found or its type is not such a union.
|
|
4964
|
+
*/
|
|
4965
|
+
function propLiteralKeys(typeNode: ts.TypeNode | undefined, name: string, ctx: AnalyzerContext): Pick<ParamInfo, 'literalKeys'> {
|
|
4966
|
+
const memberType = typeNode ? memberTypeNode(typeNode, name, ctx, 0) : null
|
|
4967
|
+
const literalKeys = memberType ? literalKeyDomain(memberType, ctx) : null
|
|
4968
|
+
return literalKeys ? { literalKeys } : {}
|
|
4969
|
+
}
|
|
4970
|
+
|
|
4971
|
+
function memberTypeNode(typeNode: ts.TypeNode, name: string, ctx: AnalyzerContext, hops: number): ts.TypeNode | null {
|
|
4972
|
+
if (hops > MAX_TYPE_HOPS) return null
|
|
4973
|
+
if (ts.isParenthesizedTypeNode(typeNode)) return memberTypeNode(typeNode.type, name, ctx, hops + 1)
|
|
4974
|
+
if (ts.isIntersectionTypeNode(typeNode)) {
|
|
4975
|
+
for (const part of typeNode.types) {
|
|
4976
|
+
const found = memberTypeNode(part, name, ctx, hops + 1)
|
|
4977
|
+
if (found) return found
|
|
4978
|
+
}
|
|
4979
|
+
return null
|
|
4980
|
+
}
|
|
4981
|
+
const members = ts.isTypeLiteralNode(typeNode) ? typeNode.members : null
|
|
4982
|
+
if (members) return memberSignatureType(members, name, ctx)
|
|
4983
|
+
if (!ts.isTypeReferenceNode(typeNode)) return null
|
|
4984
|
+
const decl = findTypeDeclaration(typeNode.typeName.getText(ctx.sourceFile), ctx.sourceFile)
|
|
4985
|
+
if (!decl) return null
|
|
4986
|
+
if (ts.isInterfaceDeclaration(decl)) return memberSignatureType(decl.members, name, ctx)
|
|
4987
|
+
return memberTypeNode(decl.type, name, ctx, hops + 1)
|
|
4988
|
+
}
|
|
4989
|
+
|
|
4990
|
+
function memberSignatureType(members: ts.NodeArray<ts.TypeElement>, name: string, ctx: AnalyzerContext): ts.TypeNode | null {
|
|
4991
|
+
for (const member of members) {
|
|
4992
|
+
if (ts.isPropertySignature(member) && member.name.getText(ctx.sourceFile) === name) return member.type ?? null
|
|
4993
|
+
}
|
|
4994
|
+
return null
|
|
4995
|
+
}
|
|
4996
|
+
|
|
4997
|
+
/**
|
|
4998
|
+
* The string literals, `null` and `undefined` a type node admits when it
|
|
4999
|
+
* admits nothing else (`'ok' | 'err' | undefined`, or a same-file alias of
|
|
5000
|
+
* such a union), or null.
|
|
5001
|
+
*/
|
|
5002
|
+
function literalKeyDomain(typeNode: ts.TypeNode, ctx: AnalyzerContext, hops = 0): ParamInfo['literalKeys'] | null {
|
|
5003
|
+
if (hops > MAX_TYPE_HOPS) return null
|
|
5004
|
+
if (ts.isParenthesizedTypeNode(typeNode)) return literalKeyDomain(typeNode.type, ctx, hops + 1)
|
|
5005
|
+
if (ts.isTypeReferenceNode(typeNode)) {
|
|
5006
|
+
const decl = findTypeDeclaration(typeNode.typeName.getText(ctx.sourceFile), ctx.sourceFile)
|
|
5007
|
+
return decl && ts.isTypeAliasDeclaration(decl) ? literalKeyDomain(decl.type, ctx, hops + 1) : null
|
|
5008
|
+
}
|
|
5009
|
+
if (!ts.isUnionTypeNode(typeNode)) return literalTypeKey(typeNode)
|
|
5010
|
+
const keys: string[] = []
|
|
5011
|
+
const nullish = new Set<'null' | 'undefined'>()
|
|
5012
|
+
for (const part of typeNode.types) {
|
|
5013
|
+
const inner = literalKeyDomain(part, ctx, hops + 1)
|
|
5014
|
+
if (!inner) return null
|
|
5015
|
+
keys.push(...inner.keys)
|
|
5016
|
+
for (const n of inner.nullish) nullish.add(n)
|
|
5017
|
+
}
|
|
5018
|
+
return { keys, nullish: [...nullish] }
|
|
5019
|
+
}
|
|
5020
|
+
|
|
5021
|
+
/** {@link literalKeyDomain} for one non-union, non-reference type node: a string literal, `null` or `undefined`. */
|
|
5022
|
+
function literalTypeKey(typeNode: ts.TypeNode): ParamInfo['literalKeys'] | null {
|
|
5023
|
+
if (typeNode.kind === ts.SyntaxKind.UndefinedKeyword) return { keys: [], nullish: ['undefined'] }
|
|
5024
|
+
if (!ts.isLiteralTypeNode(typeNode)) return null
|
|
5025
|
+
if (typeNode.literal.kind === ts.SyntaxKind.NullKeyword) return { keys: [], nullish: ['null'] }
|
|
5026
|
+
return ts.isStringLiteral(typeNode.literal) ? { keys: [typeNode.literal.text], nullish: [] } : null
|
|
5027
|
+
}
|
|
5028
|
+
|
|
4426
5029
|
function collectMemberTypes(
|
|
4427
5030
|
typeNode: ts.TypeNode,
|
|
4428
5031
|
ctx: AnalyzerContext
|
|
4429
|
-
): Map<string,
|
|
5032
|
+
): Map<string, DestructuredMemberType> | null {
|
|
4430
5033
|
const localObjectMembers = localObjectMemberTypesFor(ctx)
|
|
4431
5034
|
const fromMembers = (
|
|
4432
5035
|
members: ts.NodeArray<ts.TypeElement>
|
|
4433
|
-
): Map<string,
|
|
4434
|
-
const map = new Map<string,
|
|
5036
|
+
): Map<string, DestructuredMemberType> => {
|
|
5037
|
+
const map = new Map<string, DestructuredMemberType>()
|
|
4435
5038
|
for (const member of members) {
|
|
4436
5039
|
if (ts.isPropertySignature(member) && member.name) {
|
|
4437
5040
|
const info = member.type ? typeNodeToTypeInfo(member.type, ctx.sourceFile) : null
|
|
4438
5041
|
map.set(member.name.getText(ctx.sourceFile), {
|
|
4439
5042
|
type: info && isResolvableMemberType(info, localObjectMembers) ? info : null,
|
|
5043
|
+
declared: info,
|
|
4440
5044
|
optional: !!member.questionToken,
|
|
4441
5045
|
})
|
|
4442
5046
|
}
|
|
@@ -4505,9 +5109,11 @@ function extractPropsFromTypeMembers(
|
|
|
4505
5109
|
? typeNodeToTypeInfo(member.type, ctx.sourceFile)
|
|
4506
5110
|
: { kind: 'unknown' as const, raw: 'unknown' }
|
|
4507
5111
|
|
|
5112
|
+
const literalKeys = member.type ? literalKeyDomain(member.type, ctx) : null
|
|
4508
5113
|
ctx.propsParams.push({
|
|
4509
5114
|
name: propName,
|
|
4510
5115
|
type: propType ?? { kind: 'unknown', raw: 'unknown' },
|
|
5116
|
+
...(literalKeys && { literalKeys }),
|
|
4511
5117
|
optional: isOptional,
|
|
4512
5118
|
defaultValue: undefined,
|
|
4513
5119
|
})
|
|
@@ -4707,6 +5313,7 @@ function validateContext(ctx: AnalyzerContext): void {
|
|
|
4707
5313
|
// downstream inlining never re-embeds their stale initializer text (#2910).
|
|
4708
5314
|
markMutatedConstants(ctx)
|
|
4709
5315
|
markWrittenBindings(ctx)
|
|
5316
|
+
writeTemplatePropReads(ctx)
|
|
4710
5317
|
|
|
4711
5318
|
// BF052: init statements that write to an identifier with no visible
|
|
4712
5319
|
// declaration cause a ReferenceError in ESM strict mode. Flag them
|