@cplieger/deadset-ts 8.0.0-dev.8 → 8.0.0-dev.9

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 (75) hide show
  1. package/dist/src/analysis.js +84 -288
  2. package/dist/src/configuration-files.js +2 -9
  3. package/dist/src/consumers.js +1 -28
  4. package/dist/src/contract/contract.generated.js +20 -10
  5. package/dist/src/conventions.js +3 -8
  6. package/dist/src/failure.js +36 -0
  7. package/dist/src/fs/document.js +21 -28
  8. package/dist/src/fs/manifest.js +7 -0
  9. package/dist/src/load/classify.js +236 -0
  10. package/dist/src/load/diagnostics.js +79 -0
  11. package/dist/src/load/discover.js +230 -0
  12. package/dist/src/{emit-map.js → load/emit-map.js} +1 -1
  13. package/dist/src/load/expected-module.js +136 -0
  14. package/dist/src/load/load.js +22 -0
  15. package/dist/src/load/module-lookup.js +37 -0
  16. package/dist/src/load/plan.js +155 -0
  17. package/dist/src/{test-globals.js → load/test-globals.js} +51 -56
  18. package/dist/src/load/test-joins.js +82 -0
  19. package/dist/src/{workspace-manifests.js → load/workspace-manifests.js} +3 -3
  20. package/dist/src/{workspace-programs.js → load/workspace-programs.js} +37 -40
  21. package/dist/src/{workspace-resolution.js → load/workspace-resolution.js} +21 -59
  22. package/dist/src/{workspace-run.js → load/workspace-run.js} +4 -3
  23. package/dist/src/{workspace.js → load/workspace.js} +21 -17
  24. package/dist/src/outside-tests.js +1 -1
  25. package/dist/src/run.js +20 -26
  26. package/dist/src/scope.js +11 -19
  27. package/dist/src/session.js +22 -28
  28. package/dist/src/source-files.js +1 -1
  29. package/dist/src/type-errors.js +11 -216
  30. package/dist/src/verbs/analyze.js +90 -109
  31. package/dist/src/verbs/describe.js +5 -12
  32. package/dist/src/verbs/version.js +12 -2
  33. package/jsr.json +1 -1
  34. package/package.json +1 -1
  35. package/src/analysis.ts +68 -437
  36. package/src/configuration-files.ts +8 -10
  37. package/src/consumers.ts +2 -53
  38. package/src/contract/contract.generated.ts +20 -10
  39. package/src/conventions.ts +6 -12
  40. package/src/failure.ts +63 -0
  41. package/src/fs/document.ts +23 -27
  42. package/src/fs/manifest.ts +8 -0
  43. package/src/load/classify.ts +352 -0
  44. package/src/load/diagnostics.ts +141 -0
  45. package/src/load/discover.ts +378 -0
  46. package/src/{emit-map.ts → load/emit-map.ts} +1 -1
  47. package/src/load/expected-module.ts +188 -0
  48. package/src/load/load.ts +61 -0
  49. package/src/load/module-lookup.ts +50 -0
  50. package/src/load/plan.ts +258 -0
  51. package/src/{test-globals.ts → load/test-globals.ts} +59 -65
  52. package/src/load/test-joins.ts +98 -0
  53. package/src/{workspace-manifests.ts → load/workspace-manifests.ts} +4 -4
  54. package/src/{workspace-programs.ts → load/workspace-programs.ts} +59 -53
  55. package/src/{workspace-resolution.ts → load/workspace-resolution.ts} +31 -78
  56. package/src/{workspace-run.ts → load/workspace-run.ts} +14 -11
  57. package/src/{workspace.ts → load/workspace.ts} +28 -21
  58. package/src/outside-tests.ts +1 -1
  59. package/src/partial.ts +1 -1
  60. package/src/run.ts +26 -25
  61. package/src/scope.ts +15 -21
  62. package/src/session.ts +52 -53
  63. package/src/source-files.ts +1 -1
  64. package/src/type-errors.ts +18 -288
  65. package/src/verbs/analyze.ts +129 -136
  66. package/src/verbs/describe.ts +4 -11
  67. package/src/verbs/version.ts +13 -2
  68. package/dist/src/base-url.js +0 -18
  69. package/dist/src/discover.js +0 -374
  70. package/dist/src/setup-failure.js +0 -19
  71. package/dist/src/test-joins.js +0 -101
  72. package/src/base-url.ts +0 -24
  73. package/src/discover.ts +0 -548
  74. package/src/setup-failure.ts +0 -37
  75. package/src/test-joins.ts +0 -118
@@ -0,0 +1,378 @@
1
+ import type { BuildConfiguration, ProjectConfiguration } from "../config.ts";
2
+ import { LANGUAGE_ROWS } from "../contract/contract.generated.ts";
3
+ import { filesBelow } from "../fs/tree.ts";
4
+ import type { Host } from "../host.ts";
5
+ import { packageScope } from "../inventory.ts";
6
+ import { dirnamePath, joinPath, relativePath, resolvePath } from "../paths.ts";
7
+ import { LANGUAGE, message } from "../product.ts";
8
+ import type { Module, Scope } from "../scope.ts";
9
+ import type { Engine } from "../session.ts";
10
+ import { globExpression } from "../text/glob.ts";
11
+ import { failureExit } from "../failure.ts";
12
+
13
+ /** The names of the files a program of the language is read from. */
14
+ export const MARKERS = LANGUAGE_ROWS[LANGUAGE].markers;
15
+ const MARKER_EXPRESSIONS = MARKERS.map(globExpression);
16
+
17
+ /** Whether one file name is a compiler configuration's: one of the language row's markers. */
18
+ export function isConfigFile(name: string): boolean {
19
+ return MARKER_EXPRESSIONS.some((marker) => marker.test(name));
20
+ }
21
+
22
+ /**
23
+ * Where one configuration of a run comes from, which decides what a failure to build it
24
+ * does: a guess discovery derived is dropped, any other ends the run.
25
+ */
26
+ export type Origin = "declared" | "scope" | "derived" | "consumer";
27
+
28
+ /** One consumer the run loads. */
29
+ export interface LoadedConsumer {
30
+ /** The name the consumer publishes itself under, which every finding names it by. */
31
+ readonly id: string;
32
+ /** The consumer's directory, absolute. */
33
+ readonly path: string;
34
+ }
35
+
36
+ /** One compiler configuration a run opens. */
37
+ export interface Configuration {
38
+ /**
39
+ * The name a run gives the project: the identifier the build matrix declares for it, or,
40
+ * for a derived one, its configuration file's path below the target root, else its
41
+ * absolute path. A consumer's is its configuration file's absolute path.
42
+ */
43
+ readonly id: string;
44
+ /** The compiler configuration file, absolute. */
45
+ readonly configFile: string;
46
+ readonly origin: Origin;
47
+ /** The compiler's parse of the configuration, which discovery could read and found not circular. */
48
+ readonly parsed: Parsed;
49
+ /** The consumer the configuration loads, for one whose origin is `consumer`. */
50
+ readonly consumer?: LoadedConsumer | undefined;
51
+ }
52
+
53
+ /** Whether the run analyzes one configuration as the target's. */
54
+ export function isTargetConfiguration(configuration: Configuration): boolean {
55
+ return configuration.origin !== "consumer";
56
+ }
57
+
58
+ /**
59
+ * One project discovery derived and the run could not build, with the first line of the
60
+ * error that dropped it.
61
+ */
62
+ export interface NotBuilt {
63
+ /** The name the project would have carried, as {@link Configuration.id} spells it. */
64
+ readonly id: string;
65
+ /** The compiler configuration file, absolute. */
66
+ readonly configFile: string;
67
+ /** The error's first line, every path below the target root spelled relative to it. */
68
+ readonly error: string;
69
+ }
70
+
71
+ /** Every configuration a run opens, the target's in discovery order, then each consumer's. */
72
+ export interface Discovery {
73
+ /** Whether the matrix is the configuration document's or one discovery derived. */
74
+ readonly mode: "declared" | "derived";
75
+ readonly configurations: readonly Configuration[];
76
+ /** The derived configurations the compiler could not read, in discovery order. */
77
+ readonly notBuilt: readonly NotBuilt[];
78
+ /** Every declared consumer, in the scope's order. */
79
+ readonly consumers: readonly LoadedConsumer[];
80
+ }
81
+
82
+ /**
83
+ * The first line of one error about the target, every mention of the target root spelled
84
+ * relative to it: a path below the root loses the root and its separator, and the root
85
+ * itself is `.`.
86
+ */
87
+ export function targetRelative(text: string, targetRoot: string): string {
88
+ const root = targetRoot.endsWith("/") ? targetRoot.slice(0, -1) : targetRoot;
89
+ const [first = ""] = text.split(/\r?\n/u);
90
+ const spelled = first.split(`${root}/`).join("").split(root).join(".").trim();
91
+ return spelled === "" ? "the configuration could not be built" : spelled;
92
+ }
93
+
94
+ /** The configuration files below `root`, by absolute path in ascending order. */
95
+ function configFilesUnder(host: Host, root: string): readonly string[] {
96
+ return filesBelow(host, root, isConfigFile).map((path) => joinPath(root, path));
97
+ }
98
+
99
+ export type Parsed = ReturnType<Engine["parseConfigFile"]>;
100
+
101
+ /** The configuration files one parsed configuration's `references` name. */
102
+ function referencesOf(parsed: Parsed): readonly string[] {
103
+ // The parse answers a directory reference as the directory; the compiler reads a
104
+ // path not ending `.json` as its `tsconfig.json`:
105
+ // https://github.com/microsoft/typescript-go/blob/89d5d5b2849a0db0957065889ca58536fa6d2e4a/internal/core/projectreference.go#L18
106
+ return (parsed.projectReferences ?? []).map(({ path }) =>
107
+ path.endsWith(".json") ? path : joinPath(path, "tsconfig.json"),
108
+ );
109
+ }
110
+
111
+ /**
112
+ * The code of a configuration whose `extends` chain returns to a configuration it already
113
+ * passed. A snapshot that opens two configurations whose `extends` chains reach one such
114
+ * cycle panics (`OwnerCache.AddOwner: entry not found`, typescript 7.1.0-dev.20261014.1),
115
+ * so the analysis refuses one before any snapshot is asked to open it.
116
+ */
117
+ const CIRCULAR_EXTENDS = 18000;
118
+
119
+ /** One configuration file's parse, or why it cannot be read. */
120
+ function readConfiguration(
121
+ engine: Engine,
122
+ configFile: string,
123
+ ): { readonly parsed: Parsed } | { readonly reason: string } {
124
+ try {
125
+ const parsed = engine.parseConfigFile(configFile);
126
+ const circular = parsed.errors.find(({ code }) => code === CIRCULAR_EXTENDS);
127
+ // The compiler leaves the message's `{0}` unfilled:
128
+ // https://github.com/microsoft/TypeScript/pull/64755
129
+ return circular === undefined
130
+ ? { parsed }
131
+ : { reason: `TS${String(circular.code)}: ${circular.text.replace("{0}", () => configFile)}` };
132
+ } catch (error: unknown) {
133
+ return { reason: message(error) };
134
+ }
135
+ }
136
+
137
+ /** One configuration file the compiler parsed with no circular `extends`, and its parse. */
138
+ interface Read {
139
+ readonly configFile: string;
140
+ readonly parsed: Parsed;
141
+ }
142
+
143
+ /**
144
+ * Every configuration file reached from `pending`, each once, each followed by the
145
+ * configurations it references that `follows` admits, transitively. `unreadable` is told
146
+ * each configuration the compiler cannot read, which the walk then goes on without.
147
+ */
148
+ function derivedFrom(
149
+ engine: Engine,
150
+ host: Host,
151
+ pending: string[],
152
+ follows: (reference: string) => boolean,
153
+ unreadable: (configFile: string, reason: string) => void,
154
+ ): Read[] {
155
+ const seen = new Set<string>();
156
+ const found: Read[] = [];
157
+ for (let configFile = pending.shift(); configFile !== undefined; configFile = pending.shift()) {
158
+ const path = resolvePath(host.workingDirectory(), configFile);
159
+ if (seen.has(path)) {
160
+ continue;
161
+ }
162
+ seen.add(path);
163
+ const read = readConfiguration(engine, path);
164
+ if ("reason" in read) {
165
+ unreadable(path, read.reason);
166
+ continue;
167
+ }
168
+ found.push({ configFile: path, parsed: read.parsed });
169
+ pending.push(...referencesOf(read.parsed).filter(follows));
170
+ }
171
+ return found;
172
+ }
173
+
174
+ /** The name one module publishes itself under: the scope's, else its manifest's. */
175
+ export function moduleIdentity(host: Host, module: Module): string {
176
+ return module.id === "" ? packageScope(host, module.path)("index.ts").package : module.id;
177
+ }
178
+
179
+ /**
180
+ * The compiler configurations one consumer is loaded through: every one under its root and
181
+ * each one those reference, transitively. A consumer that is absent, no directory, holds no
182
+ * configuration or holds one the compiler cannot read ends the run naming it, because a
183
+ * finding computed without a declared consumer would claim a reference set the run never read.
184
+ */
185
+ function consumerProjects(engine: Engine, host: Host, root: string): readonly Read[] {
186
+ const kind = host.kindOf(root);
187
+ if (kind === "absent") {
188
+ throw failureExit(
189
+ "missing-consumer",
190
+ `the scope declares the consumer ${root}, and nothing is at that path: check the consumer out at ${root} and install its dependencies`,
191
+ );
192
+ }
193
+ if (kind !== "directory") {
194
+ throw failureExit(
195
+ "missing-consumer",
196
+ `the scope declares the consumer ${root}, which is not a directory: check the consumer out at ${root}`,
197
+ );
198
+ }
199
+ const found = derivedFrom(
200
+ engine,
201
+ host,
202
+ [...configFilesUnder(host, root)],
203
+ () => true,
204
+ (configFile, reason) => {
205
+ throw failureExit(
206
+ "missing-consumer",
207
+ `the consumer ${root} does not load, ${configFile} cannot be read as a compiler configuration: ${reason}`,
208
+ );
209
+ },
210
+ );
211
+ if (found.length === 0) {
212
+ throw failureExit(
213
+ "missing-consumer",
214
+ `the consumer ${root} holds no compiler configuration, so none of its references can be read: check the consumer out at ${root} with its ${MARKERS.join(", ")}`,
215
+ );
216
+ }
217
+ return found;
218
+ }
219
+
220
+ /** A target configuration a matrix or the invocation names that cannot be built, ending the run. */
221
+ function unbuilt(named: string, reason: string): never {
222
+ throw failureExit(
223
+ "no-program",
224
+ `${named} ${reason}: correct the configuration, or name the configurations to analyze`,
225
+ );
226
+ }
227
+
228
+ /**
229
+ * The projects a build matrix declares, in its order, each entry a file below the target
230
+ * root: an entry naming an absent file, a directory or a file the compiler cannot read ends
231
+ * the run naming it, and one naming an earlier entry's file adds nothing. A reference below
232
+ * the root the matrix does not name ends the run naming both, because the compiler builds a
233
+ * referenced project's sources into the referencing program without reporting their
234
+ * diagnostics. A reference outside the root is an outside project.
235
+ */
236
+ function declaredProjects(
237
+ engine: Engine,
238
+ host: Host,
239
+ targetRoot: string,
240
+ entries: readonly ProjectConfiguration[],
241
+ ): readonly Configuration[] {
242
+ const projects: Configuration[] = [];
243
+ const references = new Map<string, readonly string[]>();
244
+ for (const entry of entries) {
245
+ const configFile = joinPath(targetRoot, entry.project);
246
+ const named = `the project ${JSON.stringify(entry.id)} (${configFile})`;
247
+ const kind = host.kindOf(configFile);
248
+ if (kind !== "file") {
249
+ unbuilt(
250
+ named,
251
+ kind === "absent"
252
+ ? "does not exist"
253
+ : "is a directory, and a project names its compiler configuration file",
254
+ );
255
+ }
256
+ if (references.has(configFile)) {
257
+ continue;
258
+ }
259
+ const read = readConfiguration(engine, configFile);
260
+ if ("reason" in read) {
261
+ unbuilt(named, `cannot be read as a compiler configuration: ${read.reason}`);
262
+ }
263
+ references.set(configFile, referencesOf(read.parsed));
264
+ projects.push({ id: entry.id, configFile, origin: "declared", parsed: read.parsed });
265
+ }
266
+ for (const project of projects) {
267
+ const unnamed = references
268
+ .get(project.configFile)
269
+ ?.find((path) => !references.has(path) && relativePath(targetRoot, path) !== undefined);
270
+ if (unnamed !== undefined) {
271
+ unbuilt(
272
+ `the project ${JSON.stringify(project.id)} (${project.configFile})`,
273
+ `references ${unnamed}, which the build matrix does not name. A referenced project is built into the program that references it, so the matrix names it too`,
274
+ );
275
+ }
276
+ }
277
+ return projects;
278
+ }
279
+
280
+ /**
281
+ * The projects a run derives where the matrix declares none: the configuration the scope
282
+ * names for the target where its path names one, every compiler configuration under the
283
+ * target root outside a skipped directory, then each configuration below the root those
284
+ * reference, transitively, each once. A configuration the scope names ends the run where it
285
+ * cannot be read; one the walk found is dropped and named.
286
+ */
287
+ function derivedProjects(
288
+ engine: Engine,
289
+ host: Host,
290
+ scope: Scope,
291
+ ): { readonly configurations: readonly Configuration[]; readonly notBuilt: readonly NotBuilt[] } {
292
+ const targetRoot = scope.target.path;
293
+ const fromScope = scope.target.path.endsWith(".json")
294
+ ? [resolvePath(host.workingDirectory(), scope.target.path)]
295
+ : [];
296
+ const absoluteRoot = resolvePath(host.workingDirectory(), targetRoot);
297
+ const rootDir = resolvePath(
298
+ host.workingDirectory(),
299
+ fromScope.length > 0 ? dirnamePath(targetRoot) : targetRoot,
300
+ );
301
+ const idOf = (configFile: string): string => relativePath(targetRoot, configFile) ?? configFile;
302
+ const notBuilt: NotBuilt[] = [];
303
+ const found = derivedFrom(
304
+ engine,
305
+ host,
306
+ [...fromScope, ...configFilesUnder(host, targetRoot)],
307
+ (reference) => relativePath(rootDir, reference) !== undefined,
308
+ (configFile, reason) => {
309
+ if (fromScope.includes(configFile)) {
310
+ unbuilt(configFile, `cannot be read as a compiler configuration: ${reason}`);
311
+ }
312
+ notBuilt.push({
313
+ id: idOf(configFile),
314
+ configFile,
315
+ error: targetRelative(reason, absoluteRoot),
316
+ });
317
+ },
318
+ );
319
+ return {
320
+ configurations: found.map(({ configFile, parsed }) => ({
321
+ id: idOf(configFile),
322
+ configFile,
323
+ origin: fromScope.includes(configFile) ? "scope" : "derived",
324
+ parsed,
325
+ })),
326
+ notBuilt,
327
+ };
328
+ }
329
+
330
+ /**
331
+ * Every configuration one run opens: the build matrix's project entries in its order, or,
332
+ * where it holds none, those derived from the scope and the target tree, then each declared
333
+ * consumer's, a configuration the target or an earlier consumer opens being theirs alone. A
334
+ * target holding none ends the run with the setup failure `no-program`. No build output is
335
+ * read: a project is the files its configuration names.
336
+ */
337
+ export function discoverProjects(
338
+ engine: Engine,
339
+ host: Host,
340
+ scope: Scope,
341
+ configurations: readonly BuildConfiguration[] = [],
342
+ ): Discovery {
343
+ const declared = configurations.filter(
344
+ (entry): entry is ProjectConfiguration => "project" in entry,
345
+ );
346
+ const target =
347
+ declared.length > 0
348
+ ? {
349
+ mode: "declared" as const,
350
+ configurations: declaredProjects(engine, host, scope.target.path, declared),
351
+ notBuilt: [],
352
+ }
353
+ : { mode: "derived" as const, ...derivedProjects(engine, host, scope) };
354
+ if (target.configurations.length === 0 && target.notBuilt.length === 0) {
355
+ throw failureExit(
356
+ "no-program",
357
+ `${scope.target.path} holds no compiler configuration, no file named ${MARKERS.join(", ")}: run from the directory that holds one, or name the languages to analyze`,
358
+ );
359
+ }
360
+ const opened = new Set(target.configurations.map((one) => one.configFile));
361
+ const consumers: LoadedConsumer[] = [];
362
+ const consumed: Configuration[] = [];
363
+ for (const module of scope.consumers) {
364
+ const read = consumerProjects(engine, host, module.path);
365
+ const consumer = { id: moduleIdentity(host, module), path: module.path };
366
+ consumers.push(consumer);
367
+ for (const { configFile, parsed } of read.filter((one) => !opened.has(one.configFile))) {
368
+ opened.add(configFile);
369
+ consumed.push({ id: configFile, configFile, origin: "consumer", parsed, consumer });
370
+ }
371
+ }
372
+ return {
373
+ mode: target.mode,
374
+ configurations: [...target.configurations, ...consumed],
375
+ notBuilt: target.notBuilt,
376
+ consumers,
377
+ };
378
+ }
@@ -5,7 +5,7 @@
5
5
  * whether the path is the target's own or a workspace package's.
6
6
  */
7
7
 
8
- import { dirnamePath, joinPath, relativePath } from "./paths.ts";
8
+ import { dirnamePath, joinPath, relativePath } from "../paths.ts";
9
9
 
10
10
  /** The source extensions the compiler emits each output extension from. */
11
11
  const EMITTED: readonly { readonly emitted: string; readonly sources: readonly string[] }[] = [
@@ -0,0 +1,188 @@
1
+ import type { SourceFile } from "@typescript/native/ast";
2
+ import {
3
+ isNoSubstitutionTemplateLiteral,
4
+ isStringLiteral,
5
+ type Node,
6
+ } from "@typescript/native/ast";
7
+ import { packageOfSpecifier } from "../dependencies.ts";
8
+ import { MANIFEST } from "../fs/manifest.ts";
9
+ import { entriesOf } from "../fs/tree.ts";
10
+ import type { Host } from "../host.ts";
11
+ import { dirnamePath, isAbsolutePath, joinPath, relativePath, resolvePath } from "../paths.ts";
12
+ import { dependencySpecifiers, installedPackage, manifestsAbove } from "./module-lookup.ts";
13
+ import type { CompilerOptions } from "./plan.ts";
14
+
15
+ /** Where one project reads what its imports may name. */
16
+ export interface ModuleContext {
17
+ readonly host: Host;
18
+ /** The root of the module the project is the target's or a consumer's, absolute. */
19
+ readonly targetRoot: string;
20
+ /** The project configuration's `paths` mapping. */
21
+ readonly paths: PathsMapping;
22
+ /** Whether one manifest is a workspace member's, whose dependencies the workspace installs. */
23
+ readonly member: (manifest: string) => boolean;
24
+ }
25
+
26
+ /** One configuration's `paths` mapping, its targets read against `base`. */
27
+ interface PathsMapping {
28
+ readonly base: string;
29
+ readonly entries: readonly { readonly key: string; readonly targets: readonly string[] }[];
30
+ }
31
+
32
+ /** The string literal holding one offset, innermost first, a doc comment's included. */
33
+ function literalAt(file: SourceFile, offset: number): string | undefined {
34
+ let found: string | undefined;
35
+ const visit = (node: Node): void => {
36
+ if (offset < node.pos || offset >= node.end) {
37
+ return;
38
+ }
39
+ if (isStringLiteral(node) || isNoSubstitutionTemplateLiteral(node)) {
40
+ found = node.text;
41
+ }
42
+ // `forEachChild` does not enter a doc comment, where a JavaScript file imports types.
43
+ for (const doc of (node as { readonly jsDoc?: readonly Node[] }).jsDoc ?? []) {
44
+ visit(doc);
45
+ }
46
+ node.forEachChild(visit);
47
+ };
48
+ file.forEachChild(visit);
49
+ return found;
50
+ }
51
+
52
+ /**
53
+ * What one `paths` key's `*` matches in one specifier, `""` for a key with no `*` that
54
+ * is the specifier, or `undefined` where the key does not match it.
55
+ */
56
+ function mappedBy(key: string, specifier: string): string | undefined {
57
+ const star = key.indexOf("*");
58
+ if (star < 0) {
59
+ return key === specifier ? "" : undefined;
60
+ }
61
+ const prefix = key.slice(0, star);
62
+ const suffix = key.slice(star + 1);
63
+ return specifier.length >= prefix.length + suffix.length &&
64
+ specifier.startsWith(prefix) &&
65
+ specifier.endsWith(suffix)
66
+ ? specifier.slice(prefix.length, specifier.length - suffix.length)
67
+ : undefined;
68
+ }
69
+
70
+ /**
71
+ * One `paths` target, its first `*` replaced by `star` taken literally, as the compiler does:
72
+ * https://github.com/microsoft/typescript-go/blob/89d5d5b2849a0db0957065889ca58536fa6d2e4a/internal/module/resolver.go#L1282
73
+ */
74
+ function substituted(target: string, star: string): string {
75
+ const at = target.indexOf("*");
76
+ return at < 0 ? target : target.slice(0, at) + star + target.slice(at + 1);
77
+ }
78
+
79
+ /**
80
+ * Whether a path names something on disk, as written or with any extension; under
81
+ * `fileOnly`, only a file counts.
82
+ */
83
+ function provided(host: Host, path: string, fileOnly: boolean): boolean {
84
+ const counts = (at: string): boolean =>
85
+ fileOnly ? host.kindOf(at) === "file" : host.kindOf(at) !== "absent";
86
+ if (counts(path)) {
87
+ return true;
88
+ }
89
+ const dir = dirnamePath(path);
90
+ const stem = `${path.slice(dir.length + 1)}.`;
91
+ return entriesOf(host, dir).some(
92
+ (entry) => entry.name.startsWith(stem) && counts(joinPath(dir, entry.name)),
93
+ );
94
+ }
95
+
96
+ /** The manifest at or above `dir`, no higher than the target root, that declares `name`. */
97
+ function declaringManifest(
98
+ host: Host,
99
+ dir: string,
100
+ targetRoot: string,
101
+ name: string,
102
+ ): string | undefined {
103
+ for (const { dir: at, manifest } of manifestsAbove(host, dir, targetRoot)) {
104
+ if (dependencySpecifiers(manifest, name).length > 0) {
105
+ return joinPath(at, MANIFEST);
106
+ }
107
+ }
108
+ return undefined;
109
+ }
110
+
111
+ /**
112
+ * Why one import that the compiler cannot resolve names a module the project expects,
113
+ * with the fix, or undefined where the module is one the project does not expect.
114
+ */
115
+ function expectedModule(
116
+ context: ModuleContext,
117
+ importer: string,
118
+ specifier: string,
119
+ ): string | undefined {
120
+ const { host, targetRoot } = context;
121
+ const fix = "run the generator or the build that writes it";
122
+ if (specifier.startsWith(".") || isAbsolutePath(specifier)) {
123
+ return provided(host, resolvePath(dirnamePath(importer), specifier), false)
124
+ ? undefined
125
+ : `which names no file of the target: ${fix}`;
126
+ }
127
+ if (specifier.startsWith("#")) {
128
+ return `which the manifest's imports map to no file: ${fix}`;
129
+ }
130
+ const mapped = context.paths.entries.flatMap(({ key, targets }) => {
131
+ const star = mappedBy(key, specifier);
132
+ return star === undefined
133
+ ? []
134
+ : targets.map((target) => resolvePath(context.paths.base, substituted(target, star)));
135
+ });
136
+ const name = packageOfSpecifier(specifier);
137
+ // The compiler looks up in `node_modules` what `paths` does not resolve, so the error
138
+ // of an installed package's import is the import's own, a subpath its exports omit:
139
+ // https://github.com/microsoft/typescript-go/blob/89d5d5b2849a0db0957065889ca58536fa6d2e4a/internal/module/resolver.go#L548-L575
140
+ if (name !== undefined && installedPackage(host, dirnamePath(importer), name) !== undefined) {
141
+ return undefined;
142
+ }
143
+ if (mapped.length > 0) {
144
+ return mapped.some((path) => provided(host, path, true))
145
+ ? undefined
146
+ : `which the compiler configuration's paths map to no file: ${fix}`;
147
+ }
148
+ const manifest =
149
+ name === undefined
150
+ ? undefined
151
+ : declaringManifest(host, dirnamePath(importer), targetRoot, name);
152
+ // No run requires a nested package that is no workspace member to be installed.
153
+ if (
154
+ manifest === undefined ||
155
+ (dirnamePath(manifest) !== targetRoot && !context.member(manifest))
156
+ ) {
157
+ return undefined;
158
+ }
159
+ const where = relativePath(targetRoot, manifest) ?? manifest;
160
+ return `a dependency ${where} declares that is not installed: run the package manager's install`;
161
+ }
162
+
163
+ /** The `paths` mapping of the configuration at `configFile` whose parse answered `options`. */
164
+ export function pathsOf(configFile: string, options: CompilerOptions): PathsMapping {
165
+ // The parse answers `pathsBasePath`, the directory of the configuration that writes
166
+ // `paths` (an extended one included), though the client's option type omits it:
167
+ // https://github.com/microsoft/typescript-go/blob/89d5d5b2849a0db0957065889ca58536fa6d2e4a/internal/tsoptions/tsconfigparsing.go#L1120
168
+ const declaredAt = (options as { readonly pathsBasePath?: unknown }).pathsBasePath;
169
+ return {
170
+ base: typeof declaredAt === "string" ? declaredAt : dirnamePath(configFile),
171
+ entries: Object.entries(options.paths ?? {}).map(([key, targets]) => ({ key, targets })),
172
+ };
173
+ }
174
+
175
+ /**
176
+ * Why one import the compiler cannot resolve, at `offset` of `file`, names a module the project
177
+ * expects and nothing provides, with the fix; undefined where the project does not expect it.
178
+ */
179
+ export function missingModule(
180
+ context: ModuleContext,
181
+ file: SourceFile,
182
+ offset: number,
183
+ ): { readonly specifier: string; readonly reason: string } | undefined {
184
+ const specifier = literalAt(file, offset);
185
+ const reason =
186
+ specifier === undefined ? undefined : expectedModule(context, file.fileName, specifier);
187
+ return specifier === undefined || reason === undefined ? undefined : { specifier, reason };
188
+ }
@@ -0,0 +1,61 @@
1
+ import type { PartialConfig } from "../config.ts";
2
+ import type { Host } from "../host.ts";
3
+ import { resolvePath } from "../paths.ts";
4
+ import type { UnansweredQuestion } from "../query.ts";
5
+ import type { Scope } from "../scope.ts";
6
+ import { openSession, type Engine } from "../session.ts";
7
+ import { classify, type Classified } from "./classify.ts";
8
+ import { planRun, programBuilds, type RunPlan } from "./plan.ts";
9
+
10
+ /** The run as the load phase opens it, valid only inside the reader it is handed to. */
11
+ interface OpenedRun {
12
+ readonly plan: RunPlan;
13
+ readonly classified: Classified;
14
+ /** Every file a program of the run holds, absolute, so a file another configuration compiles is no outside file. */
15
+ readonly runFiles: ReadonlySet<string>;
16
+ }
17
+
18
+ /** What one loaded run answered, beside its plan and its classification. */
19
+ export interface LoadedRun<Result> extends Omit<OpenedRun, "runFiles"> {
20
+ readonly result: Result;
21
+ /** Every question the checker could not answer, each once, in the order first asked. */
22
+ readonly unanswered: readonly UnansweredQuestion[];
23
+ }
24
+
25
+ /**
26
+ * Plans the run, opens every configuration in one snapshot of one client, classifies every
27
+ * project, and hands the analyzed and the consumer projects to `read` while the client answers.
28
+ * A run that cannot be analyzed ends with one {@link FailureExit} before `read` is called.
29
+ */
30
+ export function loadRun<Result>(
31
+ engine: Engine,
32
+ host: Host,
33
+ scope: Scope,
34
+ config: PartialConfig,
35
+ read: (opened: OpenedRun) => Result,
36
+ ): LoadedRun<Result> {
37
+ const plan = planRun(engine, host, scope, config);
38
+ return openSession(
39
+ engine,
40
+ plan.plans.map((one) => one.configFile),
41
+ { programs: programBuilds(host, plan.plans) },
42
+ (session, unanswered) => {
43
+ const classified = classify(
44
+ host,
45
+ plan,
46
+ new Map(session.views.map((view) => [view.configFile, view])),
47
+ );
48
+ const runFiles = new Set(
49
+ session.views.flatMap((view) =>
50
+ view.ownSourceFiles().map((file) => resolvePath(host.workingDirectory(), file.fileName)),
51
+ ),
52
+ );
53
+ return {
54
+ plan,
55
+ classified,
56
+ result: read({ plan, classified, runFiles }),
57
+ unanswered: unanswered(),
58
+ };
59
+ },
60
+ );
61
+ }
@@ -0,0 +1,50 @@
1
+ /**
2
+ * Where a package an import names is installed and which manifests above an importer declare
3
+ * it: the leaf both the expected-module reading and the workspace resolution read.
4
+ */
5
+
6
+ import { DEPENDENCY_SECTIONS, INSTALLED_PACKAGES, manifestAt } from "../fs/manifest.ts";
7
+ import type { Host } from "../host.ts";
8
+ import { isRecord } from "../json-document.ts";
9
+ import { ancestors, joinPath } from "../paths.ts";
10
+
11
+ /**
12
+ * The directory `node_modules/<name>` holds for an importer in `dir`: the nearest one at or
13
+ * above `dir`, above any target root too, that is a directory, a link to one included, as the
14
+ * compiler looks a package up. Undefined where no ancestor installs it.
15
+ */
16
+ export function installedPackage(host: Host, dir: string, name: string): string | undefined {
17
+ return ancestors(dir)
18
+ .map((at) => joinPath(at, INSTALLED_PACKAGES, name))
19
+ .find((candidate) => host.kindOf(candidate) === "directory");
20
+ }
21
+
22
+ export interface ManifestAt {
23
+ readonly dir: string;
24
+ readonly manifest: Record<string, unknown>;
25
+ }
26
+
27
+ /**
28
+ * The manifests at or above `dir` and no higher than `top`, nearest first; a directory outside
29
+ * `top` reads its own manifest alone.
30
+ */
31
+ export function* manifestsAbove(host: Host, dir: string, top: string): Generator<ManifestAt> {
32
+ const chain = ancestors(dir, top);
33
+ for (const at of chain.length > 0 ? chain : [dir]) {
34
+ const manifest = manifestAt(host, at);
35
+ if (manifest !== undefined) {
36
+ yield { dir: at, manifest };
37
+ }
38
+ }
39
+ }
40
+
41
+ /** The specifiers one manifest depends on `name` with, one per dependency section naming it. */
42
+ export function dependencySpecifiers(
43
+ manifest: Readonly<Record<string, unknown>>,
44
+ name: string,
45
+ ): readonly unknown[] {
46
+ return DEPENDENCY_SECTIONS.flatMap((section) => {
47
+ const declared = manifest[section];
48
+ return isRecord(declared) && Object.hasOwn(declared, name) ? [declared[name]] : [];
49
+ });
50
+ }