@ark/attest 0.48.0 → 0.48.2

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.
@@ -7,6 +7,8 @@ export type ThrowAssertionErrorContext = {
7
7
  stack: string;
8
8
  };
9
9
  export declare const throwAssertionError: ({ stack, ...errorArgs }: ThrowAssertionErrorContext) => never;
10
+ export declare class MissingSnapshotError extends Error {
11
+ }
10
12
  export type AssertFn = (expected: unknown, actual: unknown, ctx: AssertionContext) => void;
11
13
  export type MappedTypeAssertionResult = {
12
14
  actual: unknown;
@@ -5,6 +5,8 @@ export const throwAssertionError = ({ stack, ...errorArgs }) => {
5
5
  e.stack = stack;
6
6
  throw e;
7
7
  };
8
+ export class MissingSnapshotError extends Error {
9
+ }
8
10
  export class TypeAssertionMapping {
9
11
  fn;
10
12
  constructor(fn) {
@@ -67,7 +69,7 @@ Actual: ${serializedActual}`,
67
69
  const serializedExpected = printable(expected);
68
70
  const serializedActual = printable(actual);
69
71
  throw new assert.AssertionError({
70
- message: `Assertion including at least one function or object was not between reference eqaul items
72
+ message: `Assertion including at least one function or object was not between reference equal items
71
73
  Expected: ${serializedExpected}
72
74
  Actual: ${serializedActual}`,
73
75
  expected: serializedExpected,
@@ -19,7 +19,7 @@ export const attestInternal = (value, { cfg: cfgHooks, ...ctxHooks } = {}) => {
19
19
  };
20
20
  if (!cfg.skipTypes) {
21
21
  ctx.typeRelationshipAssertionEntries = getTypeAssertionsAtPosition(position);
22
- if (ctx.typeRelationshipAssertionEntries[0][1].typeArgs[0]) {
22
+ if (ctx.typeRelationshipAssertionEntries[0]?.[1].typeArgs[0]) {
23
23
  // if there is an expected type arg, check it immediately
24
24
  assertEquals(undefined, typeEqualityMapping, ctx);
25
25
  }
@@ -29,7 +29,7 @@ export const attestInternal = (value, { cfg: cfgHooks, ...ctxHooks } = {}) => {
29
29
  export const attest = Object.assign(attestInternal, {
30
30
  instantiations: (args) => {
31
31
  const attestConfig = getConfig();
32
- if (attestConfig.skipInlineInstantiations)
32
+ if (attestConfig.skipTypes || attestConfig.skipInlineInstantiations)
33
33
  return;
34
34
  const calledFrom = caller();
35
35
  const ctx = getBenchCtx([calledFrom.file]);
@@ -29,6 +29,7 @@ export declare class ChainableAssertions implements AssertionRecord {
29
29
  get throws(): unknown;
30
30
  throwsAndHasTypeError(matchValue: string | RegExp): void;
31
31
  get completions(): any;
32
+ get jsdoc(): any;
32
33
  get type(): any;
33
34
  }
34
35
  export type AssertionKind = "value" | "type";
@@ -52,18 +53,16 @@ type snapProperty<expected, kind extends AssertionKind> = {
52
53
  unwrap: Unwrapper<expected>;
53
54
  };
54
55
  export type Unwrapper<expected = unknown> = (opts?: UnwrapOptions) => expected;
55
- export declare const nonOverlappingSatisfiesMessage = "The type of your actual value and expected satisfies constraint have no overlap";
56
+ export declare const nonOverlappingSatisfiesMessage = "This type has no overlap with your satisfies constraint";
56
57
  export type nonOverlappingSatisfiesMessage = typeof nonOverlappingSatisfiesMessage;
57
- type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage, {
58
- actual: expected;
59
- satisfies: satisfies;
60
- }> : unknown;
58
+ type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage> : unknown;
61
59
  export type comparableValueAssertion<expected, kind extends AssertionKind> = {
62
60
  snap: snapProperty<expected, kind>;
63
61
  equals: (value: expected) => nextAssertions<kind>;
64
62
  instanceOf: (constructor: Constructor) => nextAssertions<kind>;
65
63
  is: (value: expected) => nextAssertions<kind>;
66
64
  completions: CompletionsSnap;
65
+ jsdoc: comparableValueAssertion<string, kind>;
67
66
  satisfies: <const def>(def: type.validate<def> & validateExpectedOverlaps<expected, type.infer.In<def>>) => nextAssertions<kind>;
68
67
  unknown: Omit<comparableValueAssertion<unknown, kind>, "unknown">;
69
68
  unwrap: Unwrapper<expected>;
@@ -1,4 +1,4 @@
1
- import { caller } from "@ark/fs";
1
+ import { caller, positionToString } from "@ark/fs";
2
2
  import { printable, snapshot } from "@ark/util";
3
3
  import prettier from "@prettier/sync";
4
4
  import { type } from "arktype";
@@ -7,7 +7,7 @@ import { isDeepStrictEqual } from "node:util";
7
7
  import { getSnapshotByName, queueSnapshotUpdate, updateExternalSnapshot } from "../cache/snapshots.js";
8
8
  import { getConfig } from "../config.js";
9
9
  import { chainableNoOpProxy } from "../utils.js";
10
- import { TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
10
+ import { MissingSnapshotError, TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
11
11
  export class ChainableAssertions {
12
12
  ctx;
13
13
  constructor(ctx) {
@@ -68,9 +68,13 @@ export class ChainableAssertions {
68
68
  const snapName = this.ctx.lastSnapName ?? "snap";
69
69
  const expectedSerialized = snapshot(args[0]);
70
70
  if (!args.length || this.ctx.cfg.updateSnapshots) {
71
+ const position = caller();
72
+ if (this.ctx.cfg.failOnMissingSnapshots) {
73
+ throw new MissingSnapshotError(`.${snapName}() at ${positionToString(position)} must be populated.`);
74
+ }
71
75
  if (this.snapRequiresUpdate(expectedSerialized)) {
72
76
  const snapshotArgs = {
73
- position: caller(),
77
+ position,
74
78
  serializedValue: this.serializedActual,
75
79
  snapFunctionName: snapName
76
80
  };
@@ -160,6 +164,15 @@ export class ChainableAssertions {
160
164
  this.ctx.lastSnapName = "completions";
161
165
  return this.snap;
162
166
  }
167
+ get jsdoc() {
168
+ if (this.ctx.cfg.skipTypes)
169
+ return chainableNoOpProxy;
170
+ this.ctx.versionableActual = new TypeAssertionMapping(data => ({
171
+ actual: formatTypeString(data.jsdoc ?? "")
172
+ }));
173
+ this.ctx.allowRegex = true;
174
+ return this.immediateOrChained();
175
+ }
163
176
  get type() {
164
177
  if (this.ctx.cfg.skipTypes)
165
178
  return chainableNoOpProxy;
@@ -197,4 +210,4 @@ const formatTypeString = (typeString) => prettier
197
210
  })
198
211
  .slice(declarationPrefix.length)
199
212
  .trimEnd();
200
- export const nonOverlappingSatisfiesMessage = "The type of your actual value and expected satisfies constraint have no overlap";
213
+ export const nonOverlappingSatisfiesMessage = "This type has no overlap with your satisfies constraint";
@@ -89,8 +89,8 @@ const snapshotArgsToQueuedUpdate = ({ position, serializedValue, snapFunctionNam
89
89
  "`"
90
90
  : JSON.stringify(serializedValue);
91
91
  newArgText = newArgText
92
- .replace(/"\$ark.bigint-(-?\d+)"/g, "$1n")
93
- .replace(/"\$ark.undefined"/g, "undefined");
92
+ .replaceAll(/"\$ark.bigint-(-?\d+)"/g, "$1n")
93
+ .replaceAll(/"\$ark.undefined"/g, "undefined");
94
94
  return {
95
95
  position,
96
96
  snapCall,
package/out/cache/ts.d.ts CHANGED
@@ -12,6 +12,7 @@ export declare class TsServer {
12
12
  getSourceFileOrThrow(path: string): ts.SourceFile;
13
13
  }
14
14
  export declare const nearestCallExpressionChild: (node: ts.Node, position: number) => ts.CallExpression;
15
+ export declare const nearestBoundingCallExpression: (node: ts.Node, position: number) => ts.CallExpression | undefined;
15
16
  export declare const getAbsolutePosition: (file: ts.SourceFile, position: SourcePosition) => number;
16
17
  export type TsconfigInfo = {
17
18
  path: string | undefined;
package/out/cache/ts.js CHANGED
@@ -1,4 +1,4 @@
1
- import { fromCwd } from "@ark/fs";
1
+ import { fromCwd, readFile } from "@ark/fs";
2
2
  import { printable, throwError, throwInternalError } from "@ark/util";
3
3
  import * as tsvfs from "@typescript/vfs";
4
4
  import { readFileSync } from "node:fs";
@@ -20,19 +20,38 @@ export class TsServer {
20
20
  this.tsConfigInfo = tsConfigInfo ?? getTsConfigInfoOrThrow();
21
21
  const tsLibPaths = getTsLibFiles(this.tsConfigInfo.parsed.options);
22
22
  // TS represents windows paths as `C:/Users/ssalb/...`
23
- const normalizedCwd = fromCwd().replaceAll(/\\/g, "/");
24
- this.rootFiles = this.tsConfigInfo.parsed.fileNames.filter(path => path.startsWith(normalizedCwd));
23
+ const normalizedCwd = fromCwd().replaceAll("\\", "/");
24
+ this.rootFiles = this.tsConfigInfo.parsed.fileNames.filter(path => {
25
+ if (!path.startsWith(normalizedCwd))
26
+ return;
27
+ // exclude empty files as they lead to a crash
28
+ // when createVirtualTypeScriptEnvironment is called
29
+ const contents = readFile(path).trim();
30
+ return contents !== "";
31
+ });
25
32
  const system = tsvfs.createFSBackedSystem(tsLibPaths.defaultMapFromNodeModules, this.tsConfigInfo.path ? dirname(this.tsConfigInfo.path) : fromCwd(), ts);
26
33
  this.virtualEnv = tsvfs.createVirtualTypeScriptEnvironment(system, this.rootFiles, ts, this.tsConfigInfo.parsed.options);
27
34
  this.program = this.virtualEnv.languageService.getProgram();
28
35
  TsServer._instance = this;
29
36
  }
30
37
  getSourceFileOrThrow(path) {
31
- const tsPath = path.replaceAll(/\\/g, "/");
32
- const file = this.virtualEnv.getSourceFile(tsPath);
33
- if (!file)
34
- throwInternalError(`Could not find TS path ${path}`);
35
- return file;
38
+ const tsPath = path.replaceAll("\\", "/");
39
+ const existingFile = this.virtualEnv.getSourceFile(tsPath);
40
+ if (existingFile)
41
+ return existingFile;
42
+ if (!this.virtualEnv.sys.fileExists(tsPath)) {
43
+ throwInternalError(`@ark/attest: TypeScript was unable to resolve expected file at ${tsPath}.\n`);
44
+ }
45
+ const contents = this.virtualEnv.sys.readFile(tsPath);
46
+ if (!contents) {
47
+ throwInternalError(`@ark/attest: TypeScript says a file exists at ${tsPath}, but was unable to read its contents.\n`);
48
+ }
49
+ this.virtualEnv.createFile(tsPath, contents);
50
+ const createdFile = this.virtualEnv.getSourceFile(tsPath);
51
+ if (!createdFile) {
52
+ throwInternalError(`@ark/attest: TypeScript tried to create a file at ${tsPath} but was unable to access it.`);
53
+ }
54
+ return createdFile;
36
55
  }
37
56
  }
38
57
  export const nearestCallExpressionChild = (node, position) => {
@@ -42,7 +61,7 @@ export const nearestCallExpressionChild = (node, position) => {
42
61
  }
43
62
  return result;
44
63
  };
45
- const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
64
+ export const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
46
65
  (node
47
66
  .getChildren()
48
67
  .flatMap(child => nearestBoundingCallExpression(child, position) ?? [])[0] ?? (ts.isCallExpression(node) ? node : undefined))
@@ -120,10 +139,10 @@ export const getStringifiableType = (node) => {
120
139
  let stringified = typeChecker.typeToString(nodeType);
121
140
  if (stringified.includes("...")) {
122
141
  const nonTruncated = typeChecker.typeToString(nodeType, undefined, ts.TypeFormatFlags.NoTruncation);
123
- if (nonTruncated.includes(" any") && !stringified.includes(" any"))
124
- stringified = nonTruncated.replaceAll(" any", " cyclic");
125
- else
126
- stringified = nonTruncated;
142
+ stringified =
143
+ nonTruncated.includes(" any") && !stringified.includes(" any") ?
144
+ nonTruncated.replaceAll(" any", " cyclic")
145
+ : nonTruncated;
127
146
  }
128
147
  return Object.assign(nodeType, {
129
148
  toString: () => stringified,
@@ -1,8 +1,12 @@
1
1
  import * as tsvfs from "@typescript/vfs";
2
2
  import ts from "typescript";
3
- import type { AssertionsByFile, LinePositionRange } from "./writeAssertionCache.ts";
3
+ import type { LinePositionRange } from "./writeAssertionCache.ts";
4
4
  export declare const getCallLocationFromCallExpression: (callExpression: ts.CallExpression) => LinePositionRange;
5
- export declare const gatherInlineInstantiationData: (file: ts.SourceFile, fileAssertions: AssertionsByFile, attestAliasInstantiationMethodCalls: string[]) => void;
5
+ /**
6
+ * Processes inline instantiations from an attest call
7
+ * Preserves any JSDoc comments that are associated with the original expression
8
+ */
9
+ export declare const gatherInlineInstantiationData: (file: ts.SourceFile, assertionsByFile: Record<string, any[]>, instantiationMethodCalls: string[]) => void;
6
10
  export declare const getCallExpressionsByName: (startNode: ts.Node, names: string[], isSnapCall?: boolean) => ts.CallExpression[];
7
11
  export declare const getInstantiationsContributedByNode: (file: ts.SourceFile, benchBlock: ts.FunctionExpression | ts.ArrowFunction) => number;
8
12
  export declare const createOrUpdateFile: (env: tsvfs.VirtualTypeScriptEnvironment, fileName: string, fileText: string) => ts.SourceFile | undefined;
@@ -21,8 +21,12 @@ export const getCallLocationFromCallExpression = (callExpression) => {
21
21
  };
22
22
  return location;
23
23
  };
24
- export const gatherInlineInstantiationData = (file, fileAssertions, attestAliasInstantiationMethodCalls) => {
25
- const expressions = getCallExpressionsByName(file, attestAliasInstantiationMethodCalls);
24
+ /**
25
+ * Processes inline instantiations from an attest call
26
+ * Preserves any JSDoc comments that are associated with the original expression
27
+ */
28
+ export const gatherInlineInstantiationData = (file, assertionsByFile, instantiationMethodCalls) => {
29
+ const expressions = getCallExpressionsByName(file, instantiationMethodCalls);
26
30
  if (!expressions.length)
27
31
  return;
28
32
  const enclosingFunctions = expressions.map(expression => {
@@ -43,15 +47,15 @@ ${enclosingFunction.ancestor.getText()}`);
43
47
  count: getInstantiationsContributedByNode(file, body)
44
48
  };
45
49
  });
46
- const assertions = fileAssertions[getFileKey(file.fileName)] ?? [];
47
- fileAssertions[getFileKey(file.fileName)] = [
50
+ const assertions = assertionsByFile[getFileKey(file.fileName)] ?? [];
51
+ assertionsByFile[getFileKey(file.fileName)] = [
48
52
  ...assertions,
49
53
  ...instantiationInfo
50
54
  ];
51
55
  };
52
56
  export const getCallExpressionsByName = (startNode, names, isSnapCall = false) => {
53
57
  const calls = [];
54
- getDescendants(startNode).forEach(descendant => {
58
+ for (const descendant of getDescendants(startNode)) {
55
59
  if (ts.isCallExpression(descendant)) {
56
60
  if (names.includes(descendant.expression.getText()) || !names.length)
57
61
  calls.push(descendant);
@@ -62,7 +66,7 @@ export const getCallExpressionsByName = (startNode, names, isSnapCall = false) =
62
66
  calls.push(descendant);
63
67
  }
64
68
  }
65
- });
69
+ }
66
70
  return calls;
67
71
  };
68
72
  const instantiationsByPath = {};
@@ -115,8 +119,14 @@ const getBaselineSourceFile = (originalFile) => {
115
119
  const functionNames = getConfig().testDeclarationAliases;
116
120
  const calls = getCallExpressionsByName(originalFile, functionNames);
117
121
  let baselineSourceFileText = originalFile.getFullText();
118
- calls.forEach(call => {
119
- baselineSourceFileText = baselineSourceFileText.replace(call.getFullText(), "");
120
- });
122
+ // for each test function like `it` or `bench`, walk up the AST to find the complete expression
123
+ for (const call of calls) {
124
+ let currentNode = call;
125
+ // ensure we capture the entire chain like bench(...).types(...)
126
+ while (currentNode.parent && !ts.isExpressionStatement(currentNode))
127
+ currentNode = currentNode.parent;
128
+ const fullExpressionText = currentNode.getFullText();
129
+ baselineSourceFileText = baselineSourceFileText.replace(fullExpressionText, "");
130
+ }
121
131
  return baselineSourceFileText;
122
132
  };
@@ -26,6 +26,8 @@ export type TypeRelationshipAssertionData = {
26
26
  typeArgs: ArgAssertionData[];
27
27
  errors: string[];
28
28
  completions: Completions;
29
+ /** JSDoc comment for the first argument, if any */
30
+ jsdoc?: string;
29
31
  };
30
32
  export type TypeBenchmarkingAssertionData = {
31
33
  location: LinePositionRange;
@@ -33,13 +33,85 @@ export const analyzeAssertCall = (assertCall, diagnosticsByFile) => {
33
33
  const typeArgs = types.typeArgs.map(typeArg => serializeArg(typeArg, types));
34
34
  const errors = checkDiagnosticMessages(assertCall, diagnosticsByFile);
35
35
  const completions = getCompletions(assertCall);
36
- return {
36
+ // Extract JSDoc comment for first argument if available
37
+ const jsdoc = extractJSDocFromArgument(assertCall);
38
+ const result = {
37
39
  location,
38
40
  args,
39
41
  typeArgs,
40
42
  errors,
41
43
  completions
42
44
  };
45
+ if (jsdoc)
46
+ result.jsdoc = jsdoc;
47
+ return result;
48
+ };
49
+ /**
50
+ * Extract JSDoc comments associated with the first argument of a call expression
51
+ */
52
+ const extractJSDocFromArgument = (callExpr) => {
53
+ // We're only interested in the first argument
54
+ const firstArg = callExpr.arguments[0];
55
+ if (!firstArg)
56
+ return undefined;
57
+ const checker = getInternalTypeChecker();
58
+ // If the argument is a property access expression (e.g., out.foo)
59
+ if (ts.isPropertyAccessExpression(firstArg)) {
60
+ // Try to find the symbol for the property
61
+ const propSymbol = checker.getSymbolAtLocation(firstArg);
62
+ if (propSymbol) {
63
+ // Get JSDoc from property declarations
64
+ return getJSDocFromSymbol(propSymbol);
65
+ }
66
+ }
67
+ // If argument is an identifier, try to find its declaration's JSDoc
68
+ else if (ts.isIdentifier(firstArg)) {
69
+ const symbol = checker.getSymbolAtLocation(firstArg);
70
+ if (symbol)
71
+ return getJSDocFromSymbol(symbol);
72
+ }
73
+ return undefined;
74
+ };
75
+ /**
76
+ * Extract JSDoc comments from a symbol's declarations
77
+ */
78
+ const getJSDocFromSymbol = (symbol) => {
79
+ // Get JSDoc directly from the symbol if possible
80
+ const symbolDocumentation = ts.displayPartsToString(symbol.getDocumentationComment(getInternalTypeChecker()));
81
+ if (symbolDocumentation)
82
+ return symbolDocumentation.trim();
83
+ // If no symbol documentation, try to get JSDoc from declarations
84
+ const declarations = symbol.getDeclarations() || [];
85
+ for (const declaration of declarations) {
86
+ // For property declarations in object literals, get the JSDoc comment
87
+ if (ts.isPropertyAssignment(declaration) ||
88
+ ts.isShorthandPropertyAssignment(declaration) ||
89
+ ts.isPropertyDeclaration(declaration)) {
90
+ const jsDocTags = ts.getJSDocTags(declaration);
91
+ if (jsDocTags.length > 0) {
92
+ return jsDocTags
93
+ .map(tag => {
94
+ const comment = tag.comment?.toString() || "";
95
+ return tag.tagName.text + (comment ? ` ${comment}` : "");
96
+ })
97
+ .join("\n");
98
+ }
99
+ // Try to get JSDoc comment before the property
100
+ const jsDocComments = ts.getJSDocCommentsAndTags(declaration);
101
+ if (jsDocComments && jsDocComments.length > 0) {
102
+ return jsDocComments
103
+ .map(doc => {
104
+ if (ts.isJSDoc(doc))
105
+ return doc.comment || "";
106
+ return "";
107
+ })
108
+ .filter(Boolean)
109
+ .join("\n")
110
+ .trim();
111
+ }
112
+ }
113
+ }
114
+ return undefined;
43
115
  };
44
116
  const serializeArg = (arg, context) => ({
45
117
  type: arg.toString(),
package/out/cli/cli.js CHANGED
@@ -1,6 +1,6 @@
1
1
  #!/usr/bin/env node
2
2
  import { fileName } from "@ark/fs";
3
- import { basename } from "path";
3
+ import { basename } from "node:path";
4
4
  import { precache } from "./precache.js";
5
5
  import { stats } from "./stats.js";
6
6
  import { trace } from "./trace.js";
@@ -12,7 +12,7 @@ const subcommands = {
12
12
  const baseFileName = basename(fileName());
13
13
  const thisFileIndex = process.argv.findIndex(
14
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
15
+ // if running from build output in pnpm, will be `cli.js` in build output
16
16
  s => s.endsWith(baseFileName) || s.endsWith("attest"));
17
17
  if (thisFileIndex === -1)
18
18
  throw new Error(`Expected to find an argument ending with "${baseFileName}"`);
@@ -1,5 +1,5 @@
1
1
  import { ensureDir } from "@ark/fs";
2
- import { join } from "path";
2
+ import { join } from "node:path";
3
3
  import { writeAssertionData } from "../fixtures.js";
4
4
  export const precache = (args) => {
5
5
  const cacheFileToWrite = args[0] ?? join(ensureDir(".attest"), "typescript.json");
@@ -1 +1 @@
1
- export declare const baseDiagnosticTscCmd = "pnpm tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
1
+ export declare const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
package/out/cli/shared.js CHANGED
@@ -1 +1 @@
1
- export const baseDiagnosticTscCmd = "pnpm tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
1
+ export const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
package/out/cli/stats.js CHANGED
@@ -1,4 +1,4 @@
1
- import { execSync } from "child_process";
1
+ import { execSync } from "node:child_process";
2
2
  import { baseDiagnosticTscCmd } from "./shared.js";
3
3
  export const stats = (args) => {
4
4
  const packageDirs = args.length ? args : [process.cwd()];
package/out/cli/trace.js CHANGED
@@ -1,42 +1,558 @@
1
- import { ensureDir } from "@ark/fs";
2
- import { execSync } from "child_process";
3
- import { resolve } from "path";
1
+ import { ensureDir, getShellOutput, readJson, writeFile } from "@ark/fs";
2
+ import { existsSync } from "node:fs";
3
+ import { basename, join, relative, resolve } from "node:path";
4
+ import ts from "typescript";
5
+ import { TsServer, getDescendants, getStringifiableType, nearestBoundingCallExpression } from "../cache/ts.js";
4
6
  import { getConfig } from "../config.js";
5
7
  import { baseDiagnosticTscCmd } from "./shared.js";
8
+ /**
9
+ * Helper to write output to both console and collect for file output
10
+ */
11
+ const outputCapture = (() => {
12
+ let buffer = [];
13
+ return {
14
+ write: (text) => {
15
+ console.log(text);
16
+ buffer.push(text);
17
+ },
18
+ getBuffer: () => buffer.join("\n"),
19
+ getLines: () => [...buffer],
20
+ clear: () => {
21
+ buffer = [];
22
+ }
23
+ };
24
+ })();
25
+ /**
26
+ * Formats microseconds to a string of milliseconds.
27
+ */
28
+ const formatMillis = (ms, fractionDigits = 2) => (ms / 1000).toFixed(fractionDigits);
29
+ /**
30
+ * Formats microseconds to a padded string of milliseconds.
31
+ */
32
+ const formatPaddedMillis = (ms, pad, fractionDigits = 2) => formatMillis(ms, fractionDigits).padStart(pad);
33
+ // Helper to format duration in seconds to a human-readable string
34
+ const formatSeconds = (totalSeconds) => {
35
+ if (totalSeconds < 0)
36
+ totalSeconds = 0;
37
+ const hours = Math.floor(totalSeconds / 3600);
38
+ const minutes = Math.floor((totalSeconds % 3600) / 60);
39
+ const seconds = Math.floor(totalSeconds % 60);
40
+ if (hours > 0)
41
+ return `about ${hours} hour(s)`;
42
+ if (minutes > 0)
43
+ return `about ${minutes} minute(s)`;
44
+ return `${seconds}s`;
45
+ };
46
+ class ProgressDisplay {
47
+ totalItems;
48
+ processedItems = 0;
49
+ startTime = 0;
50
+ timerId;
51
+ barWidth = 30; // Width of the progress bar itself
52
+ constructor(totalItems) {
53
+ this.totalItems = totalItems;
54
+ if (this.totalItems <= 0)
55
+ this.totalItems = 0;
56
+ }
57
+ start() {
58
+ if (this.totalItems === 0)
59
+ return;
60
+ this.startTime = Date.now();
61
+ this.processedItems = 0;
62
+ this.render(); // Initial render
63
+ // Update every second for elapsed time and ETA
64
+ this.timerId = setInterval(() => this.render(), 1000);
65
+ }
66
+ update(processedCount) {
67
+ if (this.totalItems === 0)
68
+ return;
69
+ this.processedItems = Math.min(processedCount, this.totalItems);
70
+ this.render(); // Re-render on each item processed for immediate feedback
71
+ if (this.processedItems >= this.totalItems)
72
+ this.stop(); // Automatically stop if all items are processed
73
+ }
74
+ render() {
75
+ if (this.totalItems === 0 && this.processedItems === 0 && !this.startTime)
76
+ return; // Avoid rendering if not started for 0 items
77
+ const percent = this.totalItems > 0 ?
78
+ Math.min(100, (this.processedItems / this.totalItems) * 100)
79
+ : 100;
80
+ const filledLength = Math.floor((this.barWidth * percent) / 100);
81
+ const emptyLength = this.barWidth - filledLength;
82
+ const bar = `[${"=".repeat(filledLength)}${" ".repeat(emptyLength)}]`;
83
+ const elapsedMs = Date.now() - this.startTime;
84
+ const elapsedSec = elapsedMs / 1000;
85
+ const formattedElapsed = formatSeconds(elapsedSec);
86
+ let etaStr = "";
87
+ if (this.processedItems > 0 && this.processedItems < this.totalItems) {
88
+ const avgTimePerItemMs = elapsedMs / this.processedItems;
89
+ const remainingItems = this.totalItems - this.processedItems;
90
+ const etaMs = remainingItems * avgTimePerItemMs;
91
+ etaStr = ` (ETA: ${formatSeconds(etaMs / 1000)})`;
92
+ }
93
+ else if (this.processedItems >= this.totalItems && this.totalItems > 0)
94
+ etaStr = " (Done)";
95
+ const summary = `${this.processedItems}/${this.totalItems} entries (${percent.toFixed(0)}%)`;
96
+ const timeInfo = `${formattedElapsed} elapsed${etaStr}`;
97
+ process.stdout.clearLine(0); // Clear the current line
98
+ process.stdout.cursorTo(0); // Move cursor to the beginning of the line
99
+ process.stdout.write(`Processing: ${bar} ${summary} | ${timeInfo}`);
100
+ }
101
+ stop() {
102
+ if (this.timerId) {
103
+ clearInterval(this.timerId);
104
+ this.timerId = undefined;
105
+ }
106
+ if (this.totalItems > 0) {
107
+ this.processedItems = this.totalItems; // Ensure final state is 100%
108
+ this.render(); // Final render
109
+ process.stdout.write("\n"); // Move to the next line
110
+ }
111
+ }
112
+ }
6
113
  export const trace = async (args) => {
7
114
  const packageDir = resolve(args[0] ?? process.cwd());
8
115
  const config = getConfig();
9
116
  if (!config.tsconfig) {
117
+ // This message should go to console.error and also be captured if needed,
118
+ // but since it exits, direct console.error is fine.
10
119
  console.error(`attest trace must be run from a directory with a tsconfig.json file`);
11
120
  process.exit(1);
12
121
  }
13
122
  const traceDir = resolve(config.cacheDir, "trace");
14
123
  ensureDir(traceDir);
124
+ outputCapture.clear();
125
+ const initialMessages = [];
126
+ initialMessages.push(`⏳ Gathering type trace data for ${packageDir}...`);
127
+ outputCapture.write(initialMessages[0]); // This goes to console and buffer
128
+ const tracingOutput = generateTraceData(traceDir, config.tsconfig, packageDir);
129
+ const traceFile = join(traceDir, "trace.json");
130
+ if (!existsSync(traceFile)) {
131
+ outputCapture.write(`❌ No trace data found (expected a file at ${traceFile}). TSC output:\n${tracingOutput}`);
132
+ const summaryPath = join(traceDir, "summary.txt");
133
+ writeFile(summaryPath, outputCapture.getBuffer());
134
+ return;
135
+ }
136
+ // This message will be followed by the progress bar on the next line
137
+ outputCapture.write(`⏳ Analyzing type trace data for ${packageDir}...`);
138
+ analyzeTypeInstantiations(traceDir); // This function now handles its own progress display
139
+ // Collect all messages for the summary file
140
+ // The progress bar output is not part of outputCapture.getLines()
141
+ const analysisMessages = outputCapture
142
+ .getLines()
143
+ .slice(initialMessages.length + 1); // +1 for the "Analyzing..." message
144
+ const summaryContent = [
145
+ ...initialMessages,
146
+ tracingOutput,
147
+ outputCapture.getLines()[initialMessages.length], // The "Analyzing..." message
148
+ ...analysisMessages
149
+ ].join("\n");
150
+ const summaryPath = join(traceDir, "summary.txt");
151
+ writeFile(summaryPath, summaryContent);
152
+ };
153
+ const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
15
154
  try {
16
- console.log(`⏳ Gathering type trace data for ${packageDir}...`);
17
- // These cache files have to be removed before any analysis is done otherwise
18
- // the results will be meaningless.
19
- // the .attest/trace directory will contain a trace.json file and a types.json file.
20
- // the trace.json file can be viewed via a tool like https://ui.perfetto.dev/
21
- // the types.json file can be used to associate IDs from the trace file with type aliases
22
- execSync(`${baseDiagnosticTscCmd} --project ${config.tsconfig} --generateTrace ${traceDir}`, {
23
- cwd: packageDir,
24
- stdio: "inherit"
155
+ const output = getShellOutput(`${baseDiagnosticTscCmd} --project ${tsconfigPath} --generateTrace ${traceDir}`, { cwd: packageDir });
156
+ process.stdout.write(output); // Display tsc output directly
157
+ return output;
158
+ }
159
+ catch (error) {
160
+ const e = error;
161
+ const output = e.stdout ?? "";
162
+ const errorOutput = e.stderr ?? "";
163
+ process.stdout.write(output);
164
+ process.stderr.write(errorOutput);
165
+ return `${output}\n${errorOutput}`;
166
+ }
167
+ };
168
+ const initializeAnalysisContext = (traceDir) => {
169
+ const tsServer = TsServer.instance;
170
+ const tracePath = join(traceDir, "trace.json");
171
+ if (!existsSync(tracePath)) {
172
+ throw new Error(`Critical: Expected a trace file at ${tracePath}, but it was not found during context initialization.`);
173
+ }
174
+ const traceEntries = readJson(tracePath);
175
+ return {
176
+ traceDir,
177
+ tsServer,
178
+ traceEntries,
179
+ durationEntries: [],
180
+ callRanges: [],
181
+ rootCalls: [],
182
+ functionStats: {},
183
+ allFunctions: []
184
+ };
185
+ };
186
+ const filterDurationEntries = (ctx) => {
187
+ ctx.durationEntries = ctx.traceEntries.filter(entry => {
188
+ const { args, dur, ph } = entry;
189
+ return (ph === "X" &&
190
+ typeof dur === "number" &&
191
+ args &&
192
+ typeof args.path === "string" &&
193
+ typeof args.pos === "number" &&
194
+ typeof args.end === "number");
195
+ });
196
+ // This message goes to outputCapture for the summary file
197
+ outputCapture.write(`Found ${ctx.durationEntries.length} complete event traces with duration, path, and position.`);
198
+ };
199
+ const processDurationEntry = (entry, ctx) => {
200
+ const entryPath = entry.args.path;
201
+ const entryPos = entry.args.pos;
202
+ const entryEnd = entry.args.end;
203
+ const entryDur = entry.dur;
204
+ const sourceFile = ctx.tsServer.getSourceFileOrThrow(entryPath);
205
+ let callRangeData;
206
+ const callExpr = findCallExpressionInRange(sourceFile, entryPos, entryEnd);
207
+ if (callExpr) {
208
+ const functionName = extractFunctionName(callExpr);
209
+ callRangeData = {
210
+ typeId: `function-${functionName}`,
211
+ functionName
212
+ };
213
+ }
214
+ else {
215
+ const relevantNode = findMostSpecificNodeInRange(sourceFile, entryPos, entryEnd);
216
+ 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);
221
+ callRangeData = {
222
+ typeId: `node-${relevantNode.kind}-${typeNodeIdPart}`,
223
+ functionName: typeName
224
+ };
225
+ }
226
+ }
227
+ if (callRangeData) {
228
+ ctx.callRanges.push({
229
+ id: `${entry.ts}-${entryPos}-${entryEnd}`,
230
+ typeId: callRangeData.typeId,
231
+ functionName: callRangeData.functionName,
232
+ callSite: `${entryPath}:${entryPos}-${entryEnd}`,
233
+ startTime: entry.ts,
234
+ endTime: entry.ts + entryDur,
235
+ duration: entryDur,
236
+ children: [],
237
+ selfTime: entryDur
25
238
  });
26
239
  }
27
- catch (e) {
28
- console.error(String(e));
29
- }
30
- finally {
31
- console.log(`⏳ Analyzing type trace data for ${packageDir}...`);
32
- // allow analyze-trace to process the args
33
- process.argv = [
34
- "node",
35
- "node_modules/@typescript/analyze-trace/dist/analyze-trace-dir.js",
36
- traceDir
37
- ];
38
- // TypeScript's analyze-trace tool can be used to automatically detect hot-spots in your code.
39
- // It's not a perfect match for what can be optimized, but it can be a helpful place to start
40
- await import("@typescript/analyze-trace/dist/analyze-trace-dir.js");
240
+ else {
241
+ throw new Error(`Failed to identify a processable AST node for duration entry (name: ${entry.name}, path: ${entryPath}, pos: ${entryPos}-${entryEnd}).`);
41
242
  }
42
243
  };
244
+ const findCallExpressionInRange = (file, start, end) => {
245
+ const boundingCall = nearestBoundingCallExpression(file, start);
246
+ if (boundingCall && boundingCall.pos >= start && boundingCall.end <= end)
247
+ return boundingCall;
248
+ const allNodes = getDescendants(file);
249
+ const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
250
+ const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
251
+ if (callExpressions.length === 0)
252
+ return undefined;
253
+ const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
254
+ return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
255
+ };
256
+ const extractFunctionName = (callExpr) => {
257
+ if (ts.isPropertyAccessExpression(callExpr.expression))
258
+ return callExpr.expression.name.getText();
259
+ if (ts.isIdentifier(callExpr.expression))
260
+ return callExpr.expression.getText();
261
+ return "anonymousFunction";
262
+ };
263
+ const buildCallTree = (ctx) => {
264
+ // This message goes to outputCapture for the summary file
265
+ outputCapture.write(`Building call tree from ${ctx.callRanges.length} ranges...`);
266
+ ctx.callRanges.sort((a, b) => a.startTime - b.startTime);
267
+ const activeCallStack = [];
268
+ for (const call of ctx.callRanges) {
269
+ while (activeCallStack.length > 0 &&
270
+ activeCallStack[activeCallStack.length - 1].endTime < call.startTime)
271
+ activeCallStack.pop();
272
+ if (activeCallStack.length === 0)
273
+ ctx.rootCalls.push(call);
274
+ else {
275
+ const parent = activeCallStack[activeCallStack.length - 1];
276
+ parent.children.push(call);
277
+ }
278
+ activeCallStack.push(call);
279
+ }
280
+ outputCapture.write(`Call tree built with ${ctx.rootCalls.length} root calls.`);
281
+ };
282
+ const calculateSelfTimes = (call) => {
283
+ let childrenTime = 0;
284
+ for (const child of call.children)
285
+ childrenTime += calculateSelfTimes(child);
286
+ call.selfTime = call.duration - childrenTime;
287
+ if (call.selfTime < 0)
288
+ call.selfTime = 0;
289
+ return call.duration;
290
+ };
291
+ const collectFunctionStats = (call, ctx) => {
292
+ if (!ctx.functionStats[call.typeId]) {
293
+ ctx.functionStats[call.typeId] = {
294
+ typeId: call.typeId,
295
+ functionName: call.functionName,
296
+ totalTime: 0,
297
+ selfTime: 0,
298
+ count: 0,
299
+ firstLocation: call.callSite,
300
+ detailedCallSites: []
301
+ };
302
+ }
303
+ const stats = ctx.functionStats[call.typeId];
304
+ const [filePath, positionRange] = call.callSite.split(":");
305
+ if (!filePath || !positionRange)
306
+ throw new Error(`Invalid callSite format: ${call.callSite}`);
307
+ const [posStr, endStr] = positionRange.split("-");
308
+ const pos = parseInt(posStr, 10);
309
+ const end = parseInt(endStr, 10);
310
+ if (isNaN(pos) || isNaN(end)) {
311
+ throw new Error(`Invalid position in callSite: ${call.callSite}. Pos: ${posStr}, End: ${endStr}`);
312
+ }
313
+ stats.detailedCallSites.push({
314
+ path: filePath,
315
+ pos,
316
+ end,
317
+ selfTime: call.selfTime
318
+ });
319
+ stats.totalTime += call.duration;
320
+ stats.selfTime += call.selfTime;
321
+ stats.count++;
322
+ for (const child of call.children)
323
+ collectFunctionStats(child, ctx);
324
+ };
325
+ const sortAndRankFunctions = (ctx) => {
326
+ outputCapture.write("Sorting and ranking functions...");
327
+ for (const stats of Object.values(ctx.functionStats))
328
+ stats.detailedCallSites.sort((a, b) => b.selfTime - a.selfTime);
329
+ ctx.allFunctions = Object.values(ctx.functionStats).sort((a, b) => b.selfTime - a.selfTime);
330
+ };
331
+ const analyzeTypeInstantiations = (traceDir) => {
332
+ const ctx = initializeAnalysisContext(traceDir);
333
+ filterDurationEntries(ctx); // Uses outputCapture
334
+ const totalEntries = ctx.durationEntries.length;
335
+ if (totalEntries === 0) {
336
+ outputCapture.write("No duration entries with path/pos to process.");
337
+ outputCapture.write(`\n✅ Analysis complete! No data to export. Summary written to:\n` +
338
+ ` - ${join(traceDir, "summary.txt")}`);
339
+ return;
340
+ }
341
+ const progressDisplay = new ProgressDisplay(totalEntries);
342
+ progressDisplay.start();
343
+ for (const [index, entry] of ctx.durationEntries.entries()) {
344
+ try {
345
+ processDurationEntry(entry, ctx);
346
+ }
347
+ catch (e) {
348
+ progressDisplay.stop(); // Stop progress before printing error via outputCapture
349
+ outputCapture.write(`\n❌ Error processing entry ${index + 1}/${totalEntries} (Path: ${entry.args.path ?? "N/A"}, Pos: ${entry.args.pos ?? "N/A"}): ${e.message}`);
350
+ outputCapture.write("Aborting analysis due to error.");
351
+ // Early exit, summary will be written by the main trace function
352
+ return;
353
+ }
354
+ progressDisplay.update(index + 1);
355
+ }
356
+ progressDisplay.stop(); // Ensure it's stopped if loop finished
357
+ // Subsequent messages use outputCapture and will appear after the progress bar
358
+ buildCallTree(ctx); // Uses outputCapture
359
+ outputCapture.write("Calculating self-times for call tree nodes...");
360
+ for (const root of ctx.rootCalls)
361
+ calculateSelfTimes(root);
362
+ outputCapture.write("Collecting statistics...");
363
+ const ungroupedStats = collectUngroupedStats(ctx); // Uses outputCapture
364
+ for (const root of ctx.rootCalls)
365
+ collectFunctionStats(root, ctx);
366
+ sortAndRankFunctions(ctx); // Uses outputCapture
367
+ outputCapture.write("\n📊 Performance Analysis - Top Individual Calls:\n");
368
+ displayIndividualSummary(ungroupedStats); // Uses outputCapture
369
+ outputCapture.write("\n📊 Performance Analysis - Functions by Self Time:\n");
370
+ displayGroupedSummary(ctx.allFunctions); // Uses outputCapture
371
+ const rangesCsvPath = join(traceDir, "ranges.csv");
372
+ const namesCsvPath = join(traceDir, "names.csv");
373
+ const summaryFilePath = join(traceDir, "summary.txt"); // Path already defined in trace()
374
+ if (ctx.callRanges.length > 0) {
375
+ outputCapture.write("Exporting CSV reports...");
376
+ writeToCsv(rangesCsvPath, ["Function Name", "Self (ms)", "Duration (ms)", "Location"], ungroupedStats.map(stat => [
377
+ stat.functionName,
378
+ formatMillis(stat.selfTime, 3),
379
+ formatMillis(stat.duration, 3),
380
+ formatLocation(stat.callSite)
381
+ ]));
382
+ writeToCsv(namesCsvPath, [
383
+ "Function Name",
384
+ "Total Self (ms)",
385
+ "Avg Self (ms)",
386
+ "Call Count",
387
+ "Top Location",
388
+ "Top Self (ms)"
389
+ ], ctx.allFunctions.map(stats => {
390
+ const topUsage = stats.detailedCallSites[0] ?? {
391
+ path: "unknown",
392
+ pos: 0,
393
+ end: 0,
394
+ selfTime: 0
395
+ };
396
+ return [
397
+ stats.functionName,
398
+ formatMillis(stats.selfTime, 3),
399
+ formatMillis(stats.selfTime / Math.max(1, stats.count), 3),
400
+ stats.count.toString(),
401
+ formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`),
402
+ formatMillis(topUsage.selfTime, 3)
403
+ ];
404
+ }));
405
+ outputCapture.write(`\n✅ Analysis complete! Results exported to:\n` +
406
+ ` - ${rangesCsvPath} (individual calls)\n` +
407
+ ` - ${namesCsvPath} (grouped by function name)\n` +
408
+ ` - ${summaryFilePath} (complete analysis report)`);
409
+ }
410
+ else {
411
+ outputCapture.write(`\n✅ Analysis complete! No call ranges processed to export to CSV. Summary written to:\n` +
412
+ ` - ${summaryFilePath}`);
413
+ }
414
+ };
415
+ const collectUngroupedStats = (ctx) => {
416
+ outputCapture.write("Collecting and sorting ungrouped call statistics...");
417
+ const ungroupedStats = [];
418
+ const flattenCallTree = (call) => {
419
+ ungroupedStats.push({
420
+ typeId: call.typeId,
421
+ functionName: call.functionName,
422
+ callSite: call.callSite,
423
+ duration: call.duration,
424
+ selfTime: call.selfTime
425
+ });
426
+ for (const child of call.children)
427
+ flattenCallTree(child);
428
+ };
429
+ for (const root of ctx.rootCalls)
430
+ flattenCallTree(root);
431
+ return ungroupedStats.sort((a, b) => b.selfTime - a.selfTime);
432
+ };
433
+ const displayIndividualSummary = (stats) => {
434
+ displayTableHeader(["Rank", "Function Name", "Self (ms)", "Location"]);
435
+ const topN = Math.min(stats.length, 20);
436
+ for (let i = 0; i < topN; i++) {
437
+ const stat = stats[i];
438
+ const typeNameFormatted = formatTypeName(stat.functionName, 20);
439
+ const selfTimeMs = formatPaddedMillis(stat.selfTime, 15, 2);
440
+ const location = formatLocation(stat.callSite);
441
+ outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
442
+ }
443
+ };
444
+ const displayTableHeader = (columns) => {
445
+ const headerRow = [
446
+ columns[0].padEnd(4),
447
+ columns[1].padEnd(20),
448
+ columns[2].padEnd(15),
449
+ ...columns.slice(3)
450
+ ].join(" | ");
451
+ const separatorRow = [
452
+ "-".repeat(4),
453
+ "-".repeat(20),
454
+ "-".repeat(15),
455
+ ...columns.slice(3).map(col => "-".repeat(col.length))
456
+ ].join("-|-");
457
+ outputCapture.write(headerRow);
458
+ outputCapture.write(separatorRow);
459
+ };
460
+ const displayGroupedSummary = (functions) => {
461
+ displayTableHeader([
462
+ "Rank",
463
+ "Function Name",
464
+ "Total Self (ms)",
465
+ "Avg Self (ms)",
466
+ "Calls",
467
+ "Top Usage"
468
+ ]);
469
+ const topN = Math.min(functions.length, 20);
470
+ for (let i = 0; i < topN; i++) {
471
+ const stats = functions[i];
472
+ const typeNameFormatted = formatTypeName(stats.functionName, 20);
473
+ const totalTimeMs = formatPaddedMillis(stats.selfTime, 15, 2);
474
+ const avgTimeMs = formatPaddedMillis(stats.selfTime / Math.max(1, stats.count), 13, 2);
475
+ const calls = stats.count.toString().padStart(5);
476
+ const topUsage = stats.detailedCallSites[0] ?? {
477
+ path: "unknown",
478
+ pos: 0,
479
+ end: 0,
480
+ selfTime: 0
481
+ };
482
+ const topUsageTime = formatMillis(topUsage.selfTime, 2) + "ms";
483
+ const topUsageLocation = formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`);
484
+ outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
485
+ }
486
+ };
487
+ const formatTypeName = (typeName, maxLength) => {
488
+ typeName = typeName.replace(/\(\)$/, "");
489
+ if (typeName.length <= maxLength)
490
+ return typeName.padEnd(maxLength);
491
+ const charsToKeep = maxLength - 3;
492
+ const firstPart = Math.ceil(charsToKeep * 0.7);
493
+ const lastPart = charsToKeep - firstPart;
494
+ return (typeName.substring(0, firstPart) +
495
+ "..." +
496
+ (lastPart > 0 ? typeName.substring(typeName.length - lastPart) : "")).padEnd(maxLength);
497
+ };
498
+ const formatLocation = (location) => {
499
+ if (!location || location === "unknown" || !location.includes(":"))
500
+ return location || "unknown";
501
+ const parts = location.split(":");
502
+ if (parts.length < 2)
503
+ return basename(location);
504
+ const filePath = parts.slice(0, -1).join(":");
505
+ const positionRange = parts[parts.length - 1];
506
+ const relativePath = relative(process.cwd(), filePath);
507
+ const [posStr] = positionRange.split("-");
508
+ const pos = parseInt(posStr, 10);
509
+ if (isNaN(pos))
510
+ return `${relativePath}:${positionRange}`;
511
+ const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
512
+ const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
513
+ return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
514
+ };
515
+ const findMostSpecificNodeInRange = (file, start, end) => {
516
+ const allNodes = getDescendants(file);
517
+ const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
518
+ if (nodesInRange.length === 0)
519
+ return undefined;
520
+ const leafNodes = nodesInRange.filter(node => !nodesInRange.some(other => other !== node && other.pos >= node.pos && other.end <= node.end));
521
+ return findNodeByPreference(leafNodes.length > 0 ? leafNodes : nodesInRange);
522
+ };
523
+ const findNodeByPreference = (nodes) => {
524
+ if (nodes.length === 0)
525
+ return undefined;
526
+ const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
527
+ if (typeReference)
528
+ return typeReference;
529
+ const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
530
+ ts.isFunctionDeclaration(node) ||
531
+ ts.isClassDeclaration(node) ||
532
+ ts.isInterfaceDeclaration(node));
533
+ if (declaration)
534
+ return declaration;
535
+ const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
536
+ if (propertyAccess)
537
+ return propertyAccess;
538
+ const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
539
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
540
+ if (assignment)
541
+ return assignment;
542
+ const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
543
+ if (expression)
544
+ return expression;
545
+ return nodes.sort((a, b) => a.end - a.pos - (b.end - b.pos))[0];
546
+ };
547
+ const writeToCsv = (filePath, headers, rows) => {
548
+ const content = [
549
+ headers.join(","),
550
+ ...rows.map(row => row.map(escapeForCsv).join(","))
551
+ ].join("\n");
552
+ writeFile(filePath, content);
553
+ };
554
+ const escapeForCsv = (value) => {
555
+ if (value.includes(",") || value.includes('"') || value.includes("\n"))
556
+ return `"${value.replaceAll('"', '""')}"`;
557
+ return value;
558
+ };
package/out/config.d.ts CHANGED
@@ -8,6 +8,7 @@ type BaseAttestConfig = {
8
8
  tsconfig: string | null | undefined;
9
9
  compilerOptions: ts.CompilerOptions;
10
10
  updateSnapshots: boolean;
11
+ failOnMissingSnapshots: boolean;
11
12
  /** A string or list of strings representing the TypeScript version aliases to run.
12
13
  *
13
14
  * Aliases must be specified as a package.json dependency or devDependency beginning with "typescript".
package/out/config.js CHANGED
@@ -7,6 +7,7 @@ export const getDefaultAttestConfig = () => ({
7
7
  tsconfig: existsSync(fromCwd("tsconfig.json")) ? fromCwd("tsconfig.json") : undefined,
8
8
  compilerOptions: {},
9
9
  attestAliases: ["attest", "attestInternal"],
10
+ failOnMissingSnapshots: "CI" in process.env,
10
11
  updateSnapshots: false,
11
12
  skipTypes: false,
12
13
  skipInlineInstantiations: false,
@@ -52,7 +53,7 @@ const getParamValue = (param) => {
52
53
  };
53
54
  export const attestEnvPrefix = "ATTEST_";
54
55
  const addEnvConfig = (config) => {
55
- Object.entries(process.env).forEach(([k, v]) => {
56
+ for (const [k, v] of Object.entries(process.env)) {
56
57
  if (k.startsWith(attestEnvPrefix)) {
57
58
  const optionName = k.slice(attestEnvPrefix.length);
58
59
  if (optionName === "CONFIG")
@@ -60,7 +61,7 @@ const addEnvConfig = (config) => {
60
61
  else
61
62
  config[optionName] = JSON.parse(v);
62
63
  }
63
- });
64
+ }
64
65
  let k;
65
66
  for (k in config) {
66
67
  if (config[k] === false)
@@ -6,7 +6,6 @@ import type { Digit } from "@ark/util";
6
6
  * temporarily renamed to node_modules/typescript-temp, and reset after each
7
7
  * version has been executed, regardless of failures.
8
8
  *
9
- *
10
9
  * Throws an error if any version fails when the associated function is executed.
11
10
  *
12
11
  * fn should spawn a new process so the new symlinked version can be loaded.
@@ -18,22 +17,12 @@ export type TsVersionData = {
18
17
  path: string;
19
18
  };
20
19
  /**
21
- * Find and return the paths of all installed TypeScript versions, including the
22
- * all dependencies beginning with "typescript" or "@ark/attest-ts-".
23
- *
24
- * Starts checking from the current directory and looks for node_modules in parent
25
- * directories up to the file system root.
26
- *
27
- * Alternate versions can be installed using a package.json dependency like:
20
+ * Find and return the paths of all installed TypeScript versions by directly scanning
21
+ * node_modules directories in the current package and all parent packages.
28
22
  *
29
- * ```json
30
- * "@ark/attest-ts-min": "npm:typescript@5.1.6"
31
- * ```
32
- * @returns {TsVersionData[]} Each version mapped to data, e.g.:
33
- * {alias: "@ark/attest-ts-min", version: "5.1.6", path: "/home/ssalb/arktype/node_modules/@ark/attest-ts-min" } *
23
+ * This function only looks at directories, bypassing package.json entirely.
34
24
  *
35
- * @throws {Error} If a TypeScript version specified in package.json is not
36
- * installed at the expected location in node_modules.
25
+ * @returns {TsVersionData[]} Information about each TypeScript version found
37
26
  */
38
27
  export declare const findAttestTypeScriptVersions: () => TsVersionData[];
39
28
  /** Get the TypeScript version being used by attest as as string like "5.0"
@@ -1,7 +1,6 @@
1
- import { assertPackageRoot, fsRoot, readJson } from "@ark/fs";
2
- import { existsSync, renameSync, symlinkSync, unlinkSync } from "fs";
3
- import { dirname } from "path";
4
- import { join } from "path/posix";
1
+ import { assertPackageRoot, findPackageAncestors, readJson } from "@ark/fs";
2
+ import { existsSync, readdirSync, renameSync, statSync, symlinkSync, unlinkSync } from "node:fs";
3
+ import { join } from "node:path";
5
4
  import ts from "typescript";
6
5
  /**
7
6
  * Executes a provided function for an installed set of TypeScript versions.
@@ -10,7 +9,6 @@ import ts from "typescript";
10
9
  * temporarily renamed to node_modules/typescript-temp, and reset after each
11
10
  * version has been executed, regardless of failures.
12
11
  *
13
- *
14
12
  * Throws an error if any version fails when the associated function is executed.
15
13
  *
16
14
  * fn should spawn a new process so the new symlinked version can be loaded.
@@ -59,70 +57,112 @@ export const forTypeScriptVersions = (versions, fn) => {
59
57
  }
60
58
  };
61
59
  const possibleTsVersionPrefix = "typescript-";
62
- const strictTsVersionPrefix = "@ark/attest-ts-";
63
- const parseInstalledTsAlias = (installedAlias) => {
64
- if (installedAlias === "typescript")
60
+ const strictTsVersionPrefix = "attest-ts-";
61
+ /**
62
+ * Determine the alias from the directory name
63
+ */
64
+ const getDirAlias = (dirName) => {
65
+ if (dirName === "typescript")
65
66
  return "default";
66
- if (installedAlias.startsWith(possibleTsVersionPrefix))
67
- return installedAlias.slice(possibleTsVersionPrefix.length);
68
- if (installedAlias.startsWith(strictTsVersionPrefix))
69
- return installedAlias.slice(strictTsVersionPrefix.length);
67
+ if (dirName.startsWith(possibleTsVersionPrefix))
68
+ return dirName.slice(possibleTsVersionPrefix.length);
69
+ if (dirName.startsWith(strictTsVersionPrefix))
70
+ return dirName.slice(strictTsVersionPrefix.length);
70
71
  return null;
71
72
  };
72
73
  /**
73
- * Find and return the paths of all installed TypeScript versions, including the
74
- * all dependencies beginning with "typescript" or "@ark/attest-ts-".
75
- *
76
- * Starts checking from the current directory and looks for node_modules in parent
77
- * directories up to the file system root.
78
- *
79
- * Alternate versions can be installed using a package.json dependency like:
74
+ * Try to get the TypeScript version from a directory
75
+ */
76
+ const getTsVersion = (fullPath) => {
77
+ try {
78
+ // Try to read package.json for version
79
+ const packageJsonPath = join(fullPath, "package.json");
80
+ if (existsSync(packageJsonPath)) {
81
+ const packageJson = readJson(packageJsonPath);
82
+ if (packageJson &&
83
+ packageJson.name === "typescript" &&
84
+ typeof packageJson.version === "string")
85
+ return packageJson.version;
86
+ }
87
+ // As a fallback, check for the lib/typescript.js file which should exist in all TS installations
88
+ if (existsSync(join(fullPath, "lib", "typescript.js")))
89
+ return "unknown";
90
+ return null;
91
+ }
92
+ catch {
93
+ return null;
94
+ }
95
+ };
96
+ /**
97
+ * Find and return the paths of all installed TypeScript versions by directly scanning
98
+ * node_modules directories in the current package and all parent packages.
80
99
  *
81
- * ```json
82
- * "@ark/attest-ts-min": "npm:typescript@5.1.6"
83
- * ```
84
- * @returns {TsVersionData[]} Each version mapped to data, e.g.:
85
- * {alias: "@ark/attest-ts-min", version: "5.1.6", path: "/home/ssalb/arktype/node_modules/@ark/attest-ts-min" } *
100
+ * This function only looks at directories, bypassing package.json entirely.
86
101
  *
87
- * @throws {Error} If a TypeScript version specified in package.json is not
88
- * installed at the expected location in node_modules.
102
+ * @returns {TsVersionData[]} Information about each TypeScript version found
89
103
  */
90
104
  export const findAttestTypeScriptVersions = () => {
91
- let currentDir = process.cwd();
105
+ const packagePaths = findPackageAncestors(process.cwd());
92
106
  const versions = [];
93
- while (currentDir !== fsRoot) {
94
- const packageJsonPath = join(currentDir, "package.json");
95
- if (!existsSync(packageJsonPath)) {
96
- currentDir = dirname(currentDir);
107
+ const foundVersionAliases = new Set();
108
+ // Check each package's node_modules directory
109
+ for (const packagePath of packagePaths) {
110
+ const nodeModulesPath = join(packagePath, "node_modules");
111
+ if (!existsSync(nodeModulesPath) ||
112
+ !statSync(nodeModulesPath).isDirectory())
97
113
  continue;
98
- }
99
- const nodeModulesPath = join(currentDir, "node_modules");
100
- const packageJson = readJson(packageJsonPath);
101
- const dependencies = {
102
- ...packageJson.dependencies,
103
- ...packageJson.devDependencies
104
- };
105
- for (const installedAlias in dependencies) {
106
- const alias = parseInstalledTsAlias(installedAlias);
107
- if (alias === null)
114
+ // Check for regular typescript or typescript-* directories
115
+ const dirNames = readdirSync(nodeModulesPath);
116
+ for (const dirName of dirNames) {
117
+ // Skip node_modules/@* directories - we'll handle them below
118
+ if (dirName.startsWith("@"))
108
119
  continue;
109
- const path = join(nodeModulesPath, installedAlias);
110
- if (!existsSync(path)) {
111
- throw Error(`TypeScript version ${installedAlias} specified in ${packageJsonPath} must be installed at ${path} `);
112
- }
113
- const typescriptJson = readJson(join(path, "package.json"));
114
- if (typescriptJson.name !== "typescript") {
115
- if (installedAlias.startsWith(strictTsVersionPrefix))
116
- throw new Error(`Package at ${path} should be named "typescript"`);
120
+ const fullPath = join(nodeModulesPath, dirName);
121
+ if (!statSync(fullPath).isDirectory())
117
122
  continue;
123
+ const alias = getDirAlias(dirName);
124
+ if (!alias)
125
+ continue;
126
+ // Skip if we already found this alias in a closer package
127
+ if (foundVersionAliases.has(alias))
128
+ continue;
129
+ const version = getTsVersion(fullPath);
130
+ if (version) {
131
+ foundVersionAliases.add(alias);
132
+ versions.push({
133
+ alias,
134
+ version,
135
+ path: fullPath
136
+ });
137
+ }
138
+ }
139
+ // Check for @ark/attest-ts-* directories
140
+ const arkDir = join(nodeModulesPath, "@ark");
141
+ if (existsSync(arkDir) && statSync(arkDir).isDirectory()) {
142
+ const arkDirs = readdirSync(arkDir);
143
+ for (const dirName of arkDirs) {
144
+ if (!dirName.startsWith("attest-ts-"))
145
+ continue;
146
+ const fullPath = join(arkDir, dirName);
147
+ if (!statSync(fullPath).isDirectory())
148
+ continue;
149
+ const alias = getDirAlias(dirName);
150
+ if (!alias)
151
+ continue;
152
+ // Skip if we already found this alias in a closer package
153
+ if (foundVersionAliases.has(alias))
154
+ continue;
155
+ const version = getTsVersion(fullPath);
156
+ if (version) {
157
+ foundVersionAliases.add(alias);
158
+ versions.push({
159
+ alias,
160
+ version,
161
+ path: fullPath
162
+ });
163
+ }
118
164
  }
119
- versions.push({
120
- alias,
121
- version: typescriptJson.version,
122
- path
123
- });
124
165
  }
125
- currentDir = dirname(currentDir);
126
166
  }
127
167
  return versions;
128
168
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.48.0",
3
+ "version": "0.48.2",
4
4
  "license": "MIT",
5
5
  "author": {
6
6
  "name": "David Blass",
@@ -36,9 +36,9 @@
36
36
  "@typescript/analyze-trace": "0.10.1",
37
37
  "@typescript/vfs": "1.6.1",
38
38
  "prettier": "3.5.3",
39
- "@ark/fs": "0.46.0",
39
+ "arktype": "2.1.20",
40
40
  "@ark/util": "0.46.0",
41
- "arktype": "2.1.20"
41
+ "@ark/fs": "0.46.0"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "5.8.2"