@stateward/core 1.2.2 → 1.3.0

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 (67) hide show
  1. package/dist/analyses.d.ts +37 -0
  2. package/dist/analyses.js +57 -0
  3. package/dist/backend/program-record.d.ts +7 -0
  4. package/dist/backend/typescript6.d.ts +33 -32
  5. package/dist/backend/typescript6.js +1438 -139
  6. package/dist/baseline.d.ts +1 -1
  7. package/dist/baseline.js +14 -10
  8. package/dist/cache.d.ts +74 -4
  9. package/dist/cache.js +211 -37
  10. package/dist/checker.d.ts +6 -1
  11. package/dist/checker.js +10 -0
  12. package/dist/class-id.d.ts +34 -0
  13. package/dist/class-id.js +93 -0
  14. package/dist/code-text.d.ts +8 -0
  15. package/dist/code-text.js +66 -0
  16. package/dist/config-file.js +7 -5
  17. package/dist/config.d.ts +10 -2
  18. package/dist/config.js +490 -48
  19. package/dist/define.d.ts +8 -2
  20. package/dist/disk-cache.d.ts +2 -0
  21. package/dist/disk-cache.js +77 -11
  22. package/dist/engine.d.ts +33 -1
  23. package/dist/engine.js +344 -24
  24. package/dist/fact-lines.d.ts +31 -0
  25. package/dist/fact-lines.js +197 -0
  26. package/dist/facts-versions.d.ts +27 -0
  27. package/dist/facts-versions.js +99 -0
  28. package/dist/fixes.js +4 -1
  29. package/dist/ignores.d.ts +11 -0
  30. package/dist/ignores.js +74 -27
  31. package/dist/implementation.d.ts +0 -6
  32. package/dist/implementation.js +0 -17
  33. package/dist/index.d.ts +8 -9
  34. package/dist/index.js +10 -7
  35. package/dist/internal.d.ts +7 -4
  36. package/dist/internal.js +5 -3
  37. package/dist/lazy.d.ts +8 -1
  38. package/dist/lazy.js +27 -2
  39. package/dist/ledger.d.ts +2 -2
  40. package/dist/ledger.js +2 -2
  41. package/dist/off-by-default.d.ts +13 -0
  42. package/dist/off-by-default.js +15 -0
  43. package/dist/options.d.ts +21 -5
  44. package/dist/options.js +22 -7
  45. package/dist/package-facts.d.ts +211 -17
  46. package/dist/package-facts.js +520 -38
  47. package/dist/plan.d.ts +1 -1
  48. package/dist/plan.js +7 -2
  49. package/dist/release.d.ts +12 -21
  50. package/dist/release.js +26 -38
  51. package/dist/renamed.d.ts +22 -3
  52. package/dist/renamed.js +50 -16
  53. package/dist/rollout.js +7 -4
  54. package/dist/severity.d.ts +1 -1
  55. package/dist/severity.js +17 -3
  56. package/dist/test-runner.d.ts +18 -0
  57. package/dist/test-runner.js +483 -0
  58. package/dist/testing.d.ts +3 -3
  59. package/dist/testing.js +5 -5
  60. package/dist/timing.d.ts +8 -0
  61. package/dist/timing.js +35 -1
  62. package/dist/types.d.ts +692 -19
  63. package/dist/unread.d.ts +90 -0
  64. package/dist/unread.js +405 -0
  65. package/dist/vocabulary.d.ts +1 -1
  66. package/dist/vocabulary.js +1 -1
  67. package/package.json +4 -2
@@ -1,12 +1,16 @@
1
1
  import path from "node:path";
2
2
  import picomatch from "picomatch";
3
3
  import ts from "typescript";
4
+ import { codeOnOneLine } from "../code-text.js";
4
5
  import { computeFingerprints, declarationTextHash, packageDependencies, packageEntries, packageManifests, packageNames, } from "./fingerprints.js";
5
6
  import { markedComments } from "./comments.js";
6
7
  import { recordInputs, recordingHost, replays } from "./program-record.js";
7
8
  import { declarationAtPath, declarationPath } from "./qualified-ids.js";
8
9
  import { displayPath } from "../display-path.js";
9
10
  import { expandTsconfigs } from "../tsconfigs.js";
11
+ import { testRunnerFiles } from "../test-runner.js";
12
+ import { checkFactKeys, factGrainOf, factKeysDigest, pathOf, readFactKeyChecks, } from "../package-facts.js";
13
+ import { declaredPackageOf } from "../class-id.js";
10
14
  /** The tsconfig could not be read or is invalid. */
11
15
  export class TsconfigError extends Error {
12
16
  /** The one change that fixes it, shown on a `= fix:` line. */
@@ -493,6 +497,64 @@ function unresolvedImportsOf(program, file) {
493
497
  }
494
498
  return found;
495
499
  }
500
+ /**
501
+ * The package modules one file imports, as TypeScript reads its imports (not its text): import
502
+ * and export declarations, `import x = require(…)`, `import(…)`, `require(…)`, `import("…")`
503
+ * types, and the JSX runtime a file with JSX uses by the project's `jsx` option. Relative and
504
+ * absolute paths are left out: they name the project's own files.
505
+ */
506
+ export function importedModules(sourceFile, options) {
507
+ const found = new Set();
508
+ const add = (specifier) => {
509
+ if (specifier === undefined || !ts.isStringLiteralLike(specifier))
510
+ return;
511
+ const name = specifier.text;
512
+ if (name === "" || name.startsWith(".") || path.isAbsolute(name))
513
+ return;
514
+ found.add(name);
515
+ };
516
+ const seen = { jsx: false };
517
+ const visit = (node) => {
518
+ if (ts.isImportDeclaration(node) || ts.isExportDeclaration(node)) {
519
+ add(node.moduleSpecifier);
520
+ }
521
+ else if (ts.isExternalModuleReference(node)) {
522
+ add(node.expression);
523
+ }
524
+ else if (ts.isImportTypeNode(node)) {
525
+ const argument = node.argument;
526
+ if (ts.isLiteralTypeNode(argument))
527
+ add(argument.literal);
528
+ }
529
+ else if (ts.isCallExpression(node)) {
530
+ const [first] = node.arguments;
531
+ const dynamic = node.expression.kind === ts.SyntaxKind.ImportKeyword;
532
+ const required = ts.isIdentifier(node.expression) && node.expression.text === "require";
533
+ if (dynamic || required)
534
+ add(first);
535
+ }
536
+ else if (ts.isJsxElement(node) ||
537
+ ts.isJsxSelfClosingElement(node) ||
538
+ ts.isJsxFragment(node)) {
539
+ seen.jsx = true;
540
+ }
541
+ ts.forEachChild(node, visit);
542
+ };
543
+ visit(sourceFile);
544
+ if (seen.jsx) {
545
+ if (options.jsx === ts.JsxEmit.ReactJSX || options.jsx === ts.JsxEmit.ReactJSXDev) {
546
+ found.add(`${options.jsxImportSource ?? "react"}/jsx-runtime`);
547
+ }
548
+ else if (options.jsx === ts.JsxEmit.React && options.jsxFactory === undefined) {
549
+ found.add("react");
550
+ }
551
+ }
552
+ return [...found].sort();
553
+ }
554
+ /** Whether `imported` (as `importedModules` gives them) names `module` or one of its subpaths. */
555
+ export function importsModuleIn(imported, module) {
556
+ return imported.some((name) => name === module || name.startsWith(`${module}/`));
557
+ }
496
558
  /** Whether a project with these options checks with `strictNullChecks` (TypeScript 6: on unless turned off). */
497
559
  export function checksNulls(options) {
498
560
  return options.strictNullChecks ?? options.strict ?? true;
@@ -583,10 +645,7 @@ function readTsconfig(given) {
583
645
  const libraryCache = new Map();
584
646
  const DEFAULT_LIB_DIRECTORY = toTypeScriptPath(path.dirname(ts.getDefaultLibFilePath({})));
585
647
  function isLibraryFile(fileName) {
586
- return isTypeScriptLib(fileName) || fileName.includes("/node_modules/");
587
- }
588
- function isTypeScriptLib(fileName) {
589
- return fileName.startsWith(DEFAULT_LIB_DIRECTORY);
648
+ return fileName.startsWith(DEFAULT_LIB_DIRECTORY) || fileName.includes("/node_modules/");
590
649
  }
591
650
  /**
592
651
  * What decides whether a cached source file still fits: how it is parsed. The options object
@@ -618,13 +677,7 @@ export function hostWithOverlays(options, overlays, cache,
618
677
  /** Serve a file that is not in `overlays` from `cache` without reading it from disk. */
619
678
  trustCache = false,
620
679
  /** Parse the JSDoc of TypeScript files too: a rule that is on reads it (`RuleMeta.needsJsDoc`). */
621
- jsDoc = false,
622
- /**
623
- * The files kept in the process-wide `libraryCache` rather than in `cache`. A package's own
624
- * JavaScript (`openPackageSource`) goes in `cache`, so it is freed with the package's program:
625
- * kept for the process, the packages a first run reads held over 500 MB on a large app.
626
- */
627
- shared = isLibraryFile) {
680
+ jsDoc = false) {
628
681
  const base = ts.createCompilerHost(options, true);
629
682
  return {
630
683
  ...base,
@@ -641,7 +694,7 @@ shared = isLibraryFile) {
641
694
  ? { ...requested, jsDocParsingMode: ts.JSDocParsingMode.ParseForTypeErrors }
642
695
  : requested;
643
696
  const optionsKey = parseKey(languageVersionOrOptions, options);
644
- const store = shared(fileName) ? libraryCache : cache;
697
+ const store = library ? libraryCache : cache;
645
698
  // By parse settings and name: two projects (a Vite app and its node config) read the same
646
699
  // library file with different settings, and one entry per name made each evict the other,
647
700
  // so every program parsed TypeScript's lib files and @types/react again.
@@ -693,7 +746,9 @@ function matcher(patterns) {
693
746
  return picomatch([...patterns], { dot: true });
694
747
  }
695
748
  /** The files of `parsed` that stateward checks and no earlier project has claimed. */
696
- function ownFileNames(parsed, config, cwd, claimed) {
749
+ function ownFileNames(parsed, config, cwd, claimed,
750
+ /** Whether a file is a test by the project's test-runner config (`test-runner.ts`). */
751
+ isTest) {
697
752
  const included = matcher(config.include);
698
753
  const excluded = matcher(config.exclude);
699
754
  const own = [];
@@ -702,7 +757,7 @@ function ownFileNames(parsed, config, cwd, claimed) {
702
757
  continue;
703
758
  const relative = path.relative(cwd, file).split(path.sep).join("/");
704
759
  const generated = file.endsWith(".d.ts") || file.includes("/node_modules/");
705
- if (!generated && included(relative) && !excluded(relative))
760
+ if (!generated && included(relative) && !excluded(relative) && !isTest(file))
706
761
  own.push(file);
707
762
  }
708
763
  return own;
@@ -724,6 +779,207 @@ function isArrayLike(checker, type) {
724
779
  return false;
725
780
  return (checker.getTypeOfSymbol(length).flags & ts.TypeFlags.NumberLike) !== 0;
726
781
  }
782
+ /** `TypeQueries.instanceClassesOf`: the classes an awaited type holds, through unions, arrays and wrappers. */
783
+ function instanceClassesOfType(checker, start, depth) {
784
+ const classes = [];
785
+ let any = false;
786
+ const seen = new Set();
787
+ const visit = (type, path, left, whole = true) => {
788
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) {
789
+ any = true;
790
+ return;
791
+ }
792
+ if (seen.has(type))
793
+ return;
794
+ seen.add(type);
795
+ const awaited = checker.getAwaitedType(type);
796
+ if (awaited !== undefined && awaited !== type) {
797
+ visit(awaited, path, left, whole);
798
+ return;
799
+ }
800
+ if (type.isUnionOrIntersection()) {
801
+ // A class in an intersection (`User & { orders: Order[] }`) is part of the value's type.
802
+ const part = whole && !type.isIntersection();
803
+ for (const member of type.types)
804
+ visit(member, path, left, part);
805
+ return;
806
+ }
807
+ if (!(type.flags & ts.TypeFlags.Object))
808
+ return;
809
+ if (checker.isArrayType(type) || checker.isTupleType(type)) {
810
+ if (!isTypeReference(type))
811
+ return;
812
+ for (const element of checker.getTypeArguments(type))
813
+ visit(element, `${path}[]`, left);
814
+ return;
815
+ }
816
+ const symbol = type.getSymbol();
817
+ const declaration = symbol?.declarations?.find(ts.isClassDeclaration);
818
+ if (symbol !== undefined && declaration !== undefined) {
819
+ // The instance side only: `typeof User` (the constructor) has the same symbol.
820
+ const instance = isTypeReference(type) ? type.target : type;
821
+ if (instance === checker.getDeclaredTypeOfSymbol(symbol)) {
822
+ classes.push({ name: symbol.getName(), declaration, path, whole });
823
+ }
824
+ return;
825
+ }
826
+ if (left <= 0 || type.getCallSignatures().length > 0)
827
+ return;
828
+ for (const property of checker.getPropertiesOfType(type)) {
829
+ const name = property.getName();
830
+ visit(checker.getTypeOfSymbol(property), path === "" ? name : `${path}.${name}`, left - 1);
831
+ }
832
+ };
833
+ visit(start, "", depth);
834
+ return { classes, any };
835
+ }
836
+ /** How many base types `genericBaseOf` reads above the type itself. */
837
+ const GENERIC_BASE_DEPTH = 8;
838
+ /**
839
+ * `TypeQueries.genericBaseOf`: the nearest generic base of a package, with its type arguments,
840
+ * through `this` and type parameters (their constraint) and the members of an intersection. A
841
+ * base written with the subclass's own type parameter (`class Base<T> extends Repository<T>`) is
842
+ * given the argument the value's type gives that parameter (`Base<User>` gives `User`).
843
+ */
844
+ function genericBaseOfType(checker, start, inPackage, names) {
845
+ const members = start.isUnion()
846
+ ? start.types.filter((one) => !(one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
847
+ : [start];
848
+ const [only] = members;
849
+ if (only === undefined || members.length > 1)
850
+ return undefined;
851
+ const argumentOf = (type) => {
852
+ const symbol = type.getSymbol();
853
+ const declaration = symbol?.declarations?.find(ts.isClassDeclaration);
854
+ const instance = isTypeReference(type) ? type.target : type;
855
+ return symbol !== undefined &&
856
+ declaration !== undefined &&
857
+ instance === checker.getDeclaredTypeOfSymbol(symbol)
858
+ ? { kind: "class", name: symbol.getName(), declaration }
859
+ : { kind: "other", text: checker.typeToString(type) };
860
+ };
861
+ const seen = new Set();
862
+ let level = [{ type: only, given: new Map() }];
863
+ for (let depth = 0; depth <= GENERIC_BASE_DEPTH && level.length > 0; depth++) {
864
+ const next = [];
865
+ for (const { type, given } of level) {
866
+ if (seen.has(type))
867
+ continue;
868
+ seen.add(type);
869
+ // `this` in a class's method, or a type parameter: read its constraint (the class itself).
870
+ if (type.flags & ts.TypeFlags.TypeParameter) {
871
+ const constraint = checker.getBaseConstraintOfType(type);
872
+ if (constraint !== undefined && constraint !== type)
873
+ next.push({ type: constraint, given });
874
+ continue;
875
+ }
876
+ // `getRepository(User).extend({ … })` gives `Repository<User> & { … }`: read each member.
877
+ if (type.isIntersection()) {
878
+ for (const member of type.types)
879
+ next.push({ type: member, given });
880
+ continue;
881
+ }
882
+ const written = isTypeReference(type) ? checker.getTypeArguments(type) : [];
883
+ const actual = written.map((one) => given.get(one) ?? one);
884
+ const symbol = type.getSymbol();
885
+ if (symbol !== undefined && names.has(symbol.getName()) && inPackage(symbol)) {
886
+ return { name: symbol.getName(), typeArguments: actual.map(argumentOf) };
887
+ }
888
+ const target = isTypeReference(type) ? type.target : type;
889
+ if (!target.isClassOrInterface())
890
+ continue;
891
+ const parameters = target.typeParameters ?? [];
892
+ const passed = new Map();
893
+ parameters.forEach((parameter, index) => {
894
+ const argument = actual[index];
895
+ if (argument !== undefined)
896
+ passed.set(parameter, argument);
897
+ });
898
+ for (const base of checker.getBaseTypes(target))
899
+ next.push({ type: base, given: passed });
900
+ }
901
+ level = next;
902
+ }
903
+ return undefined;
904
+ }
905
+ /**
906
+ * `TypeQueries.isOrExtends`: whether a type, or one of its base types up to `GENERIC_BASE_DEPTH`
907
+ * levels, is declared by one of `classes`. A class's own type (`typeof Store`) is read as its
908
+ * instances, `this` and a type parameter as their constraint, an intersection as its members.
909
+ */
910
+ function isOrExtendsType(checker, start, classes) {
911
+ const members = start.isUnion()
912
+ ? start.types.filter((one) => !(one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)))
913
+ : [start];
914
+ const [only] = members;
915
+ if (only === undefined || members.length > 1)
916
+ return false;
917
+ const seen = new Set();
918
+ let level = [only];
919
+ for (let depth = 0; depth <= GENERIC_BASE_DEPTH && level.length > 0; depth++) {
920
+ const next = [];
921
+ for (const type of level) {
922
+ if (seen.has(type))
923
+ continue;
924
+ seen.add(type);
925
+ if (type.flags & ts.TypeFlags.TypeParameter) {
926
+ const constraint = checker.getBaseConstraintOfType(type);
927
+ if (constraint !== undefined && constraint !== type)
928
+ next.push(constraint);
929
+ continue;
930
+ }
931
+ if (type.isIntersection()) {
932
+ next.push(...type.types);
933
+ continue;
934
+ }
935
+ const symbol = type.getSymbol();
936
+ if ((symbol?.declarations ?? []).some((declaration) => classes.has(declaration))) {
937
+ return true;
938
+ }
939
+ const target = isTypeReference(type) ? type.target : type;
940
+ if (target.isClassOrInterface()) {
941
+ next.push(...checker.getBaseTypes(target));
942
+ continue;
943
+ }
944
+ // A class read as a value (`Store.create()`): its static side, read as its instances.
945
+ if (symbol !== undefined && symbol.flags & ts.SymbolFlags.Class) {
946
+ const instance = checker.getDeclaredTypeOfSymbol(symbol);
947
+ if (instance !== type)
948
+ next.push(instance);
949
+ }
950
+ }
951
+ level = next;
952
+ }
953
+ return false;
954
+ }
955
+ /** Whether a written type names a type parameter anywhere in it (`T`, `T[]`, `Promise<T>`, `T["id"]`). */
956
+ function holdsTypeParameter(checker, node) {
957
+ let found = false;
958
+ const visit = (current) => {
959
+ if (found)
960
+ return;
961
+ if (ts.isTypeReferenceNode(current) &&
962
+ checker.getTypeFromTypeNode(current).flags & ts.TypeFlags.TypeParameter) {
963
+ found = true;
964
+ return;
965
+ }
966
+ ts.forEachChild(current, visit);
967
+ };
968
+ visit(node);
969
+ return found;
970
+ }
971
+ /**
972
+ * Whether a declaration is in the global scope: in a `declare global` block, or in a file that is
973
+ * not a module (TypeScript's lib, a script `.d.ts`).
974
+ */
975
+ function isGlobalDeclaration(declaration) {
976
+ for (let node = declaration.parent;; node = node.parent) {
977
+ if (ts.isSourceFile(node))
978
+ return !ts.isExternalModule(node);
979
+ if (ts.isModuleDeclaration(node))
980
+ return (node.flags & ts.NodeFlags.GlobalAugmentation) !== 0;
981
+ }
982
+ }
727
983
  function compareLabels(a, b) {
728
984
  if (a.label < b.label)
729
985
  return -1;
@@ -773,6 +1029,22 @@ function isAnonymousObject(type) {
773
1029
  typeof type.objectFlags === "number" &&
774
1030
  (type.objectFlags & ts.ObjectFlags.Anonymous) !== 0);
775
1031
  }
1032
+ /** Which of TypeScript's own types `type` is, from its flags (`TypeQueries.builtinTypeOf`). */
1033
+ function builtinOf(type) {
1034
+ if ((type.flags & ts.TypeFlags.Any) !== 0)
1035
+ return "any";
1036
+ if ((type.flags & ts.TypeFlags.Unknown) !== 0)
1037
+ return "unknown";
1038
+ if ((type.flags & ts.TypeFlags.Never) !== 0)
1039
+ return "never";
1040
+ if ((type.flags & ts.TypeFlags.Void) !== 0)
1041
+ return "void";
1042
+ if ((type.flags & ts.TypeFlags.Undefined) !== 0)
1043
+ return "undefined";
1044
+ if ((type.flags & ts.TypeFlags.Null) !== 0)
1045
+ return "null";
1046
+ return undefined;
1047
+ }
776
1048
  function widened(checker, type) {
777
1049
  return type.isTypeParameter() ? checker.getBaseConstraintOfType(type) : type;
778
1050
  }
@@ -815,6 +1087,26 @@ function isPromiseType(checker, type) {
815
1087
  const awaited = checker.getAwaitedType(type);
816
1088
  return awaited !== undefined && awaited !== type;
817
1089
  }
1090
+ /** A type that stands for another one not known where it is declared (`T`, `T[K]`, `T extends U ? X : Y`). */
1091
+ const STANDS_FOR_ANOTHER = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.InstantiableNonPrimitive;
1092
+ /**
1093
+ * Whether a value of the type can be a promise: a promise-like type, `any`, `unknown`, a type
1094
+ * parameter or a type built on one, a type the global `Promise` is assignable to (`object`,
1095
+ * `{}`), or a union or an intersection with such a member.
1096
+ */
1097
+ function mayBePromiseType(checker, type) {
1098
+ if (type.flags & STANDS_FOR_ANOTHER)
1099
+ return true;
1100
+ if (type.isUnion())
1101
+ return type.types.some((part) => mayBePromiseType(checker, part));
1102
+ if (type.isIntersection())
1103
+ return type.types.some((part) => mayBePromiseType(checker, part));
1104
+ if (isPromiseType(checker, type))
1105
+ return true;
1106
+ const promise = checker.resolveName("Promise", undefined, ts.SymbolFlags.Type, false);
1107
+ return (promise !== undefined &&
1108
+ checker.isTypeAssignableTo(checker.getDeclaredTypeOfSymbol(promise), type));
1109
+ }
818
1110
  const NULLISH = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
819
1111
  /** The property a stated guarantee is written in by 1.1.0 (`__guarantee?: "owned"`). */
820
1112
  const GUARANTEE_PROPERTY = "__guarantee";
@@ -879,7 +1171,7 @@ function definesMarker(type) {
879
1171
  /**
880
1172
  * The declarations of a file whose written type states a guarantee, in source order
881
1173
  * (`TypeQueries.statedDeclarationsIn`). A function's return type is not one: what it states
882
- * (`Release<…>`) reaches the code through each call, which a rule reads there.
1174
+ * (`Owned<…>`) reaches the code through each call, which a rule reads there.
883
1175
  */
884
1176
  function statedDeclarationsOf(checker, sourceFile) {
885
1177
  const found = [];
@@ -1100,20 +1392,21 @@ function guaranteesOfType(checker, found) {
1100
1392
  return [...new Set(shared ?? [])].sort();
1101
1393
  }
1102
1394
  /**
1103
- * The literals of the `"__guarantee:<name>"` property of `type` (its first member that states it),
1104
- * without the `undefined` the optional property adds; undefined when no member states it.
1395
+ * The literals of the optional property `property` of `type` (its first member that states it),
1396
+ * without the `undefined` the optional property adds; undefined when no member states it. A
1397
+ * guarantee's is `"__guarantee:<name>"`.
1105
1398
  */
1106
- function guaranteeValuesOfType(checker, found, name) {
1399
+ function markerValuesOfType(checker, found, property) {
1107
1400
  const type = widened(checker, found);
1108
1401
  if (type === undefined)
1109
1402
  return undefined;
1110
1403
  for (const member of type.isUnion() ? type.types : [type]) {
1111
1404
  if (member.flags & NULLISH)
1112
1405
  continue;
1113
- const property = checker.getPropertyOfType(member, `${GUARANTEE_PREFIX}${name}`);
1114
- if (property === undefined || !(property.flags & ts.SymbolFlags.Optional))
1406
+ const marker = checker.getPropertyOfType(member, property);
1407
+ if (marker === undefined || !(marker.flags & ts.SymbolFlags.Optional))
1115
1408
  continue;
1116
- const value = checker.getTypeOfSymbol(property);
1409
+ const value = checker.getTypeOfSymbol(marker);
1117
1410
  const literals = [];
1118
1411
  for (const part of value.isUnion() ? value.types : [value]) {
1119
1412
  if (part.flags & ts.TypeFlags.Undefined)
@@ -1499,6 +1792,147 @@ function signalParameter(checker, call) {
1499
1792
  }
1500
1793
  return undefined;
1501
1794
  }
1795
+ /** As `TypeQueries.parameterTakesUnknown`. */
1796
+ function takesUnknown(checker, call, index) {
1797
+ if (call.arguments.slice(0, index + 1).some(ts.isSpreadElement))
1798
+ return false;
1799
+ const declaration = checker.getResolvedSignature(call)?.getDeclaration();
1800
+ if (declaration === undefined || ts.isJSDocSignature(declaration))
1801
+ return false;
1802
+ const parameter = declaration.parameters[index];
1803
+ if (parameter === undefined || parameter.dotDotDotToken !== undefined)
1804
+ return false;
1805
+ // The declared type, before the call's type arguments replace a type parameter.
1806
+ const type = checker.getTypeAtLocation(parameter);
1807
+ if (type.flags & ts.TypeFlags.Unknown)
1808
+ return true;
1809
+ if (!type.isTypeParameter())
1810
+ return false;
1811
+ // Only the function's own type parameter: a class's (`Map<K, V>.set`) is fixed by the instance.
1812
+ const owner = type.getSymbol()?.declarations?.[0]?.parent;
1813
+ if (owner !== declaration)
1814
+ return false;
1815
+ const constraint = type.getConstraint();
1816
+ return constraint === undefined || (constraint.flags & ts.TypeFlags.Unknown) !== 0;
1817
+ }
1818
+ /** Whether a declaration is, or is written inside, a type, interface or class with type parameters. */
1819
+ function insideGeneric(declaration) {
1820
+ for (let at = declaration; !ts.isSourceFile(at); at = at.parent) {
1821
+ if ((ts.isTypeAliasDeclaration(at) || ts.isInterfaceDeclaration(at) || ts.isClassLike(at)) &&
1822
+ (at.typeParameters ?? []).length > 0) {
1823
+ return true;
1824
+ }
1825
+ }
1826
+ return false;
1827
+ }
1828
+ /** How deep `typeShape` follows nested object types before it gives up. */
1829
+ const SHAPE_DEPTH = 8;
1830
+ /** As `TypeQueries.typeShapeOf`, for a type; `inside` holds the object types being read. */
1831
+ function typeShape(isPlatformFile, checker, type, inside) {
1832
+ if (inside.length > SHAPE_DEPTH)
1833
+ return undefined;
1834
+ if (type.flags & ts.TypeFlags.EnumLike)
1835
+ return undefined;
1836
+ if (type.isUnion()) {
1837
+ const members = [];
1838
+ let booleans = 0;
1839
+ for (const member of type.types) {
1840
+ if (member.flags & ts.TypeFlags.BooleanLiteral) {
1841
+ booleans += 1;
1842
+ continue;
1843
+ }
1844
+ const shape = typeShape(isPlatformFile, checker, member, inside);
1845
+ if (shape === undefined)
1846
+ return undefined;
1847
+ members.push(shape);
1848
+ }
1849
+ // `boolean` is `true | false` to the checker; a check tests it with `typeof`.
1850
+ if (booleans === 2)
1851
+ members.push({ kind: "primitive", name: "boolean" });
1852
+ else if (booleans === 1) {
1853
+ const literal = type.types.find((member) => member.flags & ts.TypeFlags.BooleanLiteral);
1854
+ const shape = literal === undefined ? undefined : typeShape(isPlatformFile, checker, literal, inside);
1855
+ if (shape === undefined)
1856
+ return undefined;
1857
+ members.push(shape);
1858
+ }
1859
+ return members.length === 1 && members[0] !== undefined
1860
+ ? members[0]
1861
+ : { kind: "union", members };
1862
+ }
1863
+ if (type.flags & ts.TypeFlags.Boolean)
1864
+ return { kind: "primitive", name: "boolean" };
1865
+ const literal = literalOf(checker, type);
1866
+ if (literal !== undefined && !(type.flags & ts.TypeFlags.Intersection)) {
1867
+ return { kind: "literal", literal };
1868
+ }
1869
+ if (type.flags & ts.TypeFlags.String)
1870
+ return { kind: "primitive", name: "string" };
1871
+ if (type.flags & ts.TypeFlags.Number)
1872
+ return { kind: "primitive", name: "number" };
1873
+ if (type.flags & ts.TypeFlags.BigInt)
1874
+ return { kind: "primitive", name: "bigint" };
1875
+ if (!(type.flags & ts.TypeFlags.Object) || type.isIntersection())
1876
+ return undefined;
1877
+ if (checker.isArrayType(type) && isTypeReference(type)) {
1878
+ const [element] = checker.getTypeArguments(type);
1879
+ const shape = element === undefined
1880
+ ? undefined
1881
+ : typeShape(isPlatformFile, checker, element, [...inside, type]);
1882
+ return shape === undefined ? undefined : { kind: "array", element: shape };
1883
+ }
1884
+ if (checker.isTupleType(type))
1885
+ return undefined;
1886
+ if (isTypeReference(type) && checker.getTypeArguments(type).length > 0)
1887
+ return undefined;
1888
+ if ((type.aliasTypeArguments ?? []).length > 0)
1889
+ return undefined;
1890
+ if (type.getCallSignatures().length > 0 || type.getConstructSignatures().length > 0) {
1891
+ return undefined;
1892
+ }
1893
+ if (checker.getIndexInfosOfType(type).length > 0)
1894
+ return undefined;
1895
+ const symbol = type.getSymbol();
1896
+ const declarations = symbol?.declarations ?? [];
1897
+ if (declarations.some((one) => isPlatformFile(one.getSourceFile()))) {
1898
+ return undefined;
1899
+ }
1900
+ const named = type.aliasSymbol?.getName() ?? symbol?.getName();
1901
+ const name = named === undefined || named.startsWith("__") ? undefined : named;
1902
+ // The type's identity: two types of one name (`billing.Address`, `shipping.Address`) differ.
1903
+ const first = declarations[0];
1904
+ const id = first === undefined
1905
+ ? checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation)
1906
+ : `${first.getSourceFile().fileName}:${String(first.pos)}`;
1907
+ if (inside.includes(type)) {
1908
+ return name === undefined ? undefined : { kind: "recursive", id, name };
1909
+ }
1910
+ const hidden = declarations.some((one) => ts.isClassLike(one) &&
1911
+ one.members.some((member) => (member.name !== undefined && ts.isPrivateIdentifier(member.name)) ||
1912
+ (ts.getCombinedModifierFlags(member) &
1913
+ (ts.ModifierFlags.Private | ts.ModifierFlags.Protected)) !==
1914
+ 0));
1915
+ if (hidden || declarations.some(insideGeneric))
1916
+ return undefined;
1917
+ const properties = [];
1918
+ for (const property of checker.getPropertiesOfType(type)) {
1919
+ if (property.flags & (ts.SymbolFlags.Method | ts.SymbolFlags.Accessor))
1920
+ return undefined;
1921
+ const shape = typeShape(isPlatformFile, checker, checker.getTypeOfSymbol(property), [
1922
+ ...inside,
1923
+ type,
1924
+ ]);
1925
+ if (shape === undefined)
1926
+ return undefined;
1927
+ properties.push({
1928
+ name: property.getName(),
1929
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
1930
+ shape,
1931
+ });
1932
+ }
1933
+ const text = name ?? checker.typeToString(type, undefined, ts.TypeFormatFlags.NoTruncation);
1934
+ return { kind: "object", id, name, text: text.replace(/\s+/g, " ").trim(), properties };
1935
+ }
1502
1936
  function withoutNullish(type) {
1503
1937
  const nothing = ts.TypeFlags.Null | ts.TypeFlags.Undefined;
1504
1938
  return (type.isUnion() ? type.types : [type]).filter((member) => !(member.flags & nothing));
@@ -1682,7 +2116,7 @@ function tagText(tag, sourceFile) {
1682
2116
  return text.length <= REFERENCE_TEXT_MAX ? text : `${text.slice(0, REFERENCE_TEXT_MAX - 1)}…`;
1683
2117
  }
1684
2118
  function shortText(node, sourceFile) {
1685
- const text = node.getText(sourceFile).replace(/\s+/g, " ").trim();
2119
+ const text = codeOnOneLine(node.getText(sourceFile));
1686
2120
  return text.length <= REFERENCE_TEXT_MAX ? text : `${text.slice(0, REFERENCE_TEXT_MAX - 1)}…`;
1687
2121
  }
1688
2122
  function isWrapperExpression(node) {
@@ -1881,7 +2315,7 @@ function createLedgerScan(program, typeChecker, isOwn, refOfSymbol) {
1881
2315
  const checker = typeChecker();
1882
2316
  return guaranteesOfType(checker, checker.getTypeFromTypeNode(type)).filter((one) => wanted.has(one));
1883
2317
  };
1884
- /** A rest parameter states a trait by its elements: `...stops: Release<…>[]`. */
2318
+ /** A rest parameter states a trait by its elements: `...stops: Owned<…>[]`. */
1885
2319
  const restTraits = (type, wanted) => {
1886
2320
  const checker = typeChecker();
1887
2321
  const element = checker.getIndexTypeOfType(checker.getTypeFromTypeNode(type), ts.IndexKind.Number);
@@ -3473,10 +3907,24 @@ function onlyPrimitives(checker, found, depth) {
3473
3907
  * TS2366, TS2355, TS2534 and TS7030 (`TypeQueries.reportsReachableEnd`).
3474
3908
  */
3475
3909
  const REACHABLE_END_CODES = new Set([2366, 2355, 2534, 7030]);
3476
- /** A file of the platform: TypeScript's own lib, or Node's types. */
3477
- function isPlatformSourceFile(program, file) {
3478
- return (program.isSourceFileDefaultLibrary(file) ||
3479
- /[\\/]node_modules[\\/]@types[\\/]node[\\/]/.test(file.fileName));
3910
+ /**
3911
+ * The platform's packages every project has: Node's types. TypeScript's own lib is the platform
3912
+ * too; the config's `platform` adds more (`bun-types`, `@cloudflare/workers-types`).
3913
+ */
3914
+ export const PLATFORM_PACKAGES = ["@types/node"];
3915
+ /** `@types/node` as a path pattern: `/node_modules/@types/node/`, either slash. */
3916
+ function packagePathPattern(name) {
3917
+ const escaped = name.split("/").map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"));
3918
+ return `[\\\\/]node_modules[\\\\/]${escaped.join("[\\\\/]")}[\\\\/]`;
3919
+ }
3920
+ /**
3921
+ * The test of whether a file is of the platform: TypeScript's own lib, or a file of one of the
3922
+ * platform's packages (`PLATFORM_PACKAGES` and the config's `platform`).
3923
+ */
3924
+ function platformFiles(program, extra) {
3925
+ const names = [...new Set([...PLATFORM_PACKAGES, ...extra])];
3926
+ const pattern = new RegExp(names.map(packagePathPattern).join("|"));
3927
+ return (file) => program.isSourceFileDefaultLibrary(file) || pattern.test(file.fileName);
3480
3928
  }
3481
3929
  /** Properties of the platform's types that are plain data on the closed list, as `<type>.<name>`. */
3482
3930
  const PLATFORM_PROPERTIES = new Set([
@@ -3511,13 +3959,234 @@ function isNumberType(type) {
3511
3959
  return type.types.some(isNumberType);
3512
3960
  return (type.flags & ts.TypeFlags.NumberLike) !== 0;
3513
3961
  }
3962
+ const OBJECT = { kind: "global", name: "Object" };
3963
+ const UNDEFINED = { kind: "undefined" };
3964
+ /** The type nodes whose constructor is fixed by their kind (`number` is `Number`). */
3965
+ const KEYWORD_METADATA = new Map([
3966
+ [ts.SyntaxKind.VoidKeyword, UNDEFINED],
3967
+ [ts.SyntaxKind.UndefinedKeyword, UNDEFINED],
3968
+ [ts.SyntaxKind.NeverKeyword, UNDEFINED],
3969
+ [ts.SyntaxKind.FunctionType, { kind: "global", name: "Function" }],
3970
+ [ts.SyntaxKind.ConstructorType, { kind: "global", name: "Function" }],
3971
+ [ts.SyntaxKind.ArrayType, { kind: "global", name: "Array" }],
3972
+ [ts.SyntaxKind.TupleType, { kind: "global", name: "Array" }],
3973
+ [ts.SyntaxKind.BooleanKeyword, { kind: "global", name: "Boolean" }],
3974
+ [ts.SyntaxKind.TemplateLiteralType, { kind: "global", name: "String" }],
3975
+ [ts.SyntaxKind.StringKeyword, { kind: "global", name: "String" }],
3976
+ [ts.SyntaxKind.NumberKeyword, { kind: "global", name: "Number" }],
3977
+ [ts.SyntaxKind.BigIntKeyword, { kind: "global", name: "BigInt" }],
3978
+ [ts.SyntaxKind.SymbolKeyword, { kind: "global", name: "Symbol" }],
3979
+ ]);
3980
+ function global(name) {
3981
+ return { kind: "global", name };
3982
+ }
3983
+ function sameMetadata(a, b) {
3984
+ switch (a.kind) {
3985
+ case "global":
3986
+ return b.kind === "global" && a.name === b.name;
3987
+ case "undefined":
3988
+ return b.kind === "undefined";
3989
+ case "class":
3990
+ return b.kind === "class" && a.name === b.name;
3991
+ case "unresolved":
3992
+ return b.kind === "unresolved" && a.name === b.name;
3993
+ default: {
3994
+ const unreachable = a;
3995
+ return unreachable;
3996
+ }
3997
+ }
3998
+ }
3999
+ /** The compiler's `serializeTypeNode`, giving the constructor instead of an expression. */
4000
+ function serializedTypeNode(context, given) {
4001
+ if (given === undefined)
4002
+ return OBJECT;
4003
+ let node = given;
4004
+ while (ts.isParenthesizedTypeNode(node))
4005
+ node = node.type;
4006
+ const keyword = KEYWORD_METADATA.get(node.kind);
4007
+ if (keyword !== undefined)
4008
+ return keyword;
4009
+ if (ts.isTypePredicateNode(node)) {
4010
+ return node.assertsModifier === undefined ? global("Boolean") : UNDEFINED;
4011
+ }
4012
+ if (ts.isLiteralTypeNode(node))
4013
+ return serializedLiteral(node.literal);
4014
+ if (ts.isTypeReferenceNode(node))
4015
+ return serializedReference(context, node.typeName);
4016
+ if (ts.isUnionTypeNode(node))
4017
+ return serializedMembers(context, node.types, false);
4018
+ if (ts.isIntersectionTypeNode(node))
4019
+ return serializedMembers(context, node.types, true);
4020
+ if (ts.isConditionalTypeNode(node)) {
4021
+ return serializedMembers(context, [node.trueType, node.falseType], false);
4022
+ }
4023
+ if (ts.isTypeOperatorNode(node) && node.operator === ts.SyntaxKind.ReadonlyKeyword) {
4024
+ return serializedTypeNode(context, node.type);
4025
+ }
4026
+ return OBJECT;
4027
+ }
4028
+ function serializedLiteral(literal) {
4029
+ if (ts.isPrefixUnaryExpression(literal)) {
4030
+ return ts.isBigIntLiteral(literal.operand) ? global("BigInt") : global("Number");
4031
+ }
4032
+ if (ts.isStringLiteral(literal) || ts.isNoSubstitutionTemplateLiteral(literal)) {
4033
+ return global("String");
4034
+ }
4035
+ if (ts.isNumericLiteral(literal))
4036
+ return global("Number");
4037
+ if (ts.isBigIntLiteral(literal))
4038
+ return global("BigInt");
4039
+ if (literal.kind === ts.SyntaxKind.TrueKeyword || literal.kind === ts.SyntaxKind.FalseKeyword) {
4040
+ return global("Boolean");
4041
+ }
4042
+ return UNDEFINED;
4043
+ }
4044
+ /** The compiler's `serializeUnionOrIntersectionConstituents`. */
4045
+ function serializedMembers(context, types, isIntersection) {
4046
+ let serialized;
4047
+ for (const written of types) {
4048
+ let member = written;
4049
+ while (ts.isParenthesizedTypeNode(member))
4050
+ member = member.type;
4051
+ if (member.kind === ts.SyntaxKind.NeverKeyword) {
4052
+ if (isIntersection)
4053
+ return UNDEFINED;
4054
+ continue;
4055
+ }
4056
+ if (member.kind === ts.SyntaxKind.UnknownKeyword) {
4057
+ if (!isIntersection)
4058
+ return OBJECT;
4059
+ continue;
4060
+ }
4061
+ if (member.kind === ts.SyntaxKind.AnyKeyword)
4062
+ return OBJECT;
4063
+ const nullish = member.kind === ts.SyntaxKind.UndefinedKeyword ||
4064
+ (ts.isLiteralTypeNode(member) && member.literal.kind === ts.SyntaxKind.NullKeyword);
4065
+ if (nullish && !context.keepsNullish)
4066
+ continue;
4067
+ const one = serializedTypeNode(context, member);
4068
+ if (one.kind === "global" && one.name === "Object")
4069
+ return one;
4070
+ if (serialized === undefined)
4071
+ serialized = one;
4072
+ else if (!sameMetadata(serialized, one))
4073
+ return OBJECT;
4074
+ }
4075
+ return serialized ?? UNDEFINED;
4076
+ }
4077
+ /** An import or export that brings only a type (`import type`, `import { type X }`). */
4078
+ function isTypeOnlyAlias(symbol) {
4079
+ const declarations = symbol.declarations ?? [];
4080
+ return declarations.length > 0 && declarations.every(ts.isTypeOnlyImportOrExportDeclaration);
4081
+ }
4082
+ /** The compiler's `getTypeReferenceSerializationKind` and `serializeTypeReferenceNode`. */
4083
+ function serializedReference(context, typeName) {
4084
+ const { checker } = context;
4085
+ const name = typeName.getText();
4086
+ const resolve = (symbol) => symbol !== undefined && symbol.flags & ts.SymbolFlags.Alias
4087
+ ? checker.getAliasedSymbol(symbol)
4088
+ : symbol;
4089
+ // The name as a value (what the emitted code would reach at run time) and as a type.
4090
+ const written = ts.isIdentifier(typeName)
4091
+ ? checker.resolveName(typeName.text, typeName, ts.SymbolFlags.Value, false)
4092
+ : checker.getSymbolAtLocation(typeName);
4093
+ const valueSymbol = written !== undefined && written.flags & (ts.SymbolFlags.Value | ts.SymbolFlags.Alias)
4094
+ ? written
4095
+ : undefined;
4096
+ const typeSymbol = resolve(checker.getSymbolAtLocation(typeName));
4097
+ const value = resolve(valueSymbol);
4098
+ const isTypeOnly = valueSymbol !== undefined && isTypeOnlyAlias(valueSymbol);
4099
+ if (value !== undefined && value === typeSymbol) {
4100
+ const promise = checker.resolveName("Promise", undefined, ts.SymbolFlags.Value, false);
4101
+ if (promise !== undefined && value === promise)
4102
+ return global("Promise");
4103
+ const constructorType = checker.getTypeOfSymbol(value);
4104
+ if (constructorType.getConstructSignatures().length > 0) {
4105
+ return isTypeOnly
4106
+ ? global("Function")
4107
+ : { kind: "class", name, symbol: context.refOf(value) };
4108
+ }
4109
+ }
4110
+ // A name that does not resolve gives no symbol, or the checker's unknown symbol (no declarations).
4111
+ if (typeSymbol === undefined || (typeSymbol.declarations ?? []).length === 0) {
4112
+ return isTypeOnly ? OBJECT : { kind: "unresolved", name };
4113
+ }
4114
+ const type = checker.getDeclaredTypeOfSymbol(typeSymbol);
4115
+ if (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
4116
+ return OBJECT;
4117
+ const isKind = (flags, target) => (type.flags & flags) !== 0 || checker.isTypeAssignableTo(type, target);
4118
+ if (isKind(ts.TypeFlags.Void, checker.getVoidType()) ||
4119
+ isKind(ts.TypeFlags.Undefined, checker.getUndefinedType()) ||
4120
+ isKind(ts.TypeFlags.Null, checker.getNullType()) ||
4121
+ isKind(ts.TypeFlags.Never, checker.getNeverType())) {
4122
+ return UNDEFINED;
4123
+ }
4124
+ if (isKind(ts.TypeFlags.BooleanLike, checker.getBooleanType()))
4125
+ return global("Boolean");
4126
+ if (isKind(ts.TypeFlags.NumberLike, checker.getNumberType()))
4127
+ return global("Number");
4128
+ if (isKind(ts.TypeFlags.BigIntLike, checker.getBigIntType()))
4129
+ return global("BigInt");
4130
+ if (isKind(ts.TypeFlags.StringLike, checker.getStringType()))
4131
+ return global("String");
4132
+ if (checker.isTupleType(type))
4133
+ return global("Array");
4134
+ if (isKind(ts.TypeFlags.ESSymbolLike, checker.getESSymbolType()))
4135
+ return global("Symbol");
4136
+ if (type.flags & ts.TypeFlags.Object && type.getCallSignatures().length > 0) {
4137
+ return global("Function");
4138
+ }
4139
+ if (checker.isArrayType(type))
4140
+ return global("Array");
4141
+ return OBJECT;
4142
+ }
4143
+ /** The type node TypeScript serializes for a parameter: a rest parameter's element type. */
4144
+ function metadataTypeNode(node) {
4145
+ if (!ts.isParameter(node) || node.dotDotDotToken === undefined)
4146
+ return node.type;
4147
+ const type = node.type;
4148
+ if (type === undefined)
4149
+ return undefined;
4150
+ if (ts.isArrayTypeNode(type))
4151
+ return type.elementType;
4152
+ if (ts.isTypeReferenceNode(type) && type.typeArguments?.length === 1) {
4153
+ return type.typeArguments[0];
4154
+ }
4155
+ return undefined;
4156
+ }
4157
+ function decoratorMetadata(options, context, node) {
4158
+ if (options.experimentalDecorators !== true || options.emitDecoratorMetadata !== true) {
4159
+ return { kind: "not-emitted" };
4160
+ }
4161
+ const typeNode = metadataTypeNode(node);
4162
+ return {
4163
+ kind: "emitted",
4164
+ type: serializedTypeNode({ ...context, keepsNullish: checksNulls(options) }, typeNode),
4165
+ withoutNullish: serializedTypeNode({ ...context, keepsNullish: false }, typeNode),
4166
+ };
4167
+ }
3514
4168
  export function createTypeQueries(program, own,
3515
4169
  /** The project folder qualified ids are relative to. */
3516
- root, packageOf, isEntry, dependenciesOf) {
4170
+ root, packageOf, isEntry, dependenciesOf,
4171
+ /** Packages the config adds to the platform (`Config.platform`). */
4172
+ platform = []) {
4173
+ const isPlatformFile = platformFiles(program, platform);
4174
+ // Module names resolve as from the project's tsconfig (a file there need not exist).
4175
+ const { configFilePath } = program.getCompilerOptions();
4176
+ const resolveFrom = path.join(typeof configFilePath === "string" ? path.dirname(configFilePath) : root, "__stateward_types__.ts");
3517
4177
  // The only place in the codebase that reaches the type checker. Created on the first question:
3518
4178
  // a run whose results all come from the cache never builds one.
3519
4179
  let created;
3520
4180
  const typeChecker = () => (created ??= program.getTypeChecker());
4181
+ const factNames = createFactNames(typeChecker, program, packageOf, resolveFrom, own);
4182
+ const factModuleOf = createFactModules({
4183
+ checker: typeChecker,
4184
+ program,
4185
+ names: factNames,
4186
+ own,
4187
+ isPlatformFile,
4188
+ packageOf,
4189
+ });
3521
4190
  const declarations = new Map();
3522
4191
  const declaredTraits = new Map();
3523
4192
  let anyMarker;
@@ -3567,7 +4236,7 @@ root, packageOf, isEntry, dependenciesOf) {
3567
4236
  const declarations = symbol?.declarations ?? [];
3568
4237
  if (symbol !== undefined &&
3569
4238
  declarations.length > 0 &&
3570
- declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile()))) {
4239
+ declarations.every((one) => isPlatformFile(one.getSourceFile()))) {
3571
4240
  found.add(symbol);
3572
4241
  }
3573
4242
  }
@@ -3607,7 +4276,7 @@ root, packageOf, isEntry, dependenciesOf) {
3607
4276
  const declarations = symbol?.declarations ?? [];
3608
4277
  if (symbol === undefined ||
3609
4278
  declarations.length === 0 ||
3610
- !declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile())) ||
4279
+ !declarations.every((one) => isPlatformFile(one.getSourceFile())) ||
3611
4280
  platformExtended().has(symbol)) {
3612
4281
  return undefined;
3613
4282
  }
@@ -3633,7 +4302,7 @@ root, packageOf, isEntry, dependenciesOf) {
3633
4302
  }
3634
4303
  if (declarations.some((one) => ts.isGetAccessor(one) || ts.isSetAccessor(one)))
3635
4304
  return false;
3636
- if (declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile()))) {
4305
+ if (declarations.every((one) => isPlatformFile(one.getSourceFile()))) {
3637
4306
  const owner = platformNameOf(receiver);
3638
4307
  return (owner !== undefined &&
3639
4308
  (PLATFORM_CONSTANTS.has(owner) || PLATFORM_PROPERTIES.has(`${owner}.${property.getName()}`)));
@@ -3695,6 +4364,23 @@ root, packageOf, isEntry, dependenciesOf) {
3695
4364
  },
3696
4365
  isOwnFile: (file) => own.has(toTypeScriptPath(file)),
3697
4366
  packageOf: (file) => packageOf(toTypeScriptPath(file)),
4367
+ factTarget: (module, name) => factNames.target(module, name),
4368
+ factNames: (module) => factNames.names(module),
4369
+ factNameOf: (module, declaration) => factNames.nameOf(module, declaration),
4370
+ factModuleOf,
4371
+ exportedClassOf(module, name) {
4372
+ const exported = factNames
4373
+ .modulesNamed(module)
4374
+ .flatMap((moduleSymbol) => typeChecker().getExportsOfModule(moduleSymbol))
4375
+ .find((one) => one.getName() === name);
4376
+ if (exported === undefined)
4377
+ return undefined;
4378
+ const target = exported.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(exported) : exported;
4379
+ const node = target.declarations?.find(ts.isClassLike);
4380
+ if (node === undefined)
4381
+ return undefined;
4382
+ return { file: node.getSourceFile().fileName, node };
4383
+ },
3698
4384
  literalsOf(node) {
3699
4385
  const found = typeChecker().getTypeAtLocation(node);
3700
4386
  const type = found.isTypeParameter() ? typeChecker().getBaseConstraintOfType(found) : found;
@@ -3821,6 +4507,16 @@ root, packageOf, isEntry, dependenciesOf) {
3821
4507
  }));
3822
4508
  }));
3823
4509
  },
4510
+ expectsCallableReturn(node) {
4511
+ const checker = typeChecker();
4512
+ const type = checker.getContextualType(node);
4513
+ if (type === undefined)
4514
+ return false;
4515
+ return (type.isUnion() ? type.types : [type]).some((member) => member.getCallSignatures().some((signature) => {
4516
+ const returned = checker.getReturnTypeOfSignature(signature);
4517
+ return (returned.isUnion() ? returned.types : [returned]).some((part) => part.getCallSignatures().length > 0);
4518
+ }));
4519
+ },
3824
4520
  canBeUndefined(node) {
3825
4521
  const type = widened(typeChecker(), typeChecker().getTypeAtLocation(node));
3826
4522
  // An unconstrained type parameter can be anything, undefined included.
@@ -3833,6 +4529,14 @@ root, packageOf, isEntry, dependenciesOf) {
3833
4529
  const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.Null;
3834
4530
  return (type.isUnion() ? type.types : [type]).some((member) => (member.flags & open) !== 0);
3835
4531
  },
4532
+ canBeFalse(node) {
4533
+ const checker = typeChecker();
4534
+ const type = widened(checker, checker.getTypeAtLocation(node));
4535
+ if (type === undefined)
4536
+ return true;
4537
+ const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown;
4538
+ return (type.isUnion() ? type.types : [type]).some((member) => (member.flags & open) !== 0 || member === checker.getFalseType());
4539
+ },
3836
4540
  parameterIsNever(call, argumentIndex) {
3837
4541
  const declaration = typeChecker().getResolvedSignature(call)?.declaration;
3838
4542
  if (declaration === undefined || !("parameters" in declaration))
@@ -3883,17 +4587,24 @@ root, packageOf, isEntry, dependenciesOf) {
3883
4587
  const type = checker.getContextualType(node);
3884
4588
  return type === undefined ? [] : guaranteesOfType(checker, type);
3885
4589
  },
4590
+ markerValuesOf(node, property) {
4591
+ return markerValuesOfType(typeChecker(), typeChecker().getTypeAtLocation(node), property);
4592
+ },
3886
4593
  guaranteeValuesOf(target, name, contextual = false) {
3887
4594
  const checker = typeChecker();
3888
4595
  if ("kind" in target) {
3889
4596
  const type = contextual && ts.isExpression(target)
3890
4597
  ? checker.getContextualType(target)
3891
4598
  : checker.getTypeAtLocation(target);
3892
- return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
4599
+ return type === undefined
4600
+ ? undefined
4601
+ : markerValuesOfType(checker, type, `${GUARANTEE_PREFIX}${name}`);
3893
4602
  }
3894
4603
  const declaration = declarations.get(target.id);
3895
4604
  const type = declaration === undefined ? undefined : declaredTypeOf(checker, declaration);
3896
- return type === undefined ? undefined : guaranteeValuesOfType(checker, type, name);
4605
+ return type === undefined
4606
+ ? undefined
4607
+ : markerValuesOfType(checker, type, `${GUARANTEE_PREFIX}${name}`);
3897
4608
  },
3898
4609
  heldAliasesOf(node, contextual = false) {
3899
4610
  const checker = typeChecker();
@@ -4097,6 +4808,43 @@ root, packageOf, isEntry, dependenciesOf) {
4097
4808
  return false;
4098
4809
  return typeChecker().isTypeAssignableTo(rest, typeChecker().getNonNullableType(typeChecker().getTypeAtLocation(to)));
4099
4810
  },
4811
+ valueAssignableTo(output, orUndefined, target) {
4812
+ const checker = typeChecker();
4813
+ const to = checker.getTypeAtLocation(target);
4814
+ if (orUndefined && !checker.isTypeAssignableTo(checker.getUndefinedType(), to))
4815
+ return false;
4816
+ if (output === "array") {
4817
+ const members = to.isUnion() ? to.types : [to];
4818
+ const open = ts.TypeFlags.Any | ts.TypeFlags.Unknown | ts.TypeFlags.NonPrimitive;
4819
+ return members.some((one) => (one.flags & open) !== 0 || checker.isArrayLikeType(one));
4820
+ }
4821
+ // An output that still holds a type parameter (`T[]`, `Promise<T>`) says nothing certain
4822
+ // about the value until its arguments are known.
4823
+ if (typeof output !== "string" && holdsTypeParameter(checker, output))
4824
+ return undefined;
4825
+ const declared = typeof output === "string" ? undefined : checker.getTypeFromTypeNode(output);
4826
+ const from = declared !== undefined
4827
+ ? (checker.getAwaitedType(declared) ?? declared)
4828
+ : output === "string"
4829
+ ? checker.getStringType()
4830
+ : output === "number"
4831
+ ? checker.getNumberType()
4832
+ : checker.getBooleanType();
4833
+ if (from.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown))
4834
+ return undefined;
4835
+ if (checker.isTypeAssignableTo(from, to))
4836
+ return true;
4837
+ // A brand (`string & { __brand: "Uuid" }`) adds no runtime value: the developer states that
4838
+ // the value was checked, so the type it brands counts.
4839
+ return (to.isUnion() ? to.types : [to]).some((member) => {
4840
+ if (!member.isIntersection())
4841
+ return false;
4842
+ const plain = member.types.filter((one) => (one.flags & ts.TypeFlags.Object) === 0);
4843
+ return (plain.length > 0 &&
4844
+ plain.length < member.types.length &&
4845
+ plain.every((one) => checker.isTypeAssignableTo(from, one)));
4846
+ });
4847
+ },
4100
4848
  parameterIsReadonly(call, argumentIndex) {
4101
4849
  // After a spread argument the indexes no longer line up with the parameters.
4102
4850
  if (call.arguments.slice(0, argumentIndex + 1).some(ts.isSpreadElement))
@@ -4185,6 +4933,27 @@ root, packageOf, isEntry, dependenciesOf) {
4185
4933
  arrayElementsOf(node) {
4186
4934
  return arrayElements(typeChecker().getTypeAtLocation(node));
4187
4935
  },
4936
+ arrayCanBeEmpty(node) {
4937
+ const checker = typeChecker();
4938
+ const members = definedMembers(checker, checker.getTypeAtLocation(node));
4939
+ if (members === undefined)
4940
+ return undefined;
4941
+ let empty = false;
4942
+ for (const member of members) {
4943
+ if (checker.isTupleType(member) && isTypeReference(member)) {
4944
+ const target = member.target;
4945
+ const required = "minLength" in target && typeof target.minLength === "number" ? target.minLength : 0;
4946
+ if (required === 0)
4947
+ empty = true;
4948
+ continue;
4949
+ }
4950
+ const name = platformNameOfType(member);
4951
+ if (name !== "Array" && name !== "ReadonlyArray")
4952
+ return undefined;
4953
+ empty = true;
4954
+ }
4955
+ return empty;
4956
+ },
4188
4957
  readIsPlain(node) {
4189
4958
  const checker = typeChecker();
4190
4959
  if (ts.isBindingElement(node)) {
@@ -4259,8 +5028,25 @@ root, packageOf, isEntry, dependenciesOf) {
4259
5028
  return false;
4260
5029
  const symbol = found.flags & ts.SymbolFlags.Alias ? typeChecker().getAliasedSymbol(found) : found;
4261
5030
  const declarations = symbol.declarations ?? [];
4262
- return (declarations.length > 0 &&
4263
- declarations.every((one) => isPlatformSourceFile(program, one.getSourceFile())));
5031
+ return (declarations.length > 0 && declarations.every((one) => isPlatformFile(one.getSourceFile())));
5032
+ },
5033
+ globalPackagesOf(node) {
5034
+ const found = typeChecker().getSymbolAtLocation(node);
5035
+ if (found === undefined || found.flags & ts.SymbolFlags.Alias)
5036
+ return [];
5037
+ const declarations = found.declarations ?? [];
5038
+ if (!declarations.every(isGlobalDeclaration))
5039
+ return [];
5040
+ const packages = new Set();
5041
+ for (const one of declarations) {
5042
+ const file = one.getSourceFile();
5043
+ if (isPlatformFile(file))
5044
+ continue;
5045
+ const name = packageOf(toTypeScriptPath(file.fileName));
5046
+ if (name !== undefined)
5047
+ packages.add(name);
5048
+ }
5049
+ return [...packages].sort();
4264
5050
  },
4265
5051
  isPlainClass(node) {
4266
5052
  const checker = typeChecker();
@@ -4353,6 +5139,59 @@ root, packageOf, isEntry, dependenciesOf) {
4353
5139
  const to = body.getStart(sourceFile);
4354
5140
  return starts.some((start) => start >= from && start < to);
4355
5141
  },
5142
+ genericBaseOf(node, pkg, names) {
5143
+ const checker = typeChecker();
5144
+ const inPackage = (symbol) => (symbol.declarations ?? []).some((declaration) => packageOf(toTypeScriptPath(declaration.getSourceFile().fileName)) === pkg);
5145
+ return genericBaseOfType(checker, checker.getTypeAtLocation(node), inPackage, names);
5146
+ },
5147
+ isOrExtends(node, classes) {
5148
+ return isOrExtendsType(typeChecker(), typeChecker().getTypeAtLocation(node), classes);
5149
+ },
5150
+ instanceClassesOf(node, depth) {
5151
+ return instanceClassesOfType(typeChecker(), typeChecker().getTypeAtLocation(node), depth);
5152
+ },
5153
+ propertyTypesOf(node) {
5154
+ const checker = typeChecker();
5155
+ const type = widened(checker, checker.getTypeAtLocation(node));
5156
+ if (type === undefined || !(type.flags & (ts.TypeFlags.Object | ts.TypeFlags.Intersection))) {
5157
+ return undefined;
5158
+ }
5159
+ return checker
5160
+ .getPropertiesOfType(type)
5161
+ .map((property) => {
5162
+ const own = checker.getTypeOfSymbol(property);
5163
+ const members = own.isUnion() ? own.types : [own];
5164
+ return {
5165
+ name: property.getName(),
5166
+ text: checker.typeToString(own).replace(/\s+/g, " ").trim(),
5167
+ optional: (property.flags & ts.SymbolFlags.Optional) !== 0,
5168
+ open: (own.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0,
5169
+ platform: platformNameOf(own) ?? null,
5170
+ nullish: members.some((one) => (one.flags & (ts.TypeFlags.Null | ts.TypeFlags.Undefined)) !== 0),
5171
+ };
5172
+ })
5173
+ .sort((a, b) => (a.name < b.name ? -1 : a.name > b.name ? 1 : 0));
5174
+ },
5175
+ parameterTakesUnknown(call, argumentIndex) {
5176
+ return takesUnknown(typeChecker(), call, argumentIndex);
5177
+ },
5178
+ typeShapeOf(node, from) {
5179
+ const checker = typeChecker();
5180
+ const type = from === "type"
5181
+ ? ts.isTypeNode(node)
5182
+ ? checker.getTypeFromTypeNode(node)
5183
+ : checker.getTypeAtLocation(node)
5184
+ : ts.isExpression(node)
5185
+ ? checker.getContextualType(node)
5186
+ : undefined;
5187
+ return type === undefined ? undefined : typeShape(isPlatformFile, checker, type, []);
5188
+ },
5189
+ metadataTypeOf(node) {
5190
+ return decoratorMetadata(program.getCompilerOptions(), {
5191
+ checker: typeChecker(),
5192
+ refOf: (symbol) => refOfSymbol(symbol),
5193
+ }, node);
5194
+ },
4356
5195
  narrowedBy(reference, test) {
4357
5196
  return narrowedMembers(program, typeChecker(), reference, test);
4358
5197
  },
@@ -4365,14 +5204,45 @@ root, packageOf, isEntry, dependenciesOf) {
4365
5204
  isErrorType(node) {
4366
5205
  return isErrorTypeOf(typeChecker().getTypeAtLocation(node));
4367
5206
  },
5207
+ hasNoType(node) {
5208
+ return (typeChecker().getTypeAtLocation(node).flags & ts.TypeFlags.Any) !== 0;
5209
+ },
5210
+ isOpenType(node) {
5211
+ const checker = typeChecker();
5212
+ const type = ts.isTypeNode(node)
5213
+ ? checker.getTypeFromTypeNode(node)
5214
+ : checker.getTypeAtLocation(node);
5215
+ return (type.flags & (ts.TypeFlags.Any | ts.TypeFlags.Unknown)) !== 0;
5216
+ },
5217
+ builtinTypeOf(node, read) {
5218
+ const checker = typeChecker();
5219
+ const type = ts.isTypeNode(node)
5220
+ ? checker.getTypeFromTypeNode(node)
5221
+ : checker.getTypeAtLocation(node);
5222
+ return builtinOf(read === "awaited" ? (checker.getAwaitedType(type) ?? type) : type);
5223
+ },
4368
5224
  isPromiseLike(node) {
4369
5225
  return isPromiseType(typeChecker(), typeChecker().getTypeAtLocation(node));
4370
5226
  },
5227
+ methodReturnsPromiseLike(node, name) {
5228
+ const checker = typeChecker();
5229
+ const property = checker.getTypeAtLocation(node).getProperty(name);
5230
+ if (property === undefined)
5231
+ return false;
5232
+ const signatures = checker.getTypeOfSymbol(property).getCallSignatures();
5233
+ return (signatures.length > 0 &&
5234
+ signatures.every((signature) => isPromiseType(checker, checker.getReturnTypeOfSignature(signature))));
5235
+ },
4371
5236
  returnsPromiseLike(fn) {
4372
5237
  const signature = typeChecker().getSignatureFromDeclaration(fn);
4373
5238
  return (signature !== undefined &&
4374
5239
  isPromiseType(typeChecker(), typeChecker().getReturnTypeOfSignature(signature)));
4375
5240
  },
5241
+ mayReturnPromise(fn) {
5242
+ const signature = typeChecker().getSignatureFromDeclaration(fn);
5243
+ return (signature === undefined ||
5244
+ mayBePromiseType(typeChecker(), typeChecker().getReturnTypeOfSignature(signature)));
5245
+ },
4376
5246
  hasDefinedProperty(node, name) {
4377
5247
  const type = widened(typeChecker(), typeChecker().getTypeAtLocation(node));
4378
5248
  if (type === undefined)
@@ -4474,7 +5344,7 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4474
5344
  /** What the last `open` found: the projects, their own files, and every own file of all of them. */
4475
5345
  let last;
4476
5346
  /** The program of one project, built now, as a unit; recorded for the next run when it can be. */
4477
- const buildUnit = ({ tsconfigPath, parsed, own, shared }, claimed, overlays, trustCache) => {
5347
+ const buildUnit = ({ tsconfigPath, parsed, own, shared, unreadTestConfigs }, claimed, overlays, trustCache) => {
4478
5348
  const sources = caches.get(tsconfigPath) ?? new Map();
4479
5349
  caches.set(tsconfigPath, sources);
4480
5350
  const oldProgram = previous.get(tsconfigPath);
@@ -4510,6 +5380,24 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4510
5380
  let fingerprints;
4511
5381
  /** The text hashes of read files asked for, kept in the record so a replayed program answers them. */
4512
5382
  const readPrints = {};
5383
+ /** What the config's facts keys resolve to, by digest, kept in the record the same way. */
5384
+ const factChecks = {};
5385
+ let imports;
5386
+ /** The package modules the own files import (`importedModules`), sorted. */
5387
+ const importsOf = () => {
5388
+ if (imports !== undefined)
5389
+ return imports;
5390
+ const all = new Set();
5391
+ for (const file of files) {
5392
+ const sourceFile = program.getSourceFile(file);
5393
+ if (sourceFile === undefined)
5394
+ continue;
5395
+ for (const name of importedModules(sourceFile, parsed.options))
5396
+ all.add(name);
5397
+ }
5398
+ imports = [...all].sort();
5399
+ return imports;
5400
+ };
4513
5401
  const fingerprintsOf = () => {
4514
5402
  if (fingerprints !== undefined)
4515
5403
  return fingerprints;
@@ -4522,6 +5410,8 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4522
5410
  files,
4523
5411
  fingerprints: Object.fromEntries(files.map((file) => [file, known.get(file) ?? ""])),
4524
5412
  reads: readPrints,
5413
+ imports: importsOf(),
5414
+ facts: factChecks,
4525
5415
  });
4526
5416
  cache.changed = true;
4527
5417
  }
@@ -4529,7 +5419,7 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4529
5419
  };
4530
5420
  /** What each file's rules were handed, by file: read ids, with the file each one is in. */
4531
5421
  const reads = new Map();
4532
- const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf);
5422
+ const types = createTypeQueries(program, claimed, cwd, packageOf, isEntry, dependenciesOf, config.platform);
4533
5423
  const idFileName = idFileNames(cwd);
4534
5424
  const fileId = (fileName) => `${idFileName(fileName)}#`;
4535
5425
  /** The read id of a declaration handed out: its own id when that finds it again, else its file's. */
@@ -4594,7 +5484,14 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4594
5484
  syntaxError: (file) => firstSyntaxError(program, file),
4595
5485
  unresolvedImports: (file) => unresolvedImportsOf(program, file),
4596
5486
  strictNullChecks: checksNulls(parsed.options),
5487
+ unreadTestConfigs,
4597
5488
  typesResolve: typesResolver(tsconfigPath, parsed.options),
5489
+ factKeys: (facts) => {
5490
+ const checks = checkFactKeys(facts, types);
5491
+ factChecks[factKeysDigest(facts)] = JSON.stringify(checks);
5492
+ return checks;
5493
+ },
5494
+ importsModule: (module) => importsModuleIn(importsOf(), module),
4598
5495
  bind: () => {
4599
5496
  program.getTypeChecker();
4600
5497
  },
@@ -4633,7 +5530,21 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4633
5530
  syntaxError: (file) => real().syntaxError(file),
4634
5531
  unresolvedImports: (file) => real().unresolvedImports(file),
4635
5532
  strictNullChecks: checksNulls(project.parsed.options),
5533
+ unreadTestConfigs: project.unreadTestConfigs,
4636
5534
  typesResolve: typesResolver(project.tsconfigPath, project.parsed.options),
5535
+ factKeys: (facts) => {
5536
+ const digest = factKeysDigest(facts);
5537
+ const kept = record.facts[digest];
5538
+ const known = kept === undefined ? undefined : readFactKeyChecks(kept);
5539
+ if (known !== undefined)
5540
+ return known;
5541
+ const checks = real().factKeys(facts);
5542
+ record.facts[digest] = JSON.stringify(checks);
5543
+ if (cache !== undefined)
5544
+ cache.changed = true;
5545
+ return checks;
5546
+ },
5547
+ importsModule: (module) => importsModuleIn(record.imports, module),
4637
5548
  bind: () => {
4638
5549
  real().bind();
4639
5550
  },
@@ -4673,10 +5584,14 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4673
5584
  const collected = collectConfigs(roots);
4674
5585
  const shared = collected.length > 1 ? listedTwice(collected) : new Set();
4675
5586
  const projects = collected.map(({ path: tsconfigPath, parsed }) => {
4676
- const own = ownFileNames(parsed, config, cwd, claimed);
5587
+ // The test runner's own test files join the default `exclude`, unless the config replaced it.
5588
+ const tests = config.replacesDefaultExclude
5589
+ ? { matches: () => false, unread: [] }
5590
+ : testRunnerFiles([path.dirname(tsconfigPath), config.configDir]);
5591
+ const own = ownFileNames(parsed, config, cwd, claimed, tests.matches);
4677
5592
  for (const file of own)
4678
5593
  claimed.add(file);
4679
- return { tsconfigPath, parsed, own, shared };
5594
+ return { tsconfigPath, parsed, own, shared, unreadTestConfigs: tests.unread };
4680
5595
  });
4681
5596
  if (claimed.size === 0)
4682
5597
  throw new NothingToCheckError(named);
@@ -4692,15 +5607,6 @@ export function createBackend({ config, cwd, cache, jsDoc = false, }) {
4692
5607
  reopen: (overlays) => last === undefined ? open(overlays) : build(last.projects, last.claimed, overlays, true),
4693
5608
  };
4694
5609
  }
4695
- // ---- package sources ----------------------------------------
4696
- function isSymbol(value) {
4697
- return typeof value === "object" && value !== null && "flags" in value && "escapedName" in value;
4698
- }
4699
- /**
4700
- * The module symbol of a file: the checker answers for an ES module; a CommonJS file (`exports.x
4701
- * = …`) has one only on the file itself, which TypeScript keeps without a public type, so it is
4702
- * read through reflection and checked at run time.
4703
- */
4704
5610
  /** The type alias a module exports under `name`, aliases resolved; undefined when it exports none. */
4705
5611
  function exportedAlias(checker, sourceFile, name) {
4706
5612
  const module = moduleSymbolOf(checker, sourceFile);
@@ -4747,6 +5653,28 @@ function relativeSpecifier(program, importer, file) {
4747
5653
  }
4748
5654
  }
4749
5655
  }
5656
+ // ---- facts keys ---------------------------------------------------------------------------------
5657
+ /**
5658
+ * The names a `facts` key is written in, resolved by the type checker (0041): a module as the
5659
+ * project would import it, then a dotted path through its exports and their members
5660
+ * (`"typeorm": { "Repository.find": … }`). A key names the declarations of the symbol it resolves
5661
+ * to, so it does not depend on how the module's declarations are written: two module names that
5662
+ * resolve to one symbol (an alias module that re-exports another) name the same declarations.
5663
+ */
5664
+ /** How deep `names` lists a module's paths (`Repository.find` is two). */
5665
+ const LISTED_DEPTH = 2;
5666
+ /** At most this many paths are listed per module. */
5667
+ const MAX_LISTED = 50_000;
5668
+ /** How many `export =` a module is followed through. */
5669
+ const MAX_EXPORT_EQUALS = 4;
5670
+ function isSymbol(value) {
5671
+ return typeof value === "object" && value !== null && "flags" in value && "escapedName" in value;
5672
+ }
5673
+ /**
5674
+ * The module symbol of a file: the checker answers for an ES module; a CommonJS file (`exports.x
5675
+ * = …`) has one only on the file itself, which TypeScript keeps without a public type, so it is
5676
+ * read through reflection and checked at run time.
5677
+ */
4750
5678
  function moduleSymbolOf(checker, sourceFile) {
4751
5679
  const found = checker.getSymbolAtLocation(sourceFile);
4752
5680
  if (found !== undefined)
@@ -4754,105 +5682,476 @@ function moduleSymbolOf(checker, sourceFile) {
4754
5682
  const own = Reflect.get(sourceFile, "symbol");
4755
5683
  return isSymbol(own) ? own : undefined;
4756
5684
  }
4757
- const PACKAGE_JAVASCRIPT = /\.(?:js|mjs|cjs)$/;
4758
- const PACKAGE_OPTIONS = {
4759
- allowJs: true,
4760
- checkJs: false,
4761
- noEmit: true,
4762
- target: ts.ScriptTarget.ES2022,
4763
- module: ts.ModuleKind.Preserve,
4764
- moduleResolution: ts.ModuleResolutionKind.Bundler,
4765
- lib: ["lib.es2022.d.ts"],
4766
- types: [],
4767
- skipLibCheck: true,
4768
- };
4769
- function isRelativeSpecifier(specifier) {
4770
- return specifier.startsWith("./") || specifier.startsWith("../");
4771
- }
4772
- /**
4773
- * Opens the package at `root` from `entry` (a JavaScript file in it). Its files are parsed with
4774
- * the library files' cache, so a later package or project shares TypeScript's lib files.
4775
- */
4776
- export function openPackageSource(root, entry) {
4777
- const packageRoot = toTypeScriptPath(root);
4778
- const inPackage = (file) => file.startsWith(`${packageRoot}/`) &&
4779
- !file.slice(packageRoot.length).includes("/node_modules/");
4780
- const base = hostWithOverlays(PACKAGE_OPTIONS, new Map(), new Map(), false, false, isTypeScriptLib);
4781
- const host = {
4782
- ...base,
4783
- // Relative specifiers inside the package only: another package is not followed (its calls
4784
- // stay unknown), and nothing here is an "external library" TypeScript would skip.
4785
- resolveModuleNameLiterals: (literals, containingFile) => literals.map((literal) => {
4786
- if (!isRelativeSpecifier(literal.text))
4787
- return { resolvedModule: undefined };
4788
- const found = ts.resolveModuleName(literal.text, containingFile, PACKAGE_OPTIONS, base);
4789
- const resolved = found.resolvedModule;
4790
- if (resolved === undefined ||
4791
- !PACKAGE_JAVASCRIPT.test(resolved.resolvedFileName) ||
4792
- !inPackage(toTypeScriptPath(resolved.resolvedFileName))) {
4793
- return { resolvedModule: undefined };
5685
+ function createFactNames(checker, program,
5686
+ /** The package of a file (`TypeQueries.packageOf`). */
5687
+ packageOf,
5688
+ /** A file in the project's folder that module names are resolved from (it need not exist). */
5689
+ resolveFrom,
5690
+ /** The project's own files. */
5691
+ own) {
5692
+ let ambient;
5693
+ let imported;
5694
+ const modules = new Map();
5695
+ const children = new Map();
5696
+ const targets = new Map();
5697
+ const listed = new Map();
5698
+ const resolved = (symbol) => symbol.flags & ts.SymbolFlags.Alias ? checker().getAliasedSymbol(symbol) : symbol;
5699
+ /** Whether a value can be called: a function, a class, or a value whose type has a signature. */
5700
+ const isCallable = (symbol) => (symbol.flags & (ts.SymbolFlags.Function | ts.SymbolFlags.Class)) !== 0 ||
5701
+ checker().getTypeOfSymbol(symbol).getCallSignatures().length > 0;
5702
+ /** The modules `declare module "x"` declares, by the name it is written with. */
5703
+ const ambientModules = () => {
5704
+ if (ambient !== undefined)
5705
+ return ambient;
5706
+ ambient = new Map();
5707
+ for (const symbol of checker().getAmbientModules()) {
5708
+ for (const declaration of symbol.declarations ?? []) {
5709
+ if (ts.isModuleDeclaration(declaration) &&
5710
+ ts.isStringLiteral(declaration.name) &&
5711
+ !ambient.has(declaration.name.text)) {
5712
+ ambient.set(declaration.name.text, symbol);
5713
+ }
4794
5714
  }
4795
- return { resolvedModule: { ...resolved, isExternalLibraryImport: false } };
4796
- }),
5715
+ }
5716
+ return ambient;
4797
5717
  };
4798
- const program = ts.createProgram({
4799
- rootNames: [toTypeScriptPath(entry)],
4800
- options: PACKAGE_OPTIONS,
4801
- host,
4802
- });
4803
- const files = program
4804
- .getSourceFiles()
4805
- .map((file) => file.fileName)
4806
- .filter((file) => inPackage(file) && PACKAGE_JAVASCRIPT.test(file))
4807
- .sort();
4808
- const own = new Set(files);
4809
- const types = createTypeQueries(program, own, packageRoot, packageNames(host), packageEntries(host), packageDependencies(host));
4810
- // Plugins walk the nodes with parents: the binder sets them.
4811
- const checker = program.getTypeChecker();
4812
- const idFileName = idFileNames(packageRoot);
4813
- const refOf = (symbol) => {
4814
- const resolved = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
4815
- const declaration = resolved.valueDeclaration ?? resolved.declarations?.[0];
4816
- if (declaration === undefined)
4817
- return undefined;
4818
- const file = declaration.getSourceFile().fileName;
4819
- return { id: `${idFileName(file)}#${declarationPath(declaration)}`, name: resolved.getName() };
5718
+ /**
5719
+ * The module symbols the own files' imports and re-exports reach, by the name they write: the
5720
+ * checker resolves each in its file's own mode, as the project's imports resolve.
5721
+ */
5722
+ const importedModules = () => {
5723
+ if (imported !== undefined)
5724
+ return imported;
5725
+ imported = new Map();
5726
+ for (const file of program.getSourceFiles()) {
5727
+ if (!own.has(file.fileName))
5728
+ continue;
5729
+ for (const specifier of specifiersOf(file)) {
5730
+ const found = checker().getSymbolAtLocation(specifier);
5731
+ if (found === undefined)
5732
+ continue;
5733
+ const list = imported.get(specifier.text) ?? [];
5734
+ if (!list.includes(found))
5735
+ list.push(found);
5736
+ imported.set(specifier.text, list);
5737
+ }
5738
+ }
5739
+ return imported;
4820
5740
  };
4821
- const member = (symbol, name) => {
4822
- const resolved = symbol.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(symbol) : symbol;
4823
- const escaped = ts.escapeLeadingUnderscores(name);
4824
- return (resolved.members?.get(escaped) ??
4825
- resolved.exports?.get(escaped) ??
4826
- checker.getTypeOfSymbol(resolved).getProperty(name));
5741
+ /** The module symbol of the file `module` resolves to from the project's folder in `mode`. */
5742
+ const resolvedIn = (module, mode) => {
5743
+ const file = ts.resolveModuleName(module, resolveFrom, program.getCompilerOptions(), ts.sys, undefined, undefined, mode).resolvedModule?.resolvedFileName;
5744
+ const sourceFile = file === undefined ? undefined : program.getSourceFile(file);
5745
+ return sourceFile === undefined ? undefined : moduleSymbolOf(checker(), sourceFile);
5746
+ };
5747
+ const modulesNamed = (module) => {
5748
+ const known = modules.get(module);
5749
+ if (known !== undefined)
5750
+ return known;
5751
+ // As TypeScript resolves an import: a module `declare module` declares, else the files the
5752
+ // project's imports of it reach, and those it resolves to in either mode.
5753
+ const declared = ambientModules().get(module);
5754
+ const found = declared !== undefined
5755
+ ? [declared]
5756
+ : [
5757
+ ...new Set([
5758
+ ...(importedModules().get(module) ?? []),
5759
+ resolvedIn(module, ts.ModuleKind.ESNext),
5760
+ resolvedIn(module, ts.ModuleKind.CommonJS),
5761
+ ].flatMap((one) => (one === undefined ? [] : [resolved(one)]))),
5762
+ ];
5763
+ modules.set(module, found);
5764
+ return found;
5765
+ };
5766
+ /**
5767
+ * The names one step below a symbol: a module's exports (with what its `export =` gives), a
5768
+ * class's or interface's members, and the properties of a value's type (`const path:
5769
+ * PlatformPath` gives `join`).
5770
+ */
5771
+ const childrenOf = (symbol, depth = 0) => {
5772
+ const target = resolved(symbol);
5773
+ const known = children.get(target);
5774
+ if (known !== undefined)
5775
+ return known;
5776
+ const found = new Map();
5777
+ const add = (name, one) => {
5778
+ if (one.escapedName === ts.InternalSymbolName.ExportEquals)
5779
+ return;
5780
+ const list = found.get(name) ?? [];
5781
+ if (!list.includes(one))
5782
+ list.push(one);
5783
+ found.set(name, list);
5784
+ };
5785
+ const flags = target.flags;
5786
+ if (flags & ts.SymbolFlags.Module) {
5787
+ for (const one of checker().getExportsOfModule(target))
5788
+ add(one.getName(), one);
5789
+ const whole = target.exports?.get(ts.InternalSymbolName.ExportEquals);
5790
+ if (whole !== undefined && depth < MAX_EXPORT_EQUALS) {
5791
+ for (const [name, list] of childrenOf(whole, depth + 1)) {
5792
+ for (const one of list)
5793
+ add(name, one);
5794
+ }
5795
+ // A module whose value is itself callable (`export =` of a function or a class) is
5796
+ // named by `default`, the name a default import gives it.
5797
+ const value = resolved(whole);
5798
+ if (!found.has("default") && isCallable(value))
5799
+ add("default", value);
5800
+ }
5801
+ }
5802
+ if (flags & (ts.SymbolFlags.Class | ts.SymbolFlags.Interface | ts.SymbolFlags.TypeAlias)) {
5803
+ for (const one of checker().getDeclaredTypeOfSymbol(target).getProperties()) {
5804
+ add(one.getName(), one);
5805
+ }
5806
+ }
5807
+ if (flags &
5808
+ (ts.SymbolFlags.Variable |
5809
+ ts.SymbolFlags.Property |
5810
+ ts.SymbolFlags.Accessor |
5811
+ ts.SymbolFlags.Function |
5812
+ ts.SymbolFlags.Class)) {
5813
+ for (const one of checker().getTypeOfSymbol(target).getProperties()) {
5814
+ add(one.getName(), one);
5815
+ }
5816
+ }
5817
+ children.set(target, found);
5818
+ return found;
5819
+ };
5820
+ const declarationsOf = (symbols) => new Set(symbols.flatMap((one) => resolved(one).declarations ?? []));
5821
+ /**
5822
+ * The declarations a class or a value is known by as a receiver: its own (a class, an interface,
5823
+ * an alias), and for a value (`export const client: Client`) those of its type.
5824
+ */
5825
+ const ownerDeclarationsOf = (symbol) => {
5826
+ const target = resolved(symbol);
5827
+ const own = target.declarations ?? [];
5828
+ if ((target.flags & (ts.SymbolFlags.Variable | ts.SymbolFlags.Property)) === 0)
5829
+ return own;
5830
+ const typed = checker().getTypeOfSymbol(target).getSymbol();
5831
+ return [...own, ...(typed?.declarations ?? [])];
5832
+ };
5833
+ /** Whether a member's declaration is written in one of `owners` (`class Store { save(): void }`). */
5834
+ const declaredIn = (declaration, owners) => {
5835
+ const container = declaration.parent;
5836
+ return (owners.has(container) || (ts.isTypeLiteralNode(container) && owners.has(container.parent)));
5837
+ };
5838
+ /**
5839
+ * The members one step below `owners` (`"Store.*"`): each member written in an owner is stated
5840
+ * on any call; a member an owner inherits (`find` of its `Base`) only through a receiver that is
5841
+ * the owner, or extends it. `keep` leaves members out (a package line keeps its own package's).
5842
+ */
5843
+ const membersOf = (owners, declarations, throughReceiver, keep) => {
5844
+ for (const owner of owners) {
5845
+ const ownerDeclarations = new Set(ownerDeclarationsOf(owner));
5846
+ for (const member of [...childrenOf(owner).values()].flat()) {
5847
+ for (const declaration of resolved(member).declarations ?? []) {
5848
+ if (!keep(declaration))
5849
+ continue;
5850
+ if (declaredIn(declaration, ownerDeclarations)) {
5851
+ declarations.add(declaration);
5852
+ continue;
5853
+ }
5854
+ const classes = throughReceiver.get(declaration) ?? new Set();
5855
+ for (const one of ownerDeclarations)
5856
+ classes.add(one);
5857
+ throughReceiver.set(declaration, classes);
5858
+ }
5859
+ }
5860
+ }
5861
+ };
5862
+ /** The target: a declaration stated on any call needs no receiver as well. */
5863
+ const foundTarget = (declarations, throughReceiver) => {
5864
+ for (const declaration of declarations)
5865
+ throughReceiver.delete(declaration);
5866
+ return { kind: "found", declarations, throughReceiver };
5867
+ };
5868
+ /** `"Store.*"`: the methods and properties of the class, the inherited ones by their receiver. */
5869
+ const classTarget = (owners) => {
5870
+ const declarations = new Set();
5871
+ const throughReceiver = new Map();
5872
+ membersOf(owners, declarations, throughReceiver, () => true);
5873
+ return foundTarget(declarations, throughReceiver);
5874
+ };
5875
+ /**
5876
+ * `"*"`: what the module exports, and the members of what it exports that its own package
5877
+ * declares; a member of another package (`on` of an `EventEmitter` a class extends) is never
5878
+ * stated by it.
5879
+ */
5880
+ const packageTarget = (moduleSymbols) => {
5881
+ const packages = new Set(moduleSymbols.flatMap((one) => (resolved(one).declarations ?? []).map((declaration) => packageOf(toTypeScriptPath(declaration.getSourceFile().fileName)))));
5882
+ const exported = moduleSymbols.flatMap((one) => [...childrenOf(one).values()].flat());
5883
+ const declarations = declarationsOf(exported);
5884
+ const throughReceiver = new Map();
5885
+ membersOf(exported, declarations, throughReceiver, (declaration) => packages.has(packageOf(toTypeScriptPath(declaration.getSourceFile().fileName))));
5886
+ return foundTarget(declarations, throughReceiver);
5887
+ };
5888
+ const target = (module, name) => {
5889
+ const key = `${module}\u0000${name}`;
5890
+ const known = targets.get(key);
5891
+ if (known !== undefined)
5892
+ return known;
5893
+ const moduleSymbols = modulesNamed(module);
5894
+ let found;
5895
+ if (moduleSymbols.length === 0) {
5896
+ found = { kind: "no-module" };
5897
+ }
5898
+ else {
5899
+ const grain = factGrainOf(name);
5900
+ // A grain names the members one step below what its path reaches: a class's methods and
5901
+ // properties (with the inherited ones its type has), or the module's exports and theirs.
5902
+ const path = grain.kind === "function" ? name : grain.kind === "class" ? grain.owner : "";
5903
+ let current = moduleSymbols;
5904
+ for (const part of path === "" ? [] : path.split(".")) {
5905
+ const next = [...new Set(current.flatMap((one) => childrenOf(one).get(part) ?? []))];
5906
+ current = next;
5907
+ if (next.length === 0)
5908
+ break;
5909
+ }
5910
+ found =
5911
+ current.length === 0
5912
+ ? { kind: "no-name" }
5913
+ : grain.kind === "function"
5914
+ ? { kind: "found", declarations: declarationsOf(current), throughReceiver: new Map() }
5915
+ : grain.kind === "class"
5916
+ ? classTarget(current)
5917
+ : packageTarget(moduleSymbols);
5918
+ }
5919
+ targets.set(key, found);
5920
+ return found;
5921
+ };
5922
+ /** The paths of a module up to `LISTED_DEPTH`, shortest first, each with its symbols. */
5923
+ const listedOf = (module) => {
5924
+ const known = listed.get(module);
5925
+ if (known !== undefined)
5926
+ return known;
5927
+ const found = new Map();
5928
+ let level = modulesNamed(module).flatMap((one) => [
5929
+ ...childrenOf(one),
5930
+ ]);
5931
+ for (let depth = 1; depth <= LISTED_DEPTH && level.length > 0; depth++) {
5932
+ const next = [];
5933
+ for (const [name, symbols] of level) {
5934
+ if (found.size >= MAX_LISTED)
5935
+ break;
5936
+ found.set(name, symbols);
5937
+ if (depth === LISTED_DEPTH)
5938
+ continue;
5939
+ for (const symbol of symbols) {
5940
+ for (const [child, list] of childrenOf(symbol))
5941
+ next.push([`${name}.${child}`, list]);
5942
+ }
5943
+ }
5944
+ level = next;
5945
+ }
5946
+ listed.set(module, found);
5947
+ return found;
5948
+ };
5949
+ /**
5950
+ * The shortest name in `module` that resolves to `declaration`: the declaration's own path in
5951
+ * its types (`["path", "PlatformPath", "join"]`), its last names first (`join`, then
5952
+ * `PlatformPath.join`), each resolved forward as a key is, then `default`, then the
5953
+ * declaration's own name under each of the module's exports (`Buffer.from`, where the module
5954
+ * exports a value whose type has the method), shortest export first. Nothing is listed: a hint
5955
+ * asks this for every unknown call.
5956
+ */
5957
+ const nameOf = (module, declaration) => {
5958
+ const names = pathOf(declaration);
5959
+ const resolves = (name) => {
5960
+ const found = target(module, name);
5961
+ return found.kind === "found" && found.declarations.has(declaration);
5962
+ };
5963
+ const own = [...names.map((_, at) => names.slice(names.length - 1 - at).join(".")), "default"];
5964
+ const direct = own.find(resolves);
5965
+ const last = names.at(-1);
5966
+ const moduleSymbols = modulesNamed(module);
5967
+ if (direct !== undefined || last === undefined || moduleSymbols.length === 0)
5968
+ return direct;
5969
+ const exports = [...new Set(moduleSymbols.flatMap((one) => [...childrenOf(one).keys()]))].sort((a, b) => a.length - b.length || (a < b ? -1 : a > b ? 1 : 0));
5970
+ return exports.map((name) => `${name}.${last}`).find(resolves);
4827
5971
  };
4828
5972
  return {
4829
- files,
4830
- sourceFile: (file) => program.getSourceFile(toTypeScriptPath(file)),
4831
- types,
4832
- exported(file, names) {
4833
- const sourceFile = program.getSourceFile(toTypeScriptPath(file));
4834
- const moduleSymbol = sourceFile === undefined ? undefined : moduleSymbolOf(checker, sourceFile);
4835
- const [first, ...rest] = names;
4836
- if (moduleSymbol === undefined || first === undefined)
4837
- return undefined;
4838
- let symbol = checker.getExportsOfModule(moduleSymbol).find((one) => one.getName() === first);
4839
- if (symbol === undefined) {
4840
- // `module.exports = fn`: the module is the function.
4841
- const assigned = moduleSymbol.exports?.get(ts.InternalSymbolName.ExportEquals);
4842
- const whole = assigned === undefined || !(assigned.flags & ts.SymbolFlags.Alias)
4843
- ? assigned
4844
- : checker.getAliasedSymbol(assigned);
4845
- if (whole !== undefined && (first === "default" || whole.getName() === first)) {
4846
- symbol = whole;
5973
+ modulesNamed,
5974
+ target,
5975
+ // Only the name the hint gives for a declaration, so "did you mean" and the hint agree
5976
+ // (`join`, not `posix.join` for the same function).
5977
+ names: (module) => [...listedOf(module)].flatMap(([name, symbols]) => [...declarationsOf(symbols)].some((node) => nameOf(module, node) === name) ? [name] : []),
5978
+ nameOf,
5979
+ };
5980
+ }
5981
+ /** How many aliases (imports, re-exports) a reference is followed through to its module. */
5982
+ const MAX_ALIAS_STEPS = 8;
5983
+ function unwrappedReference(node) {
5984
+ let current = node;
5985
+ while (ts.isParenthesizedExpression(current) ||
5986
+ ts.isNonNullExpression(current) ||
5987
+ ts.isAsExpression(current) ||
5988
+ ts.isSatisfiesExpression(current)) {
5989
+ current = current.expression;
5990
+ }
5991
+ return current;
5992
+ }
5993
+ /** The leftmost name of a reference: `db` of `db.users.watch`, `make` of `make().run`. */
5994
+ function referenceRoot(node) {
5995
+ const bare = unwrappedReference(node);
5996
+ if (ts.isIdentifier(bare))
5997
+ return bare;
5998
+ if (ts.isPropertyAccessExpression(bare) ||
5999
+ ts.isElementAccessExpression(bare) ||
6000
+ ts.isCallExpression(bare) ||
6001
+ ts.isNewExpression(bare)) {
6002
+ return referenceRoot(bare.expression);
6003
+ }
6004
+ return undefined;
6005
+ }
6006
+ /** The module an import or re-export declaration names (`"kit"` of `import { a } from "kit"`). */
6007
+ function specifierOf(declaration) {
6008
+ if (ts.isImportEqualsDeclaration(declaration) &&
6009
+ ts.isExternalModuleReference(declaration.moduleReference) &&
6010
+ ts.isStringLiteral(declaration.moduleReference.expression)) {
6011
+ return declaration.moduleReference.expression;
6012
+ }
6013
+ const statement = ts.findAncestor(declaration, (node) => ts.isImportDeclaration(node) || ts.isExportDeclaration(node));
6014
+ const specifier = statement !== undefined &&
6015
+ (ts.isImportDeclaration(statement) || ts.isExportDeclaration(statement))
6016
+ ? statement.moduleSpecifier
6017
+ : undefined;
6018
+ return specifier !== undefined && ts.isStringLiteral(specifier) ? specifier : undefined;
6019
+ }
6020
+ /** The module specifiers a file's top-level imports and re-exports write, in file order. */
6021
+ function specifiersOf(file) {
6022
+ return file.statements.flatMap((statement) => {
6023
+ const specifier = ts.isImportDeclaration(statement) ||
6024
+ ts.isExportDeclaration(statement) ||
6025
+ ts.isImportEqualsDeclaration(statement)
6026
+ ? specifierOf(statement)
6027
+ : undefined;
6028
+ return specifier === undefined ? [] : [specifier];
6029
+ });
6030
+ }
6031
+ /**
6032
+ * The module a `facts` key for a declaration outside the project is written from
6033
+ * (`TypeQueries.factModuleOf`), and the name in it, by the first module that names the
6034
+ * declaration (`FactNames.nameOf`) of these:
6035
+ *
6036
+ * 1. the module the reference's leftmost name is imported from, as the project writes it, after
6037
+ * following re-exports and aliases out of the project's files;
6038
+ * 2. the modules the files on that way, and the reference's own file, import or re-export;
6039
+ * 3. the module the declaration is declared in (`declare module "x"`), else its package;
6040
+ * 4. the modules of the declaration's own package the program loads: the ambient modules its files
6041
+ * declare, and the modules the program's files import from it, by name.
6042
+ *
6043
+ * A module of the project's own files is never one: a key names code outside the project.
6044
+ */
6045
+ function createFactModules(input) {
6046
+ const { checker, program, names, own, isPlatformFile, packageOf } = input;
6047
+ const known = new WeakMap();
6048
+ let byPackage;
6049
+ const isOwn = (file) => own.has(file.fileName);
6050
+ /** Whether a specifier names a module outside the project, as a key can be resolved from it. */
6051
+ const leavesProject = (specifier) => {
6052
+ const text = specifier.text;
6053
+ if (text.startsWith(".") || path.isAbsolute(text))
6054
+ return false;
6055
+ const declarations = checker().getSymbolAtLocation(specifier)?.declarations ?? [];
6056
+ return declarations.length > 0 && declarations.every((one) => !isOwn(one.getSourceFile()));
6057
+ };
6058
+ /** The modules of each package the program loads, by name: ambient ones and imported ones. */
6059
+ const modulesByPackage = () => {
6060
+ if (byPackage !== undefined)
6061
+ return byPackage;
6062
+ const found = new Map();
6063
+ const add = (file, module) => {
6064
+ const owner = packageOf(file.fileName);
6065
+ if (owner === undefined || isOwn(file))
6066
+ return;
6067
+ found.set(owner, (found.get(owner) ?? new Set()).add(module));
6068
+ };
6069
+ for (const symbol of checker().getAmbientModules()) {
6070
+ for (const declaration of symbol.declarations ?? []) {
6071
+ if (ts.isModuleDeclaration(declaration) && ts.isStringLiteral(declaration.name)) {
6072
+ add(declaration.getSourceFile(), declaration.name.text);
4847
6073
  }
4848
6074
  }
4849
- for (const name of rest) {
4850
- if (symbol === undefined)
4851
- return undefined;
4852
- symbol = member(symbol, name);
6075
+ }
6076
+ for (const file of program.getSourceFiles()) {
6077
+ for (const specifier of specifiersOf(file)) {
6078
+ if (!leavesProject(specifier))
6079
+ continue;
6080
+ const target = checker().getSymbolAtLocation(specifier)?.declarations?.[0];
6081
+ if (target !== undefined)
6082
+ add(target.getSourceFile(), specifier.text);
4853
6083
  }
4854
- return symbol === undefined ? undefined : refOf(symbol);
4855
- },
6084
+ }
6085
+ byPackage = new Map([...found].map(([owner, modules]) => [owner, [...modules].sort()]));
6086
+ return byPackage;
6087
+ };
6088
+ /** Step 1 and the files it passes: the module the reference is imported from, followed out. */
6089
+ const imported = (reference) => {
6090
+ const files = [reference.getSourceFile()];
6091
+ const root = referenceRoot(reference);
6092
+ let symbol = root === undefined ? undefined : checker().getSymbolAtLocation(root);
6093
+ for (let step = 0; step < MAX_ALIAS_STEPS && symbol !== undefined; step++) {
6094
+ if ((symbol.flags & ts.SymbolFlags.Alias) === 0)
6095
+ break;
6096
+ for (const declaration of symbol.declarations ?? []) {
6097
+ const file = declaration.getSourceFile();
6098
+ if (!isOwn(file))
6099
+ continue;
6100
+ if (!files.includes(file))
6101
+ files.push(file);
6102
+ const specifier = specifierOf(declaration);
6103
+ if (specifier !== undefined && leavesProject(specifier)) {
6104
+ return { module: specifier.text, files };
6105
+ }
6106
+ }
6107
+ symbol = checker().getImmediateAliasedSymbol(symbol);
6108
+ }
6109
+ return { files };
6110
+ };
6111
+ const isPlatformModule = (module) => {
6112
+ const declarations = names.modulesNamed(module).flatMap((one) => one.declarations ?? []);
6113
+ return (declarations.length > 0 && declarations.every((one) => isPlatformFile(one.getSourceFile())));
6114
+ };
6115
+ const search = (declaration, reference) => {
6116
+ const way = imported(reference);
6117
+ const file = declaration.getSourceFile();
6118
+ const owner = packageOf(file.fileName);
6119
+ const candidates = [
6120
+ way.module,
6121
+ ...way.files.flatMap((one) => specifiersOf(one).flatMap((specifier) => leavesProject(specifier) ? [specifier.text] : [])),
6122
+ declaredPackageOf({ packageOf }, { file: file.fileName, node: declaration }),
6123
+ ...(owner === undefined ? [] : (modulesByPackage().get(owner) ?? [])),
6124
+ ];
6125
+ for (const module of new Set(candidates)) {
6126
+ if (module === undefined)
6127
+ continue;
6128
+ const name = names.nameOf(module, declaration);
6129
+ if (name !== undefined) {
6130
+ return { kind: "named", module, name, platform: isPlatformModule(module) };
6131
+ }
6132
+ }
6133
+ return way.module === undefined
6134
+ ? { kind: "unnamed" }
6135
+ : { kind: "unnamed", through: way.module };
6136
+ };
6137
+ return (declaration, reference) => {
6138
+ const root = referenceRoot(reference);
6139
+ const symbol = root === undefined ? undefined : checker().getSymbolAtLocation(root);
6140
+ // The answer depends on the import the reference comes through, else on its file's imports.
6141
+ const key = symbol !== undefined && (symbol.flags & ts.SymbolFlags.Alias) !== 0
6142
+ ? symbol
6143
+ : reference.getSourceFile();
6144
+ let answers = known.get(declaration);
6145
+ if (answers === undefined) {
6146
+ answers = new Map();
6147
+ known.set(declaration, answers);
6148
+ }
6149
+ const cached = answers.get(key);
6150
+ if (cached !== undefined)
6151
+ return cached;
6152
+ const found = search(declaration, reference);
6153
+ answers.set(key, found);
6154
+ return found;
4856
6155
  };
4857
6156
  }
4858
6157
  /**