@ark/attest 0.56.7 → 0.57.1

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 (40) hide show
  1. package/README.md +9 -385
  2. package/out/assert/assertions.d.ts +1 -1
  3. package/out/assert/assertions.js +12 -18
  4. package/out/assert/attest.d.ts +2 -3
  5. package/out/assert/attest.js +3 -3
  6. package/out/assert/chainableAssertions.d.ts +1 -1
  7. package/out/assert/chainableAssertions.js +2 -1
  8. package/out/bench/type.js +6 -3
  9. package/out/cache/getCachedAssertions.d.ts +33 -11
  10. package/out/cache/getCachedAssertions.js +23 -46
  11. package/out/cache/snapshots.d.ts +6 -2
  12. package/out/cache/snapshots.js +32 -26
  13. package/out/cache/ts.js +6 -3
  14. package/out/cache/utils.d.ts +1 -1
  15. package/out/cache/writeAssertionCache.d.ts +1 -30
  16. package/out/cache/writeAssertionCache.js +2 -1
  17. package/out/cli/precache.js +3 -4
  18. package/out/cli/shared.d.ts +1 -1
  19. package/out/cli/shared.js +4 -1
  20. package/out/cli/trace.js +60 -25
  21. package/out/config.d.ts +6 -22
  22. package/out/config.js +5 -30
  23. package/out/fixtures.js +5 -18
  24. package/out/index.d.ts +1 -3
  25. package/out/index.js +1 -2
  26. package/out/ts7/analyze.d.ts +10 -0
  27. package/out/ts7/analyze.js +188 -0
  28. package/out/ts7/countInstantiations.d.ts +1 -0
  29. package/out/ts7/countInstantiations.js +44 -0
  30. package/out/ts7/instantiations.d.ts +13 -0
  31. package/out/ts7/instantiations.js +113 -0
  32. package/out/ts7/server.d.ts +48 -0
  33. package/out/ts7/server.js +224 -0
  34. package/out/ts7/snapshots.d.ts +5 -0
  35. package/out/ts7/snapshots.js +27 -0
  36. package/out/utils.d.ts +17 -0
  37. package/out/utils.js +33 -1
  38. package/package.json +8 -6
  39. package/out/tsVersioning.d.ts +0 -31
  40. package/out/tsVersioning.js +0 -172
@@ -0,0 +1,188 @@
1
+ import { flatMorph, throwInternalError } from "@ark/util";
2
+ import { getConfig } from "../config.js";
3
+ import { getFileKey } from "../utils.js";
4
+ import { getInstantiationsContributedByNodes } from "./instantiations.js";
5
+ import { TsgoServer, ast, getAncestors, getCallExpressionsByName, getCallLocation, getDescendants, getFirstFunctionDescendant, noTruncation } from "./server.js";
6
+ export const analyzeProjectAssertions = () => {
7
+ const config = getConfig();
8
+ const server = TsgoServer.instance;
9
+ server.disableCommentDirectives();
10
+ const assertionsByFile = {};
11
+ for (const path of server.rootFiles) {
12
+ const file = server.getSourceFileOrThrow(path);
13
+ const assertions = getCallExpressionsByName(file, config.attestAliases).map(call => analyzeAssertCall(call, file));
14
+ if (!config.skipInlineInstantiations) {
15
+ assertions.push(...getInlineInstantiationData(file, config.attestAliases.map(alias => `${alias}.instantiations`)));
16
+ }
17
+ if (assertions.length)
18
+ assertionsByFile[getFileKey(path)] = assertions;
19
+ }
20
+ return assertionsByFile;
21
+ };
22
+ const analyzeAssertCall = (call, file) => {
23
+ const args = call.arguments.map(stringifyTypeAtLocation);
24
+ const typeArgs = call.typeArguments?.map(stringifyTypeAtLocation) ?? [];
25
+ const serializeArg = (arg) => ({
26
+ type: arg.string,
27
+ relationships: {
28
+ args: args.map(other => compareTypes(arg, other)),
29
+ typeArgs: typeArgs.map(other => compareTypes(arg, other))
30
+ }
31
+ });
32
+ const result = {
33
+ location: getCallLocation(call),
34
+ args: args.map(serializeArg),
35
+ typeArgs: typeArgs.map(serializeArg),
36
+ errors: getErrorsInCall(call, file),
37
+ completions: getCompletions(call, file)
38
+ };
39
+ const jsdoc = getJsdoc(call);
40
+ if (jsdoc)
41
+ result.jsdoc = jsdoc;
42
+ return result;
43
+ };
44
+ export const stringifyTypeAtLocation = (node) => {
45
+ const checker = TsgoServer.instance.project.checker;
46
+ const type = checker.getTypeAtLocation(node);
47
+ let string = checker.typeToString(type);
48
+ if (string.includes("...")) {
49
+ const nonTruncated = checker.typeToString(type, undefined, noTruncation);
50
+ string =
51
+ nonTruncated.includes(" any") && !string.includes(" any") ?
52
+ nonTruncated.replace(/ any/g, " cyclic")
53
+ : nonTruncated;
54
+ }
55
+ return {
56
+ type,
57
+ string,
58
+ isUnresolvable: type.isErrorType()
59
+ };
60
+ };
61
+ const compareTypes = (l, r) => {
62
+ // ensure two unresolvable types are not treated as equivalent
63
+ if (l.isUnresolvable || r.isUnresolvable)
64
+ return "none";
65
+ // treat `any` as a supertype of every other type
66
+ if (l.string === "any")
67
+ return r.string === "any" ? "equality" : "supertype";
68
+ if (r.string === "any")
69
+ return "subtype";
70
+ const checker = TsgoServer.instance.project.checker;
71
+ const isSubtype = checker.isTypeAssignableTo(l.type, r.type);
72
+ const isSupertype = checker.isTypeAssignableTo(r.type, l.type);
73
+ return (isSubtype ?
74
+ isSupertype ? "equality"
75
+ : "subtype"
76
+ : isSupertype ? "supertype"
77
+ : "none");
78
+ };
79
+ const diagnosticsByFile = new Map();
80
+ const concatenateChainedErrors = (diagnostics) => diagnostics
81
+ .map(d => `${d.text}${d.messageChain ? concatenateChainedErrors(d.messageChain) : ""}`)
82
+ .join("\n");
83
+ const getErrorsInCall = (call, file) => {
84
+ let diagnostics = diagnosticsByFile.get(file);
85
+ if (!diagnostics) {
86
+ diagnostics = TsgoServer.instance.project.program
87
+ .getSemanticDiagnostics(file.fileName)
88
+ .map(d => ({
89
+ pos: d.pos,
90
+ end: d.end,
91
+ message: concatenateChainedErrors([d])
92
+ }));
93
+ diagnosticsByFile.set(file, diagnostics);
94
+ }
95
+ const start = call.getStart();
96
+ const end = call.getEnd();
97
+ return diagnostics
98
+ .filter(d => d.pos >= start && d.end <= end)
99
+ .map(d => d.message);
100
+ };
101
+ const getCompletions = (call, file) => {
102
+ const arg = call.arguments[0];
103
+ if (arg === undefined)
104
+ return {};
105
+ const text = file.getFullText();
106
+ // null prototype so inherited names like "constructor" aren't seen as duplicates
107
+ const completions = Object.create(null);
108
+ for (const descendant of getDescendants(arg)) {
109
+ if (!ast.isStringLiteral(descendant) && !ast.isTemplateLiteral(descendant))
110
+ continue;
111
+ // end is right after the closing quote, so step inside the string
112
+ const position = descendant.end - (/["'`]/.test(text[descendant.end - 1]) ? 1 : 2);
113
+ const prefix = ast.isTemplateExpression(descendant) ?
114
+ descendant.getText()
115
+ : descendant.text;
116
+ if (prefix in completions)
117
+ return `Encountered multiple completion candidates for string(s) '${prefix}'. Assertions on the same prefix must be split into multiple attest calls so the results can be distinguished.`;
118
+ const entries = TsgoServer.instance.project.languageService.getCompletionsAtPosition(file.fileName, position)?.entries ?? [];
119
+ completions[prefix] = entries
120
+ // names of optional properties are suffixed with "?"
121
+ .map(entry => entry.filterText ?? entry.name)
122
+ .filter(name => name.startsWith(prefix) && name.length > prefix.length);
123
+ }
124
+ return flatMorph(completions, (prefix, entries) => entries.length >= 1 ? [prefix, entries.sort()] : []);
125
+ };
126
+ const getJsdoc = (call) => {
127
+ const arg = call.arguments[0];
128
+ if (!arg || !(ast.isPropertyAccessExpression(arg) || ast.isIdentifier(arg)))
129
+ return;
130
+ const checker = TsgoServer.instance.project.checker;
131
+ const symbol = checker.getSymbolAtLocation(arg);
132
+ if (!symbol)
133
+ return;
134
+ const declarations = symbol.declarations.flatMap(declaration => declaration.resolve() ?? []);
135
+ // read from the AST where possible since tsgo's documentation flattens links
136
+ const documentation = ([...new Set(declarations.map(getDocumentationComment))]
137
+ .filter(Boolean)
138
+ .join("\n") || symbol.getDocumentationComment(checker)).trim();
139
+ if (documentation)
140
+ return documentation;
141
+ for (const declaration of declarations) {
142
+ if (ast.isPropertyAssignment(declaration) ||
143
+ ast.isShorthandPropertyAssignment(declaration) ||
144
+ ast.isPropertyDeclaration(declaration)) {
145
+ const tags = ast.getJSDocTags(declaration);
146
+ if (tags.length) {
147
+ return tags
148
+ .map(tag => {
149
+ const name = TsgoServer.instance.getOriginalText(tag.tagName);
150
+ const comment = ast.getTextOfJSDocComment(tag.comment);
151
+ return name + (comment ? ` ${comment}` : "");
152
+ })
153
+ .join("\n");
154
+ }
155
+ }
156
+ }
157
+ };
158
+ // like TS, only the last JSDoc block of each host is documentation
159
+ const getDocumentationComment = (declaration) => {
160
+ const hosts = [declaration];
161
+ // a variable statement's JSDoc belongs to its first variable
162
+ const statement = declaration.parent?.parent;
163
+ if (statement &&
164
+ ast.isVariableStatement(statement) &&
165
+ statement.declarationList.declarations[0].pos === declaration.pos)
166
+ hosts.push(statement);
167
+ return hosts
168
+ .map(host => {
169
+ const doc = host.jsDoc?.[host.jsDoc.length - 1];
170
+ return doc && ast.isJSDoc(doc) && ast.getTextOfJSDocComment(doc.comment);
171
+ })
172
+ .filter(Boolean)
173
+ .join("\n");
174
+ };
175
+ const getInlineInstantiationData = (file, instantiationMethodCalls) => {
176
+ const calls = getCallExpressionsByName(file, instantiationMethodCalls);
177
+ const blocks = calls.map(call => {
178
+ // the test containing the statement that calls attest.instantiations
179
+ const testStatement = getAncestors(call).filter(ancestor => ast.isExpressionStatement(ancestor))[1];
180
+ return ((testStatement && getFirstFunctionDescendant(testStatement)) ??
181
+ throwInternalError(`Unable to resolve test associated with ${call.getText()}`));
182
+ });
183
+ const counts = getInstantiationsContributedByNodes(file, blocks);
184
+ return calls.map((call, i) => ({
185
+ location: getCallLocation(call),
186
+ count: counts[i]
187
+ }));
188
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,44 @@
1
+ import { execFile } from "node:child_process";
2
+ import { readFileSync, rmSync, writeFileSync } from "node:fs";
3
+ import { availableParallelism } from "node:os";
4
+ const tscPath = process.argv[2];
5
+ const { files, configPaths } = JSON.parse(readFileSync(0, "utf8"));
6
+ // this process owns the files so they're removed even if a run is
7
+ // interrupted, which would otherwise end its parent without cleanup
8
+ process.on("exit", () => {
9
+ for (const path in files)
10
+ rmSync(path, { force: true });
11
+ });
12
+ for (const signal of ["SIGINT", "SIGTERM"])
13
+ process.on(signal, () => process.exit(1));
14
+ for (const [path, contents] of Object.entries(files))
15
+ writeFileSync(path, contents);
16
+ const countInstantiations = (configPath) => new Promise((resolve, reject) => execFile(process.execPath, [
17
+ tscPath,
18
+ "--project",
19
+ configPath,
20
+ "--noEmit",
21
+ "--extendedDiagnostics",
22
+ // parallel checkers each instantiate their own copies of types
23
+ "--singleThreaded"
24
+ ], { maxBuffer: 1e8 },
25
+ // tsc exits non-zero for type errors, which don't affect the count,
26
+ // but skips checking entirely for errors like syntax errors or
27
+ // invalid options, which it reports by omitting the check time
28
+ (_, stdout, stderr) => {
29
+ const count = /Instantiations:\s+(\d+)/.exec(stdout)?.[1];
30
+ if (count === undefined || !stdout.includes("Check time:")) {
31
+ reject(new Error(`Unable to read instantiations for ${configPath}:\n${stdout}${stderr}`));
32
+ }
33
+ else
34
+ resolve(Number(count));
35
+ }));
36
+ const counts = Array.from({ length: configPaths.length });
37
+ let next = 0;
38
+ const worker = async () => {
39
+ while (next < configPaths.length) {
40
+ const i = next++;
41
+ counts[i] = await countInstantiations(configPaths[i]);
42
+ }
43
+ };
44
+ void Promise.all(Array.from({ length: Math.min(availableParallelism(), configPaths.length) }, worker)).then(() => process.stdout.write(JSON.stringify(counts)));
@@ -0,0 +1,13 @@
1
+ import type { SourcePosition } from "@ark/fs";
2
+ import { type Node, type SourceFile } from "./server.ts";
3
+ /**
4
+ * tsgo's API doesn't expose instantiation counts, so each block is checked by
5
+ * a separate tsc process alongside the rest of its file with test calls
6
+ * removed, and compared against that file on its own.
7
+ *
8
+ * Unlike TS 5's in-process measurement, tsc fully checks every file the
9
+ * program includes, so work a block shares with its dependencies is counted
10
+ * in the baseline rather than attributed to the block.
11
+ */
12
+ export declare const getInstantiationsContributedByNodes: (file: SourceFile, blocks: Node[]) => number[];
13
+ export declare const getBenchInstantiations: (position: SourcePosition) => number;
@@ -0,0 +1,113 @@
1
+ import { throwError } from "@ark/util";
2
+ import { execFileSync } from "node:child_process";
3
+ import { basename, dirname, extname, join } from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { isPositionWithinRange } from "../cache/getCachedAssertions.js";
6
+ import { getConfig } from "../config.js";
7
+ import { TsgoServer, ast, getCallExpressionsByName, getCallLocation, getFirstFunctionDescendant, tempId, tscPath } from "./server.js";
8
+ const countInstantiationsScript = fileURLToPath(new URL(`./countInstantiations${extname(fileURLToPath(import.meta.url))}`, import.meta.url));
9
+ /**
10
+ * tsgo's API doesn't expose instantiation counts, so each block is checked by
11
+ * a separate tsc process alongside the rest of its file with test calls
12
+ * removed, and compared against that file on its own.
13
+ *
14
+ * Unlike TS 5's in-process measurement, tsc fully checks every file the
15
+ * program includes, so work a block shares with its dependencies is counted
16
+ * in the baseline rather than attributed to the block.
17
+ */
18
+ export const getInstantiationsContributedByNodes = (file, blocks) => {
19
+ if (!blocks.length)
20
+ return [];
21
+ const baselineText = getBaselineText(file);
22
+ const variants = [
23
+ baselineText,
24
+ ...blocks.map(block => `${baselineText}\nconst $attestIsolatedBench = ${block.getFullText()}`)
25
+ ];
26
+ const { projectConfig } = TsgoServer.instance;
27
+ const fileDir = dirname(file.fileName);
28
+ const fileBase = basename(file.fileName);
29
+ const files = {};
30
+ const configPaths = variants.map((text, i) => {
31
+ // dot-prefixed so test runner globs don't pick it up
32
+ const sourcePath = join(fileDir, `.attest-${tempId}-${i}-${fileBase}`);
33
+ const configPath = join(projectConfig.dir, `.attest-${tempId}-${i}.tsconfig.json`);
34
+ files[sourcePath] = text;
35
+ files[configPath] = JSON.stringify({
36
+ extends: projectConfig.extends,
37
+ compilerOptions: {
38
+ ...projectConfig.compilerOptions,
39
+ // reused build info would skip checking unchanged files
40
+ incremental: false,
41
+ composite: false,
42
+ tsBuildInfoFile: null,
43
+ // declaration emit would fully check the exported types of both the
44
+ // baseline and the variant, hiding work a bench shares with them
45
+ declaration: false,
46
+ declarationMap: false,
47
+ declarationDir: null,
48
+ emitDeclarationOnly: false,
49
+ isolatedDeclarations: false,
50
+ // a bench excluded from the project may be outside its rootDir
51
+ rootDir: null,
52
+ // otherwise counts depend on whether declarations are checked
53
+ skipLibCheck: true
54
+ },
55
+ files: [sourcePath],
56
+ include: []
57
+ });
58
+ return configPath;
59
+ });
60
+ const [baseline, ...counts] = JSON.parse(execFileSync(process.execPath, [countInstantiationsScript, tscPath], {
61
+ input: JSON.stringify({ files, configPaths }),
62
+ encoding: "utf8",
63
+ maxBuffer: 1e8
64
+ }));
65
+ return counts.map(count => count - baseline);
66
+ };
67
+ const getBaselineText = (file) => {
68
+ const text = file.getFullText();
69
+ // remove each complete test expression, e.g. bench(...).types(...)
70
+ const removedRanges = getCallExpressionsByName(file, getConfig().testDeclarationAliases)
71
+ .map(call => {
72
+ let node = call;
73
+ while (node.parent && !ast.isExpressionStatement(node))
74
+ node = node.parent;
75
+ return node;
76
+ })
77
+ .sort((l, r) => l.pos - r.pos);
78
+ let baselineText = "";
79
+ let position = 0;
80
+ for (const statement of removedRanges) {
81
+ // nested test calls are removed with the statement containing them
82
+ if (statement.pos < position)
83
+ continue;
84
+ baselineText += text.slice(position, statement.pos);
85
+ position = statement.end;
86
+ }
87
+ return baselineText + text.slice(position);
88
+ };
89
+ const benchCountsByFile = new Map();
90
+ export const getBenchInstantiations = (position) => {
91
+ let benchCounts = benchCountsByFile.get(position.file);
92
+ if (!benchCounts) {
93
+ // count every bench in the file at once so tsc can run in parallel
94
+ const file = TsgoServer.instance.getSourceFileOrThrow(position.file);
95
+ const benches = getCallExpressionsByName(file, getConfig().testDeclarationAliases).flatMap(call => {
96
+ const body = getFirstFunctionDescendant(call);
97
+ // e.g. bench("name", fn), which has no inline body to measure
98
+ return body ? [{ call, body }] : [];
99
+ });
100
+ const counts = getInstantiationsContributedByNodes(file, benches.map(bench => bench.body));
101
+ benchCounts = benches.map((bench, i) => ({
102
+ location: getCallLocation(bench.call),
103
+ count: counts[i]
104
+ }));
105
+ benchCountsByFile.set(position.file, benchCounts);
106
+ }
107
+ // calls are listed outermost first, e.g. it(...) before a bench inside it
108
+ const innermost = benchCounts
109
+ .filter(({ location }) => isPositionWithinRange(position, location))
110
+ .pop();
111
+ return (innermost?.count ??
112
+ throwError(`No call expressions with an inline function matching the name(s) '${getConfig().testDeclarationAliases.join()}' were found at ${position.file}:${position.line}:${position.char}`));
113
+ };
@@ -0,0 +1,48 @@
1
+ import { type JsonObject } from "@ark/util";
2
+ import type * as tsgoAst from "typescript/ast";
3
+ import type * as tsgoApi from "typescript/sync";
4
+ import type { LinePositionRange } from "../cache/getCachedAssertions.ts";
5
+ export declare const ast: typeof tsgoAst;
6
+ export declare const noTruncation: number;
7
+ export declare const tscPath: string;
8
+ export declare const tempId: string;
9
+ export type Node = tsgoAst.Node;
10
+ export type SourceFile = tsgoAst.SourceFile;
11
+ export type CallExpression = tsgoAst.CallExpression;
12
+ export type Project = tsgoApi.Project;
13
+ export type Type = tsgoApi.Type;
14
+ export declare class TsgoServer {
15
+ projectConfig: ProjectConfig;
16
+ configPath: string;
17
+ project: Project;
18
+ rootFiles: string[];
19
+ private api;
20
+ private config;
21
+ private snapshot;
22
+ private originalTextByPath;
23
+ private filesOutsideProject;
24
+ private static _instance;
25
+ static get instance(): TsgoServer;
26
+ private constructor();
27
+ /**
28
+ * tsgo only reports diagnostics after applying @ts-expect-error and
29
+ * @ts-ignore, so they're disabled in root files without shifting positions
30
+ */
31
+ disableCommentDirectives(): void;
32
+ /** the node's text as written, before any directives were disabled */
33
+ getOriginalText(node: Node): string;
34
+ getSourceFileOrThrow(path: string): SourceFile;
35
+ private getFileOutsideProject;
36
+ private openProject;
37
+ }
38
+ export type ProjectConfig = {
39
+ /** where attest's configs are written, beside the base config if any */
40
+ dir: string;
41
+ extends: string | undefined;
42
+ compilerOptions: JsonObject;
43
+ };
44
+ export declare const getDescendants: (node: Node) => Node[];
45
+ export declare const getAncestors: (node: Node) => Node[];
46
+ export declare const getCallExpressionsByName: (startNode: Node, names: string[]) => CallExpression[];
47
+ export declare const getCallLocation: (call: CallExpression) => LinePositionRange;
48
+ export declare const getFirstFunctionDescendant: (node: Node) => Node | undefined;
@@ -0,0 +1,224 @@
1
+ import { fromCwd } from "@ark/fs";
2
+ import { throwError, throwInternalError } from "@ark/util";
3
+ import { existsSync } from "node:fs";
4
+ import { createRequire } from "node:module";
5
+ import { dirname, join, resolve } from "node:path";
6
+ import { threadId } from "node:worker_threads";
7
+ import ts from "typescript";
8
+ import { getConfig } from "../config.js";
9
+ import { isTs7, narrowToNamedTestFiles } from "../utils.js";
10
+ // resolved relative to attest so the API matches the installed typescript
11
+ const requireTypeScript = createRequire(import.meta.url);
12
+ // only loaded for TS 7+ so this module can be imported unconditionally
13
+ export const ast = isTs7 ? requireTypeScript("typescript/ast") : undefined;
14
+ const { API, TypeFormatFlags } = isTs7 ? requireTypeScript("typescript/sync") : {};
15
+ const { createFileSystemLayer } = isTs7 ? requireTypeScript("typescript/fs") : {};
16
+ export const noTruncation = isTs7 ? TypeFormatFlags.NoTruncation : 0;
17
+ export const tscPath = join(dirname(requireTypeScript.resolve("typescript/package.json")), "bin", "tsc");
18
+ // unique to this thread, since worker threads share a pid
19
+ export const tempId = `${process.pid}-${threadId}`;
20
+ export class TsgoServer {
21
+ projectConfig;
22
+ configPath;
23
+ project;
24
+ rootFiles;
25
+ api;
26
+ config;
27
+ snapshot;
28
+ originalTextByPath = new Map();
29
+ filesOutsideProject = new Map();
30
+ static _instance = null;
31
+ static get instance() {
32
+ return (TsgoServer._instance ??= new TsgoServer());
33
+ }
34
+ constructor() {
35
+ if (ts.version.startsWith("7.0."))
36
+ throwError(`@ark/attest requires TypeScript 7.1+ (found ${ts.version})`);
37
+ this.api = new API({ cwd: fromCwd() });
38
+ this.projectConfig = getProjectConfig();
39
+ // only exists in tsgo's view of the filesystem, so nothing is written
40
+ this.configPath = join(this.projectConfig.dir, ".attest.tsconfig.json");
41
+ this.config = JSON.stringify({
42
+ extends: this.projectConfig.extends,
43
+ compilerOptions: this.projectConfig.compilerOptions
44
+ });
45
+ this.project = this.openProject();
46
+ const configErrors = this.project.program.getConfigFileParsingDiagnostics();
47
+ if (configErrors.length)
48
+ throwError(configErrors.map(error => error.text).join("\n"));
49
+ const normalizedCwd = fromCwd().replace(/\\/g, "/");
50
+ this.rootFiles = narrowToNamedTestFiles(this.project.parsedCommandLine.fileNames.filter(path => path.startsWith(normalizedCwd)));
51
+ }
52
+ /**
53
+ * tsgo only reports diagnostics after applying @ts-expect-error and
54
+ * @ts-ignore, so they're disabled in root files without shifting positions
55
+ */
56
+ disableCommentDirectives() {
57
+ if (this.originalTextByPath.size)
58
+ return;
59
+ const files = [];
60
+ for (const path of this.rootFiles) {
61
+ const file = this.getSourceFileOrThrow(path);
62
+ const contents = getTextWithoutCommentDirectives(file);
63
+ if (contents === undefined)
64
+ continue;
65
+ this.originalTextByPath.set(path, file.getFullText());
66
+ files.push([path, contents]);
67
+ }
68
+ if (files.length)
69
+ this.project = this.openProject(files);
70
+ }
71
+ /** the node's text as written, before any directives were disabled */
72
+ getOriginalText(node) {
73
+ const text = this.originalTextByPath.get(node.getSourceFile().fileName);
74
+ return text?.slice(node.getStart(), node.end) ?? node.getText();
75
+ }
76
+ getSourceFileOrThrow(path) {
77
+ const normalizedPath = path.replace(/\\/g, "/");
78
+ return (this.project.program.getSourceFile(normalizedPath) ??
79
+ this.getFileOutsideProject(normalizedPath) ??
80
+ throwInternalError(`@ark/attest: TypeScript was unable to resolve expected file at ${path}.`));
81
+ }
82
+ // e.g. benches excluded by tsconfig, which are only read for their syntax
83
+ getFileOutsideProject(path) {
84
+ if (!this.filesOutsideProject.has(path) && existsSync(path)) {
85
+ this.filesOutsideProject.set(path, this.api.createSourceFileFromFile(path).sourceFile);
86
+ }
87
+ return this.filesOutsideProject.get(path);
88
+ }
89
+ openProject(files = []) {
90
+ const snapshot = this.api.createSnapshot({
91
+ openProjects: [this.configPath],
92
+ fileSystem: createFileSystemLayer([
93
+ [this.configPath, this.config],
94
+ ...files
95
+ ])
96
+ });
97
+ this.snapshot?.dispose();
98
+ this.snapshot = snapshot;
99
+ return (snapshot.getConfiguredProject(this.configPath) ??
100
+ throwInternalError(`@ark/attest: Unable to load ${this.configPath}`));
101
+ }
102
+ }
103
+ /**
104
+ * tsgo only loads projects from config files, so attest's compilerOptions are
105
+ * applied by configs beside the base config, which keeps relative paths and
106
+ * ${configDir} resolving exactly as they would from the base config
107
+ */
108
+ const getProjectConfig = () => {
109
+ const { tsconfig, compilerOptions } = getConfig();
110
+ const baseConfigPath = tsconfig === null ? undefined
111
+ : tsconfig === undefined ? findTsconfig(fromCwd())
112
+ : resolve(tsconfig);
113
+ return {
114
+ dir: baseConfigPath ? dirname(baseConfigPath) : fromCwd(),
115
+ extends: baseConfigPath,
116
+ compilerOptions
117
+ };
118
+ };
119
+ const findTsconfig = (fromDir) => {
120
+ const path = join(fromDir, "tsconfig.json");
121
+ if (existsSync(path))
122
+ return path;
123
+ const parentDir = dirname(fromDir);
124
+ return parentDir === fromDir ? undefined : findTsconfig(parentDir);
125
+ };
126
+ // tsgo's grammar, which unlike TS 5 allows any number of leading slashes but
127
+ // only spaces and tabs as whitespace
128
+ const singleLineDirective = /^\/{2,}[\t ]*@ts-(?:expect-error|ignore)/;
129
+ const multiLineDirective = /^[\t ]*[*/]*[\t ]*@ts-(?:expect-error|ignore)/;
130
+ const lineBreak = /[\n\r\u2028\u2029]/g;
131
+ const literalKinds = () => new Set([
132
+ ast.SyntaxKind.StringLiteral,
133
+ ast.SyntaxKind.NoSubstitutionTemplateLiteral,
134
+ ast.SyntaxKind.TemplateHead,
135
+ ast.SyntaxKind.TemplateMiddle,
136
+ ast.SyntaxKind.TemplateTail,
137
+ ast.SyntaxKind.RegularExpressionLiteral,
138
+ ast.SyntaxKind.JsxText
139
+ ]);
140
+ /**
141
+ * Returns the file's text with each comment tsgo would treat as a directive
142
+ * changed from @ts- to @ts_, or undefined if it has none
143
+ */
144
+ const getTextWithoutCommentDirectives = (file) => {
145
+ const text = file.getFullText();
146
+ if (!text.includes("@ts-"))
147
+ return;
148
+ const kinds = literalKinds();
149
+ const literalEnds = new Map();
150
+ // like a literal, a shebang line can't contain a comment
151
+ if (text.startsWith("#!")) {
152
+ const shebangEnd = text.search(lineBreak);
153
+ literalEnds.set(0, shebangEnd === -1 ? text.length : shebangEnd);
154
+ }
155
+ for (const node of getDescendants(file)) {
156
+ if (kinds.has(node.kind)) {
157
+ // JsxText has no trivia, so its leading whitespace is part of it
158
+ literalEnds.set(ast.isJsxText(node) ? node.pos : node.getStart(), node.end);
159
+ }
160
+ }
161
+ const chars = text.split("");
162
+ let changed = false;
163
+ const disable = (start, end, directive) => {
164
+ const comment = text.slice(start, end);
165
+ if (!directive.test(comment))
166
+ return;
167
+ chars[start + comment.indexOf("@ts-") + 3] = "_";
168
+ changed = true;
169
+ };
170
+ for (let i = 0; i < text.length; i++) {
171
+ const literalEnd = literalEnds.get(i);
172
+ if (literalEnd !== undefined && literalEnd > i)
173
+ i = literalEnd - 1;
174
+ else if (text.startsWith("//", i)) {
175
+ lineBreak.lastIndex = i;
176
+ const commentEnd = lineBreak.exec(text)?.index ?? text.length;
177
+ disable(i, commentEnd, singleLineDirective);
178
+ i = commentEnd;
179
+ }
180
+ else if (text.startsWith("/*", i)) {
181
+ const closeStart = text.indexOf("*/", i + 2);
182
+ const commentEnd = closeStart === -1 ? text.length : closeStart + 2;
183
+ // only the last line of a block comment can be a directive
184
+ let lastLineStart = i;
185
+ lineBreak.lastIndex = i;
186
+ while (lineBreak.test(text) && lineBreak.lastIndex <= commentEnd)
187
+ lastLineStart = lineBreak.lastIndex;
188
+ disable(lastLineStart, commentEnd, multiLineDirective);
189
+ i = commentEnd - 1;
190
+ }
191
+ }
192
+ return changed ? chars.join("") : undefined;
193
+ };
194
+ export const getDescendants = (node) => {
195
+ const descendants = [];
196
+ const collect = (descendant) => {
197
+ descendants.push(descendant);
198
+ descendant.forEachChild(collect);
199
+ };
200
+ collect(node);
201
+ return descendants;
202
+ };
203
+ export const getAncestors = (node) => {
204
+ const ancestors = [];
205
+ let baseNode = node.parent;
206
+ while (baseNode?.parent !== undefined) {
207
+ ancestors.push(baseNode);
208
+ baseNode = baseNode.parent;
209
+ }
210
+ return ancestors;
211
+ };
212
+ export const getCallExpressionsByName = (startNode, names) => getDescendants(startNode).filter((node) => ast.isCallExpression(node) &&
213
+ (!names.length || names.includes(node.expression.getText())));
214
+ export const getCallLocation = (call) => {
215
+ const file = call.getSourceFile();
216
+ const start = file.getLineAndCharacterOfPosition(call.getStart());
217
+ const end = file.getLineAndCharacterOfPosition(call.getEnd());
218
+ // trace positions are 1-based and TS positions are 0-based
219
+ return {
220
+ start: { line: start.line + 1, char: start.character + 1 },
221
+ end: { line: end.line + 1, char: end.character + 1 }
222
+ };
223
+ };
224
+ export const getFirstFunctionDescendant = (node) => getDescendants(node).find(descendant => ast.isArrowFunction(descendant) || ast.isFunctionExpression(descendant));
@@ -0,0 +1,5 @@
1
+ import { type SourcePosition } from "@ark/fs";
2
+ import type { SnapCallArgs } from "../cache/snapshots.ts";
3
+ import { type CallExpression, type Node } from "./server.ts";
4
+ export declare const getSnapCallArgs: (position: SourcePosition, functionName: string) => SnapCallArgs;
5
+ export declare const nearestBoundingCallExpression: (node: Node, position: number) => CallExpression | undefined;
@@ -0,0 +1,27 @@
1
+ import { positionToString } from "@ark/fs";
2
+ import { throwInternalError } from "@ark/util";
3
+ import { TsgoServer, ast, getDescendants } from "./server.js";
4
+ export const getSnapCallArgs = (position, functionName) => {
5
+ const file = TsgoServer.instance.getSourceFileOrThrow(position.file);
6
+ const call = nearestBoundingCallExpression(file,
7
+ // TS uses 0-based line and char #s
8
+ file.getPositionOfLineAndCharacter(position.line - 1, position.char - 1));
9
+ if (!call ||
10
+ !getDescendants(call).some(node => ast.isIdentifier(node) && node.text === functionName)) {
11
+ throwInternalError(`Unable to locate expected inline ${functionName} call from assertion at ${positionToString(position)}.`);
12
+ }
13
+ return {
14
+ pos: call.arguments.pos,
15
+ end: call.arguments.end,
16
+ firstArgText: call.arguments[0]?.getText()
17
+ };
18
+ };
19
+ export const nearestBoundingCallExpression = (node, position) => {
20
+ if (node.pos > position || node.end < position)
21
+ return;
22
+ let nearest;
23
+ node.forEachChild(child => {
24
+ nearest ??= nearestBoundingCallExpression(child, position);
25
+ });
26
+ return nearest ?? (ast.isCallExpression(node) ? node : undefined);
27
+ };