@ark/attest 0.48.0 → 0.48.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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,8 +1,35 @@
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);
6
33
  export const trace = async (args) => {
7
34
  const packageDir = resolve(args[0] ?? process.cwd());
8
35
  const config = getConfig();
@@ -12,31 +39,420 @@ export const trace = async (args) => {
12
39
  }
13
40
  const traceDir = resolve(config.cacheDir, "trace");
14
41
  ensureDir(traceDir);
42
+ outputCapture.clear();
43
+ const initialMessages = [];
44
+ initialMessages.push(`⏳ Gathering type trace data for ${packageDir}...`);
45
+ outputCapture.write(initialMessages[0]);
46
+ const tracingOutput = generateTraceData(traceDir, config.tsconfig, packageDir);
47
+ const traceFile = join(traceDir, "trace.json");
48
+ if (!existsSync(traceFile)) {
49
+ outputCapture.write(`❌ No trace data found (expected a file at ${traceFile}). TSC output:\n${tracingOutput}`);
50
+ // Write what we have to summary and exit
51
+ const summaryPath = join(traceDir, "summary.txt");
52
+ writeFile(summaryPath, outputCapture.getBuffer());
53
+ return;
54
+ }
55
+ outputCapture.write(`⏳ Analyzing type trace data for ${packageDir}...`);
56
+ analyzeTypeInstantiations(traceDir);
57
+ const analysisMessages = outputCapture
58
+ .getLines()
59
+ .slice(initialMessages.length);
60
+ const summaryContent = [
61
+ ...initialMessages,
62
+ tracingOutput,
63
+ ...analysisMessages
64
+ ].join("\n");
65
+ const summaryPath = join(traceDir, "summary.txt");
66
+ writeFile(summaryPath, summaryContent);
67
+ };
68
+ const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
15
69
  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"
70
+ const output = getShellOutput(`${baseDiagnosticTscCmd} --project ${tsconfigPath} --generateTrace ${traceDir}`, { cwd: packageDir });
71
+ process.stdout.write(output);
72
+ return output;
73
+ }
74
+ catch (error) {
75
+ // even if tsc returns a non-zero exit code,
76
+ // we can still proceed as long as the trace.json
77
+ // file was generated. The existence of trace.json is checked later.
78
+ const e = error;
79
+ const output = e.stdout ?? "";
80
+ const errorOutput = e.stderr ?? "";
81
+ process.stdout.write(output);
82
+ process.stderr.write(errorOutput);
83
+ return `${output}\n${errorOutput}`;
84
+ }
85
+ };
86
+ const initializeAnalysisContext = (traceDir) => {
87
+ const tsServer = TsServer.instance;
88
+ const tracePath = join(traceDir, "trace.json");
89
+ if (!existsSync(tracePath)) {
90
+ // This case should be caught by the `trace` function earlier,
91
+ // but as a safeguard:
92
+ throw new Error(`Critical: Expected a trace file at ${tracePath}, but it was not found during context initialization.`);
93
+ }
94
+ const traceEntries = readJson(tracePath); // Assuming readJson returns TraceEntry[]
95
+ return {
96
+ traceDir,
97
+ tsServer,
98
+ traceEntries,
99
+ durationEntries: [],
100
+ callRanges: [],
101
+ rootCalls: [],
102
+ functionStats: {},
103
+ allFunctions: []
104
+ };
105
+ };
106
+ const filterDurationEntries = (ctx) => {
107
+ ctx.durationEntries = ctx.traceEntries.filter(entry => {
108
+ const { args, dur, ph } = entry;
109
+ return (ph === "X" && // "X" denotes a complete event
110
+ typeof dur === "number" && // Duration must exist and be a number
111
+ args &&
112
+ typeof args.path === "string" &&
113
+ typeof args.pos === "number" &&
114
+ typeof args.end === "number");
115
+ });
116
+ outputCapture.write(`Found ${ctx.durationEntries.length} complete event traces with duration, path, and position.`);
117
+ };
118
+ const processDurationEntry = (entry, ctx) => {
119
+ // These properties are guaranteed by filterDurationEntries
120
+ const entryPath = entry.args.path;
121
+ const entryPos = entry.args.pos;
122
+ const entryEnd = entry.args.end;
123
+ const entryDur = entry.dur; // Duration in microseconds
124
+ const sourceFile = ctx.tsServer.getSourceFileOrThrow(entryPath);
125
+ let callRangeData;
126
+ const callExpr = findCallExpressionInRange(sourceFile, entryPos, entryEnd);
127
+ if (callExpr) {
128
+ const functionName = extractFunctionName(callExpr);
129
+ callRangeData = {
130
+ typeId: `function-${functionName}`,
131
+ functionName
132
+ };
133
+ }
134
+ else {
135
+ const relevantNode = findMostSpecificNodeInRange(sourceFile, entryPos, entryEnd);
136
+ if (relevantNode) {
137
+ const nodeType = getStringifiableType(relevantNode);
138
+ const nodeKind = ts.SyntaxKind[relevantNode.kind];
139
+ const typeName = `${nodeKind}: ${nodeType.toString().substring(0, 25)}`;
140
+ // Ensure typeId is unique and meaningful
141
+ const typeNodeIdPart = nodeType.id ?? nodeType.toString().substring(0, 20);
142
+ callRangeData = {
143
+ typeId: `node-${relevantNode.kind}-${typeNodeIdPart}`,
144
+ functionName: typeName
145
+ };
146
+ }
147
+ }
148
+ if (callRangeData) {
149
+ ctx.callRanges.push({
150
+ id: `${entry.ts}-${entryPos}-${entryEnd}`,
151
+ typeId: callRangeData.typeId,
152
+ functionName: callRangeData.functionName,
153
+ callSite: `${entryPath}:${entryPos}-${entryEnd}`,
154
+ startTime: entry.ts,
155
+ endTime: entry.ts + entryDur,
156
+ duration: entryDur,
157
+ children: [],
158
+ selfTime: entryDur // Initial selfTime is full duration
25
159
  });
26
160
  }
27
- catch (e) {
28
- console.error(String(e));
161
+ else {
162
+ // If no call expression and no other relevant node is found for a duration entry,
163
+ // this indicates an issue with the trace data or our processing logic.
164
+ throw new Error(`Failed to identify a processable AST node for duration entry (name: ${entry.name}, path: ${entryPath}, pos: ${entryPos}-${entryEnd}). This entry will be skipped.`);
165
+ }
166
+ };
167
+ const findCallExpressionInRange = (file, start, end) => {
168
+ const boundingCall = nearestBoundingCallExpression(file, start);
169
+ if (boundingCall && boundingCall.pos >= start && boundingCall.end <= end)
170
+ return boundingCall;
171
+ const allNodes = getDescendants(file);
172
+ const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
173
+ const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
174
+ if (callExpressions.length === 0)
175
+ return undefined;
176
+ const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
177
+ return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
178
+ };
179
+ const extractFunctionName = (callExpr) => {
180
+ if (ts.isPropertyAccessExpression(callExpr.expression))
181
+ return callExpr.expression.name.getText();
182
+ if (ts.isIdentifier(callExpr.expression))
183
+ return callExpr.expression.getText();
184
+ return "anonymousFunction"; // More specific than just "anonymous"
185
+ };
186
+ const buildCallTree = (ctx) => {
187
+ ctx.callRanges.sort((a, b) => a.startTime - b.startTime);
188
+ const activeCallStack = [];
189
+ for (const call of ctx.callRanges) {
190
+ while (activeCallStack.length > 0 &&
191
+ activeCallStack[activeCallStack.length - 1].endTime < call.startTime)
192
+ activeCallStack.pop();
193
+ if (activeCallStack.length === 0)
194
+ ctx.rootCalls.push(call);
195
+ else {
196
+ const parent = activeCallStack[activeCallStack.length - 1];
197
+ parent.children.push(call);
198
+ }
199
+ activeCallStack.push(call);
200
+ }
201
+ };
202
+ const calculateSelfTimes = (call) => {
203
+ let childrenTime = 0;
204
+ for (const child of call.children)
205
+ childrenTime += calculateSelfTimes(child);
206
+ call.selfTime = call.duration - childrenTime;
207
+ if (call.selfTime < 0) {
208
+ // This can happen due to precision issues or overlapping trace entries.
209
+ // Log a warning, but clamp to 0 to avoid negative self-times.
210
+ // console.warn(`Warning: Negative self-time calculated for ${call.functionName} at ${call.callSite}. Clamping to 0.`);
211
+ call.selfTime = 0;
212
+ }
213
+ return call.duration;
214
+ };
215
+ const collectFunctionStats = (call, ctx) => {
216
+ if (!ctx.functionStats[call.typeId]) {
217
+ ctx.functionStats[call.typeId] = {
218
+ typeId: call.typeId,
219
+ functionName: call.functionName,
220
+ totalTime: 0,
221
+ selfTime: 0,
222
+ count: 0,
223
+ firstLocation: call.callSite, // Should always be present
224
+ detailedCallSites: []
225
+ };
29
226
  }
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
227
+ const stats = ctx.functionStats[call.typeId];
228
+ const [filePath, positionRange] = call.callSite.split(":");
229
+ if (!filePath || !positionRange)
230
+ throw new Error(`Invalid callSite format: ${call.callSite}`);
231
+ const [posStr, endStr] = positionRange.split("-");
232
+ const pos = parseInt(posStr, 10);
233
+ const end = parseInt(endStr, 10);
234
+ if (isNaN(pos) || isNaN(end)) {
235
+ throw new Error(`Invalid position in callSite: ${call.callSite}. Pos: ${posStr}, End: ${endStr}`);
236
+ }
237
+ stats.detailedCallSites.push({
238
+ path: filePath,
239
+ pos,
240
+ end,
241
+ selfTime: call.selfTime
242
+ });
243
+ stats.totalTime += call.duration;
244
+ stats.selfTime += call.selfTime;
245
+ stats.count++;
246
+ for (const child of call.children)
247
+ collectFunctionStats(child, ctx);
248
+ };
249
+ const sortAndRankFunctions = (ctx) => {
250
+ for (const stats of Object.values(ctx.functionStats))
251
+ stats.detailedCallSites.sort((a, b) => b.selfTime - a.selfTime);
252
+ ctx.allFunctions = Object.values(ctx.functionStats).sort((a, b) => b.selfTime - a.selfTime);
253
+ };
254
+ const analyzeTypeInstantiations = (traceDir) => {
255
+ const ctx = initializeAnalysisContext(traceDir);
256
+ filterDurationEntries(ctx);
257
+ for (const entry of ctx.durationEntries) {
258
+ // Errors in processDurationEntry will propagate and stop analysis for that entry
259
+ // or potentially the whole script if not caught at a higher level (which is intended now).
260
+ processDurationEntry(entry, ctx);
261
+ }
262
+ buildCallTree(ctx);
263
+ for (const root of ctx.rootCalls)
264
+ calculateSelfTimes(root);
265
+ const ungroupedStats = collectUngroupedStats(ctx);
266
+ for (const root of ctx.rootCalls)
267
+ collectFunctionStats(root, ctx);
268
+ sortAndRankFunctions(ctx);
269
+ outputCapture.write("\n📊 Performance Analysis - Top Individual Calls:\n");
270
+ displayIndividualSummary(ungroupedStats);
271
+ outputCapture.write("\n📊 Performance Analysis - Functions by Self Time:\n");
272
+ displayGroupedSummary(ctx.allFunctions);
273
+ const rangesCsvPath = join(traceDir, "ranges.csv");
274
+ const namesCsvPath = join(traceDir, "names.csv");
275
+ const summaryFilePath = join(traceDir, "summary.txt"); // Renamed to avoid conflict
276
+ writeToCsv(rangesCsvPath, ["Function Name", "Self (ms)", "Duration (ms)", "Location"], ungroupedStats.map(stat => [
277
+ stat.functionName,
278
+ formatMillis(stat.selfTime, 3),
279
+ formatMillis(stat.duration, 3),
280
+ formatLocation(stat.callSite)
281
+ ]));
282
+ writeToCsv(namesCsvPath, [
283
+ "Function Name",
284
+ "Total Self (ms)",
285
+ "Avg Self (ms)",
286
+ "Call Count",
287
+ "Top Location",
288
+ "Top Self (ms)"
289
+ ], ctx.allFunctions.map(stats => {
290
+ const topUsage = stats.detailedCallSites[0] ?? {
291
+ path: "unknown",
292
+ pos: 0,
293
+ end: 0,
294
+ selfTime: 0
295
+ };
296
+ return [
297
+ stats.functionName,
298
+ formatMillis(stats.selfTime, 3),
299
+ formatMillis(stats.selfTime / Math.max(1, stats.count), 3), // Avoid division by zero
300
+ stats.count.toString(),
301
+ formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`),
302
+ formatMillis(topUsage.selfTime, 3)
37
303
  ];
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");
304
+ }));
305
+ outputCapture.write(`\n✅ Analysis complete! Results exported to:\n` +
306
+ ` - ${rangesCsvPath} (individual calls)\n` +
307
+ ` - ${namesCsvPath} (grouped by function name)\n` +
308
+ ` - ${summaryFilePath} (complete analysis report)`);
309
+ };
310
+ const collectUngroupedStats = (ctx) => {
311
+ const ungroupedStats = [];
312
+ const flattenCallTree = (call) => {
313
+ ungroupedStats.push({
314
+ typeId: call.typeId,
315
+ functionName: call.functionName,
316
+ callSite: call.callSite,
317
+ duration: call.duration,
318
+ selfTime: call.selfTime
319
+ });
320
+ for (const child of call.children)
321
+ flattenCallTree(child);
322
+ };
323
+ for (const root of ctx.rootCalls)
324
+ flattenCallTree(root);
325
+ return ungroupedStats.sort((a, b) => b.selfTime - a.selfTime);
326
+ };
327
+ const displayIndividualSummary = (stats) => {
328
+ displayTableHeader(["Rank", "Function Name", "Self (ms)", "Location"]);
329
+ const topN = Math.min(stats.length, 20);
330
+ for (let i = 0; i < topN; i++) {
331
+ const stat = stats[i];
332
+ const typeNameFormatted = formatTypeName(stat.functionName, 20);
333
+ const selfTimeMs = formatPaddedMillis(stat.selfTime, 15, 2);
334
+ const location = formatLocation(stat.callSite);
335
+ outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
41
336
  }
42
337
  };
338
+ const displayTableHeader = (columns) => {
339
+ const headerRow = [
340
+ columns[0].padEnd(4),
341
+ columns[1].padEnd(20),
342
+ columns[2].padEnd(15),
343
+ ...columns.slice(3)
344
+ ].join(" | ");
345
+ const separatorRow = [
346
+ "-".repeat(4),
347
+ "-".repeat(20),
348
+ "-".repeat(15),
349
+ ...columns.slice(3).map(col => "-".repeat(col.length))
350
+ ].join("-|-");
351
+ outputCapture.write(headerRow);
352
+ outputCapture.write(separatorRow);
353
+ };
354
+ const displayGroupedSummary = (functions) => {
355
+ displayTableHeader([
356
+ "Rank",
357
+ "Function Name",
358
+ "Total Self (ms)",
359
+ "Avg Self (ms)",
360
+ "Calls",
361
+ "Top Usage"
362
+ ]);
363
+ const topN = Math.min(functions.length, 20);
364
+ for (let i = 0; i < topN; i++) {
365
+ const stats = functions[i];
366
+ const typeNameFormatted = formatTypeName(stats.functionName, 20);
367
+ const totalTimeMs = formatPaddedMillis(stats.selfTime, 15, 2);
368
+ const avgTimeMs = formatPaddedMillis(stats.selfTime / Math.max(1, stats.count), // Avoid division by zero
369
+ 13, 2);
370
+ const calls = stats.count.toString().padStart(5);
371
+ const topUsage = stats.detailedCallSites[0] ?? {
372
+ path: "unknown",
373
+ pos: 0,
374
+ end: 0,
375
+ selfTime: 0
376
+ };
377
+ const topUsageTime = formatMillis(topUsage.selfTime, 2) + "ms";
378
+ const topUsageLocation = formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`);
379
+ outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
380
+ }
381
+ };
382
+ const formatTypeName = (typeName, maxLength) => {
383
+ typeName = typeName.replace(/\(\)$/, "");
384
+ if (typeName.length <= maxLength)
385
+ return typeName.padEnd(maxLength);
386
+ const charsToKeep = maxLength - 3; // "..."
387
+ const firstPart = Math.ceil(charsToKeep * 0.7);
388
+ const lastPart = charsToKeep - firstPart;
389
+ return (typeName.substring(0, firstPart) +
390
+ "..." +
391
+ (lastPart > 0 ? typeName.substring(typeName.length - lastPart) : "")).padEnd(maxLength);
392
+ };
393
+ const formatLocation = (location) => {
394
+ if (!location || location === "unknown" || !location.includes(":"))
395
+ return location || "unknown";
396
+ const parts = location.split(":");
397
+ if (parts.length < 2)
398
+ return basename(location); // Fallback for unexpected format
399
+ const filePath = parts.slice(0, -1).join(":"); // Handle paths with colons
400
+ const positionRange = parts[parts.length - 1];
401
+ // This function now expects TsServer.instance.getSourceFileOrThrow to handle file existence
402
+ // and getLineAndCharacterOfPosition to handle valid positions.
403
+ // Errors from these will propagate up.
404
+ const relativePath = relative(process.cwd(), filePath);
405
+ const [posStr] = positionRange.split("-");
406
+ const pos = parseInt(posStr, 10);
407
+ if (isNaN(pos)) {
408
+ // If pos is not a number, fallback to simpler formatting
409
+ return `${relativePath}:${positionRange}`;
410
+ }
411
+ const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
412
+ const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
413
+ return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
414
+ };
415
+ const findMostSpecificNodeInRange = (file, start, end) => {
416
+ const allNodes = getDescendants(file);
417
+ const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
418
+ if (nodesInRange.length === 0)
419
+ return undefined;
420
+ const leafNodes = nodesInRange.filter(node => !nodesInRange.some(other => other !== node && other.pos >= node.pos && other.end <= node.end));
421
+ return findNodeByPreference(leafNodes.length > 0 ? leafNodes : nodesInRange); // Fallback to nodesInRange if no clear leaf
422
+ };
423
+ const findNodeByPreference = (nodes) => {
424
+ if (nodes.length === 0)
425
+ return undefined;
426
+ const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
427
+ if (typeReference)
428
+ return typeReference;
429
+ const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
430
+ ts.isFunctionDeclaration(node) ||
431
+ ts.isClassDeclaration(node) ||
432
+ ts.isInterfaceDeclaration(node));
433
+ if (declaration)
434
+ return declaration;
435
+ const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
436
+ if (propertyAccess)
437
+ return propertyAccess;
438
+ const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
439
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
440
+ if (assignment)
441
+ return assignment;
442
+ const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
443
+ if (expression)
444
+ return expression;
445
+ return nodes.sort((a, b) => a.end - a.pos - (b.end - b.pos))[0]; // Smallest node as a fallback
446
+ };
447
+ const writeToCsv = (filePath, headers, rows) => {
448
+ const content = [
449
+ headers.join(","),
450
+ ...rows.map(row => row.map(escapeForCsv).join(","))
451
+ ].join("\n");
452
+ writeFile(filePath, content);
453
+ };
454
+ const escapeForCsv = (value) => {
455
+ if (value.includes(",") || value.includes('"') || value.includes("\n"))
456
+ return `"${value.replaceAll('"', '""')}"`;
457
+ return value;
458
+ };
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.1",
4
4
  "license": "MIT",
5
5
  "author": {
6
6
  "name": "David Blass",