@openrewrite/rewrite 8.101.1 → 8.101.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (34) hide show
  1. package/dist/java/rpc.d.ts.map +1 -1
  2. package/dist/java/rpc.js +3 -1
  3. package/dist/java/rpc.js.map +1 -1
  4. package/dist/javascript/markers.d.ts +26 -0
  5. package/dist/javascript/markers.d.ts.map +1 -1
  6. package/dist/javascript/markers.js +21 -0
  7. package/dist/javascript/markers.js.map +1 -1
  8. package/dist/javascript/name-resolver.d.ts +68 -0
  9. package/dist/javascript/name-resolver.d.ts.map +1 -0
  10. package/dist/javascript/name-resolver.js +820 -0
  11. package/dist/javascript/name-resolver.js.map +1 -0
  12. package/dist/javascript/package-exported-types.d.ts +11 -0
  13. package/dist/javascript/package-exported-types.d.ts.map +1 -1
  14. package/dist/javascript/package-exported-types.js +63 -2
  15. package/dist/javascript/package-exported-types.js.map +1 -1
  16. package/dist/javascript/parser.d.ts +4 -0
  17. package/dist/javascript/parser.d.ts.map +1 -1
  18. package/dist/javascript/parser.js +27 -4
  19. package/dist/javascript/parser.js.map +1 -1
  20. package/dist/javascript/type-mapping.d.ts +17 -1
  21. package/dist/javascript/type-mapping.d.ts.map +1 -1
  22. package/dist/javascript/type-mapping.js +53 -5
  23. package/dist/javascript/type-mapping.js.map +1 -1
  24. package/dist/rewrite-javascript-version.txt +1 -1
  25. package/dist/rpc/request/dependency-types.js +17 -6
  26. package/dist/rpc/request/dependency-types.js.map +1 -1
  27. package/package.json +1 -1
  28. package/src/java/rpc.ts +3 -1
  29. package/src/javascript/markers.ts +50 -0
  30. package/src/javascript/name-resolver.ts +853 -0
  31. package/src/javascript/package-exported-types.ts +66 -3
  32. package/src/javascript/parser.ts +28 -4
  33. package/src/javascript/type-mapping.ts +58 -6
  34. package/src/rpc/request/dependency-types.ts +19 -7
@@ -0,0 +1,853 @@
1
+ /*
2
+ * Copyright 2026 the original author or authors.
3
+ * <p>
4
+ * Licensed under the Moderne Source Available License (the "License");
5
+ * you may not use this file except in compliance with the License.
6
+ * You may obtain a copy of the License at
7
+ * <p>
8
+ * https://docs.moderne.io/licensing/moderne-source-available-license
9
+ * <p>
10
+ * Unless required by applicable law or agreed to in writing, software
11
+ * distributed under the License is distributed on an "AS IS" BASIS,
12
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13
+ * See the License for the specific language governing permissions and
14
+ * limitations under the License.
15
+ */
16
+ import ts from "typescript";
17
+ import * as path from "path";
18
+ import {randomId} from "../uuid";
19
+ import {JS} from "./tree";
20
+ import {ResolvedNames} from "./markers";
21
+ import {JavaScriptTypeMapping} from "./type-mapping";
22
+ import {moduleName} from "./package-name";
23
+
24
+ /** A lone surrogate prints as a six character `\uXXXX` escape in place of its one code unit. */
25
+ const ESCAPED_SURROGATE_GROWTH = 5;
26
+
27
+ type DeclarationKind = "class" | "interface" | "enum" | "enum-member" | "method" | "constructor" | "field" | "module";
28
+
29
+ /** A declaration as every reference to it names it. */
30
+ interface Target {
31
+ readonly name: string;
32
+ /** What the names of its members start from, which a module's file is not. */
33
+ readonly owner: string;
34
+ readonly pkg: string | null;
35
+ readonly kind: DeclarationKind;
36
+ }
37
+
38
+ /** What a file's declarations are named from. */
39
+ interface Place {
40
+ /** The file's module, from the root of its repository or its package. */
41
+ readonly module: string;
42
+ /** The file, from the same root, which is what names the module. */
43
+ readonly file: string;
44
+ /** The npm package holding the file, null for the repository and for the default library. */
45
+ readonly pkg: string | null;
46
+ /** Whether the file was indexed apart from the repository, so that no declaration row of ours stands in it. */
47
+ readonly external: boolean;
48
+ /** The parser's own naming, which a package's files and a declaration file go by. */
49
+ readonly mapping?: JavaScriptTypeMapping;
50
+ }
51
+
52
+ /** Each row of a file, with the names and the kinds they share. */
53
+ class Rows {
54
+ readonly names: string[] = [];
55
+ readonly packages: (string | null)[] = [];
56
+ readonly kinds: string[] = [];
57
+ readonly spans: number[] = [];
58
+ private readonly nameIndices = new Map<string, number>();
59
+ private readonly kindIndices = new Map<string, number>();
60
+ private readonly printed: (offset: number) => number;
61
+
62
+ constructor(private readonly sourceFile: ts.SourceFile) {
63
+ this.printed = printedOffsets(sourceFile.text);
64
+ }
65
+
66
+ add(node: ts.Node, name: string, pkg: string | null, kind: string): void {
67
+ const key = `${pkg}\0${name}`;
68
+ let nameIndex = this.nameIndices.get(key);
69
+ if (nameIndex === undefined) {
70
+ this.nameIndices.set(key, nameIndex = this.names.length);
71
+ this.names.push(name);
72
+ this.packages.push(pkg);
73
+ }
74
+ let kindIndex = this.kindIndices.get(kind);
75
+ if (kindIndex === undefined) {
76
+ this.kindIndices.set(kind, kindIndex = this.kinds.length);
77
+ this.kinds.push(kind);
78
+ }
79
+ this.spans.push(this.printed(node.getStart(this.sourceFile)), this.printed(node.getEnd()), nameIndex, kindIndex);
80
+ }
81
+ }
82
+
83
+ /** Gives a reference and its declaration one canonical name, from what the checker resolves each name to. */
84
+ export class JavaScriptNameResolver {
85
+ private readonly checker: ts.TypeChecker;
86
+ private readonly roots: string[];
87
+ private readonly targets = new Map<ts.Symbol, Target | undefined>();
88
+ private readonly places = new Map<string, Place | undefined>();
89
+ private readonly mappings = new Map<string, JavaScriptTypeMapping>();
90
+ private readonly packageNames = new Map<string, string | undefined>();
91
+
92
+ /**
93
+ * @param resolveModule resolves a specifier as the program did, for one it did not load
94
+ * @param repositoryRoot what a path in the repository is relative to
95
+ */
96
+ constructor(private readonly program: ts.Program,
97
+ private readonly resolveModule: (specifier: ts.StringLiteralLike) => string | undefined,
98
+ repositoryRoot: string) {
99
+ this.checker = program.getTypeChecker();
100
+ // Module resolution reports a symlinked path by what it links to.
101
+ this.roots = [...new Set([repositoryRoot, ts.sys.realpath?.(repositoryRoot) ?? repositoryRoot])];
102
+ }
103
+
104
+ resolvedNames(sourceFile: ts.SourceFile): ResolvedNames {
105
+ const rows = new Rows(sourceFile);
106
+ const visit = (node: ts.Node): void => {
107
+ this.rowsAt(node, rows);
108
+ ts.forEachChild(node, visit);
109
+ };
110
+ visit(sourceFile);
111
+ const {names, packages, kinds, spans} = rows;
112
+ return {kind: JS.Markers.ResolvedNames, id: randomId(), names, packages, kinds, spans};
113
+ }
114
+
115
+ private rowsAt(node: ts.Node, rows: Rows): void {
116
+ try {
117
+ if (ts.isIdentifier(node) || ts.isPrivateIdentifier(node)) {
118
+ this.nameRows(node, rows);
119
+ } else if (ts.isStringLiteralLike(node) && isModuleSpecifier(node)) {
120
+ this.add(rows, node, this.specifiedModule(node), "import-ref");
121
+ } else if (ts.isStringLiteralLike(node) || ts.isNumericLiteral(node)) {
122
+ this.literalNameRow(node, rows);
123
+ } else if (ts.isConstructorDeclaration(node)) {
124
+ this.keywordRow(node, ts.SyntaxKind.ConstructorKeyword, rows);
125
+ } else if (isNamelessDefaultExport(node)) {
126
+ this.keywordRow(node, ts.SyntaxKind.DefaultKeyword, rows);
127
+ }
128
+ } catch {
129
+ // The checker asserts on some code it cannot place, and one name must not cost the file its LST.
130
+ }
131
+ }
132
+
133
+ private nameRows(name: ts.Identifier | ts.PrivateIdentifier, rows: Rows): void {
134
+ const parent = name.parent;
135
+ if (this.isOwnModule(name)) {
136
+ const place = this.placeOf(name.getSourceFile().fileName);
137
+ this.add(rows, name, place && moduleTarget(place), undefined);
138
+ return;
139
+ }
140
+ if (ts.isShorthandPropertyAssignment(parent) && parent.name === name) {
141
+ this.shorthandRows(name, parent, rows);
142
+ return;
143
+ }
144
+ if (ts.isParameter(parent) && parent.name === name && ts.isParameterPropertyDeclaration(parent, parent.parent)) {
145
+ const [, property] = this.checker.getSymbolsOfParameterPropertyDeclaration(parent, name.text);
146
+ this.declarationRow(name, property, rows);
147
+ return;
148
+ }
149
+ const symbol = this.checker.getSymbolAtLocation(name);
150
+ if (isBoundProperty(name)) {
151
+ const element = name.parent as ts.BindingElement;
152
+ if (!(symbol && symbol.flags & ts.SymbolFlags.Alias)) {
153
+ const read = propertyOf(this.checker.getTypeAtLocation(element.parent), name.text);
154
+ if (read) {
155
+ this.referenceRow(name, read, rows, moduleSpecifierOf(element) ? "import-ref" : undefined);
156
+ }
157
+ }
158
+ if (element.propertyName === name) {
159
+ return;
160
+ }
161
+ }
162
+ if (!symbol) {
163
+ return;
164
+ }
165
+ if (isBinding(name, symbol)) {
166
+ const target = this.targetOf(symbol);
167
+ if (target && this.isUnbound(symbol, target)) {
168
+ rows.add(name, target.name, target.pkg, target.kind);
169
+ } else {
170
+ this.add(rows, name, target, "import-ref");
171
+ }
172
+ return;
173
+ }
174
+ // The binding it is assigned to declares it. A reference here would be a call on the declaration's own line.
175
+ const assigned = (ts.isFunctionExpression(parent) || ts.isClassExpression(parent)) && parent.name === name &&
176
+ !isExportedValue(parent) ? this.assignedTarget(parent) : undefined;
177
+ if (assigned) {
178
+ return;
179
+ }
180
+ const expected = this.contextualProperty(name);
181
+ const fills = expected !== undefined && !expected.declarations?.includes(parent as ts.Declaration);
182
+ if (fills) {
183
+ this.referenceRow(name, expected, rows);
184
+ }
185
+ if (ts.isJsxAttribute(parent)) {
186
+ return;
187
+ }
188
+ if (declares(symbol, name)) {
189
+ this.declarationRow(name, symbol, rows);
190
+ } else if (!fills) {
191
+ this.referenceRow(name, symbol, rows);
192
+ }
193
+ }
194
+
195
+ /** How a CommonJS file names itself, which the checker answers with whatever is being assigned. */
196
+ private isOwnModule(name: ts.Identifier | ts.PrivateIdentifier): boolean {
197
+ if (name.text !== "module" && name.text !== "exports") {
198
+ return false;
199
+ }
200
+ const file = name.getSourceFile() as ts.SourceFile & { commonJsModuleIndicator?: ts.Node, symbol?: ts.Symbol };
201
+ if (!file.commonJsModuleIndicator || ts.getNameOfDeclaration(name.parent as ts.Declaration) === name) {
202
+ return false;
203
+ }
204
+ const bound = this.checker.resolveName(name.text, name, ts.SymbolFlags.Value, true);
205
+ return bound === file.symbol || bound !== undefined && (bound.flags & ts.SymbolFlags.ModuleExports) !== 0;
206
+ }
207
+
208
+ /** `{a}` reads the value `a` and declares a property of the same name, in that order, as a click on it does. */
209
+ private shorthandRows(name: ts.Identifier | ts.PrivateIdentifier, element: ts.ShorthandPropertyAssignment, rows: Rows): void {
210
+ const value = this.checker.getShorthandAssignmentValueSymbol(element);
211
+ if (value) {
212
+ this.referenceRow(name, value, rows);
213
+ }
214
+ const property = this.checker.getSymbolAtLocation(name);
215
+ if (property && !(property.flags & ts.SymbolFlags.Alias) && this.declared(property) !== (value && this.targetOf(value))) {
216
+ this.declarationRow(name, property, rows);
217
+ }
218
+ }
219
+
220
+ /** A declaration named by a string or a number, which a reference by name still reaches. */
221
+ private literalNameRow(literal: ts.StringLiteralLike | ts.NumericLiteral, rows: Rows): void {
222
+ const declaration = literal.parent as ts.Declaration;
223
+ if (ts.getNameOfDeclaration(declaration) === literal) {
224
+ const symbol = this.symbolOfDeclaration(declaration);
225
+ if (symbol) {
226
+ this.declarationRow(literal, symbol, rows);
227
+ }
228
+ }
229
+ }
230
+
231
+ /** A declaration with no name of its own stands on its keyword, as `constructor` and `export default` do. */
232
+ private keywordRow(declaration: ts.Node, keyword: ts.SyntaxKind, rows: Rows): void {
233
+ const token = declaration.getChildren().flatMap(child => child.kind === ts.SyntaxKind.SyntaxList ? child.getChildren() : [child])
234
+ .find(child => child.kind === keyword);
235
+ const symbol = this.symbolOfDeclaration(declaration);
236
+ if (token && symbol) {
237
+ this.declarationRow(token, symbol, rows);
238
+ }
239
+ }
240
+
241
+ private declarationRow(node: ts.Node, symbol: ts.Symbol, rows: Rows): void {
242
+ const target = this.declared(symbol);
243
+ const declaration = symbol.declarations?.find(d => nameOf(d) === node) ?? symbol.declarations?.[0];
244
+ if (target && declaration && target === this.valueTarget(declaration)) {
245
+ this.add(rows, node, target, undefined);
246
+ } else if (target && declaration) {
247
+ rows.add(node, target.name, target.pkg, this.kindOf(symbol, declaration));
248
+ }
249
+ }
250
+
251
+ private referenceRow(node: ts.Node, symbol: ts.Symbol, rows: Rows, kind?: string): void {
252
+ this.add(rows, node, this.targetOf(symbol), kind);
253
+ }
254
+
255
+ /** A row for a name that refers to `target`, in the kind given, else the one its target asks for. */
256
+ private add(rows: Rows, node: ts.Node, target: Target | undefined, kind: string | undefined): void {
257
+ if (!target) {
258
+ return;
259
+ }
260
+ if (kind) {
261
+ rows.add(node, target.name, target.pkg, kind);
262
+ } else if (isConstructed(node) && (target.kind === "class" || target.kind === "interface")) {
263
+ rows.add(node, `${target.name}.<init>`, target.pkg, "constructor-call");
264
+ } else {
265
+ rows.add(node, target.name, target.pkg, referenceKind(target.kind));
266
+ }
267
+ }
268
+
269
+ /** The property an object literal's key fills in the type the literal is expected to have. */
270
+ private contextualProperty(name: ts.Identifier | ts.PrivateIdentifier): ts.Symbol | undefined {
271
+ const element = name.parent;
272
+ const inLiteral = ts.isObjectLiteralElementLike(element) && ts.isObjectLiteralExpression(element.parent) ||
273
+ ts.isJsxAttribute(element);
274
+ if (!inLiteral || element.name !== name) {
275
+ return undefined;
276
+ }
277
+ const expected = this.checker.getContextualType(element.parent as ts.Expression);
278
+ return expected && propertyOf(expected, name.text);
279
+ }
280
+
281
+ private targetOf(symbol: ts.Symbol): Target | undefined {
282
+ if (!(symbol.flags & ts.SymbolFlags.Alias)) {
283
+ return this.declared(symbol);
284
+ }
285
+ const aliased = this.checker.getAliasedSymbol(symbol);
286
+ if (aliased.declarations?.length) {
287
+ return this.declared(aliased);
288
+ }
289
+ const binding = this.moduleBinding(symbol, new Set());
290
+ return binding && (this.resolvedModule(binding.specifier) ?? this.unbound(binding.declaration));
291
+ }
292
+
293
+ /** The declaration that binds a symbol to a module, through whatever assignments and exports stand between them. */
294
+ private moduleBinding(symbol: ts.Symbol, seen: Set<ts.Symbol>): { declaration: ts.Declaration, specifier: ts.StringLiteralLike } | undefined {
295
+ if (seen.has(symbol)) {
296
+ return undefined;
297
+ }
298
+ seen.add(symbol);
299
+ for (const declaration of symbol.declarations ?? []) {
300
+ const specifier = moduleSpecifierOf(declaration);
301
+ if (specifier) {
302
+ return ts.isStringLiteralLike(specifier) ? {declaration, specifier} : undefined;
303
+ }
304
+ const source = this.assignedSymbol(declaration);
305
+ const bound = source && this.moduleBinding(source, seen);
306
+ if (bound) {
307
+ return bound;
308
+ }
309
+ }
310
+ return undefined;
311
+ }
312
+
313
+ /** A binding to a module that does not resolve, which is all there is of what it binds. A re-export binds nothing here. */
314
+ private unbound(binding: ts.Declaration): Target | undefined {
315
+ const symbol = this.symbolOfDeclaration(binding);
316
+ return symbol && !ts.isExportSpecifier(binding) && !ts.isNamespaceExport(binding) ? this.declared(symbol) : undefined;
317
+ }
318
+
319
+ /** Whether a binding is the target of its own uses, which only {@link unbound} makes an alias. */
320
+ private isUnbound(binding: ts.Symbol, target: Target): boolean {
321
+ return (binding.flags & ts.SymbolFlags.Alias) !== 0 && this.targets.get(binding) === target;
322
+ }
323
+
324
+ private assignedSymbol(declaration: ts.Node): ts.Symbol | undefined {
325
+ if (ts.isExportSpecifier(declaration)) {
326
+ return this.checker.getExportSpecifierLocalTargetSymbol(declaration);
327
+ }
328
+ if (ts.isShorthandPropertyAssignment(declaration)) {
329
+ return this.checker.getShorthandAssignmentValueSymbol(declaration);
330
+ }
331
+ const parent = declaration.parent as ts.Node | undefined;
332
+ const assigned = ts.isExportAssignment(declaration) ? declaration.expression :
333
+ ts.isBinaryExpression(declaration) ? declaration.right :
334
+ parent && ts.isBinaryExpression(parent) && parent.left === declaration ? parent.right :
335
+ undefined;
336
+ return assigned && this.checker.getSymbolAtLocation(leftmost(assigned));
337
+ }
338
+
339
+ private specifiedModule(specifier: ts.StringLiteralLike): Target | undefined {
340
+ const symbol = this.checker.getSymbolAtLocation(specifier);
341
+ const declaration = symbol?.declarations?.[0];
342
+ if (!declaration || isAugmentation(declaration)) {
343
+ return this.resolvedModule(specifier);
344
+ }
345
+ if (ts.isModuleDeclaration(declaration)) {
346
+ return this.declared(symbol!);
347
+ }
348
+ const place = this.placeOf(declaration.getSourceFile().fileName);
349
+ return place && moduleTarget(place);
350
+ }
351
+
352
+ private resolvedModule(specifier: ts.StringLiteralLike): Target | undefined {
353
+ const file = this.resolveModule(specifier);
354
+ const place = file === undefined ? undefined : this.placeOf(file);
355
+ return place && moduleTarget(place);
356
+ }
357
+
358
+ private symbolOfDeclaration(declaration: ts.Node): ts.Symbol | undefined {
359
+ return (declaration as { symbol?: ts.Symbol }).symbol;
360
+ }
361
+
362
+ private declared(symbol: ts.Symbol): Target | undefined {
363
+ const declaration = primaryDeclaration(symbol);
364
+ if (!declaration || ts.isIndexSignatureDeclaration(declaration)) {
365
+ return undefined;
366
+ }
367
+ // A transient symbol, as a union's property is, has no owner, where the symbol it stands for does.
368
+ const own = symbol.flags & ts.SymbolFlags.Transient ? this.symbolOfDeclaration(declaration) ?? symbol : symbol;
369
+ if (!this.targets.has(own)) {
370
+ this.targets.set(own, undefined);
371
+ this.targets.set(own, this.isLocal(own, declaration) ? undefined : this.target(own, declaration));
372
+ }
373
+ return this.targets.get(own);
374
+ }
375
+
376
+ private target(symbol: ts.Symbol, declaration: ts.Declaration): Target | undefined {
377
+ const place = this.placeOf(declaration.getSourceFile().fileName);
378
+ if (!place) {
379
+ return undefined;
380
+ }
381
+ const name = this.nameIn(place, symbol, declaration);
382
+ if (isNamedByFile(declaration, place)) {
383
+ return {...moduleTarget(place), owner: name};
384
+ }
385
+ const value = this.valueTarget(declaration);
386
+ return value?.name === name ? value : {name, owner: name, pkg: place.pkg, kind: this.kindOf(symbol, declaration)};
387
+ }
388
+
389
+ /** What a property holds by name, which is the one declaration when it restates it, as `module.exports = {f}` does `f`. */
390
+ private valueTarget(declaration: ts.Declaration): Target | undefined {
391
+ const value = ts.isShorthandPropertyAssignment(declaration) ? this.checker.getShorthandAssignmentValueSymbol(declaration) :
392
+ ts.isPropertyAssignment(declaration) && ts.isIdentifier(declaration.initializer) ?
393
+ this.checker.getSymbolAtLocation(declaration.initializer) : undefined;
394
+ return value && this.targetOf(value);
395
+ }
396
+
397
+ private isLocal(symbol: ts.Symbol, declaration: ts.Declaration): boolean {
398
+ if (isMember(symbol, declaration)) {
399
+ const owner = (symbol as { parent?: ts.Symbol }).parent;
400
+ const ownerDeclaration = owner?.valueDeclaration ?? owner?.declarations?.[0];
401
+ if (owner && ownerDeclaration) {
402
+ return this.isLocal(owner, ownerDeclaration);
403
+ }
404
+ }
405
+ let child: ts.Node = ts.getNameOfDeclaration(declaration) ?? declaration;
406
+ for (let node = child.parent; node && !ts.isSourceFile(node); child = node, node = node.parent) {
407
+ if (ts.isFunctionLike(node) && node.name !== child || ts.isMappedTypeNode(node) || ts.isInferTypeNode(node)) {
408
+ return true;
409
+ }
410
+ }
411
+ return false;
412
+ }
413
+
414
+ private nameIn(place: Place, symbol: ts.Symbol, declaration: ts.Declaration): string {
415
+ if (ts.isSourceFile(declaration) || isModuleExportsObject(declaration)) {
416
+ return place.module;
417
+ }
418
+ if (ts.isModuleDeclaration(declaration) && ts.isStringLiteral(declaration.name)) {
419
+ const augmented = isAugmentation(declaration) ? this.specifiedModule(declaration.name) : undefined;
420
+ return augmented?.owner ?? moduleName(declaration.name.text);
421
+ }
422
+ if (place.mapping && isNamedByType(declaration)) {
423
+ return place.mapping.fullyQualifiedName(symbol);
424
+ }
425
+ if (ts.isObjectLiteralExpression(declaration)) {
426
+ return this.objectName(declaration, place);
427
+ }
428
+ if (ts.isTypeLiteralNode(declaration)) {
429
+ return this.literalName(declaration, place);
430
+ }
431
+ if (isExpression(declaration)) {
432
+ return this.expressionName(declaration, place);
433
+ }
434
+ if (ts.isBinaryExpression(declaration) && isModuleExports(declaration.left)) {
435
+ return this.exportedValueName(declaration.right, place);
436
+ }
437
+ return `${this.ownerName(place, symbol, declaration)}.${lastSegment(declaration)}`;
438
+ }
439
+
440
+ private ownerName(place: Place, symbol: ts.Symbol, declaration: ts.Declaration): string {
441
+ if (place.mapping && ts.isFunctionDeclaration(declaration)) {
442
+ return place.mapping.functionOwnerName(declaration);
443
+ }
444
+ const owner = this.ownerOf(symbol, declaration);
445
+ return owner && !isGlobalScope(owner) ? this.declared(owner)?.owner ?? place.module : place.module;
446
+ }
447
+
448
+ private ownerOf(symbol: ts.Symbol, declaration: ts.Declaration): ts.Symbol | undefined {
449
+ if (ts.isTypeParameterDeclaration(declaration)) {
450
+ return this.symbolOfDeclaration(declaration.parent);
451
+ }
452
+ const namespace = ts.findAncestor(declaration.parent, ts.isModuleDeclaration);
453
+ return (symbol as { parent?: ts.Symbol }).parent ?? (namespace && this.symbolOfDeclaration(namespace));
454
+ }
455
+
456
+ /** The name an object literal's members hang from: what it is assigned to. */
457
+ private objectName(object: ts.ObjectLiteralExpression, place: Place): string {
458
+ return isExportedValue(object) ? place.module : this.literalName(object, place);
459
+ }
460
+
461
+ /** A function or a class is named by what it is assigned to, as its members are. */
462
+ private expressionName(expression: ts.FunctionExpression | ts.ArrowFunction | ts.ClassExpression, place: Place): string {
463
+ if (isExportedValue(expression)) {
464
+ return this.exportedValueName(expression, place);
465
+ }
466
+ const own = expression.name?.text;
467
+ if (!own || this.assignedTarget(expression)) {
468
+ return this.literalName(expression, place);
469
+ }
470
+ return assignedName(outermost(expression)) ? `${place.module}.${own}` : `${this.literalName(expression, place)}.${own}`;
471
+ }
472
+
473
+ /** What `module.exports =` gives the value it is assigned, which `export default` gives `default`. */
474
+ private exportedValueName(value: ts.Expression, place: Place): string {
475
+ const named = ts.isFunctionExpression(value) || ts.isClassExpression(value) ? value.name : undefined;
476
+ return `${place.module}.${named?.text ?? "default"}`;
477
+ }
478
+
479
+ private literalName(literal: ts.Node, place: Place): string {
480
+ if (ts.isExportAssignment(outermost(literal).parent)) {
481
+ return `${place.module}.default`;
482
+ }
483
+ const assigned = this.assignedTarget(literal);
484
+ if (assigned) {
485
+ return assigned.owner;
486
+ }
487
+ const {line, column} = lineAndColumn(literal.getSourceFile(), literal.getStart());
488
+ return `${place.module}.<object:${line}:${column}>`;
489
+ }
490
+
491
+ private assignedTarget(literal: ts.Node): Target | undefined {
492
+ const assigned = assignedName(outermost(literal));
493
+ const symbol = assigned && this.checker.getSymbolAtLocation(assigned);
494
+ return symbol && this.targetOf(symbol);
495
+ }
496
+
497
+ private kindOf(symbol: ts.Symbol, declaration: ts.Declaration): DeclarationKind {
498
+ if (ts.isModuleDeclaration(declaration)) {
499
+ return "module";
500
+ }
501
+ if (ts.isClassLike(declaration)) {
502
+ return "class";
503
+ }
504
+ if (ts.isInterfaceDeclaration(declaration) || ts.isTypeAliasDeclaration(declaration) || ts.isTypeParameterDeclaration(declaration)) {
505
+ return "interface";
506
+ }
507
+ if (ts.isEnumDeclaration(declaration)) {
508
+ return "enum";
509
+ }
510
+ if (ts.isEnumMember(declaration)) {
511
+ return "enum-member";
512
+ }
513
+ if (ts.isConstructorDeclaration(declaration)) {
514
+ return "constructor";
515
+ }
516
+ if (ts.isAccessor(declaration)) {
517
+ return "field";
518
+ }
519
+ if (ts.isFunctionLike(declaration)) {
520
+ return "method";
521
+ }
522
+ const value = assignedValue(declaration);
523
+ if (value && ts.isClassExpression(unwrapped(value))) {
524
+ return "class";
525
+ }
526
+ // A package's property is the field the walk indexed it as, whatever it holds.
527
+ const external = this.placeOf(declaration.getSourceFile().fileName)?.external;
528
+ return !external && this.checker.getTypeOfSymbolAtLocation(symbol, declaration).getCallSignatures().length > 0 ? "method" : "field";
529
+ }
530
+
531
+ private placeOf(fileName: string): Place | undefined {
532
+ if (!this.places.has(fileName)) {
533
+ this.places.set(fileName, this.place(fileName));
534
+ }
535
+ return this.places.get(fileName);
536
+ }
537
+
538
+ private place(fileName: string): Place | undefined {
539
+ const file = fileName.replace(/\\/g, "/");
540
+ const sourceFile = this.program.getSourceFile(fileName);
541
+ if (sourceFile && this.program.isSourceFileDefaultLibrary(sourceFile)) {
542
+ return this.mappedPlace(file, path.dirname(path.dirname(file)), null, true);
543
+ }
544
+ const nodeModules = "/node_modules/";
545
+ const at = file.lastIndexOf(nodeModules);
546
+ if (at >= 0) {
547
+ const segments = file.substring(at + nodeModules.length).split("/");
548
+ const directory = segments.slice(0, segments[0].startsWith("@") ? 2 : 1).join("/");
549
+ const root = file.substring(0, at + nodeModules.length) + directory;
550
+ return this.mappedPlace(file, root, this.packageNameAt(root) ?? directory, true);
551
+ }
552
+ for (const root of this.roots) {
553
+ const relative = path.relative(root, path.resolve(root, file)).replace(/\\/g, "/");
554
+ if (!relative.startsWith("../") && !path.isAbsolute(relative)) {
555
+ return sourceFile?.isDeclarationFile ? this.mappedPlace(file, root, null, false) :
556
+ {module: withoutExtension(relative), file: relative, pkg: null, external: false};
557
+ }
558
+ }
559
+ return undefined;
560
+ }
561
+
562
+ private mappedPlace(file: string, root: string, pkg: string | null, external: boolean): Place {
563
+ let mapping = this.mappings.get(root);
564
+ if (!mapping) {
565
+ this.mappings.set(root, mapping = new JavaScriptTypeMapping(this.checker, root, true));
566
+ }
567
+ const relative = path.relative(root, file).replace(/\\/g, "/");
568
+ return {module: withoutExtension(relative), file: relative, pkg, external, mapping};
569
+ }
570
+
571
+ private packageNameAt(directory: string): string | undefined {
572
+ if (!this.packageNames.has(directory)) {
573
+ this.packageNames.set(directory, readPackageName(directory));
574
+ }
575
+ return this.packageNames.get(directory);
576
+ }
577
+ }
578
+
579
+ function withoutExtension(file: string): string {
580
+ return file.replace(/\.[^/.]+$/, "");
581
+ }
582
+
583
+ function moduleTarget(place: Place): Target {
584
+ return {name: place.file, owner: place.module, pkg: place.pkg, kind: "module"};
585
+ }
586
+
587
+ /** A module is its file. A namespace is too, except where a declaration row of ours stands on it. */
588
+ function isNamedByFile(declaration: ts.Declaration, place: Place): boolean {
589
+ return ts.isSourceFile(declaration) || isModuleExportsObject(declaration) ||
590
+ ts.isModuleDeclaration(declaration) && (ts.isStringLiteral(declaration.name) || place.external);
591
+ }
592
+
593
+ function referenceKind(kind: DeclarationKind): string {
594
+ switch (kind) {
595
+ case "method":
596
+ return "method-call";
597
+ case "field":
598
+ case "enum-member":
599
+ return "field-access";
600
+ default:
601
+ return "type-ref";
602
+ }
603
+ }
604
+
605
+ /** The implementation over an overload signature, and a class over the interface merged with it. */
606
+ function primaryDeclaration(symbol: ts.Symbol): ts.Declaration | undefined {
607
+ const declarations = symbol.declarations;
608
+ if (!declarations?.length) {
609
+ return undefined;
610
+ }
611
+ return declarations.find(ts.isClassLike) ||
612
+ declarations.find(d => ts.isFunctionLike(d) && (d as ts.FunctionLikeDeclaration).body !== undefined) ||
613
+ namingDeclarations(symbol)[0];
614
+ }
615
+
616
+ /** What declares a symbol, which the container of an expando does only when nothing else does. */
617
+ function namingDeclarations(symbol: ts.Symbol): ts.Declaration[] {
618
+ const declarations = symbol.declarations ?? [];
619
+ const written = declarations.filter(d => !ts.isIdentifier(d));
620
+ return written.length > 0 ? written : declarations;
621
+ }
622
+
623
+ /** Where a declaration is named. `module.exports =` is at `exports`, unless what it assigns is named or the module's own. */
624
+ function nameOf(declaration: ts.Declaration): ts.Node | undefined {
625
+ if (ts.isBinaryExpression(declaration) && isModuleExports(declaration.left)) {
626
+ const value = unwrapped(declaration.right);
627
+ const named = (ts.isFunctionExpression(value) || ts.isClassExpression(value)) && value.name;
628
+ return !named && !ts.isObjectLiteralExpression(value) && ts.isPropertyAccessExpression(declaration.left) ?
629
+ declaration.left.name : undefined;
630
+ }
631
+ return ts.getNameOfDeclaration(declaration);
632
+ }
633
+
634
+ /** Whether a value is what `module.exports =` assigns. */
635
+ function isExportedValue(value: ts.Node): boolean {
636
+ const parent = outermost(value).parent;
637
+ return ts.isBinaryExpression(parent) && isModuleExports(parent.left);
638
+ }
639
+
640
+ function declares(symbol: ts.Symbol, name: ts.Node): boolean {
641
+ return namingDeclarations(symbol).some(declaration => nameOf(declaration) === name);
642
+ }
643
+
644
+ function isBinding(name: ts.Identifier | ts.PrivateIdentifier, symbol: ts.Symbol): boolean {
645
+ const parent = name.parent;
646
+ return ts.isImportSpecifier(parent) || ts.isImportClause(parent) || ts.isNamespaceImport(parent) ||
647
+ ts.isImportEqualsDeclaration(parent) || ts.isExportSpecifier(parent) || ts.isNamespaceExport(parent) ||
648
+ (symbol.flags & ts.SymbolFlags.Alias) !== 0 && declares(symbol, name) ||
649
+ isModuleExports(parent) && ts.isBinaryExpression(parent.parent) && parent.parent.left === parent && !declares(symbol, name);
650
+ }
651
+
652
+ /** Whether `name` reads a property in an object pattern, which `const {a} = b` does as it declares `a`. */
653
+ function isBoundProperty(name: ts.Identifier | ts.PrivateIdentifier): boolean {
654
+ const element = name.parent;
655
+ return ts.isBindingElement(element) && ts.isObjectBindingPattern(element.parent) &&
656
+ name === (element.propertyName ?? element.name);
657
+ }
658
+
659
+ function isConstructed(name: ts.Node): boolean {
660
+ return ts.isNewExpression(name.parent) && name.parent.expression === name ||
661
+ ts.isPropertyAccessExpression(name.parent) && name.parent.name === name &&
662
+ ts.isNewExpression(name.parent.parent) && name.parent.parent.expression === name.parent;
663
+ }
664
+
665
+ function isModuleExports(node: ts.Node): boolean {
666
+ return ts.isPropertyAccessExpression(node) && node.name.text === "exports" &&
667
+ ts.isIdentifier(node.expression) && node.expression.text === "module" ||
668
+ ts.isIdentifier(node) && node.text === "exports";
669
+ }
670
+
671
+ /** `module.exports = {...}`, which is the module's own value, and its members the module's. */
672
+ function isModuleExportsObject(declaration: ts.Declaration): boolean {
673
+ return ts.isBinaryExpression(declaration) && isModuleExports(declaration.left) &&
674
+ ts.isObjectLiteralExpression(unwrapped(declaration.right));
675
+ }
676
+
677
+ /** The value inside any parentheses or assertion, where {@link outermost} is the expression around it. */
678
+ function unwrapped(expression: ts.Expression): ts.Expression {
679
+ let value = expression;
680
+ while (ts.isParenthesizedExpression(value) || ts.isAssertionExpression(value) || ts.isSatisfiesExpression(value) ||
681
+ ts.isNonNullExpression(value)) {
682
+ value = value.expression;
683
+ }
684
+ return value;
685
+ }
686
+
687
+ function isExpression(declaration: ts.Declaration): declaration is ts.FunctionExpression | ts.ArrowFunction | ts.ClassExpression {
688
+ return ts.isFunctionExpression(declaration) || ts.isArrowFunction(declaration) || ts.isClassExpression(declaration);
689
+ }
690
+
691
+ /** What the parser names by its type, which a package's own naming gives whole. */
692
+ function isNamedByType(declaration: ts.Declaration): boolean {
693
+ return ts.isClassLike(declaration) || ts.isInterfaceDeclaration(declaration) || ts.isEnumDeclaration(declaration) ||
694
+ ts.isTypeAliasDeclaration(declaration) || ts.isModuleDeclaration(declaration);
695
+ }
696
+
697
+ function isGlobalScope(symbol: ts.Symbol | undefined): boolean {
698
+ return symbol?.declarations?.some(d => ts.isModuleDeclaration(d) && (d.flags & ts.NodeFlags.GlobalAugmentation) !== 0) === true;
699
+ }
700
+
701
+ function lastSegment(declaration: ts.Declaration): string {
702
+ const name = ts.getNameOfDeclaration(declaration);
703
+ if (!name) {
704
+ return ts.isConstructorDeclaration(declaration) ? "<constructor>" : "default";
705
+ }
706
+ return ts.isComputedPropertyName(name) ? name.getText() : (name as ts.Identifier).text;
707
+ }
708
+
709
+ /** The expression in the position a literal is assigned from, past any parentheses or assertion around it. */
710
+ function outermost(literal: ts.Node): ts.Node {
711
+ let value = literal;
712
+ while (ts.isParenthesizedExpression(value.parent) || ts.isAssertionExpression(value.parent) ||
713
+ ts.isSatisfiesExpression(value.parent) || ts.isNonNullExpression(value.parent)) {
714
+ value = value.parent;
715
+ }
716
+ return value;
717
+ }
718
+
719
+ /** The name a value or a type literal is assigned to, as `o` in `const o = {}`, or none. */
720
+ function assignedName(value: ts.Node): ts.Node | undefined {
721
+ const parent = value.parent;
722
+ if ((ts.isVariableDeclaration(parent) || ts.isPropertyAssignment(parent) || ts.isPropertyDeclaration(parent) ||
723
+ ts.isPropertySignature(parent) || ts.isTypeAliasDeclaration(parent)) &&
724
+ (parent as { name: ts.Node }).name !== value) {
725
+ return (parent as { name: ts.Node }).name;
726
+ }
727
+ if (!ts.isBinaryExpression(parent) || parent.right !== value || parent.operatorToken.kind !== ts.SyntaxKind.EqualsToken) {
728
+ return undefined;
729
+ }
730
+ const left = parent.left;
731
+ if (ts.isPropertyAccessExpression(left) && left.name.text === "prototype") {
732
+ return leftmost(left.expression);
733
+ }
734
+ return ts.isPropertyAccessExpression(left) ? left.name : left;
735
+ }
736
+
737
+ function assignedValue(declaration: ts.Node): ts.Expression | undefined {
738
+ if (ts.isVariableDeclaration(declaration) || ts.isPropertyAssignment(declaration) || ts.isPropertyDeclaration(declaration)) {
739
+ return declaration.initializer;
740
+ }
741
+ if (ts.isBinaryExpression(declaration)) {
742
+ return declaration.right;
743
+ }
744
+ const parent = declaration.parent as ts.Node | undefined;
745
+ return parent && ts.isBinaryExpression(parent) && parent.left === declaration ? parent.right : undefined;
746
+ }
747
+
748
+ function propertyOf(type: ts.Type, name: string): ts.Symbol | undefined {
749
+ return type.isUnion() ? type.types.map(t => t.getProperty(name)).find(p => p !== undefined) : type.getProperty(name);
750
+ }
751
+
752
+ function leftmost(expression: ts.Expression): ts.Expression {
753
+ while (ts.isPropertyAccessExpression(expression) || ts.isElementAccessExpression(expression) ||
754
+ ts.isParenthesizedExpression(expression)) {
755
+ expression = expression.expression;
756
+ }
757
+ return expression;
758
+ }
759
+
760
+ /** Counted as the search index counts: lines end at a line feed and nothing else, as TypeScript's do not. */
761
+ function lineAndColumn(file: ts.SourceFile, offset: number): { line: number, column: number } {
762
+ const before = file.text.substring(0, offset);
763
+ const lineStart = before.lastIndexOf("\n") + 1;
764
+ return {line: before.split("\n").length, column: offset - lineStart + 1};
765
+ }
766
+
767
+ function printedOffsets(text: string): (offset: number) => number {
768
+ const surrogates = [...text.matchAll(/\p{Cs}/gu)].map(match => match.index);
769
+ return surrogates.length === 0 ? offset => offset :
770
+ offset => offset + ESCAPED_SURROGATE_GROWTH * surrogates.filter(at => at < offset).length;
771
+ }
772
+
773
+ function isModuleSpecifier(node: ts.StringLiteralLike): boolean {
774
+ const parent = node.parent;
775
+ if (ts.isImportDeclaration(parent) || ts.isExportDeclaration(parent)) {
776
+ return parent.moduleSpecifier === node;
777
+ }
778
+ if (ts.isExternalModuleReference(parent)) {
779
+ return true;
780
+ }
781
+ if (ts.isLiteralTypeNode(parent)) {
782
+ return ts.isImportTypeNode(parent.parent);
783
+ }
784
+ return ts.isModuleDeclaration(parent) || ts.isCallExpression(parent) && isModuleLoad(parent) && parent.arguments[0] === node;
785
+ }
786
+
787
+ /** In a module, `declare module` adds to the module it names, and declares none. */
788
+ function isAugmentation(node: ts.Node): boolean {
789
+ return ts.isModuleDeclaration(node) && ts.isExternalModule(node.getSourceFile());
790
+ }
791
+
792
+ function isModuleLoad(call: ts.CallExpression): boolean {
793
+ return call.expression.kind === ts.SyntaxKind.ImportKeyword ||
794
+ ts.isIdentifier(call.expression) && call.expression.text === "require";
795
+ }
796
+
797
+ /** `export default` of a value with no name of its own, as `export default a.b` has in `b`. */
798
+ function isNamelessDefaultExport(node: ts.Node): boolean {
799
+ if (ts.isExportAssignment(node)) {
800
+ return !node.isExportEquals && !ts.isIdentifier(node.expression) && !ts.isPropertyAccessExpression(node.expression);
801
+ }
802
+ return (ts.isFunctionDeclaration(node) || ts.isClassDeclaration(node)) && !node.name;
803
+ }
804
+
805
+ /** Declared where a function runs, as `this.x =` is, but on the class or module that holds it. */
806
+ function isMember(symbol: ts.Symbol, declaration: ts.Declaration): boolean {
807
+ return ts.isBinaryExpression(declaration) || ts.isPropertyAccessExpression(declaration) ||
808
+ ts.isElementAccessExpression(declaration) || ts.isCallExpression(declaration) ||
809
+ ts.isParameter(declaration) && (symbol.flags & ts.SymbolFlags.Property) !== 0;
810
+ }
811
+
812
+ function moduleSpecifierOf(declaration: ts.Node): ts.Expression | undefined {
813
+ if (ts.isImportClause(declaration)) {
814
+ return declaration.parent.moduleSpecifier;
815
+ }
816
+ if (ts.isNamespaceImport(declaration)) {
817
+ return declaration.parent.parent.moduleSpecifier;
818
+ }
819
+ if (ts.isImportSpecifier(declaration)) {
820
+ return declaration.parent.parent.parent.moduleSpecifier;
821
+ }
822
+ if (ts.isExportSpecifier(declaration)) {
823
+ return declaration.parent.parent.moduleSpecifier;
824
+ }
825
+ if (ts.isNamespaceExport(declaration)) {
826
+ return declaration.parent.moduleSpecifier;
827
+ }
828
+ if (ts.isImportEqualsDeclaration(declaration)) {
829
+ return ts.isExternalModuleReference(declaration.moduleReference) ?
830
+ declaration.moduleReference.expression : undefined;
831
+ }
832
+ if (ts.isBindingElement(declaration)) {
833
+ return moduleSpecifierOf(declaration.parent.parent);
834
+ }
835
+ if (ts.isVariableDeclaration(declaration) && declaration.initializer) {
836
+ return requiredModule(declaration.initializer);
837
+ }
838
+ return undefined;
839
+ }
840
+
841
+ function requiredModule(expression: ts.Expression): ts.Expression | undefined {
842
+ const root = leftmost(expression);
843
+ return ts.isCallExpression(root) && isModuleLoad(root) ? root.arguments[0] : undefined;
844
+ }
845
+
846
+ function readPackageName(directory: string): string | undefined {
847
+ try {
848
+ const {name} = JSON.parse(ts.sys.readFile(`${directory}/package.json`) ?? "{}");
849
+ return typeof name === "string" ? name : undefined;
850
+ } catch {
851
+ return undefined;
852
+ }
853
+ }