@ark/attest 0.18.0 → 0.18.2

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.
package/README.md CHANGED
@@ -66,7 +66,7 @@ export const mochaGlobalTeardown = teardown
66
66
 
67
67
  You should also add `.attest` to your repository's `.gitignore` file.
68
68
 
69
- Bun support is currently pending a [bug in the way their source maps translate to stack traces](https://github.com/oven-sh/bun/issues/7120). If this is a problem for you, please 👍 that issue so they prioritize it!
69
+ Bun support is currently pending [them supporting @prettier/sync for type formatting](https://github.com/oven-sh/bun/issues/10768). If this is a problem for you, please 👍 that issue so they prioritize it!
70
70
 
71
71
  ## Assertions
72
72
 
@@ -4,9 +4,9 @@ export type ThrowAssertionErrorContext = {
4
4
  message: string;
5
5
  expected?: unknown;
6
6
  actual?: unknown;
7
- ctx: AssertionContext;
7
+ stack: string;
8
8
  };
9
- export declare const throwAssertionError: ({ ctx, ...errorArgs }: ThrowAssertionErrorContext) => never;
9
+ export declare const throwAssertionError: ({ stack, ...errorArgs }: ThrowAssertionErrorContext) => never;
10
10
  export type AssertFn = (expected: unknown, actual: unknown, ctx: AssertionContext) => void;
11
11
  export type MappedTypeAssertionResult = {
12
12
  actual: unknown;
@@ -1,9 +1,8 @@
1
1
  import { printable, throwInternalError } from "@ark/util";
2
- import { AssertionError } from "node:assert";
3
2
  import * as assert from "node:assert/strict";
4
- export const throwAssertionError = ({ ctx, ...errorArgs }) => {
3
+ export const throwAssertionError = ({ stack, ...errorArgs }) => {
5
4
  const e = new assert.AssertionError(errorArgs);
6
- e.stack = ctx.assertionStack;
5
+ e.stack = stack;
7
6
  throw e;
8
7
  };
9
8
  export class TypeAssertionMapping {
@@ -28,8 +27,12 @@ export const versionableAssertion = (fn) => (expected, actual, ctx) => {
28
27
  catch (e) {
29
28
  errorMessage += `❌TypeScript@${version}:${e}\n`;
30
29
  }
31
- if (errorMessage)
32
- throw new AssertionError({ message: errorMessage });
30
+ if (errorMessage) {
31
+ throwAssertionError({
32
+ stack: ctx.assertionStack,
33
+ message: errorMessage
34
+ });
35
+ }
33
36
  }
34
37
  }
35
38
  else
@@ -85,7 +88,7 @@ export const typeEqualityMapping = new TypeAssertionMapping(data => {
85
88
  return null;
86
89
  });
87
90
  export const assertEqualOrMatching = versionableAssertion((expected, actual, ctx) => {
88
- const assertionArgs = { actual, expected, ctx };
91
+ const assertionArgs = { actual, expected, stack: ctx.assertionStack };
89
92
  if (typeof actual !== "string") {
90
93
  throwAssertionError({
91
94
  message: `Value was of type ${typeof actual} (expected a string).`,
@@ -113,8 +116,12 @@ export const assertEqualOrMatching = versionableAssertion((expected, actual, ctx
113
116
  }
114
117
  });
115
118
  export const getThrownMessage = (result, ctx) => {
116
- if (!("threw" in result))
117
- throwAssertionError({ message: "Function didn't throw.", ctx });
119
+ if (!("threw" in result)) {
120
+ throwAssertionError({
121
+ message: "Function didn't throw",
122
+ stack: ctx.assertionStack
123
+ });
124
+ }
118
125
  return result.threw;
119
126
  };
120
127
  export const callAssertedFunction = (asserted) => {
@@ -35,6 +35,6 @@ export const attest = Object.assign(attestInternal, {
35
35
  const ctx = getBenchCtx([calledFrom.file]);
36
36
  ctx.benchCallPosition = calledFrom;
37
37
  ctx.lastSnapCallPosition = calledFrom;
38
- instantiationDataHandler({ ...ctx, kind: "instantiations" }, args, false);
38
+ instantiationDataHandler({ ...ctx, lastSnapFunctionName: "instantiations" }, args, false);
39
39
  }
40
40
  });
@@ -49,7 +49,7 @@ export class ChainableAssertions {
49
49
  instanceOf(expected) {
50
50
  if (!(this.ctx.actual instanceof expected)) {
51
51
  throwAssertionError({
52
- ctx: this.ctx,
52
+ stack: this.ctx.assertionStack,
53
53
  message: `Expected an instance of ${expected.name} (was ${typeof this.ctx.actual === "object" && this.ctx.actual !== null ?
54
54
  this.ctx.actual.constructor.name
55
55
  : this.serializedActual})`
@@ -141,7 +141,12 @@ export class ChainableAssertions {
141
141
  if (this.ctx.cfg.skipTypes)
142
142
  return chainableNoOpProxy;
143
143
  this.ctx.actual = new TypeAssertionMapping(data => {
144
- checkCompletionsForErrors(data.completions);
144
+ if (typeof data.completions === "string") {
145
+ // if the completions were ambiguously defined, e.g. two string
146
+ // literals with the same value, they are writen as an error
147
+ // message to the JSON. Throw it immediately.
148
+ throw new Error(data.completions);
149
+ }
145
150
  return { actual: data.completions };
146
151
  });
147
152
  this.ctx.lastSnapName = "completions";
@@ -173,10 +178,6 @@ export class ChainableAssertions {
173
178
  };
174
179
  }
175
180
  }
176
- const checkCompletionsForErrors = (completions) => {
177
- if (typeof completions === "string")
178
- throw new Error(completions);
179
- };
180
181
  const declarationPrefix = "type T = ";
181
182
  const formatTypeString = (typeString) => prettier
182
183
  .format(`${declarationPrefix}${typeString}`, {
@@ -1,6 +1,6 @@
1
- import { snapshot } from "@ark/util";
2
- import { AssertionError } from "node:assert";
1
+ import { snapshot, throwInternalError } from "@ark/util";
3
2
  import process from "node:process";
3
+ import { throwAssertionError } from "../assert/assertions.js";
4
4
  import { queueSnapshotUpdate, writeSnapshotUpdatesOnExit } from "../cache/snapshots.js";
5
5
  import { stringifyMeasure } from "./measure.js";
6
6
  export const queueBaselineUpdateIfNeeded = (updated, baseline, ctx) => {
@@ -9,15 +9,18 @@ export const queueBaselineUpdateIfNeeded = (updated, baseline, ctx) => {
9
9
  return;
10
10
  const serializedValue = snapshot(updated);
11
11
  if (!ctx.lastSnapCallPosition) {
12
- throw new Error(`Unable to update baseline for ${ctx.qualifiedName} ('lastSnapCallPosition' was unset).`);
12
+ throwInternalError(`Unable to update baseline for ${ctx.qualifiedName} ('lastSnapCallPosition' was unset)`);
13
+ }
14
+ if (!ctx.lastSnapFunctionName) {
15
+ throwInternalError(`Unable to update baseline for ${ctx.qualifiedName} ('lastSnapFunctionName' was unset)`);
13
16
  }
14
17
  queueSnapshotUpdate({
15
18
  position: ctx.lastSnapCallPosition,
16
19
  serializedValue,
17
- snapFunctionName: ctx.kind,
20
+ snapFunctionName: ctx.lastSnapFunctionName,
18
21
  baselinePath: ctx.qualifiedPath
19
22
  });
20
- if (ctx.kind === "types")
23
+ if (ctx.lastSnapFunctionName === "types")
21
24
  writeSnapshotUpdatesOnExit();
22
25
  };
23
26
  /** Pretty print comparison and set the process.exitCode to 1 if delta threshold is exceeded */
@@ -42,8 +45,8 @@ const handlePositiveDelta = (formattedDelta, ctx) => {
42
45
  console.error(`📈 ${message}`);
43
46
  if (ctx.cfg.benchErrorOnThresholdExceeded) {
44
47
  const errorSummary = `❌ ${message}`;
45
- if (ctx.kind === "instantiations")
46
- throw new AssertionError({ message: errorSummary });
48
+ if (ctx.lastSnapFunctionName === "instantiations")
49
+ throwAssertionError({ stack: ctx.assertionStack, message: errorSummary });
47
50
  else {
48
51
  process.exitCode = 1;
49
52
  // Summarize failures at the end of output
@@ -52,10 +52,11 @@ export type BenchContext = {
52
52
  qualifiedName: string;
53
53
  options: InternalBenchOptions;
54
54
  cfg: ParsedAttestConfig;
55
+ assertionStack: string;
55
56
  benchCallPosition: SourcePosition;
56
57
  lastSnapCallPosition: SourcePosition | undefined;
58
+ lastSnapFunctionName: string | undefined;
57
59
  isAsync: boolean;
58
- kind: TimeAssertionName | "types" | "instantiations";
59
60
  };
60
61
  export type BenchableFunction = () => unknown | Promise<unknown>;
61
62
  export type InitialBenchAssertions<Fn extends BenchableFunction> = BenchAssertions<Fn> & BenchTypeAssertions;
@@ -1,4 +1,4 @@
1
- import { caller, rmRf } from "@ark/fs";
1
+ import { caller, getCallStack, rmRf } from "@ark/fs";
2
2
  import { performance } from "node:perf_hooks";
3
3
  import { ensureCacheDirs, getConfig } from "../config.js";
4
4
  import { chainableNoOpProxy } from "../utils.js";
@@ -138,7 +138,7 @@ export class BenchAssertions {
138
138
  console.groupEnd();
139
139
  queueBaselineUpdateIfNeeded(createTimeMeasure(ms), baseline, {
140
140
  ...this.ctx,
141
- kind: name
141
+ lastSnapFunctionName: name
142
142
  });
143
143
  return this.getNextAssertions();
144
144
  }
@@ -159,7 +159,7 @@ export class BenchAssertions {
159
159
  console.groupEnd();
160
160
  queueBaselineUpdateIfNeeded(markResults, baseline, {
161
161
  ...this.ctx,
162
- kind: "mark"
162
+ lastSnapFunctionName: "mark"
163
163
  });
164
164
  return this.getNextAssertions();
165
165
  }
@@ -220,5 +220,7 @@ export const getBenchCtx = (qualifiedPath, isAsync = false, options = {}) => ({
220
220
  cfg: getConfig(),
221
221
  benchCallPosition: caller(),
222
222
  lastSnapCallPosition: undefined,
223
- isAsync
223
+ lastSnapFunctionName: undefined,
224
+ isAsync,
225
+ assertionStack: getCallStack({ offset: 1 }).join("\n")
224
226
  });
package/out/bench/type.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { caller } from "@ark/fs";
2
+ import { throwInternalError } from "@ark/util";
2
3
  import ts from "typescript";
3
4
  import { getBenchAssertionsAtPosition } from "../cache/getCachedAssertions.js";
4
5
  import { TsServer, getAbsolutePosition, getAncestors, getDescendants, nearestCallExpressionChild } from "../cache/ts.js";
@@ -9,7 +10,7 @@ import { createTypeComparison } from "./measure.js";
9
10
  export const createBenchTypeAssertion = (ctx) => ({
10
11
  types: (...args) => {
11
12
  ctx.lastSnapCallPosition = caller();
12
- instantiationDataHandler({ ...ctx, kind: "types" }, args[0]);
13
+ instantiationDataHandler({ ...ctx, lastSnapFunctionName: "types" }, args[0]);
13
14
  }
14
15
  });
15
16
  export const getContributedInstantiations = (ctx) => {
@@ -23,7 +24,7 @@ export const getContributedInstantiations = (ctx) => {
23
24
  }
24
25
  const body = getDescendants(firstMatchingNamedCall).find(node => ts.isArrowFunction(node) || ts.isFunctionExpression(node));
25
26
  if (!body)
26
- throw new Error("Unable to retrieve contents of the call expression");
27
+ throwInternalError("Unable to retrieve contents of the call expression");
27
28
  return getInstantiationsContributedByNode(file, body);
28
29
  };
29
30
  export const instantiationDataHandler = (ctx, args, isBenchFunction = true) => {
@@ -1,4 +1,5 @@
1
1
  import { filePath, positionToString, readFile, readJson, shell, writeFile, writeJson } from "@ark/fs";
2
+ import { throwInternalError } from "@ark/util";
2
3
  import { existsSync } from "node:fs";
3
4
  import { basename, dirname, isAbsolute, join } from "node:path";
4
5
  import { getConfig } from "../config.js";
@@ -39,7 +40,7 @@ const findCallExpressionAncestor = (position, functionName) => {
39
40
  const calls = getCallExpressionsByName(startNode, [functionName], true);
40
41
  if (calls.length)
41
42
  return startNode;
42
- throw new Error(`Unable to locate expected inline ${functionName} call from assertion at ${positionToString(position)}.`);
43
+ throwInternalError(`Unable to locate expected inline ${functionName} call from assertion at ${positionToString(position)}.`);
43
44
  };
44
45
  export const updateExternalSnapshot = ({ serializedValue: value, position, name, customPath }) => {
45
46
  const snapshotPath = resolveSnapshotPath(position.file, customPath);
package/out/cache/ts.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { fromCwd } from "@ark/fs";
2
- import { throwInternalError } from "@ark/util";
2
+ import { printable, throwInternalError } from "@ark/util";
3
3
  import * as tsvfs from "@typescript/vfs";
4
4
  import { readFileSync } from "node:fs";
5
5
  import { dirname, join } from "node:path";
@@ -31,14 +31,14 @@ export class TsServer {
31
31
  const tsPath = path.replaceAll(/\\/g, "/");
32
32
  const file = this.virtualEnv.getSourceFile(tsPath);
33
33
  if (!file)
34
- throw new Error(`Could not find ${path}.`);
34
+ throwInternalError(`Could not find TS path ${path}`);
35
35
  return file;
36
36
  }
37
37
  }
38
38
  export const nearestCallExpressionChild = (node, position) => {
39
39
  const result = nearestBoundingCallExpression(node, position);
40
40
  if (!result) {
41
- throw new Error(`Unable to find bounding call expression at position ${position} in ${node.getSourceFile().fileName}`);
41
+ throwInternalError(`Unable to find bounding call expression at position ${position} in ${node.getSourceFile().fileName}`);
42
42
  }
43
43
  return result;
44
44
  };
@@ -52,7 +52,7 @@ export const getAbsolutePosition = (file, position) => {
52
52
  // TS uses 0-based line and char #s
53
53
  position.line - 1, position.char - 1);
54
54
  if (!pos) {
55
- throw new Error(`Absolute position was not able to be found in ${file.fileName}`);
55
+ throwInternalError(`Absolute position ${printable(position)} does not exist in ${file.fileName}`);
56
56
  }
57
57
  return pos;
58
58
  };
@@ -61,7 +61,7 @@ export const getTsConfigInfoOrThrow = () => {
61
61
  const tsconfig = config.tsconfig;
62
62
  const configFilePath = tsconfig ?? ts.findConfigFile(fromCwd(), ts.sys.fileExists, "tsconfig.json");
63
63
  if (!configFilePath) {
64
- throw new Error(`File ${tsconfig ?? join(fromCwd(), "tsconfig.json")} must exist.`);
64
+ throw new Error(`File ${tsconfig ?? join(fromCwd(), "tsconfig.json")} must exist`);
65
65
  }
66
66
  const configFileText = readFileSync(configFilePath).toString();
67
67
  const result = ts.parseConfigFileTextToJson(configFilePath, configFileText);
@@ -1,4 +1,5 @@
1
1
  import { filePath } from "@ark/fs";
2
+ import { throwInternalError } from "@ark/util";
2
3
  import * as tsvfs from "@typescript/vfs";
3
4
  import ts from "typescript";
4
5
  import { getConfig } from "../config.js";
@@ -33,8 +34,10 @@ export const gatherInlineInstantiationData = (file, fileAssertions, attestAliasI
33
34
  });
34
35
  const instantiationInfo = enclosingFunctions.map(enclosingFunction => {
35
36
  const body = getDescendants(enclosingFunction.ancestor).find(node => ts.isArrowFunction(node) || ts.isFunctionExpression(node));
36
- if (!body)
37
- throw new Error("Unable to find file contents");
37
+ if (!body) {
38
+ throwInternalError(`Unable to resolve source associated with TS Node:
39
+ ${enclosingFunction.ancestor.getText()}`);
40
+ }
38
41
  return {
39
42
  location: enclosingFunction.position,
40
43
  count: getInstantiationsContributedByNode(file, body)
package/out/cli/trace.js CHANGED
@@ -4,8 +4,12 @@ import { resolve } from "path";
4
4
  import { getConfig } from "../config.js";
5
5
  import { baseDiagnosticTscCmd } from "./shared.js";
6
6
  export const trace = async (args) => {
7
- const packageDir = args[0] ?? process.cwd();
7
+ const packageDir = resolve(args[0] ?? process.cwd());
8
8
  const config = getConfig();
9
+ if (!config.tsconfig) {
10
+ console.error(`attest trace must be run from a directory with a tsconfig.json file`);
11
+ process.exit(1);
12
+ }
9
13
  const traceDir = resolve(config.cacheDir, "trace");
10
14
  ensureDir(traceDir);
11
15
  try {
@@ -15,7 +19,7 @@ export const trace = async (args) => {
15
19
  // the .attest/trace directory will contain a trace.json file and a types.json file.
16
20
  // the trace.json file can be viewed via a tool like https://ui.perfetto.dev/
17
21
  // the types.json file can be used to associate IDs from the trace file with type aliases
18
- execSync(`${baseDiagnosticTscCmd} --generateTrace ${traceDir}`, {
22
+ execSync(`${baseDiagnosticTscCmd} --project ${config.tsconfig} --generateTrace ${traceDir}`, {
19
23
  cwd: packageDir,
20
24
  stdio: "inherit"
21
25
  });
package/out/fixtures.js CHANGED
@@ -16,7 +16,7 @@ export const setup = (options) => {
16
16
  if (config.skipTypes)
17
17
  return teardown;
18
18
  if (config.tsVersions.length === 1 &&
19
- config.tsVersions[0].alias === "typescript")
19
+ config.tsVersions[0].alias === "default")
20
20
  writeAssertionData(config.defaultAssertionCachePath);
21
21
  else {
22
22
  forTypeScriptVersions(config.tsVersions, version => {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@ark/attest",
3
- "version": "0.18.0",
3
+ "version": "0.18.2",
4
4
  "author": {
5
5
  "name": "David Blass",
6
6
  "email": "david@arktype.io",
@@ -35,9 +35,9 @@
35
35
  "@typescript/analyze-trace": "0.10.1",
36
36
  "prettier": "3.3.3",
37
37
  "@prettier/sync": "0.5.2",
38
- "arktype": "2.0.0-rc.7",
39
- "@ark/util": "0.9.0",
40
- "@ark/fs": "0.9.0"
38
+ "@ark/fs": "0.11.0",
39
+ "@ark/util": "0.11.0",
40
+ "arktype": "2.0.0-rc.9"
41
41
  },
42
42
  "devDependencies": {
43
43
  "typescript": "5.6.2"