@ark/attest 0.56.6 → 0.57.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 (40) hide show
  1. package/README.md +11 -24
  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 +3 -1
  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 +4 -22
  22. package/out/config.js +4 -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 +2 -0
  37. package/out/utils.js +3 -0
  38. package/package.json +8 -6
  39. package/out/tsVersioning.d.ts +0 -31
  40. package/out/tsVersioning.js +0 -172
package/out/cli/trace.js CHANGED
@@ -2,9 +2,47 @@ import { ensureDir, getShellOutput, readJson, writeFile } from "@ark/fs";
2
2
  import { existsSync } from "node:fs";
3
3
  import { basename, join, relative, resolve } from "node:path";
4
4
  import ts from "typescript";
5
- import { TsServer, getDescendants, getStringifiableType, nearestBoundingCallExpression } from "../cache/ts.js";
5
+ import { TsServer, getDescendants as getDescendantsTs5, getStringifiableType, nearestBoundingCallExpression as nearestBoundingCallExpressionTs5 } from "../cache/ts.js";
6
6
  import { getConfig } from "../config.js";
7
+ import { stringifyTypeAtLocation } from "../ts7/analyze.js";
8
+ import { TsgoServer, ast, getDescendants as getDescendantsTs7 } from "../ts7/server.js";
9
+ import { nearestBoundingCallExpression as nearestBoundingCallExpressionTs7 } from "../ts7/snapshots.js";
10
+ import { isTs7 } from "../utils.js";
7
11
  import { baseDiagnosticTscCmd } from "./shared.js";
12
+ // TS 7's AST matches TS 5's shape for everything used here
13
+ const syntax = isTs7 ? ast : ts;
14
+ const getSourceFile = (path) => isTs7 ?
15
+ TsgoServer.instance.getSourceFileOrThrow(path)
16
+ : TsServer.instance.getSourceFileOrThrow(path);
17
+ const utf8ByPath = new Map();
18
+ // tsgo's trace positions are UTF-8 byte offsets rather than UTF-16 indices
19
+ const getTextPosition = (path, position) => {
20
+ if (!isTs7)
21
+ return position;
22
+ const text = getSourceFile(path).getFullText();
23
+ let utf8 = utf8ByPath.get(path);
24
+ if (!utf8)
25
+ utf8ByPath.set(path, (utf8 = Buffer.from(text)));
26
+ return utf8.length === text.length ?
27
+ position
28
+ : utf8.subarray(0, position).toString().length;
29
+ };
30
+ const getDescendants = (node) => isTs7 ? getDescendantsTs7(node) : getDescendantsTs5(node);
31
+ const nearestBoundingCallExpression = (node, position) => isTs7 ?
32
+ nearestBoundingCallExpressionTs7(node, position)
33
+ : nearestBoundingCallExpressionTs5(node, position);
34
+ const describeType = (node) => {
35
+ if (isTs7) {
36
+ const { type, string } = stringifyTypeAtLocation(node);
37
+ return { name: string, id: `${type.id}` };
38
+ }
39
+ const type = getStringifiableType(node);
40
+ const name = type.toString();
41
+ return {
42
+ name,
43
+ id: `${type.id ?? name.substring(0, 20)}`
44
+ };
45
+ };
8
46
  /**
9
47
  * Helper to write output to both console and collect for file output
10
48
  */
@@ -166,7 +204,6 @@ const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
166
204
  }
167
205
  };
168
206
  const initializeAnalysisContext = (traceDir) => {
169
- const tsServer = TsServer.instance;
170
207
  const tracePath = join(traceDir, "trace.json");
171
208
  if (!existsSync(tracePath)) {
172
209
  throw new Error(`Critical: Expected a trace file at ${tracePath}, but it was not found during context initialization.`);
@@ -174,7 +211,6 @@ const initializeAnalysisContext = (traceDir) => {
174
211
  const traceEntries = readJson(tracePath);
175
212
  return {
176
213
  traceDir,
177
- tsServer,
178
214
  traceEntries,
179
215
  durationEntries: [],
180
216
  callRanges: [],
@@ -198,10 +234,10 @@ const filterDurationEntries = (ctx) => {
198
234
  };
199
235
  const processDurationEntry = (entry, ctx) => {
200
236
  const entryPath = entry.args.path;
201
- const entryPos = entry.args.pos;
202
- const entryEnd = entry.args.end;
237
+ const entryPos = getTextPosition(entryPath, entry.args.pos);
238
+ const entryEnd = getTextPosition(entryPath, entry.args.end);
203
239
  const entryDur = entry.dur;
204
- const sourceFile = ctx.tsServer.getSourceFileOrThrow(entryPath);
240
+ const sourceFile = getSourceFile(entryPath);
205
241
  let callRangeData;
206
242
  const callExpr = findCallExpressionInRange(sourceFile, entryPos, entryEnd);
207
243
  if (callExpr) {
@@ -214,12 +250,11 @@ const processDurationEntry = (entry, ctx) => {
214
250
  else {
215
251
  const relevantNode = findMostSpecificNodeInRange(sourceFile, entryPos, entryEnd);
216
252
  if (relevantNode) {
217
- const nodeType = getStringifiableType(relevantNode);
218
- const nodeKind = ts.SyntaxKind[relevantNode.kind];
219
- const typeName = `${nodeKind}: ${nodeType.toString().substring(0, 25)}`;
220
- const typeNodeIdPart = nodeType.id ?? nodeType.toString().substring(0, 20);
253
+ const nodeType = describeType(relevantNode);
254
+ const nodeKind = syntax.SyntaxKind[relevantNode.kind];
255
+ const typeName = `${nodeKind}: ${nodeType.name.substring(0, 25)}`;
221
256
  callRangeData = {
222
- typeId: `node-${relevantNode.kind}-${typeNodeIdPart}`,
257
+ typeId: `node-${relevantNode.kind}-${nodeType.id}`,
223
258
  functionName: typeName
224
259
  };
225
260
  }
@@ -247,16 +282,16 @@ const findCallExpressionInRange = (file, start, end) => {
247
282
  return boundingCall;
248
283
  const allNodes = getDescendants(file);
249
284
  const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
250
- const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
285
+ const callExpressions = nodesInRange.filter(node => syntax.isCallExpression(node));
251
286
  if (callExpressions.length === 0)
252
287
  return undefined;
253
- const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
288
+ const methodCalls = callExpressions.filter(call => syntax.isPropertyAccessExpression(call.expression));
254
289
  return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
255
290
  };
256
291
  const extractFunctionName = (callExpr) => {
257
- if (ts.isPropertyAccessExpression(callExpr.expression))
292
+ if (syntax.isPropertyAccessExpression(callExpr.expression))
258
293
  return callExpr.expression.name.getText();
259
- if (ts.isIdentifier(callExpr.expression))
294
+ if (syntax.isIdentifier(callExpr.expression))
260
295
  return callExpr.expression.getText();
261
296
  return "anonymousFunction";
262
297
  };
@@ -508,7 +543,7 @@ const formatLocation = (location) => {
508
543
  const pos = parseInt(posStr, 10);
509
544
  if (isNaN(pos))
510
545
  return `${relativePath}:${positionRange}`;
511
- const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
546
+ const sourceFile = getSourceFile(filePath);
512
547
  const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
513
548
  return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
514
549
  };
@@ -523,23 +558,23 @@ const findMostSpecificNodeInRange = (file, start, end) => {
523
558
  const findNodeByPreference = (nodes) => {
524
559
  if (nodes.length === 0)
525
560
  return undefined;
526
- const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
561
+ const typeReference = nodes.find(node => syntax.isTypeReferenceNode(node) || syntax.isTypeQueryNode(node));
527
562
  if (typeReference)
528
563
  return typeReference;
529
- const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
530
- ts.isFunctionDeclaration(node) ||
531
- ts.isClassDeclaration(node) ||
532
- ts.isInterfaceDeclaration(node));
564
+ const declaration = nodes.find(node => syntax.isVariableDeclaration(node) ||
565
+ syntax.isFunctionDeclaration(node) ||
566
+ syntax.isClassDeclaration(node) ||
567
+ syntax.isInterfaceDeclaration(node));
533
568
  if (declaration)
534
569
  return declaration;
535
- const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
570
+ const propertyAccess = nodes.find(node => syntax.isPropertyAccessExpression(node));
536
571
  if (propertyAccess)
537
572
  return propertyAccess;
538
- const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
539
- node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
573
+ const assignment = nodes.find(node => syntax.isBinaryExpression(node) &&
574
+ node.operatorToken.kind === syntax.SyntaxKind.EqualsToken);
540
575
  if (assignment)
541
576
  return assignment;
542
- const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
577
+ const expression = nodes.find(node => syntax.isExpressionStatement(node) || syntax.isExpression(node));
543
578
  if (expression)
544
579
  return expression;
545
580
  return nodes.sort((a, b) => a.end - a.pos - (b.end - b.pos))[0];
package/out/config.d.ts CHANGED
@@ -1,28 +1,12 @@
1
- import { type autocomplete } from "@ark/util";
1
+ import { type JsonObject } from "@ark/util";
2
2
  import type * as prettier from "prettier";
3
- import type ts from "typescript";
4
- import { type TsVersionData } from "./tsVersioning.ts";
5
- export type TsVersionAliases = autocomplete<"*"> | string[];
6
3
  export type BenchErrorConfig = "runtime" | "types" | boolean;
7
4
  type BaseAttestConfig = {
8
5
  tsconfig: string | null | undefined;
9
- compilerOptions: ts.CompilerOptions;
6
+ /** compilerOptions as they would be written in tsconfig.json */
7
+ compilerOptions: JsonObject;
10
8
  updateSnapshots: boolean;
11
9
  failOnMissingSnapshots: boolean;
12
- /** A string or list of strings representing the TypeScript version aliases to run.
13
- *
14
- * Aliases must be specified as a package.json dependency or devDependency beginning with "typescript".
15
- * Alternate aliases can be specified using the "npm:" prefix:
16
- * ```json
17
- * "typescript": "latest",
18
- * "typescript-next: "npm:typescript@next",
19
- * "typescript-1": "npm:typescript@5.2"
20
- * "typescript-2": "npm:typescript@5.1"
21
- * ```
22
- *
23
- * "*" can be pased to run all discovered versions beginning with "typescript".
24
- */
25
- tsVersions: TsVersionAliases | TsVersionData[];
26
10
  skipTypes: boolean;
27
11
  skipInlineInstantiations: boolean;
28
12
  attestAliases: string[];
@@ -49,9 +33,7 @@ export declare const getDefaultAttestConfig: () => BaseAttestConfig;
49
33
  export declare const attestEnvPrefix = "ATTEST_";
50
34
  export interface ParsedAttestConfig extends Readonly<BaseAttestConfig> {
51
35
  cacheDir: string;
52
- assertionCacheDir: string;
53
- defaultAssertionCachePath: string;
54
- tsVersions: TsVersionData[];
36
+ assertionCachePath: string;
55
37
  }
56
38
  export declare const getConfig: () => ParsedAttestConfig;
57
39
  export declare const ensureCacheDirs: () => void;
package/out/config.js CHANGED
@@ -1,8 +1,7 @@
1
1
  import { ensureDir, fromCwd } from "@ark/fs";
2
- import { isArray, liftArray, tryParseNumber } from "@ark/util";
2
+ import { tryParseNumber } from "@ark/util";
3
3
  import { existsSync } from "node:fs";
4
4
  import { join, resolve } from "node:path";
5
- import { findAttestTypeScriptVersions } from "./tsVersioning.js";
6
5
  export const getDefaultAttestConfig = () => ({
7
6
  tsconfig: existsSync(fromCwd("tsconfig.json")) ? fromCwd("tsconfig.json") : undefined,
8
7
  compilerOptions: {},
@@ -11,7 +10,6 @@ export const getDefaultAttestConfig = () => ({
11
10
  updateSnapshots: false,
12
11
  skipTypes: false,
13
12
  skipInlineInstantiations: false,
14
- tsVersions: "default",
15
13
  benchPercentThreshold: 20,
16
14
  benchErrorOnThresholdExceeded: true,
17
15
  filter: undefined,
@@ -45,7 +43,7 @@ const getParamValue = (param) => {
45
43
  return null;
46
44
  if (param === "benchPercentThreshold")
47
45
  return tryParseNumber(raw, { errorOnFail: true });
48
- if (param === "tsVersions" || param === "attestAliases")
46
+ if (param === "attestAliases")
49
47
  return raw.split(",");
50
48
  if (param === "typeToStringFormat" || param === "compilerOptions")
51
49
  return JSON.parse(raw);
@@ -75,33 +73,10 @@ const addEnvConfig = (config) => {
75
73
  return config;
76
74
  };
77
75
  const parseConfig = () => {
78
- const baseConfig = addEnvConfig(getDefaultAttestConfig());
79
76
  const cacheDir = resolve(".attest");
80
- const assertionCacheDir = join(cacheDir, "assertions");
81
- const defaultAssertionCachePath = join(assertionCacheDir, "typescript.json");
82
- return Object.assign(baseConfig, {
77
+ return Object.assign(addEnvConfig(getDefaultAttestConfig()), {
83
78
  cacheDir,
84
- assertionCacheDir,
85
- defaultAssertionCachePath,
86
- tsVersions: baseConfig.skipTypes ? []
87
- : isTsVersionAliases(baseConfig.tsVersions) ?
88
- parseTsVersions(baseConfig.tsVersions)
89
- : baseConfig.tsVersions
90
- });
91
- };
92
- const isTsVersionAliases = (v) => typeof v === "string" || (isArray(v) && typeof v[0] === "string");
93
- const parseTsVersions = (aliases) => {
94
- const versions = findAttestTypeScriptVersions();
95
- if (aliases === "*" || (isArray(aliases) && aliases[0] === "*"))
96
- return versions;
97
- return liftArray(aliases).map(alias => {
98
- const matching = versions.find(v => v.alias === alias);
99
- if (!matching) {
100
- throw new Error(`Specified TypeScript version ${alias} does not exist.` +
101
- ` It should probably be specified in package.json like:
102
- "@ark/attest-ts-${alias}": "npm:typescript@latest"`);
103
- }
104
- return matching;
79
+ assertionCachePath: join(cacheDir, "assertions.json")
105
80
  });
106
81
  };
107
82
  let cachedConfig;
@@ -116,5 +91,4 @@ if (!globalThis.localStorage?.getItem)
116
91
  export const ensureCacheDirs = () => {
117
92
  cachedConfig ??= getConfig();
118
93
  ensureDir(cachedConfig.cacheDir);
119
- ensureDir(cachedConfig.assertionCacheDir);
120
94
  };
package/out/fixtures.js CHANGED
@@ -1,10 +1,10 @@
1
- import { fileName, shell, writeJson } from "@ark/fs";
1
+ import { writeJson } from "@ark/fs";
2
2
  import { rmSync } from "node:fs";
3
- import { join } from "node:path";
4
3
  import { writeSnapshotUpdatesOnExit } from "./cache/snapshots.js";
5
4
  import { analyzeProjectAssertions } from "./cache/writeAssertionCache.js";
6
5
  import { ensureCacheDirs, getConfig } from "./config.js";
7
- import { forTypeScriptVersions } from "./tsVersioning.js";
6
+ import { analyzeProjectAssertions as analyzeProjectAssertionsTs7 } from "./ts7/analyze.js";
7
+ import { isTs7 } from "./utils.js";
8
8
  export const setup = (options) => {
9
9
  const { ...config } = getConfig();
10
10
  if (options)
@@ -14,25 +14,12 @@ export const setup = (options) => {
14
14
  ensureCacheDirs();
15
15
  if (config.skipTypes)
16
16
  return teardown;
17
- if (config.tsVersions.length === 1 &&
18
- config.tsVersions[0].alias === "default")
19
- writeAssertionData(config.defaultAssertionCachePath);
20
- else {
21
- forTypeScriptVersions(config.tsVersions, version => {
22
- const precachePath = join(config.assertionCacheDir, version.alias + ".json");
23
- // if we're in our own repo, we need to pnpm to use the root script to execute ts directly
24
- if (fileName().endsWith("ts"))
25
- shell(`pnpm attest precache ${precachePath}`);
26
- // otherwise, just use npm to run the CLI command from build output
27
- else
28
- shell(`npm exec -c "attest precache ${precachePath}"`);
29
- });
30
- }
17
+ writeAssertionData(config.assertionCachePath);
31
18
  return teardown;
32
19
  };
33
20
  export const writeAssertionData = (toPath) => {
34
21
  console.log("⏳ Waiting for TypeScript to check your project (this may take a while)...");
35
- writeJson(toPath, analyzeProjectAssertions());
22
+ writeJson(toPath, isTs7 ? analyzeProjectAssertionsTs7() : analyzeProjectAssertions());
36
23
  };
37
24
  export const cleanup = () => writeSnapshotUpdatesOnExit();
38
25
  /** alias for cleanup to align with vitest and others */
package/out/index.d.ts CHANGED
@@ -2,8 +2,6 @@ export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.ts";
2
2
  export { caller, type CallerOfOptions } from "@ark/fs";
3
3
  export { attest } from "./assert/attest.ts";
4
4
  export { bench } from "./bench/bench.ts";
5
- export { getBenchAssertionsAtPosition, getTypeAssertionsAtPosition } from "./cache/getCachedAssertions.ts";
6
- export type { ArgAssertionData, LinePositionRange, TypeAssertionData, TypeRelationship } from "./cache/writeAssertionCache.ts";
5
+ export { getBenchAssertionAtPosition, getTypeAssertionAtPosition, type ArgAssertionData, type LinePositionRange, type TypeAssertionData, type TypeRelationship } from "./cache/getCachedAssertions.ts";
7
6
  export { getDefaultAttestConfig, type AttestConfig } from "./config.ts";
8
- export { findAttestTypeScriptVersions, getPrimaryTsVersionUnderTest } from "./tsVersioning.ts";
9
7
  export { contextualize } from "./utils.ts";
package/out/index.js CHANGED
@@ -3,7 +3,6 @@ export { cleanup, setup, teardown, writeAssertionData } from "./fixtures.js";
3
3
  export { caller } from "@ark/fs";
4
4
  export { attest } from "./assert/attest.js";
5
5
  export { bench } from "./bench/bench.js";
6
- export { getBenchAssertionsAtPosition, getTypeAssertionsAtPosition } from "./cache/getCachedAssertions.js";
6
+ export { getBenchAssertionAtPosition, getTypeAssertionAtPosition } from "./cache/getCachedAssertions.js";
7
7
  export { getDefaultAttestConfig } from "./config.js";
8
- export { findAttestTypeScriptVersions, getPrimaryTsVersionUnderTest } from "./tsVersioning.js";
9
8
  export { contextualize } from "./utils.js";
@@ -0,0 +1,10 @@
1
+ import type { AssertionsByFile } from "../cache/getCachedAssertions.ts";
2
+ import { type Node, type Type } from "./server.ts";
3
+ export declare const analyzeProjectAssertions: () => AssertionsByFile;
4
+ type StringifiedType = {
5
+ type: Type;
6
+ string: string;
7
+ isUnresolvable: boolean;
8
+ };
9
+ export declare const stringifyTypeAtLocation: (node: Node) => StringifiedType;
10
+ export {};
@@ -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;