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