@ark/attest 0.41.3 → 0.43.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.
@@ -29,7 +29,7 @@ export const attestInternal = (value, { cfg: cfgHooks, ...ctxHooks } = {}) => {
29
29
  export const attest = Object.assign(attestInternal, {
30
30
  instantiations: (args) => {
31
31
  const attestConfig = getConfig();
32
- if (attestConfig.skipInlineInstantiations)
32
+ if (attestConfig.skipTypes || attestConfig.skipInlineInstantiations)
33
33
  return;
34
34
  const calledFrom = caller();
35
35
  const ctx = getBenchCtx([calledFrom.file]);
package/out/cache/ts.d.ts CHANGED
@@ -12,6 +12,7 @@ export declare class TsServer {
12
12
  getSourceFileOrThrow(path: string): ts.SourceFile;
13
13
  }
14
14
  export declare const nearestCallExpressionChild: (node: ts.Node, position: number) => ts.CallExpression;
15
+ export declare const nearestBoundingCallExpression: (node: ts.Node, position: number) => ts.CallExpression | undefined;
15
16
  export declare const getAbsolutePosition: (file: ts.SourceFile, position: SourcePosition) => number;
16
17
  export type TsconfigInfo = {
17
18
  path: string | undefined;
package/out/cache/ts.js CHANGED
@@ -42,7 +42,7 @@ export const nearestCallExpressionChild = (node, position) => {
42
42
  }
43
43
  return result;
44
44
  };
45
- const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
45
+ export const nearestBoundingCallExpression = (node, position) => node.pos <= position && node.end >= position ?
46
46
  (node
47
47
  .getChildren()
48
48
  .flatMap(child => nearestBoundingCallExpression(child, position) ?? [])[0] ?? (ts.isCallExpression(node) ? node : undefined))
package/out/cli/trace.js CHANGED
@@ -1,6 +1,10 @@
1
- import { ensureDir } from "@ark/fs";
1
+ import { ensureDir, readJson, writeFile } from "@ark/fs";
2
2
  import { execSync } from "child_process";
3
+ import { existsSync } from "node:fs";
4
+ import { basename, join, relative } from "node:path";
3
5
  import { resolve } from "path";
6
+ import ts from "typescript";
7
+ import { TsServer, getDescendants, getStringifiableType, nearestBoundingCallExpression } from "../cache/ts.js";
4
8
  import { getConfig } from "../config.js";
5
9
  import { baseDiagnosticTscCmd } from "./shared.js";
6
10
  export const trace = async (args) => {
@@ -14,29 +18,375 @@ export const trace = async (args) => {
14
18
  ensureDir(traceDir);
15
19
  try {
16
20
  console.log(`⏳ Gathering type trace data for ${packageDir}...`);
17
- // These cache files have to be removed before any analysis is done otherwise
18
- // the results will be meaningless.
19
- // the .attest/trace directory will contain a trace.json file and a types.json file.
20
- // the trace.json file can be viewed via a tool like https://ui.perfetto.dev/
21
- // the types.json file can be used to associate IDs from the trace file with type aliases
22
- execSync(`${baseDiagnosticTscCmd} --project ${config.tsconfig} --generateTrace ${traceDir}`, {
23
- cwd: packageDir,
24
- stdio: "inherit"
25
- });
21
+ generateTraceData(traceDir, config.tsconfig, packageDir);
26
22
  }
27
23
  catch (e) {
28
24
  console.error(String(e));
29
25
  }
30
26
  finally {
31
27
  console.log(`⏳ Analyzing type trace data for ${packageDir}...`);
32
- // allow analyze-trace to process the args
33
- process.argv = [
34
- "node",
35
- "node_modules/@typescript/analyze-trace/dist/analyze-trace-dir.js",
36
- traceDir
37
- ];
38
- // TypeScript's analyze-trace tool can be used to automatically detect hot-spots in your code.
39
- // It's not a perfect match for what can be optimized, but it can be a helpful place to start
40
- await import("@typescript/analyze-trace/dist/analyze-trace-dir.js");
28
+ analyzeTypeInstantiations(traceDir);
29
+ }
30
+ };
31
+ const generateTraceData = (traceDir, tsconfigPath, packageDir) => {
32
+ execSync(`${baseDiagnosticTscCmd} --project ${tsconfigPath} --generateTrace ${traceDir}`, {
33
+ cwd: packageDir,
34
+ stdio: "inherit"
35
+ });
36
+ };
37
+ const initializeAnalysisContext = (traceDir) => {
38
+ const tsServer = TsServer.instance;
39
+ // Load trace data
40
+ const tracePath = join(traceDir, "trace.json");
41
+ if (!existsSync(tracePath))
42
+ throw new Error(`Expected a trace file at ${tracePath}`);
43
+ const traceEntries = readJson(tracePath);
44
+ return {
45
+ traceDir,
46
+ tsServer,
47
+ traceEntries,
48
+ durationEntries: [],
49
+ callRanges: [],
50
+ rootCalls: [],
51
+ functionStats: {},
52
+ allFunctions: []
53
+ };
54
+ };
55
+ const filterDurationEntries = (ctx) => {
56
+ ctx.durationEntries = ctx.traceEntries.filter(entry => entry.ph === "X" &&
57
+ entry.dur !== undefined &&
58
+ entry.args.path &&
59
+ entry.args.pos &&
60
+ entry.args.end);
61
+ console.log(`Found ${ctx.durationEntries.length} traces with duration information`);
62
+ };
63
+ const processDurationEntry = (entry, ctx) => {
64
+ try {
65
+ const sourceFile = ctx.tsServer.getSourceFileOrThrow(entry.args.path);
66
+ const pos = entry.args.pos;
67
+ const end = entry.args.end;
68
+ // First try to find any call expression in the range
69
+ const callExpr = findCallExpressionInRange(sourceFile, pos, end);
70
+ if (callExpr)
71
+ processCallExpression(callExpr, entry, pos, end, ctx);
72
+ else {
73
+ // Try to process as another type of node
74
+ processNonCallNode(sourceFile, entry, pos, end, ctx);
75
+ }
76
+ }
77
+ catch (e) {
78
+ handleProcessingError(e, entry);
79
+ }
80
+ };
81
+ /**
82
+ * Find any call expression within the given range, with preference for method calls
83
+ */
84
+ const findCallExpressionInRange = (file, start, end) => {
85
+ // First try the default nearest bounding call expression
86
+ const boundingCall = nearestBoundingCallExpression(file, start);
87
+ if (boundingCall)
88
+ return boundingCall;
89
+ // If that fails, search for any call expressions in the range
90
+ const allNodes = getDescendants(file);
91
+ const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
92
+ // Find all call expressions in the range
93
+ const callExpressions = nodesInRange.filter(node => ts.isCallExpression(node));
94
+ if (callExpressions.length === 0)
95
+ return undefined;
96
+ // Prioritize method calls (e.g. x.and(), x.or())
97
+ const methodCalls = callExpressions.filter(call => ts.isPropertyAccessExpression(call.expression));
98
+ // Return a method call if found, otherwise the first call expression
99
+ return methodCalls.length > 0 ? methodCalls[0] : callExpressions[0];
100
+ };
101
+ /**
102
+ * Extract function or method name from a call expression, normalizing the format
103
+ */
104
+ const extractFunctionName = (callExpr) => {
105
+ // For method calls like x.and()
106
+ if (ts.isPropertyAccessExpression(callExpr.expression))
107
+ return callExpr.expression.name.getText();
108
+ // For direct function calls like type() or scope()
109
+ if (ts.isIdentifier(callExpr.expression))
110
+ return callExpr.expression.getText();
111
+ // For other expressions, try to get a reasonable name
112
+ return "anonymous";
113
+ };
114
+ const processCallExpression = (callExpr, entry, pos, end, ctx) => {
115
+ // Simply use the function name for grouping
116
+ const functionName = extractFunctionName(callExpr);
117
+ // Use the function name for both ID and display name
118
+ // This will ensure all calls to the same function are grouped together
119
+ const typeId = `function-${functionName}`;
120
+ const typeName = functionName;
121
+ const callSite = `${entry.args.path}:${pos}-${end}`;
122
+ ctx.callRanges.push({
123
+ id: `${entry.ts}-${pos}-${end}`,
124
+ typeId,
125
+ typeName,
126
+ callSite,
127
+ startTime: entry.ts,
128
+ endTime: entry.ts + (entry.dur || 0),
129
+ duration: entry.dur || 0,
130
+ children: [],
131
+ selfTime: entry.dur || 0
132
+ });
133
+ };
134
+ const processNonCallNode = (sourceFile, entry, pos, end, ctx) => {
135
+ const relevantNode = findMostSpecificNodeInRange(sourceFile, pos, end);
136
+ if (!relevantNode)
137
+ return;
138
+ const nodeType = getStringifiableType(relevantNode);
139
+ const nodeKind = ts.SyntaxKind[relevantNode.kind];
140
+ const typeName = `${nodeKind}: ${nodeType.toString().substring(0, 25)}`;
141
+ const typeId = `node-${relevantNode.kind}-${nodeType.id || nodeType.toString().substring(0, 20)}`;
142
+ const callSite = `${entry.args.path}:${pos}-${end}`;
143
+ ctx.callRanges.push({
144
+ id: `${entry.ts}-${pos}-${end}`,
145
+ typeId,
146
+ typeName,
147
+ callSite,
148
+ startTime: entry.ts,
149
+ endTime: entry.ts + (entry.dur || 0),
150
+ duration: entry.dur || 0,
151
+ children: [],
152
+ selfTime: entry.dur || 0
153
+ });
154
+ };
155
+ const handleProcessingError = (e, entry) => {
156
+ if (!(e instanceof Error))
157
+ throw e;
158
+ // Silent failure for common case of not finding a call expression
159
+ if (e.message?.includes("Unable to find bounding call expression"))
160
+ return;
161
+ console.warn(`Error processing entry at ${entry.args.path}:${entry.args.pos}: ${e.message}`);
162
+ };
163
+ const buildCallTree = (ctx) => {
164
+ // Sort by start time for nesting analysis
165
+ ctx.callRanges.sort((a, b) => a.startTime - b.startTime);
166
+ const activeCallStack = [];
167
+ ctx.callRanges.forEach(call => {
168
+ popFinishedCalls(call, activeCallStack);
169
+ assignToParentOrRoot(call, activeCallStack, ctx);
170
+ activeCallStack.push(call);
171
+ });
172
+ };
173
+ const popFinishedCalls = (call, activeCallStack) => {
174
+ while (activeCallStack.length > 0 &&
175
+ activeCallStack[activeCallStack.length - 1].endTime < call.startTime)
176
+ activeCallStack.pop();
177
+ };
178
+ const assignToParentOrRoot = (call, activeCallStack, ctx) => {
179
+ if (activeCallStack.length === 0) {
180
+ // This is a root call
181
+ ctx.rootCalls.push(call);
182
+ }
183
+ else {
184
+ // This call is nested inside the current active call
185
+ const parent = activeCallStack[activeCallStack.length - 1];
186
+ parent.children.push(call);
41
187
  }
42
188
  };
189
+ const calculateSelfTimes = (call) => {
190
+ let childrenTime = 0;
191
+ for (const child of call.children)
192
+ childrenTime += calculateSelfTimes(child);
193
+ call.selfTime = call.duration - childrenTime;
194
+ return call.duration;
195
+ };
196
+ const collectFunctionStats = (call, ctx) => {
197
+ // Initialize stats object if needed
198
+ if (!ctx.functionStats[call.typeId]) {
199
+ ctx.functionStats[call.typeId] = {
200
+ typeId: call.typeId,
201
+ typeName: call.typeName,
202
+ callSites: new Set(),
203
+ totalTime: 0,
204
+ selfTime: 0,
205
+ count: 0,
206
+ firstLocation: call.callSite,
207
+ detailedCallSites: []
208
+ };
209
+ }
210
+ const stats = ctx.functionStats[call.typeId];
211
+ // Track detailed call site information
212
+ addCallSiteToStats(call, stats);
213
+ // Update aggregate metrics
214
+ stats.callSites.add(call.callSite);
215
+ stats.totalTime += call.duration;
216
+ stats.selfTime += call.selfTime;
217
+ stats.count++;
218
+ // Process children
219
+ call.children.forEach(child => collectFunctionStats(child, ctx));
220
+ };
221
+ const addCallSiteToStats = (call, stats) => {
222
+ const [filePath, positionRange] = call.callSite.split(":");
223
+ const [posStr, endStr] = positionRange.split("-");
224
+ stats.detailedCallSites.push({
225
+ path: filePath,
226
+ pos: parseInt(posStr),
227
+ end: parseInt(endStr),
228
+ selfTime: call.selfTime
229
+ });
230
+ };
231
+ const sortAndRankFunctions = (ctx) => {
232
+ // Sort each function's call sites by self-time
233
+ Object.values(ctx.functionStats).forEach(stats => {
234
+ stats.detailedCallSites.sort((a, b) => b.selfTime - a.selfTime);
235
+ });
236
+ // Sort functions by self-time
237
+ ctx.allFunctions = Object.values(ctx.functionStats).sort((a, b) => b.selfTime - a.selfTime);
238
+ };
239
+ const displaySummary = (ctx) => {
240
+ const top20Functions = ctx.allFunctions.slice(0, 20);
241
+ console.log("\nTop Functions by Self Type-Checking Time:\n");
242
+ console.log("Rank | Type Name | Self Time (ms) | Calls | Unique Sites | Top Usage (ms)");
243
+ console.log("-----|-----------------------------------------------|----------------|-------|--------------|-------------------------------------------");
244
+ top20Functions.forEach((stats, index) => printFunctionSummary(stats, index));
245
+ };
246
+ const printFunctionSummary = (stats, index) => {
247
+ const typeNameFormatted = formatTypeName(stats.typeName, 45);
248
+ const selfTimeMs = (stats.selfTime / 1000).toFixed(2).padStart(14);
249
+ const calls = stats.count.toString().padStart(5);
250
+ const sites = stats.callSites.size.toString().padStart(12);
251
+ // Get details about top usage site
252
+ const topUsage = stats.detailedCallSites[0] || {
253
+ path: "unknown",
254
+ pos: 0,
255
+ end: 0,
256
+ selfTime: 0
257
+ };
258
+ const topUsageTime = (topUsage.selfTime / 1000).toFixed(2) + "ms";
259
+ const topUsageLocation = formatLocation(`${topUsage.path}:${topUsage.pos}-${topUsage.end}`);
260
+ console.log(`${(index + 1).toString().padStart(4)} | ${typeNameFormatted} | ${selfTimeMs} | ${calls} | ${sites} | ${topUsageLocation} (${topUsageTime})`);
261
+ };
262
+ const writeDetailedReport = (ctx) => {
263
+ const outputPath = join(ctx.traceDir, "analysis.txt");
264
+ let outputContent = createReportHeader();
265
+ // Add detailed information for each function
266
+ ctx.allFunctions.forEach((stats, index) => {
267
+ outputContent += createFunctionReport(stats, index);
268
+ });
269
+ // Write to file
270
+ writeFile(outputPath, outputContent);
271
+ console.log(`\n✅ Analysis complete! A more detailed breakdown is available at ${outputPath}`);
272
+ };
273
+ const createReportHeader = () => "TypeScript Type-Checking Performance Analysis\n" +
274
+ "===========================================\n\n" +
275
+ "Functions sorted by total self type-checking time\n\n";
276
+ const createFunctionReport = (stats, index) => {
277
+ let report = `${index + 1}. ${stats.typeName}\n`;
278
+ report += ` Self time: ${(stats.selfTime / 1000).toFixed(2)} ms\n`;
279
+ report += ` Total time: ${(stats.totalTime / 1000).toFixed(2)} ms\n`;
280
+ report += ` Call count: ${stats.count}\n`;
281
+ report += ` Unique call sites: ${stats.callSites.size}\n`;
282
+ if (stats.detailedCallSites.length > 0) {
283
+ report += ` Top call sites by self time:\n`;
284
+ stats.detailedCallSites.forEach((site, i) => {
285
+ report += ` ${i + 1}. ${site.path}:${site.pos}-${site.end}\n`;
286
+ report += ` Self time: ${(site.selfTime / 1000).toFixed(2)} ms\n`;
287
+ });
288
+ }
289
+ report += "\n";
290
+ return report;
291
+ };
292
+ /**
293
+ * Format a type name for display, ensuring the most identifiable parts are preserved
294
+ */
295
+ const formatTypeName = (typeName, maxLength) => {
296
+ // Remove any () from the name
297
+ typeName = typeName.replace(/\(\)$/, "");
298
+ if (typeName.length <= maxLength)
299
+ return typeName.padEnd(maxLength);
300
+ // Default truncation strategy
301
+ const charsToKeep = maxLength - 3; // Account for "..."
302
+ const firstPart = Math.ceil(charsToKeep * 0.7); // Keep more of the start
303
+ const lastPart = charsToKeep - firstPart;
304
+ return (typeName.substring(0, firstPart) +
305
+ "..." +
306
+ (lastPart > 0 ? typeName.substring(typeName.length - lastPart) : "")).padEnd(maxLength);
307
+ };
308
+ /**
309
+ * Format a file location to be more readable with relative path and line:char
310
+ */
311
+ const formatLocation = (location) => {
312
+ if (!location || location === "unknown")
313
+ return "unknown";
314
+ // Extract file path and position range
315
+ const [filePath, positionRange] = location.split(":");
316
+ try {
317
+ const relativePath = relative(process.cwd(), filePath);
318
+ // Get position values
319
+ const [posStr] = positionRange.split("-");
320
+ const pos = parseInt(posStr);
321
+ // Get the source file to convert position to line:character
322
+ const sourceFile = TsServer.instance.getSourceFileOrThrow(filePath);
323
+ const lineAndChar = sourceFile.getLineAndCharacterOfPosition(pos);
324
+ // Format as relative-path:line:char
325
+ return `${relativePath}:${lineAndChar.line + 1}:${lineAndChar.character + 1}`;
326
+ }
327
+ catch {
328
+ // If any part fails, return the basic filename as fallback
329
+ return basename(filePath) + (positionRange ? `:${positionRange}` : "");
330
+ }
331
+ };
332
+ /**
333
+ * Finds the most specific non-trivial node within the given range
334
+ */
335
+ const findMostSpecificNodeInRange = (file, start, end) => {
336
+ // Get all descendants in the file
337
+ const allNodes = getDescendants(file);
338
+ // Filter nodes that are completely contained within our range
339
+ const nodesInRange = allNodes.filter(node => node.pos >= start && node.end <= end);
340
+ // Find most specific nodes (leaf nodes)
341
+ const leafNodes = nodesInRange.filter(node => !nodesInRange.some(other => other !== node && other.pos >= node.pos && other.end <= node.end));
342
+ // Find nodes in order of preference
343
+ return findNodeByPreference(leafNodes);
344
+ };
345
+ const findNodeByPreference = (nodes) => {
346
+ // 1. Type references
347
+ const typeReference = nodes.find(node => ts.isTypeReferenceNode(node) || ts.isTypeQueryNode(node));
348
+ if (typeReference)
349
+ return typeReference;
350
+ // 2. Declarations
351
+ const declaration = nodes.find(node => ts.isVariableDeclaration(node) ||
352
+ ts.isFunctionDeclaration(node) ||
353
+ ts.isClassDeclaration(node) ||
354
+ ts.isInterfaceDeclaration(node));
355
+ if (declaration)
356
+ return declaration;
357
+ // 3. Property accesses
358
+ const propertyAccess = nodes.find(node => ts.isPropertyAccessExpression(node));
359
+ if (propertyAccess)
360
+ return propertyAccess;
361
+ // 4. Assignments
362
+ const assignment = nodes.find(node => ts.isBinaryExpression(node) &&
363
+ node.operatorToken.kind === ts.SyntaxKind.EqualsToken);
364
+ if (assignment)
365
+ return assignment;
366
+ // 5. Expressions
367
+ const expression = nodes.find(node => ts.isExpressionStatement(node) || ts.isExpression(node));
368
+ if (expression)
369
+ return expression;
370
+ // Default: first node
371
+ return nodes[0];
372
+ };
373
+ const analyzeTypeInstantiations = (traceDir) => {
374
+ // Initialize the analysis context
375
+ const ctx = initializeAnalysisContext(traceDir);
376
+ // Filter entries with duration information
377
+ filterDurationEntries(ctx);
378
+ // Process each duration entry to extract call ranges
379
+ ctx.durationEntries.forEach(entry => processDurationEntry(entry, ctx));
380
+ // Build call tree from ranges
381
+ buildCallTree(ctx);
382
+ // Calculate self-time for each call
383
+ ctx.rootCalls.forEach(calculateSelfTimes);
384
+ // Collect statistics about function types
385
+ ctx.rootCalls.forEach(call => collectFunctionStats(call, ctx));
386
+ // Sort and rank functions by self-time
387
+ sortAndRankFunctions(ctx);
388
+ // Display summary to console
389
+ displaySummary(ctx);
390
+ // Write detailed report to file
391
+ writeDetailedReport(ctx);
392
+ };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.41.3",
3
+ "version": "0.43.0",
4
4
  "license": "MIT",
5
5
  "author": {
6
6
  "name": "David Blass",
@@ -36,12 +36,12 @@
36
36
  "@typescript/analyze-trace": "0.10.1",
37
37
  "@typescript/vfs": "1.6.0",
38
38
  "prettier": "3.4.2",
39
- "@ark/util": "0.40.0",
40
- "@ark/fs": "0.40.0",
41
- "arktype": "2.1.0"
39
+ "@ark/util": "0.43.0",
40
+ "arktype": "2.1.1",
41
+ "@ark/fs": "0.43.0"
42
42
  },
43
43
  "devDependencies": {
44
- "typescript": "5.8.0-beta"
44
+ "typescript": "5.8.2"
45
45
  },
46
46
  "peerDependencies": {
47
47
  "typescript": "*"