@ark/attest 0.48.1 → 0.49.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,8 +7,6 @@ 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
- }
12
10
  export type AssertFn = (expected: unknown, actual: unknown, ctx: AssertionContext) => void;
13
11
  export type MappedTypeAssertionResult = {
14
12
  actual: unknown;
@@ -5,8 +5,6 @@ export const throwAssertionError = ({ stack, ...errorArgs }) => {
5
5
  e.stack = stack;
6
6
  throw e;
7
7
  };
8
- export class MissingSnapshotError extends Error {
9
- }
10
8
  export class TypeAssertionMapping {
11
9
  fn;
12
10
  constructor(fn) {
@@ -53,9 +53,12 @@ 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 = "This type has no overlap with your satisfies constraint";
56
+ export declare const nonOverlappingSatisfiesMessage = "The type of your actual value and expected satisfies constraint have no overlap";
57
57
  export type nonOverlappingSatisfiesMessage = typeof nonOverlappingSatisfiesMessage;
58
- type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage> : unknown;
58
+ type validateExpectedOverlaps<expected, satisfies> = isDisjoint<expected, satisfies> extends true ? ErrorType<nonOverlappingSatisfiesMessage, {
59
+ actual: expected;
60
+ satisfies: satisfies;
61
+ }> : unknown;
59
62
  export type comparableValueAssertion<expected, kind extends AssertionKind> = {
60
63
  snap: snapProperty<expected, kind>;
61
64
  equals: (value: expected) => nextAssertions<kind>;
@@ -1,4 +1,4 @@
1
- import { caller, positionToString } from "@ark/fs";
1
+ import { caller } 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 { MissingSnapshotError, TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
10
+ import { TypeAssertionMapping, assertEqualOrMatching, assertEquals, assertSatisfies, callAssertedFunction, getThrownMessage, throwAssertionError } from "./assertions.js";
11
11
  export class ChainableAssertions {
12
12
  ctx;
13
13
  constructor(ctx) {
@@ -68,13 +68,9 @@ 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
- }
75
71
  if (this.snapRequiresUpdate(expectedSerialized)) {
76
72
  const snapshotArgs = {
77
- position,
73
+ position: caller(),
78
74
  serializedValue: this.serializedActual,
79
75
  snapFunctionName: snapName
80
76
  };
@@ -210,4 +206,4 @@ const formatTypeString = (typeString) => prettier
210
206
  })
211
207
  .slice(declarationPrefix.length)
212
208
  .trimEnd();
213
- export const nonOverlappingSatisfiesMessage = "This type has no overlap with your satisfies constraint";
209
+ export const nonOverlappingSatisfiesMessage = "The type of your actual value and expected satisfies constraint have no overlap";
package/out/cache/ts.js CHANGED
@@ -36,22 +36,12 @@ export class TsServer {
36
36
  }
37
37
  getSourceFileOrThrow(path) {
38
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`);
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.`);
44
43
  }
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;
44
+ return file;
55
45
  }
56
46
  }
57
47
  export const nearestCallExpressionChild = (node, position) => {
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,20 +16,11 @@ const outputCapture = (() => {
16
16
  buffer.push(text);
17
17
  },
18
18
  getBuffer: () => buffer.join("\n"),
19
- getLines: () => [...buffer],
20
19
  clear: () => {
21
20
  buffer = [];
22
21
  }
23
22
  };
24
23
  })();
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
24
  export const trace = async (args) => {
34
25
  const packageDir = resolve(args[0] ?? process.cwd());
35
26
  const config = getConfig();
@@ -39,43 +30,40 @@ export const trace = async (args) => {
39
30
  }
40
31
  const traceDir = resolve(config.cacheDir, "trace");
41
32
  ensureDir(traceDir);
33
+ let tracingOutput = "";
42
34
  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);
35
+ outputCapture.write(`⏳ Gathering type trace data for ${packageDir}...`);
36
+ tracingOutput = generateTraceData(traceDir, config.tsconfig, packageDir);
47
37
  const traceFile = join(traceDir, "trace.json");
48
38
  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());
39
+ outputCapture.write(`❌ No trace data found (expected a file at ${join(traceDir, "trace.json")})`);
53
40
  return;
54
41
  }
55
42
  outputCapture.write(`⏳ Analyzing type trace data for ${packageDir}...`);
56
43
  analyzeTypeInstantiations(traceDir);
57
- const analysisMessages = outputCapture
58
- .getLines()
59
- .slice(initialMessages.length);
60
- const summaryContent = [
61
- ...initialMessages,
62
- tracingOutput,
63
- ...analysisMessages
64
- ].join("\n");
44
+ // Write summary file containing our messages followed by compiler output
45
+ // This ensures the initial message comes first in the file
65
46
  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");
66
52
  writeFile(summaryPath, summaryContent);
67
53
  };
68
54
  const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
69
55
  try {
56
+ // Capture the output instead of just displaying it
70
57
  const output = getShellOutput(`${baseDiagnosticTscCmd} --project ${tsconfigPath} --generateTrace ${traceDir}`, { cwd: packageDir });
58
+ // Display the output to the console as before
71
59
  process.stdout.write(output);
72
60
  return output;
73
61
  }
74
- catch (error) {
62
+ catch (_) {
75
63
  // even if tsc returns a non-zero exit code,
76
64
  // 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;
65
+ // file was generated
66
+ const e = _;
79
67
  const output = e.stdout ?? "";
80
68
  const errorOutput = e.stderr ?? "";
81
69
  process.stdout.write(output);
@@ -85,13 +73,11 @@ const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
85
73
  };
86
74
  const initializeAnalysisContext = (traceDir) => {
87
75
  const tsServer = TsServer.instance;
76
+ // Load trace data
88
77
  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[]
78
+ if (!existsSync(tracePath))
79
+ throw new Error(`Expected a trace file at ${tracePath}`);
80
+ const traceEntries = readJson(tracePath);
95
81
  return {
96
82
  traceDir,
97
83
  tsServer,
@@ -104,115 +90,147 @@ const initializeAnalysisContext = (traceDir) => {
104
90
  };
105
91
  };
106
92
  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.`);
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`);
117
99
  };
118
100
  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
- };
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);
146
112
  }
147
113
  }
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
159
- });
160
- }
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.`);
114
+ catch (e) {
115
+ handleProcessingError(e, entry);
165
116
  }
166
117
  };
118
+ /**
119
+ * Find any call expression within the given range, with preference for method calls
120
+ */
167
121
  const findCallExpressionInRange = (file, start, end) => {
122
+ // First try the default nearest bounding call expression
168
123
  const boundingCall = nearestBoundingCallExpression(file, start);
169
- if (boundingCall && boundingCall.pos >= start && boundingCall.end <= end)
124
+ if (boundingCall)
170
125
  return boundingCall;
126
+ // If that fails, search for any call expressions in the range
171
127
  const allNodes = getDescendants(file);
172
128
  const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
129
+ // Find all call expressions in the range
173
130
  const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
174
131
  if (callExpressions.length === 0)
175
132
  return undefined;
133
+ // Prioritize method calls (e.g. x.and(), x.or())
176
134
  const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
135
+ // Return a method call if found, otherwise the first call expression
177
136
  return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
178
137
  };
138
+ /**
139
+ * Extract function or method name from a call expression, normalizing the format
140
+ */
179
141
  const extractFunctionName = (callExpr) => {
142
+ // For method calls like x.and()
180
143
  if (ts.isPropertyAccessExpression(callExpr.expression))
181
144
  return callExpr.expression.name.getText();
145
+ // For direct function calls like type() or scope()
182
146
  if (ts.isIdentifier(callExpr.expression))
183
147
  return callExpr.expression.getText();
184
- return "anonymousFunction"; // More specific than just "anonymous"
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}`);
185
198
  };
186
199
  const buildCallTree = (ctx) => {
200
+ // Sort by start time for nesting analysis
187
201
  ctx.callRanges.sort((a, b) => a.startTime - b.startTime);
188
202
  const activeCallStack = [];
189
203
  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
- }
204
+ popFinishedCalls(call, activeCallStack);
205
+ assignToParentOrRoot(call, activeCallStack, ctx);
199
206
  activeCallStack.push(call);
200
207
  }
201
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
+ }
224
+ };
202
225
  const calculateSelfTimes = (call) => {
203
226
  let childrenTime = 0;
204
227
  for (const child of call.children)
205
228
  childrenTime += calculateSelfTimes(child);
206
229
  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
230
  return call.duration;
214
231
  };
215
232
  const collectFunctionStats = (call, ctx) => {
233
+ // Initialize stats object if needed
216
234
  if (!ctx.functionStats[call.typeId]) {
217
235
  ctx.functionStats[call.typeId] = {
218
236
  typeId: call.typeId,
@@ -220,65 +238,74 @@ const collectFunctionStats = (call, ctx) => {
220
238
  totalTime: 0,
221
239
  selfTime: 0,
222
240
  count: 0,
223
- firstLocation: call.callSite, // Should always be present
241
+ firstLocation: call.callSite,
224
242
  detailedCallSites: []
225
243
  };
226
244
  }
227
245
  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) => {
228
257
  const [filePath, positionRange] = call.callSite.split(":");
229
- if (!filePath || !positionRange)
230
- throw new Error(`Invalid callSite format: ${call.callSite}`);
231
258
  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
259
  stats.detailedCallSites.push({
238
260
  path: filePath,
239
- pos,
240
- end,
261
+ pos: parseInt(posStr),
262
+ end: parseInt(endStr),
241
263
  selfTime: call.selfTime
242
264
  });
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
265
  };
249
266
  const sortAndRankFunctions = (ctx) => {
267
+ // Sort each function's call sites by self-time
250
268
  for (const stats of Object.values(ctx.functionStats))
251
269
  stats.detailedCallSites.sort((a, b) => b.selfTime - a.selfTime);
270
+ // Sort functions by self-time
252
271
  ctx.allFunctions = Object.values(ctx.functionStats).sort((a, b) => b.selfTime - a.selfTime);
253
272
  };
254
273
  const analyzeTypeInstantiations = (traceDir) => {
274
+ // Initialize the analysis context
255
275
  const ctx = initializeAnalysisContext(traceDir);
276
+ // Filter entries with duration information
256
277
  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).
278
+ // Process each duration entry to extract call ranges
279
+ for (const entry of ctx.durationEntries)
260
280
  processDurationEntry(entry, ctx);
261
- }
281
+ // Build call tree from ranges
262
282
  buildCallTree(ctx);
283
+ // Calculate self-time for each call
263
284
  for (const root of ctx.rootCalls)
264
285
  calculateSelfTimes(root);
286
+ // Collect statistics by view type
265
287
  const ungroupedStats = collectUngroupedStats(ctx);
266
- for (const root of ctx.rootCalls)
267
- collectFunctionStats(root, ctx);
288
+ for (const call of ctx.rootCalls)
289
+ collectFunctionStats(call, ctx);
290
+ // Sort and rank functions
268
291
  sortAndRankFunctions(ctx);
292
+ // Display summaries to console
269
293
  outputCapture.write("\n📊 Performance Analysis - Top Individual Calls:\n");
270
294
  displayIndividualSummary(ungroupedStats);
271
295
  outputCapture.write("\n📊 Performance Analysis - Functions by Self Time:\n");
272
296
  displayGroupedSummary(ctx.allFunctions);
297
+ // Write CSV reports
273
298
  const rangesCsvPath = join(traceDir, "ranges.csv");
274
299
  const namesCsvPath = join(traceDir, "names.csv");
275
- const summaryFilePath = join(traceDir, "summary.txt"); // Renamed to avoid conflict
300
+ const summaryPath = join(traceDir, "summary.txt");
301
+ // Export individual ranges to CSV
276
302
  writeToCsv(rangesCsvPath, ["Function Name", "Self (ms)", "Duration (ms)", "Location"], ungroupedStats.map(stat => [
277
303
  stat.functionName,
278
- formatMillis(stat.selfTime, 3),
279
- formatMillis(stat.duration, 3),
304
+ (stat.selfTime / 1000).toFixed(3),
305
+ (stat.duration / 1000).toFixed(3),
280
306
  formatLocation(stat.callSite)
281
307
  ]));
308
+ // Export grouped functions to CSV
282
309
  writeToCsv(namesCsvPath, [
283
310
  "Function Name",
284
311
  "Total Self (ms)",
@@ -287,7 +314,7 @@ const analyzeTypeInstantiations = (traceDir) => {
287
314
  "Top Location",
288
315
  "Top Self (ms)"
289
316
  ], ctx.allFunctions.map(stats => {
290
- const topUsage = stats.detailedCallSites[0] ?? {
317
+ const topUsage = stats.detailedCallSites[0] || {
291
318
  path: "unknown",
292
319
  pos: 0,
293
320
  end: 0,
@@ -295,20 +322,24 @@ const analyzeTypeInstantiations = (traceDir) => {
295
322
  };
296
323
  return [
297
324
  stats.functionName,
298
- formatMillis(stats.selfTime, 3),
299
- formatMillis(stats.selfTime / Math.max(1, stats.count), 3), // Avoid division by zero
325
+ (stats.selfTime / 1000).toFixed(3),
326
+ (stats.selfTime / stats.count / 1000).toFixed(3),
300
327
  stats.count.toString(),
301
328
  formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`),
302
- formatMillis(topUsage.selfTime, 3)
329
+ (topUsage.selfTime / 1000).toFixed(3)
303
330
  ];
304
331
  }));
305
332
  outputCapture.write(`\n✅ Analysis complete! Results exported to:\n` +
306
333
  ` - ${rangesCsvPath} (individual calls)\n` +
307
334
  ` - ${namesCsvPath} (grouped by function name)\n` +
308
- ` - ${summaryFilePath} (complete analysis report)`);
335
+ ` - ${summaryPath} (complete analysis report)`);
309
336
  };
337
+ /**
338
+ * Collect statistics for individual (ungrouped) calls
339
+ */
310
340
  const collectUngroupedStats = (ctx) => {
311
341
  const ungroupedStats = [];
342
+ // Flatten the call tree into individual entries
312
343
  const flattenCallTree = (call) => {
313
344
  ungroupedStats.push({
314
345
  typeId: call.typeId,
@@ -322,35 +353,46 @@ const collectUngroupedStats = (ctx) => {
322
353
  };
323
354
  for (const root of ctx.rootCalls)
324
355
  flattenCallTree(root);
356
+ // Sort by self time in descending order
325
357
  return ungroupedStats.sort((a, b) => b.selfTime - a.selfTime);
326
358
  };
359
+ /**
360
+ * Display a summary of individual calls
361
+ */
327
362
  const displayIndividualSummary = (stats) => {
328
363
  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];
364
+ const top20 = stats.slice(0, 20);
365
+ for (const [index, stat] of top20.entries()) {
332
366
  const typeNameFormatted = formatTypeName(stat.functionName, 20);
333
- const selfTimeMs = formatPaddedMillis(stat.selfTime, 15, 2);
367
+ const selfTimeMs = (stat.selfTime / 1000).toFixed(2).padStart(15);
334
368
  const location = formatLocation(stat.callSite);
335
- outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
369
+ outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${location}`);
336
370
  }
337
371
  };
372
+ /**
373
+ * Display a summary table header with aligned columns
374
+ */
338
375
  const displayTableHeader = (columns) => {
376
+ // Create header row with standard column widths
339
377
  const headerRow = [
340
378
  columns[0].padEnd(4),
341
379
  columns[1].padEnd(20),
342
380
  columns[2].padEnd(15),
343
381
  ...columns.slice(3)
344
382
  ].join(" | ");
383
+ // Create separator line matching the header column widths
345
384
  const separatorRow = [
346
- "-".repeat(4),
347
- "-".repeat(20),
348
- "-".repeat(15),
385
+ "----",
386
+ "--------------------",
387
+ "---------------",
349
388
  ...columns.slice(3).map(col => "-".repeat(col.length))
350
389
  ].join("-|-");
351
390
  outputCapture.write(headerRow);
352
391
  outputCapture.write(separatorRow);
353
392
  };
393
+ /**
394
+ * Display a combined summary of grouped functions showing both total and average times
395
+ */
354
396
  const displayGroupedSummary = (functions) => {
355
397
  displayTableHeader([
356
398
  "Rank",
@@ -360,90 +402,109 @@ const displayGroupedSummary = (functions) => {
360
402
  "Calls",
361
403
  "Top Usage"
362
404
  ]);
363
- const topN = Math.min(functions.length, 20);
364
- for (let i = 0; i < topN; i++) {
365
- const stats = functions[i];
405
+ for (const [index, stats] of functions.slice(0, 20).entries()) {
366
406
  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);
407
+ const totalTimeMs = (stats.selfTime / 1000).toFixed(2).padStart(15);
408
+ const avgTimeMs = (stats.selfTime / stats.count / 1000)
409
+ .toFixed(2)
410
+ .padStart(13);
370
411
  const calls = stats.count.toString().padStart(5);
371
- const topUsage = stats.detailedCallSites[0] ?? {
412
+ // Get details about top usage site
413
+ const topUsage = stats.detailedCallSites[0] || {
372
414
  path: "unknown",
373
415
  pos: 0,
374
416
  end: 0,
375
417
  selfTime: 0
376
418
  };
377
- const topUsageTime = formatMillis(topUsage.selfTime, 2) + "ms";
419
+ const topUsageTime = (topUsage.selfTime / 1000).toFixed(2) + "ms";
378
420
  const topUsageLocation = formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`);
379
- outputCapture.write(`${(i + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
421
+ outputCapture.write(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${totalTimeMs} | ${avgTimeMs} | ${calls} | ${topUsageLocation} (${topUsageTime})`);
380
422
  }
381
423
  };
424
+ /**
425
+ * Format a type name for display, ensuring the most identifiable parts are preserved
426
+ */
382
427
  const formatTypeName = (typeName, maxLength) => {
428
+ // Remove any () from the name
383
429
  typeName = typeName.replace(/\(\)$/, "");
384
430
  if (typeName.length <= maxLength)
385
431
  return typeName.padEnd(maxLength);
386
- const charsToKeep = maxLength - 3; // "..."
387
- const firstPart = Math.ceil(charsToKeep * 0.7);
432
+ // Default truncation strategy
433
+ const charsToKeep = maxLength - 3; // Account for "..."
434
+ const firstPart = Math.ceil(charsToKeep * 0.7); // Keep more of the start
388
435
  const lastPart = charsToKeep - firstPart;
389
436
  return (typeName.substring(0, firstPart) +
390
437
  "..." +
391
438
  (lastPart > 0 ? typeName.substring(typeName.length - lastPart) : "")).padEnd(maxLength);
392
439
  };
440
+ /**
441
+ * Format a file location to be more readable with relative path and line:char
442
+ */
393
443
  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}`;
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}` : "");
410
462
  }
411
- const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
412
- const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
413
- return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
414
463
  };
464
+ /**
465
+ * Finds the most specific non-trivial node within the given range
466
+ */
415
467
  const findMostSpecificNodeInRange = (file, start, end) => {
468
+ // Get all descendants in the file
416
469
  const allNodes = getDescendants(file);
470
+ // Filter nodes that are completely contained within our range
417
471
  const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
418
- if (nodesInRange.length === 0)
419
- return undefined;
472
+ // Find most specific nodes (leaf nodes)
420
473
  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
474
+ // Find nodes in order of preference
475
+ return findNodeByPreference(leafNodes);
422
476
  };
423
477
  const findNodeByPreference = (nodes) => {
424
- if (nodes.length === 0)
425
- return undefined;
478
+ // 1. Type references
426
479
  const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
427
480
  if (typeReference)
428
481
  return typeReference;
482
+ // 2. Declarations
429
483
  const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
430
484
  ts.isFunctionDeclaration(node) ||
431
485
  ts.isClassDeclaration(node) ||
432
486
  ts.isInterfaceDeclaration(node));
433
487
  if (declaration)
434
488
  return declaration;
489
+ // 3. Property accesses
435
490
  const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
436
491
  if (propertyAccess)
437
492
  return propertyAccess;
493
+ // 4. Assignments
438
494
  const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
439
495
  node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
440
496
  if (assignment)
441
497
  return assignment;
498
+ // 5. Expressions
442
499
  const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
443
500
  if (expression)
444
501
  return expression;
445
- return nodes.sort((a, b) => a.end - a.pos - (b.end - b.pos))[0]; // Smallest node as a fallback
502
+ // Default: first node
503
+ return nodes[0];
446
504
  };
505
+ /**
506
+ * Write data to a CSV file
507
+ */
447
508
  const writeToCsv = (filePath, headers, rows) => {
448
509
  const content = [
449
510
  headers.join(","),
@@ -451,8 +512,14 @@ const writeToCsv = (filePath, headers, rows) => {
451
512
  ].join("\n");
452
513
  writeFile(filePath, content);
453
514
  };
515
+ /**
516
+ * Escape string for CSV format
517
+ */
454
518
  const escapeForCsv = (value) => {
455
- if (value.includes(",") || value.includes('"') || value.includes("\n"))
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
456
522
  return `"${value.replaceAll('"', '""')}"`;
523
+ }
457
524
  return value;
458
525
  };
package/out/config.d.ts CHANGED
@@ -8,7 +8,6 @@ type BaseAttestConfig = {
8
8
  tsconfig: string | null | undefined;
9
9
  compilerOptions: ts.CompilerOptions;
10
10
  updateSnapshots: boolean;
11
- failOnMissingSnapshots: boolean;
12
11
  /** A string or list of strings representing the TypeScript version aliases to run.
13
12
  *
14
13
  * Aliases must be specified as a package.json dependency or devDependency beginning with "typescript".
package/out/config.js CHANGED
@@ -7,7 +7,6 @@ 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,
11
10
  updateSnapshots: false,
12
11
  skipTypes: false,
13
12
  skipInlineInstantiations: false,
@@ -111,39 +111,14 @@ export const findAttestTypeScriptVersions = () => {
111
111
  if (!existsSync(nodeModulesPath) ||
112
112
  !statSync(nodeModulesPath).isDirectory())
113
113
  continue;
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-"))
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("@"))
145
120
  continue;
146
- const fullPath = join(arkDir, dirName);
121
+ const fullPath = join(nodeModulesPath, dirName);
147
122
  if (!statSync(fullPath).isDirectory())
148
123
  continue;
149
124
  const alias = getDirAlias(dirName);
@@ -162,6 +137,36 @@ export const findAttestTypeScriptVersions = () => {
162
137
  });
163
138
  }
164
139
  }
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}`);
165
170
  }
166
171
  }
167
172
  return versions;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.48.1",
3
+ "version": "0.49.0",
4
4
  "license": "MIT",
5
5
  "author": {
6
6
  "name": "David Blass",
@@ -36,9 +36,9 @@
36
36
  "@typescript/analyze-trace": "0.10.1",
37
37
  "@typescript/vfs": "1.6.1",
38
38
  "prettier": "3.5.3",
39
- "@ark/fs": "0.46.0",
40
- "@ark/util": "0.46.0",
41
- "arktype": "2.1.20"
39
+ "@ark/fs": "0.49.0",
40
+ "@ark/util": "0.49.0",
41
+ "arktype": "2.1.22"
42
42
  },
43
43
  "devDependencies": {
44
44
  "typescript": "5.8.2"