@ark/attest 0.9.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 (51) hide show
  1. package/LICENSE +7 -0
  2. package/README.md +284 -0
  3. package/out/assert/assertions.d.ts +28 -0
  4. package/out/assert/assertions.js +119 -0
  5. package/out/assert/attest.d.ts +26 -0
  6. package/out/assert/attest.js +40 -0
  7. package/out/assert/chainableAssertions.d.ts +68 -0
  8. package/out/assert/chainableAssertions.js +176 -0
  9. package/out/bench/await1k.d.ts +1 -0
  10. package/out/bench/await1k.js +1002 -0
  11. package/out/bench/baseline.d.ts +5 -0
  12. package/out/bench/baseline.js +60 -0
  13. package/out/bench/bench.d.ts +58 -0
  14. package/out/bench/bench.js +216 -0
  15. package/out/bench/call1k.d.ts +1 -0
  16. package/out/bench/call1k.js +1002 -0
  17. package/out/bench/measure.d.ts +29 -0
  18. package/out/bench/measure.js +48 -0
  19. package/out/bench/type.d.ts +16 -0
  20. package/out/bench/type.js +36 -0
  21. package/out/cache/getCachedAssertions.d.ts +11 -0
  22. package/out/cache/getCachedAssertions.js +70 -0
  23. package/out/cache/snapshots.d.ts +29 -0
  24. package/out/cache/snapshots.js +153 -0
  25. package/out/cache/ts.d.ts +45 -0
  26. package/out/cache/ts.js +127 -0
  27. package/out/cache/utils.d.ts +9 -0
  28. package/out/cache/utils.js +114 -0
  29. package/out/cache/writeAssertionCache.d.ts +42 -0
  30. package/out/cache/writeAssertionCache.js +141 -0
  31. package/out/cli/cli.d.ts +2 -0
  32. package/out/cli/cli.js +25 -0
  33. package/out/cli/precache.d.ts +1 -0
  34. package/out/cli/precache.js +7 -0
  35. package/out/cli/shared.d.ts +1 -0
  36. package/out/cli/shared.js +1 -0
  37. package/out/cli/stats.d.ts +1 -0
  38. package/out/cli/stats.js +54 -0
  39. package/out/cli/trace.d.ts +1 -0
  40. package/out/cli/trace.js +37 -0
  41. package/out/config.d.ts +42 -0
  42. package/out/config.js +94 -0
  43. package/out/fixtures.d.ts +6 -0
  44. package/out/fixtures.js +29 -0
  45. package/out/index.d.ts +9 -0
  46. package/out/index.js +8 -0
  47. package/out/tsVersioning.d.ts +45 -0
  48. package/out/tsVersioning.js +119 -0
  49. package/out/utils.d.ts +15 -0
  50. package/out/utils.js +36 -0
  51. package/package.json +48 -0
@@ -0,0 +1,114 @@
1
+ import { filePath } from "@ark/fs";
2
+ import { throwInternalError } from "@ark/util";
3
+ import * as tsvfs from "@typescript/vfs";
4
+ import ts from "typescript";
5
+ import { getConfig } from "../config.js";
6
+ import { getFileKey } from "../utils.js";
7
+ import { getDescendants, getFirstAncestorByKindOrThrow, getProgram, getTsConfigInfoOrThrow, getTsLibFiles } from "./ts.js";
8
+ export const getCallLocationFromCallExpression = (callExpression) => {
9
+ const start = ts.getLineAndCharacterOfPosition(callExpression.getSourceFile(), callExpression.getStart());
10
+ const end = ts.getLineAndCharacterOfPosition(callExpression.getSourceFile(), callExpression.getEnd());
11
+ // Add 1 to everything, since trace positions are 1-based and TS positions are 0-based.
12
+ const location = {
13
+ start: {
14
+ line: start.line + 1,
15
+ char: start.character + 1
16
+ },
17
+ end: {
18
+ line: end.line + 1,
19
+ char: end.character + 1
20
+ }
21
+ };
22
+ return location;
23
+ };
24
+ export const gatherInlineInstantiationData = (file, fileAssertions, attestAliasInstantiationMethodCalls) => {
25
+ const expressions = getCallExpressionsByName(file, attestAliasInstantiationMethodCalls);
26
+ if (!expressions.length)
27
+ return;
28
+ const enclosingFunctions = expressions.map(expression => {
29
+ const attestInstantiationsExpression = getFirstAncestorByKindOrThrow(expression, ts.SyntaxKind.ExpressionStatement);
30
+ return {
31
+ ancestor: getFirstAncestorByKindOrThrow(attestInstantiationsExpression, ts.SyntaxKind.ExpressionStatement),
32
+ position: getCallLocationFromCallExpression(expression)
33
+ };
34
+ });
35
+ const instantiationInfo = enclosingFunctions.map(enclosingFunction => {
36
+ const body = getDescendants(enclosingFunction.ancestor).find(node => ts.isArrowFunction(node) || ts.isFunctionExpression(node));
37
+ if (!body)
38
+ throw new Error("Unable to find file contents");
39
+ return {
40
+ location: enclosingFunction.position,
41
+ count: getInstantiationsContributedByNode(file, body)
42
+ };
43
+ });
44
+ const assertions = fileAssertions[getFileKey(file.fileName)] ?? [];
45
+ fileAssertions[getFileKey(file.fileName)] = [
46
+ ...assertions,
47
+ ...instantiationInfo
48
+ ];
49
+ };
50
+ export const getCallExpressionsByName = (startNode, names, isSnapCall = false) => {
51
+ const calls = [];
52
+ getDescendants(startNode).forEach(descendant => {
53
+ if (ts.isCallExpression(descendant)) {
54
+ if (names.includes(descendant.expression.getText()) || !names.length)
55
+ calls.push(descendant);
56
+ }
57
+ else if (isSnapCall) {
58
+ if (ts.isIdentifier(descendant)) {
59
+ if (names.includes(descendant.getText()) || !names.length)
60
+ calls.push(descendant);
61
+ }
62
+ }
63
+ });
64
+ return calls;
65
+ };
66
+ const instantiationsByPath = {};
67
+ export const getInstantiationsContributedByNode = (file, benchBlock) => {
68
+ const originalPath = filePath(file.fileName);
69
+ const fakePath = originalPath + ".nonexistent.ts";
70
+ const baselineFile = getBaselineSourceFile(file);
71
+ const baselineFileWithBenchBlock = baselineFile + `\nconst $attestIsolatedBench = ${benchBlock.getFullText()}`;
72
+ if (!instantiationsByPath[fakePath]) {
73
+ const instantiationsWithoutNode = getInstantiationsWithFile(baselineFile, fakePath);
74
+ instantiationsByPath[fakePath] = instantiationsWithoutNode;
75
+ }
76
+ const instantiationsWithNode = getInstantiationsWithFile(baselineFileWithBenchBlock, fakePath);
77
+ return instantiationsWithNode - instantiationsByPath[fakePath];
78
+ };
79
+ export const createOrUpdateFile = (env, fileName, fileText) => {
80
+ env.sys.fileExists(fileName) ?
81
+ env.updateFile(fileName, fileText)
82
+ : env.createFile(fileName, fileText);
83
+ return env.getSourceFile(fileName);
84
+ };
85
+ const getInstantiationsWithFile = (fileText, fileName) => {
86
+ const env = getIsolatedEnv();
87
+ const file = createOrUpdateFile(env, fileName, fileText);
88
+ const program = getProgram(env);
89
+ program.emit(file);
90
+ const count = program.getInstantiationCount();
91
+ if (count === undefined)
92
+ throwInternalError(`Unable to gather instantiation count for ${fileText}`);
93
+ return count;
94
+ };
95
+ let virtualEnv = undefined;
96
+ export const getIsolatedEnv = () => {
97
+ if (virtualEnv !== undefined)
98
+ return virtualEnv;
99
+ const tsconfigInfo = getTsConfigInfoOrThrow();
100
+ const libFiles = getTsLibFiles(tsconfigInfo.parsed.options);
101
+ const projectRoot = process.cwd();
102
+ const system = tsvfs.createFSBackedSystem(libFiles.defaultMapFromNodeModules, projectRoot, ts);
103
+ virtualEnv = tsvfs.createVirtualTypeScriptEnvironment(system, [], ts, tsconfigInfo.parsed.options);
104
+ return virtualEnv;
105
+ };
106
+ const getBaselineSourceFile = (originalFile) => {
107
+ const functionNames = getConfig().testDeclarationAliases;
108
+ const calls = getCallExpressionsByName(originalFile, functionNames);
109
+ let baselineSourceFileText = originalFile.getFullText();
110
+ calls.forEach(call => {
111
+ baselineSourceFileText = baselineSourceFileText.replace(call.getFullText(), "");
112
+ });
113
+ return baselineSourceFileText;
114
+ };
@@ -0,0 +1,42 @@
1
+ import type { LinePosition } from "@ark/fs";
2
+ import ts from "typescript";
3
+ import { type StringifiableType } from "./ts.js";
4
+ export type AssertionsByFile = Record<string, TypeAssertionData[]>;
5
+ export declare const analyzeProjectAssertions: () => AssertionsByFile;
6
+ export declare const getAssertionsInFile: (file: ts.SourceFile, diagnosticsByFile: DiagnosticsByFile, attestAliases: string[]) => TypeAssertionData[];
7
+ export declare const analyzeAssertCall: (assertCall: ts.CallExpression, diagnosticsByFile: DiagnosticsByFile) => TypeAssertionData;
8
+ export type Completions = Record<string, string[]> | string;
9
+ export type DiagnosticData = {
10
+ start: number;
11
+ end: number;
12
+ message: string;
13
+ };
14
+ export type DiagnosticsByFile = Record<string, DiagnosticData[]>;
15
+ export declare const getDiagnosticsByFile: () => DiagnosticsByFile;
16
+ export type ArgAssertionData = {
17
+ type: string;
18
+ relationships: {
19
+ args: TypeRelationship[];
20
+ typeArgs: TypeRelationship[];
21
+ };
22
+ };
23
+ export type TypeRelationshipAssertionData = {
24
+ location: LinePositionRange;
25
+ args: ArgAssertionData[];
26
+ typeArgs: ArgAssertionData[];
27
+ errors: string[];
28
+ completions: Completions;
29
+ };
30
+ export type TypeBenchmarkingAssertionData = {
31
+ location: LinePositionRange;
32
+ count: number;
33
+ };
34
+ export type TypeAssertionKind = "bench" | "type";
35
+ export type TypeAssertionData<kind extends TypeAssertionKind = TypeAssertionKind> = kind extends "bench" ? TypeBenchmarkingAssertionData : TypeRelationshipAssertionData;
36
+ export type LinePositionRange = {
37
+ start: LinePosition;
38
+ end: LinePosition;
39
+ };
40
+ export type TypeRelationship = "subtype" | "supertype" | "equality" | "none";
41
+ export declare const compareTsTypes: (l: StringifiableType, r: StringifiableType) => TypeRelationship;
42
+ export declare const checkDiagnosticMessages: (attestCall: ts.CallExpression, diagnosticsByFile: DiagnosticsByFile) => string[];
@@ -0,0 +1,141 @@
1
+ import { flatMorph } from "@ark/util";
2
+ import ts from "typescript";
3
+ import { getConfig } from "../config.js";
4
+ import { getFileKey } from "../utils.js";
5
+ import { TsServer, extractArgumentTypesFromCall, getDescendants, getInternalTypeChecker } from "./ts.js";
6
+ import { gatherInlineInstantiationData, getCallExpressionsByName, getCallLocationFromCallExpression } from "./utils.js";
7
+ export const analyzeProjectAssertions = () => {
8
+ const config = getConfig();
9
+ const instance = TsServer.instance;
10
+ const filePaths = instance.rootFiles;
11
+ const diagnosticsByFile = getDiagnosticsByFile();
12
+ const assertionsByFile = {};
13
+ const attestAliasInstantiationMethodCalls = config.attestAliases.map(alias => `${alias}.instantiations`);
14
+ for (const path of filePaths) {
15
+ const file = instance.getSourceFileOrThrow(path);
16
+ const assertionsInFile = getAssertionsInFile(file, diagnosticsByFile, config.attestAliases);
17
+ if (assertionsInFile.length)
18
+ assertionsByFile[getFileKey(file.fileName)] = assertionsInFile;
19
+ if (!config.skipInlineInstantiations) {
20
+ gatherInlineInstantiationData(file, assertionsByFile, attestAliasInstantiationMethodCalls);
21
+ }
22
+ }
23
+ return assertionsByFile;
24
+ };
25
+ export const getAssertionsInFile = (file, diagnosticsByFile, attestAliases) => {
26
+ const assertCalls = getCallExpressionsByName(file, attestAliases);
27
+ return assertCalls.map(call => analyzeAssertCall(call, diagnosticsByFile));
28
+ };
29
+ export const analyzeAssertCall = (assertCall, diagnosticsByFile) => {
30
+ const types = extractArgumentTypesFromCall(assertCall);
31
+ const location = getCallLocationFromCallExpression(assertCall);
32
+ const args = types.args.map(arg => serializeArg(arg, types));
33
+ const typeArgs = types.typeArgs.map(typeArg => serializeArg(typeArg, types));
34
+ const errors = checkDiagnosticMessages(assertCall, diagnosticsByFile);
35
+ const completions = getCompletions(assertCall);
36
+ return {
37
+ location,
38
+ args,
39
+ typeArgs,
40
+ errors,
41
+ completions
42
+ };
43
+ };
44
+ const serializeArg = (arg, context) => ({
45
+ type: arg.toString(),
46
+ relationships: {
47
+ args: context.args.map(other => compareTsTypes(arg, other)),
48
+ typeArgs: context.typeArgs.map(other => compareTsTypes(arg, other))
49
+ }
50
+ });
51
+ const getCompletions = (attestCall) => {
52
+ const arg = attestCall.arguments[0];
53
+ if (arg === undefined)
54
+ return {};
55
+ const descendants = getDescendants(arg);
56
+ const file = attestCall.getSourceFile();
57
+ const text = file.getFullText();
58
+ const completions = {};
59
+ for (const descendant of descendants) {
60
+ if (ts.isStringLiteral(descendant) || ts.isTemplateLiteral(descendant)) {
61
+ // descendant.pos tends to be an open quote while d.end tends to be right after the closing quote.
62
+ // It seems to be more consistent using this to get the pos for the completion over descendant.pos
63
+ const lastPositionOfInnerString = descendant.end - (/["'`]/.test(text[descendant.end - 1]) ? 1 : 2);
64
+ const completionData = TsServer.instance.virtualEnv.languageService.getCompletionsAtPosition(file.fileName, lastPositionOfInnerString, undefined);
65
+ const prefix = "text" in descendant ? descendant.text : descendant.getText();
66
+ const entries = completionData?.entries ?? [];
67
+ if (prefix in completions)
68
+ 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.`;
69
+ completions[prefix] = [];
70
+ for (const entry of entries) {
71
+ if (entry.name.startsWith(prefix) && entry.name.length > prefix.length)
72
+ completions[prefix].push(entry.name);
73
+ }
74
+ }
75
+ }
76
+ return flatMorph(completions, (prefix, entries) => entries.length >= 1 ? [prefix, entries.sort()] : []);
77
+ };
78
+ export const getDiagnosticsByFile = () => {
79
+ const diagnosticsByFile = {};
80
+ const diagnostics = getInternalTypeChecker().getDiagnostics();
81
+ for (const diagnostic of diagnostics)
82
+ addDiagnosticDataFrom(diagnostic, diagnosticsByFile);
83
+ return diagnosticsByFile;
84
+ };
85
+ const addDiagnosticDataFrom = (diagnostic, diagnosticsByFile) => {
86
+ const filePath = diagnostic.file?.fileName;
87
+ if (!filePath)
88
+ return;
89
+ const fileKey = getFileKey(filePath);
90
+ const start = diagnostic.start ?? -1;
91
+ const end = start + (diagnostic.length ?? 0);
92
+ let message = diagnostic.messageText;
93
+ if (typeof message === "object")
94
+ message = concatenateChainedErrors([message]);
95
+ const data = {
96
+ start,
97
+ end,
98
+ message
99
+ };
100
+ if (diagnosticsByFile[fileKey])
101
+ diagnosticsByFile[fileKey].push(data);
102
+ else
103
+ diagnosticsByFile[fileKey] = [data];
104
+ };
105
+ const concatenateChainedErrors = (diagnostics) => diagnostics
106
+ .map(msg => `${msg.messageText}${msg.next ? concatenateChainedErrors(msg.next) : ""}`)
107
+ .join("\n");
108
+ export const compareTsTypes = (l, r) => {
109
+ const lString = l.toString();
110
+ const rString = r.toString();
111
+ // Ensure two unresolvable types are not treated as equivalent
112
+ if (l.isUnresolvable || r.isUnresolvable)
113
+ return "none";
114
+ // Treat `any` as a supertype of every other type
115
+ if (lString === "any")
116
+ return rString === "any" ? "equality" : "supertype";
117
+ if (rString === "any")
118
+ return "subtype";
119
+ // Otherwise, determine if the types are equivalent by checking mutual assignability
120
+ const checker = getInternalTypeChecker();
121
+ const isSubtype = checker.isTypeAssignableTo(l, r);
122
+ const isSupertype = checker.isTypeAssignableTo(r, l);
123
+ return (isSubtype ?
124
+ isSupertype ? "equality"
125
+ : "subtype"
126
+ : isSupertype ? "supertype"
127
+ : "none");
128
+ };
129
+ export const checkDiagnosticMessages = (attestCall, diagnosticsByFile) => {
130
+ const fileKey = getFileKey(attestCall.getSourceFile().fileName);
131
+ const fileDiagnostics = diagnosticsByFile[fileKey];
132
+ if (!fileDiagnostics)
133
+ return [];
134
+ const diagnosticMessagesInArgRange = [];
135
+ for (const diagnostic of fileDiagnostics) {
136
+ if (diagnostic.start >= attestCall.getStart() &&
137
+ diagnostic.end <= attestCall.getEnd())
138
+ diagnosticMessagesInArgRange.push(diagnostic.message);
139
+ }
140
+ return diagnosticMessagesInArgRange;
141
+ };
@@ -0,0 +1,2 @@
1
+ #!/usr/bin/env node
2
+ export {};
package/out/cli/cli.js ADDED
@@ -0,0 +1,25 @@
1
+ #!/usr/bin/env node
2
+ import { fileName } from "@ark/fs";
3
+ import { basename } from "path";
4
+ import { precache } from "./precache.js";
5
+ import { stats } from "./stats.js";
6
+ import { trace } from "./trace.js";
7
+ const subcommands = {
8
+ precache,
9
+ trace,
10
+ stats
11
+ };
12
+ const baseFileName = basename(fileName());
13
+ const thisFileIndex = process.argv.findIndex(
14
+ // if running from build output in npm, will be a file called `attest`
15
+ // if running from build output in pnpm, will be cli.js in build output
16
+ s => s.endsWith(baseFileName) || s.endsWith("attest"));
17
+ if (thisFileIndex === -1)
18
+ throw new Error(`Expected to find an argument ending with "${baseFileName}"`);
19
+ const subcommand = process.argv[thisFileIndex + 1];
20
+ if (!(subcommand in subcommands)) {
21
+ console.error(`Expected a command like 'attest <subcommand>', where <subcommand> is one of:\n${Object.keys(subcommands)}`);
22
+ process.exit(1);
23
+ }
24
+ const args = process.argv.slice(thisFileIndex + 2);
25
+ subcommands[subcommand](args);
@@ -0,0 +1 @@
1
+ export declare const precache: (args: string[]) => void;
@@ -0,0 +1,7 @@
1
+ import { ensureDir } from "@ark/fs";
2
+ import { join } from "path";
3
+ import { writeAssertionData } from "../fixtures.js";
4
+ export const precache = (args) => {
5
+ const cacheFileToWrite = args[0] ?? join(ensureDir(".attest"), "typescript.json");
6
+ writeAssertionData(cacheFileToWrite);
7
+ };
@@ -0,0 +1 @@
1
+ export declare const baseDiagnosticTscCmd = "pnpm tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
@@ -0,0 +1 @@
1
+ export const baseDiagnosticTscCmd = "pnpm tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
@@ -0,0 +1 @@
1
+ export declare const stats: (args: string[]) => void;
@@ -0,0 +1,54 @@
1
+ import { execSync } from "child_process";
2
+ import { baseDiagnosticTscCmd } from "./shared.js";
3
+ export const stats = (args) => {
4
+ const packageDirs = args.length ? args : [process.cwd()];
5
+ const listedStats = packageDirs.map((packageDir) => {
6
+ console.log(`⏳ Gathering type perf data for ${packageDir}...`);
7
+ let output;
8
+ try {
9
+ output = execSync(baseDiagnosticTscCmd, {
10
+ cwd: packageDir,
11
+ stdio: "pipe"
12
+ }).toString();
13
+ }
14
+ catch (e) {
15
+ output = e.stdout?.toString() ?? "";
16
+ output += e.stderr?.toString() ?? "";
17
+ console.error(`❗Encountered one or more errors checking types for ${packageDir}- results may be inaccurate❗`);
18
+ }
19
+ const stats = parseTsDiagnosticsOutput(output);
20
+ logTypePerfStats(stats);
21
+ return stats;
22
+ });
23
+ const aggregatedStats = listedStats.reduce((aggregatedStats, packageStats) => ({
24
+ checkTime: aggregatedStats.checkTime + packageStats.checkTime,
25
+ types: aggregatedStats.types + packageStats.types,
26
+ instantiations: aggregatedStats.instantiations + packageStats.instantiations
27
+ }), {
28
+ checkTime: 0,
29
+ types: 0,
30
+ instantiations: 0
31
+ });
32
+ console.log("📊 aggregated type performance:");
33
+ logTypePerfStats(aggregatedStats);
34
+ };
35
+ const parseTsDiagnosticsOutput = (output) => {
36
+ const lines = output.split("\n");
37
+ const results = {
38
+ checkTime: 0,
39
+ types: 0,
40
+ instantiations: 0
41
+ };
42
+ for (const line of lines) {
43
+ if (line.startsWith("Check time:"))
44
+ results.checkTime = parseFloat(line.split(":")[1].trim());
45
+ else if (line.startsWith("Types:"))
46
+ results.types = parseInt(line.split(":")[1].trim(), 10);
47
+ else if (line.startsWith("Instantiations:"))
48
+ results.instantiations = parseInt(line.split(":")[1].trim(), 10);
49
+ }
50
+ return results;
51
+ };
52
+ const logTypePerfStats = (stats) => {
53
+ console.log(JSON.stringify(stats, null, 4));
54
+ };
@@ -0,0 +1 @@
1
+ export declare const trace: (args: string[]) => Promise<void>;
@@ -0,0 +1,37 @@
1
+ import { execSync } from "child_process";
2
+ import { existsSync } from "fs";
3
+ import { join } from "path";
4
+ import { baseDiagnosticTscCmd } from "./shared.js";
5
+ export const trace = async (args) => {
6
+ const packageDir = args[0] ?? process.cwd();
7
+ if (!existsSync(packageDir)) {
8
+ throw new Error(`trace requires an argument for an existing directory to trace, e.g. 'pnpm attest trace packages/api'`);
9
+ }
10
+ try {
11
+ console.log(`⏳ Gathering type trace data for ${packageDir}...`);
12
+ // These cache files have to be removed before any analysis is done otherwise
13
+ // the results will be meaningless.
14
+ // the .tstrace directory will contain a trace.json file and a types.json file.
15
+ // the trace.json file can be viewed via a tool like https://ui.perfetto.dev/
16
+ // the types.json file can be used to associate IDs from the trace file with type aliases
17
+ execSync(`${baseDiagnosticTscCmd} --generateTrace .tstrace`, {
18
+ cwd: packageDir,
19
+ stdio: "inherit"
20
+ });
21
+ }
22
+ catch (e) {
23
+ console.error(String(e));
24
+ }
25
+ finally {
26
+ console.log(`⏳ Analyzing type trace data for ${packageDir}...`);
27
+ // allow analyze-trace to process the args
28
+ process.argv = [
29
+ "node",
30
+ "node_modules/@typescript/analyze-trace/dist/analyze-trace-dir.js",
31
+ join(packageDir, ".tstrace")
32
+ ];
33
+ // TypeScript's analyze-trace tool can be used to automatically detect hot-spots in your code.
34
+ // It's not a perfect match for what can be optimized, but it can be a helpful place to start
35
+ await import("@typescript/analyze-trace/dist/analyze-trace-dir.js");
36
+ }
37
+ };
@@ -0,0 +1,42 @@
1
+ import { type autocomplete } from "@ark/util";
2
+ import { type TsVersionData } from "./tsVersioning.js";
3
+ export type TsVersionAliases = autocomplete<"*"> | string[];
4
+ type BaseAttestConfig = {
5
+ tsconfig: string | undefined;
6
+ updateSnapshots: boolean;
7
+ /** A string or list of strings representing the TypeScript version aliases to run.
8
+ *
9
+ * Aliases must be specified as a package.json dependency or devDependency beginning with "typescript".
10
+ * Alternate aliases can be specified using the "npm:" prefix:
11
+ * ```json
12
+ * "typescript": "latest",
13
+ * "typescript-next: "npm:typescript@next",
14
+ * "typescript-1": "npm:typescript@5.2"
15
+ * "typescript-2": "npm:typescript@5.1"
16
+ * ```
17
+ *
18
+ * "*" can be pased to run all discovered versions beginning with "typescript".
19
+ */
20
+ tsVersions: TsVersionAliases | TsVersionData[];
21
+ skipTypes: boolean;
22
+ skipInlineInstantiations: boolean;
23
+ attestAliases: string[];
24
+ benchPercentThreshold: number;
25
+ benchErrorOnThresholdExceeded: boolean;
26
+ filter: string | undefined;
27
+ testDeclarationAliases: string[];
28
+ formatter: string;
29
+ shouldFormat: boolean;
30
+ };
31
+ export type AttestConfig = Partial<BaseAttestConfig>;
32
+ export declare const getDefaultAttestConfig: () => BaseAttestConfig;
33
+ export declare const attestEnvPrefix = "ATTEST_";
34
+ export interface ParsedAttestConfig extends Readonly<BaseAttestConfig> {
35
+ cacheDir: string;
36
+ assertionCacheDir: string;
37
+ defaultAssertionCachePath: string;
38
+ tsVersions: TsVersionData[];
39
+ }
40
+ export declare const getConfig: () => ParsedAttestConfig;
41
+ export declare const ensureCacheDirs: () => void;
42
+ export {};
package/out/config.js ADDED
@@ -0,0 +1,94 @@
1
+ import { ensureDir, fromCwd } from "@ark/fs";
2
+ import { arrayFrom, isArray, tryParseNumber } from "@ark/util";
3
+ import { existsSync } from "node:fs";
4
+ import { join, resolve } from "node:path";
5
+ import { findAttestTypeScriptVersions } from "./tsVersioning.js";
6
+ export const getDefaultAttestConfig = () => ({
7
+ tsconfig: existsSync(fromCwd("tsconfig.json")) ? fromCwd("tsconfig.json") : undefined,
8
+ attestAliases: ["attest", "attestInternal"],
9
+ updateSnapshots: false,
10
+ skipTypes: false,
11
+ skipInlineInstantiations: false,
12
+ tsVersions: "typescript",
13
+ benchPercentThreshold: 20,
14
+ benchErrorOnThresholdExceeded: true,
15
+ filter: undefined,
16
+ testDeclarationAliases: ["bench", "it", "test"],
17
+ formatter: `npm exec --no -- prettier --write`,
18
+ shouldFormat: true
19
+ });
20
+ const hasFlag = (flag) => process.argv.some(arg => arg.includes(flag));
21
+ const getParamValue = (param) => {
22
+ const paramIndex = process.argv.findIndex(arg => arg.includes(param));
23
+ if (paramIndex === -1)
24
+ return undefined;
25
+ const raw = process.argv[paramIndex + 1];
26
+ if (raw === "true")
27
+ return true;
28
+ if (raw === "false")
29
+ return false;
30
+ if (param === "benchPercentThreshold")
31
+ return tryParseNumber(raw, { errorOnFail: true });
32
+ if (param === "tsVersions" || param === "attestAliases")
33
+ return raw.split(",");
34
+ return raw;
35
+ };
36
+ export const attestEnvPrefix = "ATTEST_";
37
+ const addEnvConfig = (config) => {
38
+ Object.entries(process.env).forEach(([k, v]) => {
39
+ if (k.startsWith(attestEnvPrefix)) {
40
+ const optionName = k.slice(attestEnvPrefix.length);
41
+ if (optionName === "CONFIG")
42
+ Object.assign(config, JSON.parse(v));
43
+ else
44
+ config[optionName] = JSON.parse(v);
45
+ }
46
+ });
47
+ let k;
48
+ for (k in config) {
49
+ if (config[k] === false)
50
+ config[k] = hasFlag(k);
51
+ else {
52
+ const value = getParamValue(k);
53
+ if (value !== undefined)
54
+ config[k] = value;
55
+ }
56
+ }
57
+ return config;
58
+ };
59
+ const parseConfig = () => {
60
+ const baseConfig = addEnvConfig(getDefaultAttestConfig());
61
+ const cacheDir = resolve(".attest");
62
+ const assertionCacheDir = join(cacheDir, "assertions");
63
+ const defaultAssertionCachePath = join(assertionCacheDir, "typescript.json");
64
+ return Object.assign(baseConfig, {
65
+ cacheDir,
66
+ assertionCacheDir,
67
+ defaultAssertionCachePath,
68
+ tsVersions: baseConfig.skipTypes ? []
69
+ : isTsVersionAliases(baseConfig.tsVersions) ?
70
+ parseTsVersions(baseConfig.tsVersions)
71
+ : baseConfig.tsVersions
72
+ });
73
+ };
74
+ const isTsVersionAliases = (v) => typeof v === "string" || (isArray(v) && typeof v[0] === "string");
75
+ const parseTsVersions = (aliases) => {
76
+ const versions = findAttestTypeScriptVersions();
77
+ if (aliases === "*")
78
+ return versions;
79
+ return arrayFrom(aliases).map(alias => {
80
+ const matching = versions.find(v => v.alias === alias);
81
+ if (!matching) {
82
+ throw new Error(`Specified TypeScript version ${alias} does not exist.` +
83
+ ` It should probably be specified in package.json like:
84
+ "typescript-${alias}": "npm:typescript@latest"`);
85
+ }
86
+ return matching;
87
+ });
88
+ };
89
+ const cachedConfig = parseConfig();
90
+ export const getConfig = () => cachedConfig;
91
+ export const ensureCacheDirs = () => {
92
+ ensureDir(cachedConfig.cacheDir);
93
+ ensureDir(cachedConfig.assertionCacheDir);
94
+ };
@@ -0,0 +1,6 @@
1
+ import { type AttestConfig } from "./config.js";
2
+ export declare const setup: (options?: Partial<AttestConfig>) => typeof teardown;
3
+ export declare const writeAssertionData: (toPath: string) => void;
4
+ export declare const cleanup: () => void;
5
+ /** alias for cleanup to align with vitest and others */
6
+ export declare const teardown: () => void;
@@ -0,0 +1,29 @@
1
+ import { shell, writeJson } from "@ark/fs";
2
+ import { rmSync } from "node:fs";
3
+ import { join } from "node:path";
4
+ import { writeSnapshotUpdatesOnExit } from "./cache/snapshots.js";
5
+ import { analyzeProjectAssertions } from "./cache/writeAssertionCache.js";
6
+ import { ensureCacheDirs, getConfig } from "./config.js";
7
+ import { forTypeScriptVersions } from "./tsVersioning.js";
8
+ export const setup = (options = {}) => {
9
+ const config = getConfig();
10
+ Object.assign(config, options);
11
+ rmSync(config.cacheDir, { recursive: true, force: true });
12
+ ensureCacheDirs();
13
+ if (config.skipTypes)
14
+ return teardown;
15
+ if (config.tsVersions.length === 1 &&
16
+ config.tsVersions[0].alias === "typescript")
17
+ writeAssertionData(config.defaultAssertionCachePath);
18
+ else {
19
+ forTypeScriptVersions(config.tsVersions, version => shell(`npm exec -c "attest precache ${join(config.assertionCacheDir, version.alias + ".json")}"`));
20
+ }
21
+ return teardown;
22
+ };
23
+ export const writeAssertionData = (toPath) => {
24
+ console.log("⏳ Waiting for TypeScript to check your project (this may take a while)...");
25
+ writeJson(toPath, analyzeProjectAssertions());
26
+ };
27
+ export const cleanup = () => writeSnapshotUpdatesOnExit();
28
+ /** alias for cleanup to align with vitest and others */
29
+ export const teardown = cleanup;
package/out/index.d.ts ADDED
@@ -0,0 +1,9 @@
1
+ export { caller, type CallerOfOptions } from "@ark/fs";
2
+ export { attest } from "./assert/attest.js";
3
+ export { bench } from "./bench/bench.js";
4
+ export { getBenchAssertionsAtPosition, getTypeAssertionsAtPosition } from "./cache/getCachedAssertions.js";
5
+ export type { ArgAssertionData, LinePositionRange, TypeAssertionData, TypeRelationship } from "./cache/writeAssertionCache.js";
6
+ export { getDefaultAttestConfig, type AttestConfig } from "./config.js";
7
+ export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.js";
8
+ export { findAttestTypeScriptVersions, getPrimaryTsVersionUnderTest } from "./tsVersioning.js";
9
+ export { contextualize } from "./utils.js";
package/out/index.js ADDED
@@ -0,0 +1,8 @@
1
+ export { caller } from "@ark/fs";
2
+ export { attest } from "./assert/attest.js";
3
+ export { bench } from "./bench/bench.js";
4
+ export { getBenchAssertionsAtPosition, getTypeAssertionsAtPosition } from "./cache/getCachedAssertions.js";
5
+ export { getDefaultAttestConfig } from "./config.js";
6
+ export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.js";
7
+ export { findAttestTypeScriptVersions, getPrimaryTsVersionUnderTest } from "./tsVersioning.js";
8
+ export { contextualize } from "./utils.js";