@ark/attest 0.49.0 → 0.51.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -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) {
@@ -53,12 +53,9 @@ type snapProperty<expected, kind extends AssertionKind> = {
53
53
  unwrap: Unwrapper<expected>;
54
54
  };
55
55
  export type Unwrapper<expected = unknown> = (opts?: UnwrapOptions) => expected;
56
- 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";
57
57
  export type nonOverlappingSatisfiesMessage = typeof nonOverlappingSatisfiesMessage;
58
- type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage, {
59
- actual: expected;
60
- satisfies: satisfies;
61
- }> : unknown;
58
+ type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage> : unknown;
62
59
  export type comparableValueAssertion<expected, kind extends AssertionKind> = {
63
60
  snap: snapProperty<expected, kind>;
64
61
  equals: (value: expected) => nextAssertions<kind>;
@@ -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
  };
@@ -206,4 +210,4 @@ const formatTypeString = (typeString) => prettier
206
210
  })
207
211
  .slice(declarationPrefix.length)
208
212
  .trimEnd();
209
- 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";
package/out/cache/ts.js CHANGED
@@ -2,7 +2,7 @@ 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";
5
- import { dirname, join } from "node:path";
5
+ import { resolve, dirname, join } from "node:path";
6
6
  import ts from "typescript";
7
7
  import { getConfig } from "../config.js";
8
8
  export class TsServer {
@@ -36,12 +36,22 @@ export class TsServer {
36
36
  }
37
37
  getSourceFileOrThrow(path) {
38
38
  const tsPath = path.replaceAll("\\", "/");
39
- const file = this.virtualEnv.getSourceFile(tsPath);
40
- if (!file) {
41
- throwInternalError(`TypeScript was unable to resolve expected file at ${path}.\n
42
- Make sure it is included in your tsconfig.json.`);
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`);
43
44
  }
44
- return file;
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;
45
55
  }
46
56
  }
47
57
  export const nearestCallExpressionChild = (node, position) => {
@@ -100,7 +110,8 @@ const instantiateTsconfigFromPath = (path) => {
100
110
  throwConfigParseError(result.error);
101
111
  const rawConfig = result.config;
102
112
  rawConfig.compilerOptions = Object.assign(rawConfig.compilerOptions ?? {}, arkConfig.compilerOptions);
103
- const instantiatedConfig = ts.parseJsonConfigFileContent(rawConfig, ts.sys, dirname(path), {}, path);
113
+ const configPath = resolve(path);
114
+ const instantiatedConfig = ts.parseJsonConfigFileContent(rawConfig, ts.sys, dirname(configPath), {}, configPath);
104
115
  if (instantiatedConfig.errors.length > 0)
105
116
  throwConfigInstantiationError(instantiatedConfig);
106
117
  return instantiatedConfig;
package/out/cli/cli.js CHANGED
@@ -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}"`);
package/out/cli/trace.js CHANGED
@@ -16,54 +16,148 @@ const outputCapture = (() => {
16
16
  buffer.push(text);
17
17
  },
18
18
  getBuffer: () => buffer.join("\n"),
19
+ getLines: () => [...buffer],
19
20
  clear: () => {
20
21
  buffer = [];
21
22
  }
22
23
  };
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
+ }
24
113
  export const trace = async (args) => {
25
114
  const packageDir = resolve(args[0] ?? process.cwd());
26
115
  const config = getConfig();
27
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.
28
119
  console.error(`attest trace must be run from a directory with a tsconfig.json file`);
29
120
  process.exit(1);
30
121
  }
31
122
  const traceDir = resolve(config.cacheDir, "trace");
32
123
  ensureDir(traceDir);
33
- let tracingOutput = "";
34
124
  outputCapture.clear();
35
- outputCapture.write(`⏳ Gathering type trace data for ${packageDir}...`);
36
- tracingOutput = generateTraceData(traceDir, config.tsconfig, packageDir);
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);
37
129
  const traceFile = join(traceDir, "trace.json");
38
130
  if (!existsSync(traceFile)) {
39
- outputCapture.write(`❌ No trace data found (expected a file at ${join(traceDir, "trace.json")})`);
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());
40
134
  return;
41
135
  }
136
+ // This message will be followed by the progress bar on the next line
42
137
  outputCapture.write(`⏳ Analyzing type trace data for ${packageDir}...`);
43
- analyzeTypeInstantiations(traceDir);
44
- // Write summary file containing our messages followed by compiler output
45
- // This ensures the initial message comes first in the file
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");
46
150
  const summaryPath = join(traceDir, "summary.txt");
47
- const summaryContent = outputCapture.getBuffer().split("\n")[0] +
48
- "\n" +
49
- tracingOutput +
50
- "\n" +
51
- outputCapture.getBuffer().split("\n").slice(1).join("\n");
52
151
  writeFile(summaryPath, summaryContent);
53
152
  };
54
153
  const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
55
154
  try {
56
- // Capture the output instead of just displaying it
57
155
  const output = getShellOutput(`${baseDiagnosticTscCmd} --project ${tsconfigPath} --generateTrace ${traceDir}`, { cwd: packageDir });
58
- // Display the output to the console as before
59
- process.stdout.write(output);
156
+ process.stdout.write(output); // Display tsc output directly
60
157
  return output;
61
158
  }
62
- catch (_) {
63
- // even if tsc returns a non-zero exit code,
64
- // we can still proceed as long as the trace.json
65
- // file was generated
66
- const e = _;
159
+ catch (error) {
160
+ const e = error;
67
161
  const output = e.stdout ?? "";
68
162
  const errorOutput = e.stderr ?? "";
69
163
  process.stdout.write(output);
@@ -73,10 +167,10 @@ const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
73
167
  };
74
168
  const initializeAnalysisContext = (traceDir) => {
75
169
  const tsServer = TsServer.instance;
76
- // Load trace data
77
170
  const tracePath = join(traceDir, "trace.json");
78
- if (!existsSync(tracePath))
79
- throw new Error(`Expected a trace file at ${tracePath}`);
171
+ if (!existsSync(tracePath)) {
172
+ throw new Error(`Critical: Expected a trace file at ${tracePath}, but it was not found during context initialization.`);
173
+ }
80
174
  const traceEntries = readJson(tracePath);
81
175
  return {
82
176
  traceDir,
@@ -90,147 +184,111 @@ const initializeAnalysisContext = (traceDir) => {
90
184
  };
91
185
  };
92
186
  const filterDurationEntries = (ctx) => {
93
- ctx.durationEntries = ctx.traceEntries.filter(entry => entry.ph === "X" &&
94
- entry.dur !== undefined &&
95
- entry.args.path &&
96
- entry.args.pos &&
97
- entry.args.end);
98
- outputCapture.write(`Found ${ctx.durationEntries.length} traces with duration information`);
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.`);
99
198
  };
100
199
  const processDurationEntry = (entry, ctx) => {
101
- try {
102
- const sourceFile = ctx.tsServer.getSourceFileOrThrow(entry.args.path);
103
- const pos = entry.args.pos;
104
- const end = entry.args.end;
105
- // First try to find any call expression in the range
106
- const callExpr = findCallExpressionInRange(sourceFile, pos, end);
107
- if (callExpr)
108
- processCallExpression(callExpr, entry, pos, end, ctx);
109
- else {
110
- // Try to process as another type of node
111
- processNonCallNode(sourceFile, entry, pos, end, 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
+ };
112
225
  }
113
226
  }
114
- catch (e) {
115
- handleProcessingError(e, entry);
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
238
+ });
239
+ }
240
+ else {
241
+ throw new Error(`Failed to identify a processable AST node for duration entry (name: ${entry.name}, path: ${entryPath}, pos: ${entryPos}-${entryEnd}).`);
116
242
  }
117
243
  };
118
- /**
119
- * Find any call expression within the given range, with preference for method calls
120
- */
121
244
  const findCallExpressionInRange = (file, start, end) => {
122
- // First try the default nearest bounding call expression
123
245
  const boundingCall = nearestBoundingCallExpression(file, start);
124
- if (boundingCall)
246
+ if (boundingCall && boundingCall.pos >= start && boundingCall.end <= end)
125
247
  return boundingCall;
126
- // If that fails, search for any call expressions in the range
127
248
  const allNodes = getDescendants(file);
128
249
  const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
129
- // Find all call expressions in the range
130
250
  const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
131
251
  if (callExpressions.length === 0)
132
252
  return undefined;
133
- // Prioritize method calls (e.g. x.and(), x.or())
134
253
  const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
135
- // Return a method call if found, otherwise the first call expression
136
254
  return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
137
255
  };
138
- /**
139
- * Extract function or method name from a call expression, normalizing the format
140
- */
141
256
  const extractFunctionName = (callExpr) => {
142
- // For method calls like x.and()
143
257
  if (ts.isPropertyAccessExpression(callExpr.expression))
144
258
  return callExpr.expression.name.getText();
145
- // For direct function calls like type() or scope()
146
259
  if (ts.isIdentifier(callExpr.expression))
147
260
  return callExpr.expression.getText();
148
- // For other expressions, try to get a reasonable name
149
- return "anonymous";
150
- };
151
- const processCallExpression = (callExpr, entry, pos, end, ctx) => {
152
- // Simply use the function name for grouping
153
- const functionName = extractFunctionName(callExpr);
154
- // Use the function name for both ID and display name
155
- // This will ensure all calls to the same function are grouped together
156
- const typeId = `function-${functionName}`;
157
- const callSite = `${entry.args.path}:${pos}-${end}`;
158
- ctx.callRanges.push({
159
- id: `${entry.ts}-${pos}-${end}`,
160
- typeId,
161
- functionName,
162
- callSite,
163
- startTime: entry.ts,
164
- endTime: entry.ts + (entry.dur || 0),
165
- duration: entry.dur || 0,
166
- children: [],
167
- selfTime: entry.dur || 0
168
- });
169
- };
170
- const processNonCallNode = (sourceFile, entry, pos, end, ctx) => {
171
- const relevantNode = findMostSpecificNodeInRange(sourceFile, pos, end);
172
- if (!relevantNode)
173
- return;
174
- const nodeType = getStringifiableType(relevantNode);
175
- const nodeKind = ts.SyntaxKind[relevantNode.kind];
176
- const typeName = `${nodeKind}: ${nodeType.toString().substring(0, 25)}`;
177
- const typeId = `node-${relevantNode.kind}-${nodeType.id || nodeType.toString().substring(0, 20)}`;
178
- const callSite = `${entry.args.path}:${pos}-${end}`;
179
- ctx.callRanges.push({
180
- id: `${entry.ts}-${pos}-${end}`,
181
- typeId,
182
- functionName: typeName,
183
- callSite,
184
- startTime: entry.ts,
185
- endTime: entry.ts + (entry.dur || 0),
186
- duration: entry.dur || 0,
187
- children: [],
188
- selfTime: entry.dur || 0
189
- });
190
- };
191
- const handleProcessingError = (e, entry) => {
192
- if (!(e instanceof Error))
193
- throw e;
194
- // Silent failure for common case of not finding a call expression
195
- if (e.message?.includes("Unable to find bounding call expression"))
196
- return;
197
- console.warn(`Error processing entry at ${entry.args.path}:${entry.args.pos}: ${e.message}`);
261
+ return "anonymousFunction";
198
262
  };
199
263
  const buildCallTree = (ctx) => {
200
- // Sort by start time for nesting analysis
264
+ // This message goes to outputCapture for the summary file
265
+ outputCapture.write(`Building call tree from ${ctx.callRanges.length} ranges...`);
201
266
  ctx.callRanges.sort((a, b) => a.startTime - b.startTime);
202
267
  const activeCallStack = [];
203
268
  for (const call of ctx.callRanges) {
204
- popFinishedCalls(call, activeCallStack);
205
- assignToParentOrRoot(call, activeCallStack, ctx);
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
+ }
206
278
  activeCallStack.push(call);
207
279
  }
208
- };
209
- const popFinishedCalls = (call, activeCallStack) => {
210
- while (activeCallStack.length > 0 &&
211
- activeCallStack[activeCallStack.length - 1].endTime < call.startTime)
212
- activeCallStack.pop();
213
- };
214
- const assignToParentOrRoot = (call, activeCallStack, ctx) => {
215
- if (activeCallStack.length === 0) {
216
- // This is a root call
217
- ctx.rootCalls.push(call);
218
- }
219
- else {
220
- // This call is nested inside the current active call
221
- const parent = activeCallStack[activeCallStack.length - 1];
222
- parent.children.push(call);
223
- }
280
+ outputCapture.write(`Call tree built with ${ctx.rootCalls.length} root calls.`);
224
281
  };
225
282
  const calculateSelfTimes = (call) => {
226
283
  let childrenTime = 0;
227
284
  for (const child of call.children)
228
285
  childrenTime += calculateSelfTimes(child);
229
286
  call.selfTime = call.duration - childrenTime;
287
+ if (call.selfTime < 0)
288
+ call.selfTime = 0;
230
289
  return call.duration;
231
290
  };
232
291
  const collectFunctionStats = (call, ctx) => {
233
- // Initialize stats object if needed
234
292
  if (!ctx.functionStats[call.typeId]) {
235
293
  ctx.functionStats[call.typeId] = {
236
294
  typeId: call.typeId,
@@ -243,103 +301,120 @@ const collectFunctionStats = (call, ctx) => {
243
301
  };
244
302
  }
245
303
  const stats = ctx.functionStats[call.typeId];
246
- // Track detailed call site information
247
- addCallSiteToStats(call, stats);
248
- // Update aggregate metrics
249
- stats.totalTime += call.duration;
250
- stats.selfTime += call.selfTime;
251
- stats.count++;
252
- // Process children
253
- for (const child of call.children)
254
- collectFunctionStats(child, ctx);
255
- };
256
- const addCallSiteToStats = (call, stats) => {
257
304
  const [filePath, positionRange] = call.callSite.split(":");
305
+ if (!filePath || !positionRange)
306
+ throw new Error(`Invalid callSite format: ${call.callSite}`);
258
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
+ }
259
313
  stats.detailedCallSites.push({
260
314
  path: filePath,
261
- pos: parseInt(posStr),
262
- end: parseInt(endStr),
315
+ pos,
316
+ end,
263
317
  selfTime: call.selfTime
264
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);
265
324
  };
266
325
  const sortAndRankFunctions = (ctx) => {
267
- // Sort each function's call sites by self-time
326
+ outputCapture.write("Sorting and ranking functions...");
268
327
  for (const stats of Object.values(ctx.functionStats))
269
328
  stats.detailedCallSites.sort((a, b) => b.selfTime - a.selfTime);
270
- // Sort functions by self-time
271
329
  ctx.allFunctions = Object.values(ctx.functionStats).sort((a, b) => b.selfTime - a.selfTime);
272
330
  };
273
331
  const analyzeTypeInstantiations = (traceDir) => {
274
- // Initialize the analysis context
275
332
  const ctx = initializeAnalysisContext(traceDir);
276
- // Filter entries with duration information
277
- filterDurationEntries(ctx);
278
- // Process each duration entry to extract call ranges
279
- for (const entry of ctx.durationEntries)
280
- processDurationEntry(entry, ctx);
281
- // Build call tree from ranges
282
- buildCallTree(ctx);
283
- // Calculate self-time for each call
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...");
284
360
  for (const root of ctx.rootCalls)
285
361
  calculateSelfTimes(root);
286
- // Collect statistics by view type
287
- const ungroupedStats = collectUngroupedStats(ctx);
288
- for (const call of ctx.rootCalls)
289
- collectFunctionStats(call, ctx);
290
- // Sort and rank functions
291
- sortAndRankFunctions(ctx);
292
- // Display summaries to console
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
293
367
  outputCapture.write("\n📊 Performance Analysis - Top Individual Calls:\n");
294
- displayIndividualSummary(ungroupedStats);
368
+ displayIndividualSummary(ungroupedStats); // Uses outputCapture
295
369
  outputCapture.write("\n📊 Performance Analysis - Functions by Self Time:\n");
296
- displayGroupedSummary(ctx.allFunctions);
297
- // Write CSV reports
370
+ displayGroupedSummary(ctx.allFunctions); // Uses outputCapture
298
371
  const rangesCsvPath = join(traceDir, "ranges.csv");
299
372
  const namesCsvPath = join(traceDir, "names.csv");
300
- const summaryPath = join(traceDir, "summary.txt");
301
- // Export individual ranges to CSV
302
- writeToCsv(rangesCsvPath, ["Function Name", "Self (ms)", "Duration (ms)", "Location"], ungroupedStats.map(stat => [
303
- stat.functionName,
304
- (stat.selfTime / 1000).toFixed(3),
305
- (stat.duration / 1000).toFixed(3),
306
- formatLocation(stat.callSite)
307
- ]));
308
- // Export grouped functions to CSV
309
- writeToCsv(namesCsvPath, [
310
- "Function Name",
311
- "Total Self (ms)",
312
- "Avg Self (ms)",
313
- "Call Count",
314
- "Top Location",
315
- "Top Self (ms)"
316
- ], ctx.allFunctions.map(stats => {
317
- const topUsage = stats.detailedCallSites[0] || {
318
- path: "unknown",
319
- pos: 0,
320
- end: 0,
321
- selfTime: 0
322
- };
323
- return [
324
- stats.functionName,
325
- (stats.selfTime / 1000).toFixed(3),
326
- (stats.selfTime / stats.count / 1000).toFixed(3),
327
- stats.count.toString(),
328
- formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`),
329
- (topUsage.selfTime / 1000).toFixed(3)
330
- ];
331
- }));
332
- outputCapture.write(`\n✅ Analysis complete! Results exported to:\n` +
333
- ` - ${rangesCsvPath} (individual calls)\n` +
334
- ` - ${namesCsvPath} (grouped by function name)\n` +
335
- ` - ${summaryPath} (complete analysis report)`);
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
+ }
336
414
  };
337
- /**
338
- * Collect statistics for individual (ungrouped) calls
339
- */
340
415
  const collectUngroupedStats = (ctx) => {
416
+ outputCapture.write("Collecting and sorting ungrouped call statistics...");
341
417
  const ungroupedStats = [];
342
- // Flatten the call tree into individual entries
343
418
  const flattenCallTree = (call) => {
344
419
  ungroupedStats.push({
345
420
  typeId: call.typeId,
@@ -353,46 +428,35 @@ const collectUngroupedStats = (ctx) => {
353
428
  };
354
429
  for (const root of ctx.rootCalls)
355
430
  flattenCallTree(root);
356
- // Sort by self time in descending order
357
431
  return ungroupedStats.sort((a, b) => b.selfTime - a.selfTime);
358
432
  };
359
- /**
360
- * Display a summary of individual calls
361
- */
362
433
  const displayIndividualSummary = (stats) => {
363
434
  displayTableHeader(["Rank", "Function Name", "Self (ms)", "Location"]);
364
- const top20 = stats.slice(0, 20);
365
- for (const [index, stat] of top20.entries()) {
435
+ const topN = Math.min(stats.length, 20);
436
+ for (let i = 0; i < topN; i++) {
437
+ const stat = stats[i];
366
438
  const typeNameFormatted = formatTypeName(stat.functionName, 20);
367
- const selfTimeMs = (stat.selfTime / 1000).toFixed(2).padStart(15);
439
+ const selfTimeMs = formatPaddedMillis(stat.selfTime, 15, 2);
368
440
  const location = formatLocation(stat.callSite);
369
- outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
441
+ outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
370
442
  }
371
443
  };
372
- /**
373
- * Display a summary table header with aligned columns
374
- */
375
444
  const displayTableHeader = (columns) => {
376
- // Create header row with standard column widths
377
445
  const headerRow = [
378
446
  columns[0].padEnd(4),
379
447
  columns[1].padEnd(20),
380
448
  columns[2].padEnd(15),
381
449
  ...columns.slice(3)
382
450
  ].join(" | ");
383
- // Create separator line matching the header column widths
384
451
  const separatorRow = [
385
- "----",
386
- "--------------------",
387
- "---------------",
452
+ "-".repeat(4),
453
+ "-".repeat(20),
454
+ "-".repeat(15),
388
455
  ...columns.slice(3).map(col => "-".repeat(col.length))
389
456
  ].join("-|-");
390
457
  outputCapture.write(headerRow);
391
458
  outputCapture.write(separatorRow);
392
459
  };
393
- /**
394
- * Display a combined summary of grouped functions showing both total and average times
395
- */
396
460
  const displayGroupedSummary = (functions) => {
397
461
  displayTableHeader([
398
462
  "Rank",
@@ -402,109 +466,84 @@ const displayGroupedSummary = (functions) => {
402
466
  "Calls",
403
467
  "Top Usage"
404
468
  ]);
405
- for (const [index, stats] of functions.slice(0, 20).entries()) {
469
+ const topN = Math.min(functions.length, 20);
470
+ for (let i = 0; i < topN; i++) {
471
+ const stats = functions[i];
406
472
  const typeNameFormatted = formatTypeName(stats.functionName, 20);
407
- const totalTimeMs = (stats.selfTime / 1000).toFixed(2).padStart(15);
408
- const avgTimeMs = (stats.selfTime / stats.count / 1000)
409
- .toFixed(2)
410
- .padStart(13);
473
+ const totalTimeMs = formatPaddedMillis(stats.selfTime, 15, 2);
474
+ const avgTimeMs = formatPaddedMillis(stats.selfTime / Math.max(1, stats.count), 13, 2);
411
475
  const calls = stats.count.toString().padStart(5);
412
- // Get details about top usage site
413
- const topUsage = stats.detailedCallSites[0] || {
476
+ const topUsage = stats.detailedCallSites[0] ?? {
414
477
  path: "unknown",
415
478
  pos: 0,
416
479
  end: 0,
417
480
  selfTime: 0
418
481
  };
419
- const topUsageTime = (topUsage.selfTime / 1000).toFixed(2) + "ms";
482
+ const topUsageTime = formatMillis(topUsage.selfTime, 2) + "ms";
420
483
  const topUsageLocation = formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`);
421
- outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
484
+ outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
422
485
  }
423
486
  };
424
- /**
425
- * Format a type name for display, ensuring the most identifiable parts are preserved
426
- */
427
487
  const formatTypeName = (typeName, maxLength) => {
428
- // Remove any () from the name
429
488
  typeName = typeName.replace(/\(\)$/, "");
430
489
  if (typeName.length <= maxLength)
431
490
  return typeName.padEnd(maxLength);
432
- // Default truncation strategy
433
- const charsToKeep = maxLength - 3; // Account for "..."
434
- const firstPart = Math.ceil(charsToKeep * 0.7); // Keep more of the start
491
+ const charsToKeep = maxLength - 3;
492
+ const firstPart = Math.ceil(charsToKeep * 0.7);
435
493
  const lastPart = charsToKeep - firstPart;
436
494
  return (typeName.substring(0, firstPart) +
437
495
  "..." +
438
496
  (lastPart > 0 ? typeName.substring(typeName.length - lastPart) : "")).padEnd(maxLength);
439
497
  };
440
- /**
441
- * Format a file location to be more readable with relative path and line:char
442
- */
443
498
  const formatLocation = (location) => {
444
- if (!location || location === "unknown")
445
- return "unknown";
446
- // Extract file path and position range
447
- const [filePath, positionRange] = location.split(":");
448
- try {
449
- const relativePath = relative(process.cwd(), filePath);
450
- // Get position values
451
- const [posStr] = positionRange.split("-");
452
- const pos = parseInt(posStr);
453
- // Get the source file to convert position to line:character
454
- const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
455
- const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
456
- // Format as relative-path:line:char
457
- return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
458
- }
459
- catch {
460
- // If any part fails, return the basic filename as fallback
461
- return basename(filePath) + (positionRange ? `:${positionRange}` : "");
462
- }
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}`;
463
514
  };
464
- /**
465
- * Finds the most specific non-trivial node within the given range
466
- */
467
515
  const findMostSpecificNodeInRange = (file, start, end) => {
468
- // Get all descendants in the file
469
516
  const allNodes = getDescendants(file);
470
- // Filter nodes that are completely contained within our range
471
517
  const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
472
- // Find most specific nodes (leaf nodes)
518
+ if (nodesInRange.length === 0)
519
+ return undefined;
473
520
  const leafNodes = nodesInRange.filter(node => !nodesInRange.some(other => other !== node && other.pos >= node.pos && other.end <= node.end));
474
- // Find nodes in order of preference
475
- return findNodeByPreference(leafNodes);
521
+ return findNodeByPreference(leafNodes.length > 0 ? leafNodes : nodesInRange);
476
522
  };
477
523
  const findNodeByPreference = (nodes) => {
478
- // 1. Type references
524
+ if (nodes.length === 0)
525
+ return undefined;
479
526
  const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
480
527
  if (typeReference)
481
528
  return typeReference;
482
- // 2. Declarations
483
529
  const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
484
530
  ts.isFunctionDeclaration(node) ||
485
531
  ts.isClassDeclaration(node) ||
486
532
  ts.isInterfaceDeclaration(node));
487
533
  if (declaration)
488
534
  return declaration;
489
- // 3. Property accesses
490
535
  const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
491
536
  if (propertyAccess)
492
537
  return propertyAccess;
493
- // 4. Assignments
494
538
  const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
495
539
  node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
496
540
  if (assignment)
497
541
  return assignment;
498
- // 5. Expressions
499
542
  const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
500
543
  if (expression)
501
544
  return expression;
502
- // Default: first node
503
- return nodes[0];
545
+ return nodes.sort((a, b) => a.end - a.pos - (b.end - b.pos))[0];
504
546
  };
505
- /**
506
- * Write data to a CSV file
507
- */
508
547
  const writeToCsv = (filePath, headers, rows) => {
509
548
  const content = [
510
549
  headers.join(","),
@@ -512,14 +551,8 @@ const writeToCsv = (filePath, headers, rows) => {
512
551
  ].join("\n");
513
552
  writeFile(filePath, content);
514
553
  };
515
- /**
516
- * Escape string for CSV format
517
- */
518
554
  const escapeForCsv = (value) => {
519
- if (value.includes(",") || value.includes('"') || value.includes("\n")) {
520
- // If the value contains commas, double quotes, or newlines, wrap it in quotes
521
- // and escape any double quotes by doubling them
555
+ if (value.includes(",") || value.includes('"') || value.includes("\n"))
522
556
  return `"${value.replaceAll('"', '""')}"`;
523
- }
524
557
  return value;
525
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,
@@ -111,14 +111,39 @@ export const findAttestTypeScriptVersions = () => {
111
111
  if (!existsSync(nodeModulesPath) ||
112
112
  !statSync(nodeModulesPath).isDirectory())
113
113
  continue;
114
- try {
115
- // Check for regular typescript or typescript-* directories
116
- const dirNames = readdirSync(nodeModulesPath);
117
- for (const dirName of dirNames) {
118
- // Skip node_modules/@* directories - we'll handle them below
119
- if (dirName.startsWith("@"))
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("@"))
119
+ continue;
120
+ const fullPath = join(nodeModulesPath, dirName);
121
+ if (!statSync(fullPath).isDirectory())
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-"))
120
145
  continue;
121
- const fullPath = join(nodeModulesPath, dirName);
146
+ const fullPath = join(arkDir, dirName);
122
147
  if (!statSync(fullPath).isDirectory())
123
148
  continue;
124
149
  const alias = getDirAlias(dirName);
@@ -137,36 +162,6 @@ export const findAttestTypeScriptVersions = () => {
137
162
  });
138
163
  }
139
164
  }
140
- // Check for @ark/attest-ts-* directories
141
- const arkDir = join(nodeModulesPath, "@ark");
142
- if (existsSync(arkDir) && statSync(arkDir).isDirectory()) {
143
- const arkDirs = readdirSync(arkDir);
144
- for (const dirName of arkDirs) {
145
- if (!dirName.startsWith("attest-ts-"))
146
- continue;
147
- const fullPath = join(arkDir, dirName);
148
- if (!statSync(fullPath).isDirectory())
149
- continue;
150
- const alias = getDirAlias(dirName);
151
- if (!alias)
152
- continue;
153
- // Skip if we already found this alias in a closer package
154
- if (foundVersionAliases.has(alias))
155
- continue;
156
- const version = getTsVersion(fullPath);
157
- if (version) {
158
- foundVersionAliases.add(alias);
159
- versions.push({
160
- alias,
161
- version,
162
- path: fullPath
163
- });
164
- }
165
- }
166
- }
167
- }
168
- catch (err) {
169
- console.warn(`Warning: Error scanning ${nodeModulesPath}: ${err}`);
170
165
  }
171
166
  }
172
167
  return versions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.49.0",
3
+ "version": "0.51.0",
4
4
  "license": "MIT",
5
5
  "author": {
6
6
  "name": "David Blass",
@@ -32,16 +32,16 @@
32
32
  "attest": "out/cli/cli.js"
33
33
  },
34
34
  "dependencies": {
35
- "@prettier/sync": "0.5.5",
35
+ "@prettier/sync": "0.6.1",
36
36
  "@typescript/analyze-trace": "0.10.1",
37
37
  "@typescript/vfs": "1.6.1",
38
- "prettier": "3.5.3",
39
- "@ark/fs": "0.49.0",
40
- "@ark/util": "0.49.0",
41
- "arktype": "2.1.22"
38
+ "prettier": "3.6.2",
39
+ "@ark/fs": "0.51.0",
40
+ "arktype": "2.1.23",
41
+ "@ark/util": "0.51.0"
42
42
  },
43
43
  "devDependencies": {
44
- "typescript": "5.8.2"
44
+ "typescript": "5.9.3"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "typescript": "*"