@ark/attest 0.56.7 → 0.57.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.
Files changed (40) hide show
  1. package/README.md +9 -385
  2. package/out/assert/assertions.d.ts +1 -1
  3. package/out/assert/assertions.js +12 -18
  4. package/out/assert/attest.d.ts +2 -3
  5. package/out/assert/attest.js +3 -3
  6. package/out/assert/chainableAssertions.d.ts +1 -1
  7. package/out/assert/chainableAssertions.js +2 -1
  8. package/out/bench/type.js +6 -3
  9. package/out/cache/getCachedAssertions.d.ts +33 -11
  10. package/out/cache/getCachedAssertions.js +23 -46
  11. package/out/cache/snapshots.d.ts +6 -2
  12. package/out/cache/snapshots.js +32 -26
  13. package/out/cache/ts.js +6 -3
  14. package/out/cache/utils.d.ts +1 -1
  15. package/out/cache/writeAssertionCache.d.ts +1 -30
  16. package/out/cache/writeAssertionCache.js +2 -1
  17. package/out/cli/precache.js +3 -4
  18. package/out/cli/shared.d.ts +1 -1
  19. package/out/cli/shared.js +4 -1
  20. package/out/cli/trace.js +60 -25
  21. package/out/config.d.ts +6 -22
  22. package/out/config.js +5 -30
  23. package/out/fixtures.js +5 -18
  24. package/out/index.d.ts +1 -3
  25. package/out/index.js +1 -2
  26. package/out/ts7/analyze.d.ts +10 -0
  27. package/out/ts7/analyze.js +188 -0
  28. package/out/ts7/countInstantiations.d.ts +1 -0
  29. package/out/ts7/countInstantiations.js +44 -0
  30. package/out/ts7/instantiations.d.ts +13 -0
  31. package/out/ts7/instantiations.js +113 -0
  32. package/out/ts7/server.d.ts +48 -0
  33. package/out/ts7/server.js +224 -0
  34. package/out/ts7/snapshots.d.ts +5 -0
  35. package/out/ts7/snapshots.js +27 -0
  36. package/out/utils.d.ts +17 -0
  37. package/out/utils.js +33 -1
  38. package/package.json +8 -6
  39. package/out/tsVersioning.d.ts +0 -31
  40. package/out/tsVersioning.js +0 -172
package/README.md CHANGED
@@ -16,391 +16,15 @@ npm install @ark/attest
16
16
 
17
17
  _Note: This package is still in alpha! Your feedback will help us iterate toward a stable 1.0._
18
18
 
19
- ## Setup
19
+ ## Docs
20
20
 
21
- To use attest's type assertions, you'll need to call our setup/cleanup methods before your first test and after your last test, respectively. This usually involves some kind of globalSetup/globalTeardown config.
21
+ See [arktype.io/docs/attest](https://arktype.io/docs/attest) for:
22
22
 
23
- > [!IMPORTANT]
24
- > If you run your tests in watch mode or otherwise iteratively during dev, you will want to enable [`--skipTypes` mode](#skiptypes).
23
+ - [Setup](https://arktype.io/docs/attest) with Vitest, Mocha and other test runners
24
+ - [Assertions](https://arktype.io/docs/attest/assertions) for types, values, errors, completions and JSDoc
25
+ - [Benches](https://arktype.io/docs/attest/benches) measuring type instantiations and runtime
26
+ - [Options](https://arktype.io/docs/attest/options) like `skipTypes` and `typeToStringFormat`
27
+ - The [CLI](https://arktype.io/docs/attest/cli) for type performance stats and traces
28
+ - [Integrating](https://arktype.io/docs/attest/integration) attest's type data into your own assertions
25
29
 
26
- ### Vitest
27
-
28
- `vitest.config.ts`
29
-
30
- ```ts
31
- import { defineConfig } from "vitest/config"
32
-
33
- export default defineConfig({
34
- test: {
35
- globalSetup: ["setupVitest.ts"]
36
- }
37
- })
38
- ```
39
-
40
- `setupVitest.ts`
41
-
42
- ```ts
43
- import { setup } from "@ark/attest"
44
-
45
- // config options can be passed here
46
- export default () => setup({})
47
- ```
48
-
49
- ### Mocha
50
-
51
- `package.json`
52
-
53
- ```json
54
- "mocha": {
55
- "require": "./setupMocha.ts"
56
- }
57
- ```
58
-
59
- `setupMocha.ts`
60
-
61
- ```ts
62
- import { setup, teardown } from "@ark/attest"
63
-
64
- // config options can be passed here
65
- export const mochaGlobalSetup = () => setup({})
66
-
67
- export const mochaGlobalTeardown = teardown
68
- ```
69
-
70
- You should also add `.attest` to your repository's `.gitignore` file.
71
-
72
- 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!
73
-
74
- ## Assertions
75
-
76
- Here are some simple examples of type assertions and snapshotting:
77
-
78
- ```ts
79
- // @ark/attest assertions can be made from any unit test framework with a global setup/teardown
80
- describe("attest features", () => {
81
- it("type and value assertions", () => {
82
- const even = type("number%2")
83
- // asserts even.infer is exactly number
84
- attest<number>(even.infer)
85
- // make assertions about types and values seamlessly
86
- attest(even.infer).type.toString.snap("number")
87
- // including object literals- no more long inline strings!
88
- attest(even.json).snap({
89
- intersection: [{ domain: "number" }, { divisor: 2 }]
90
- })
91
- })
92
-
93
- it("error assertions", () => {
94
- // Check type errors, runtime errors, or both at the same time!
95
- // @ts-expect-error
96
- attest(() => type("number%0")).throwsAndHasTypeError(
97
- "% operator must be followed by a non-zero integer literal (was 0)"
98
- )
99
- // @ts-expect-error
100
- attest(() => type({ "[object]": "string" })).type.errors(
101
- "Indexed key definition 'object' must be a string, number or symbol"
102
- )
103
- })
104
-
105
- it("completion snapshotting", () => {
106
- // snapshot expected completions for any string literal!
107
- // @ts-expect-error (if your expression would throw, prepend () =>)
108
- attest(() => type({ a: "a", b: "b" })).completions({
109
- a: ["any", "alpha", "alphanumeric"],
110
- b: ["bigint", "boolean"]
111
- })
112
- type Legends = { faker?: "🐐"; [others: string]: unknown }
113
- // works for keys or index access as well (may need prettier-ignore to avoid removing quotes)
114
- // prettier-ignore
115
- attest({ "f": "🐐" } as Legends).completions({ "f": ["faker"] })
116
- })
117
-
118
- it("jsdoc snapshotting", () => {
119
- // match or snapshot expected jsdoc associated with the value passed to attest
120
- const T = type({
121
- /** FOO */
122
- foo: "string"
123
- })
124
-
125
- const out = T.assert({ foo: "foo" })
126
-
127
- attest(out.foo).jsdoc.snap("FOO")
128
- })
129
-
130
- it("integrate runtime logic with type assertions", () => {
131
- const arrayOf = type("<t>", "t[]")
132
- const numericArray = arrayOf("number | bigint")
133
- // flexibly combine runtime logic with type assertions to customize your
134
- // tests beyond what is possible from pure static-analysis based type testing tools
135
- if (getPrimaryTsVersionUnderTest().startsWith("5")) {
136
- // this assertion will only occur when testing TypeScript 5+!
137
- attest<(number | bigint)[]>(numericArray.infer)
138
- }
139
- })
140
-
141
- it("integrated type performance benchmarking", () => {
142
- const User = type({
143
- kind: "'admin'",
144
- "powers?": "string[]"
145
- })
146
- .or({
147
- kind: "'superadmin'",
148
- "superpowers?": "string[]"
149
- })
150
- .or({
151
- kind: "'pleb'"
152
- })
153
- attest.instantiations([7574, "instantiations"])
154
- })
155
- })
156
- ```
157
-
158
- ## Options
159
-
160
- Options can be specified in one of 3 ways:
161
-
162
- - An argument passed to your test process, e.g. `--skipTypes` or `--benchPercentThreshold 10`
163
- - An environment variable with an `ATTEST_` prefix, e.g. `ATTEST_skipTypes=1` or `ATTEST_benchPercentThreshold=10`
164
- - Passed as an option to attest's `setup` function, e.g.:
165
-
166
- `setupVitest.ts`
167
-
168
- ```ts
169
- import * as attest from "@ark/attest"
170
-
171
- export const setup = () =>
172
- attest.setup({
173
- skipTypes: true,
174
- benchPercentThreshold: 10
175
- })
176
- ```
177
-
178
- Here are the current defaults for all available options. Please note, some of these are experimental and subject to change:
179
-
180
- ```ts
181
- export const getDefaultAttestConfig = (): BaseAttestConfig => ({
182
- tsconfig:
183
- existsSync(fromCwd("tsconfig.json")) ? fromCwd("tsconfig.json") : undefined,
184
- attestAliases: ["attest", "attestInternal"],
185
- updateSnapshots: false,
186
- skipTypes: false,
187
- skipInlineInstantiations: false,
188
- tsVersions: "typescript",
189
- benchPercentThreshold: 20,
190
- benchErrorOnThresholdExceeded: true,
191
- filter: undefined,
192
- testDeclarationAliases: ["bench", "it", "test"],
193
- formatter: `npm exec --no -- prettier --write`,
194
- shouldFormat: true,
195
- typeToStringFormat: {}
196
- })
197
- ```
198
-
199
- ### `skipTypes`
200
-
201
- `skipTypes` is extremely useful for iterating quickly during development without having to typecheck your project to test runtime logic.
202
-
203
- When this setting is enabled, setup will skip type checking and all assertions requiring type information will be skipped.
204
-
205
- You likely want two scripts, one for running tests with types and one for tests without:
206
-
207
- ```json
208
- "test": "ATTEST_skipTypes=1 vitest run",
209
- "testWithTypes": "vitest run",
210
- ```
211
-
212
- Our recommendation is to use `test` when:
213
-
214
- - Only wanting to test runtime logic during development
215
- - Running tests in watch mode or via VSCode's Test Explorer
216
-
217
- Use `testWithTypes` when:
218
-
219
- - You've made changes to your types and want to recheck your type-level assertions
220
- - You're running your tests in CI
221
-
222
- ### `typeToStringFormat`
223
-
224
- A set of [`prettier.Options`](https://prettier.io/docs/en/options.html) overrides that apply specifically `type.toString` formatting.
225
-
226
- Any options you provide will override the defaults, which are as follows:
227
-
228
- ```jsonc
229
- {
230
- "semi": false,
231
- // note this print width is optimized for type serialization, not general code
232
- "printWidth": 60,
233
- "trailingComma": "none",
234
- "parser": "typescript"
235
- }
236
- ```
237
-
238
- The easiest way to provide overrides is to the `setup` function, but they can also be provided as a JSON serialized string either passed to a `--typeToStringFormat` CLI flag or set as the value of `ATTEST_typeToStringFormat` on `process.env`.
239
-
240
- ## Benches
241
-
242
- Benches are run separately from tests and don't require any special setup. If the below file was `benches.ts`, you could run it using something like `tsx benches.ts` or `ts-node benches.ts`:
243
-
244
- ```ts
245
- // Combinatorial template literals often result in expensive types- let's benchmark this one!
246
- type makeComplexType<s extends string> =
247
- s extends `${infer head}${infer tail}` ? head | tail | makeComplexType<tail>
248
- : s
249
-
250
- bench("bench type", () => {
251
- return {} as makeComplexType<"defenestration">
252
- // This is an inline snapshot that will be populated or compared when you run the file
253
- }).types([169, "instantiations"])
254
-
255
- bench(
256
- "bench runtime and type",
257
- () => {
258
- return {} as makeComplexType<"antidisestablishmentarianism">
259
- },
260
- fakeCallOptions
261
- )
262
- // Average time it takes the function execute
263
- .mean([2, "ms"])
264
- // Seems like our type is O(n) with respect to the length of the input- not bad!
265
- .types([337, "instantiations"])
266
- ```
267
-
268
- If you're benchmarking an API, you'll need to include a "baseline expression" so that instantiations created when your API is initially invoked don't add noise to the individual tests.
269
-
270
- Here's an example of what that looks like:
271
-
272
- ```ts
273
- import { bench } from "@ark/attest"
274
- import { type } from "arktype"
275
-
276
- // baseline expression
277
- type("boolean")
278
-
279
- bench("single-quoted", () => {
280
- const _ = type("'nineteen characters'")
281
- // would be 2697 without baseline
282
- }).types([610, "instantiations"])
283
-
284
- bench("keyword", () => {
285
- const _ = type("string")
286
- // would be 2507 without baseline
287
- }).types([356, "instantiations"])
288
- ```
289
-
290
- > [!WARNING]
291
- > Be sure your baseline expression is not identical to an expression you are using in any of your benchmarks. If it is, the individual benchmarks will reuse its cached types, leading to reduced (or 0) instantiations.
292
-
293
- If you'd like to fail in CI above a threshold, you can add flags like the following (default value is 20%, but it will not throw unless `--benchErrorOnThresholdExceeded` is set):
294
-
295
- ```
296
- tsx ./p99/within-limit/p99-tall-simple.bench.ts --benchErrorOnThresholdExceeded --benchPercentThreshold 10
297
- ```
298
-
299
- ## CLI
300
-
301
- Attest also includes a built-in `attest` CLI including the following commands:
302
-
303
- ### `stats`
304
-
305
- ```bash
306
- npm run attest stats packages/*
307
- ```
308
-
309
- Summarizes key type performance metrics for each package (check time, instantiations, and type count).
310
-
311
- Expects any number of args representing package directories to check, optionally specified using glob patterns like `packages/*`.
312
-
313
- If no directories are provided, defaults to CWD.
314
-
315
- ### `trace`
316
-
317
- ```bash
318
- npm run attest trace .
319
- ```
320
-
321
- Creates a trace.json file in `.attest/trace` that can be viewed as a type performance heat map via a tool like https://ui.perfetto.dev/. Also summarizes any hot spots as identified by `@typescript/analyze-trace`.
322
-
323
- Trace expects a single argument representing the root directory of the root package for which to gather type information.
324
-
325
- ## Integration
326
-
327
- ### Setup
328
-
329
- If you're a library author wanting to integrate type into your own assertions instead of using the `attest` API, you'll need to call `setup` with a list of `attestAliases` to ensure type data is collected from your own functions:
330
-
331
- ```ts
332
- // attest will only collect type data from functions with names listed in `attestAliases`
333
- setup({ attestAliases: ["yourCustomAssert"] })
334
-
335
- // There are many other config options, but some are primarily internal- use others at your own risk!
336
- ```
337
-
338
- You'll need to make sure that setup with whatever aliases you need before the first test runs. As part of the setup process, attest will search for the specified assertion calls and cache their types in a temporary file that will be referenced during test execution.
339
-
340
- This ensures that type assertions can be made across processes without creating a new TSServer instance for each.
341
-
342
- ### TS Versions
343
-
344
- There is a tsVersions setting that allows testing multiple TypeScript aliases at once.
345
-
346
- ````ts globalSetup.ts
347
- import { setup } from "@ark/attest"
348
- /** A string or list of strings representing the TypeScript version aliases to run.
349
- *
350
- * Aliases must be specified as a package.json dependency or devDependency beginning with "typescript".
351
- * Alternate aliases can be specified using the "npm:" prefix:
352
- * ```json
353
- * "typescript": "latest",
354
- * "typescript-next": "npm:typescript@next",
355
- * "typescript-1": "npm:typescript@5.2"
356
- * "typescript-2": "npm:typescript@5.1"
357
- * ```
358
- *
359
- * "*" can be pased to run all discovered versions beginning with "typescript".
360
- */
361
- setup({ tsVersions: "*" })
362
- ````
363
-
364
- ### APIs
365
-
366
- The most flexible attest APIs are `getTypeAssertionsAtPosition` and `caller`.
367
-
368
- Here's an example of how you might use them in your own API:
369
-
370
- ```ts
371
- import { getTypeAssertionsAtPosition, caller } from "@ark/attest"
372
-
373
- const yourCustomAssert = <expectedType>(actualValue: expectedType) => {
374
- const position = caller()
375
- const types = getTypeAssertionsAtPosition(position)
376
- // assert that the type of actualValue is the same as the type of expectedType
377
- const relationship = types[0].args[0].relationships.typeArgs[0]
378
- if (relationship === undefined) {
379
- throw new Error(
380
- `yourCustomAssert requires a type arg representing the expected type, e.g. 'yourCustomAssert<"foo">("foo")'`
381
- )
382
- }
383
- if (relationship !== "equality") {
384
- throw new Error(
385
- `Expected ${types.typeArgs[0].type}, got ${types.args[0].type} with relationship ${relationship}`
386
- )
387
- }
388
- }
389
- ```
390
-
391
- A user might then use `yourCustomAssert` like this:
392
-
393
- ```ts
394
- import { yourCustomAssert } from "your-package"
395
-
396
- test("my code", () => {
397
- // Ok
398
- yourCustomAssert<"foo">(`${"f"}oo` as const)
399
- // Error: `Expected boolean, got true with relationship subtype`
400
- yourCustomAssert<boolean>(true)
401
- // Error: `Expected 5, got number with relationship supertype`
402
- yourCustomAssert<5>(2 + 3)
403
- })
404
- ```
405
-
406
- Please don't hesitate to a GitHub [issue](https://github.com/arktypeio/arktype/issues/new/choose) or [discussion](https://github.com/arktypeio/arktype/discussions/new/choose) or reach out on [ArkType's Discord](https://arktype.io/discord) if you have any questions or feedback- we'd love to hear from you! ⛵
30
+ Please don't hesitate to open a GitHub [issue](https://github.com/arktypeio/arktype/issues/new/choose) or [discussion](https://github.com/arktypeio/arktype/discussions/new/choose) or reach out on [ArkType's Discord](https://arktype.io/discord) if you have any questions or feedback- we'd love to hear from you! ⛵
@@ -1,4 +1,4 @@
1
- import type { TypeRelationshipAssertionData } from "../cache/writeAssertionCache.ts";
1
+ import type { TypeRelationshipAssertionData } from "../cache/getCachedAssertions.ts";
2
2
  import type { AssertionContext } from "./attest.ts";
3
3
  export type ThrowAssertionErrorContext = {
4
4
  message: string;
@@ -15,27 +15,21 @@ export class TypeAssertionMapping {
15
15
  }
16
16
  export const versionableAssertion = (fn) => (expected, actual, ctx) => {
17
17
  if (actual instanceof TypeAssertionMapping) {
18
- if (!ctx.typeRelationshipAssertionEntries) {
19
- throwInternalError(`Unexpected missing typeAssertionEntries when passed a TypeAssertionMapper`);
18
+ if (!ctx.typeAssertion) {
19
+ throwInternalError(`Unexpected missing typeAssertion when passed a TypeAssertionMapper`);
20
20
  }
21
- for (const [version, data] of ctx.typeRelationshipAssertionEntries) {
22
- let errorMessage = "";
23
- try {
24
- const mapped = actual.fn(data, ctx);
25
- if (mapped !== null) {
26
- fn("expected" in mapped ? mapped.expected : expected, mapped.actual, ctx);
27
- }
28
- }
29
- catch (e) {
30
- errorMessage += `❌TypeScript@${version}:${e}\n`;
31
- }
32
- if (errorMessage) {
33
- throwAssertionError({
34
- stack: ctx.assertionStack,
35
- message: errorMessage
36
- });
21
+ try {
22
+ const mapped = actual.fn(ctx.typeAssertion, ctx);
23
+ if (mapped !== null) {
24
+ fn("expected" in mapped ? mapped.expected : expected, mapped.actual, ctx);
37
25
  }
38
26
  }
27
+ catch (e) {
28
+ throwAssertionError({
29
+ stack: ctx.assertionStack,
30
+ message: `${e}`
31
+ });
32
+ }
39
33
  }
40
34
  else
41
35
  fn(expected, actual, ctx);
@@ -1,7 +1,7 @@
1
1
  import { type SourcePosition } from "@ark/fs";
2
2
  import type { ErrorMessage } from "@ark/util";
3
3
  import type { Measure } from "../bench/measure.ts";
4
- import { type VersionedTypeAssertion } from "../cache/getCachedAssertions.ts";
4
+ import { type TypeAssertionData } from "../cache/getCachedAssertions.ts";
5
5
  import { type AttestConfig } from "../config.ts";
6
6
  import { type TypeAssertionMapping } from "./assertions.ts";
7
7
  import { ChainableAssertions, type AssertionKind, type rootAssertions } from "./chainableAssertions.ts";
@@ -21,8 +21,7 @@ export type AssertionContext = {
21
21
  position: SourcePosition;
22
22
  defaultExpected?: unknown;
23
23
  assertionStack: string;
24
- typeRelationshipAssertionEntries?: VersionedTypeAssertion<"type">[];
25
- typeBenchmarkingAssertionEntries?: VersionedTypeAssertion<"bench">[];
24
+ typeAssertion?: TypeAssertionData<"type">;
26
25
  lastSnapName?: string;
27
26
  };
28
27
  export type InternalAssertionHooks = {
@@ -1,7 +1,7 @@
1
1
  import { caller, getCallStack } from "@ark/fs";
2
2
  import { getBenchCtx } from "../bench/bench.js";
3
3
  import { instantiationDataHandler } from "../bench/type.js";
4
- import { getTypeAssertionsAtPosition } from "../cache/getCachedAssertions.js";
4
+ import { getTypeAssertionAtPosition } from "../cache/getCachedAssertions.js";
5
5
  import { getConfig } from "../config.js";
6
6
  import { assertEquals, typeEqualityMapping } from "./assertions.js";
7
7
  import { ChainableAssertions } from "./chainableAssertions.js";
@@ -18,8 +18,8 @@ export const attestInternal = (value, { cfg: cfgHooks, ...ctxHooks } = {}) => {
18
18
  ...ctxHooks
19
19
  };
20
20
  if (!cfg.skipTypes) {
21
- ctx.typeRelationshipAssertionEntries = getTypeAssertionsAtPosition(position);
22
- if (ctx.typeRelationshipAssertionEntries[0]?.[1].typeArgs[0]) {
21
+ ctx.typeAssertion = getTypeAssertionAtPosition(position);
22
+ if (ctx.typeAssertion.typeArgs[0]) {
23
23
  // if there is an expected type arg, check it immediately
24
24
  assertEquals(undefined, typeEqualityMapping, ctx);
25
25
  }
@@ -1,6 +1,6 @@
1
1
  import { snapshot, type Constructor, type ErrorType, type isDisjoint } from "@ark/util";
2
2
  import { type } from "arktype";
3
- import type { Completions } from "../cache/writeAssertionCache.ts";
3
+ import type { Completions } from "../cache/getCachedAssertions.ts";
4
4
  import type { AssertionContext } from "./attest.ts";
5
5
  export type ChainableAssertionOptions = {
6
6
  allowRegex?: boolean;
@@ -15,7 +15,8 @@ export class ChainableAssertions {
15
15
  }
16
16
  get unversionedActual() {
17
17
  if (this.versionableActual instanceof TypeAssertionMapping) {
18
- return this.versionableActual.fn(this.ctx.typeRelationshipAssertionEntries[0][1], this.ctx).actual;
18
+ return this.versionableActual.fn(this.ctx.typeAssertion, this.ctx)
19
+ .actual;
19
20
  }
20
21
  return this.versionableActual;
21
22
  }
package/out/bench/type.js CHANGED
@@ -1,10 +1,12 @@
1
1
  import { caller } from "@ark/fs";
2
2
  import { throwInternalError } from "@ark/util";
3
3
  import ts from "typescript";
4
- import { getBenchAssertionsAtPosition } from "../cache/getCachedAssertions.js";
4
+ import { getBenchAssertionAtPosition } from "../cache/getCachedAssertions.js";
5
5
  import { TsServer, getAbsolutePosition, getAncestors, getDescendants, nearestCallExpressionChild } from "../cache/ts.js";
6
6
  import { getCallExpressionsByName, getInstantiationsContributedByNode } from "../cache/utils.js";
7
7
  import { getConfig } from "../config.js";
8
+ import { getBenchInstantiations } from "../ts7/instantiations.js";
9
+ import { isTs7 } from "../utils.js";
8
10
  import { compareToBaseline, queueBaselineUpdateIfNeeded } from "./baseline.js";
9
11
  import { createTypeComparison } from "./measure.js";
10
12
  export const createBenchTypeAssertion = (ctx) => ({
@@ -29,8 +31,9 @@ export const getContributedInstantiations = (ctx) => {
29
31
  };
30
32
  export const instantiationDataHandler = (ctx, args, isBenchFunction = true) => {
31
33
  const instantiationsContributed = isBenchFunction ?
32
- getContributedInstantiations(ctx)
33
- : getBenchAssertionsAtPosition(ctx.benchCallPosition)[0][1].count;
34
+ isTs7 ? getBenchInstantiations(ctx.benchCallPosition)
35
+ : getContributedInstantiations(ctx)
36
+ : getBenchAssertionAtPosition(ctx.benchCallPosition).count;
34
37
  const comparison = createTypeComparison(instantiationsContributed, args);
35
38
  compareToBaseline(comparison, ctx);
36
39
  queueBaselineUpdateIfNeeded(comparison.updated, args, ctx);
@@ -1,11 +1,33 @@
1
- import { type SourcePosition } from "@ark/fs";
2
- import type { AssertionsByFile, TypeAssertionData, TypeAssertionKind } from "./writeAssertionCache.ts";
3
- export type VersionedAssertionsByFile = [
4
- tsVersion: string,
5
- relationshipAssertions: AssertionsByFile,
6
- benchAssertions: AssertionsByFile
7
- ];
8
- export declare const getCachedAssertionEntries: () => VersionedAssertionsByFile[];
9
- export type VersionedTypeAssertion<kind extends TypeAssertionKind = TypeAssertionKind> = [tsVersion: string, assertionData: TypeAssertionData<kind>];
10
- export declare const getTypeAssertionsAtPosition: (position: SourcePosition) => VersionedTypeAssertion<"type">[];
11
- export declare const getBenchAssertionsAtPosition: (position: SourcePosition) => VersionedTypeAssertion<"bench">[];
1
+ import { type LinePosition, type SourcePosition } from "@ark/fs";
2
+ export type AssertionsByFile = Record<string, TypeAssertionData[]>;
3
+ export type Completions = Record<string, string[]> | string;
4
+ export type ArgAssertionData = {
5
+ type: string;
6
+ relationships: {
7
+ args: TypeRelationship[];
8
+ typeArgs: TypeRelationship[];
9
+ };
10
+ };
11
+ export type TypeRelationshipAssertionData = {
12
+ location: LinePositionRange;
13
+ args: ArgAssertionData[];
14
+ typeArgs: ArgAssertionData[];
15
+ errors: string[];
16
+ completions: Completions;
17
+ /** JSDoc comment for the first argument, if any */
18
+ jsdoc?: string;
19
+ };
20
+ export type TypeBenchmarkingAssertionData = {
21
+ location: LinePositionRange;
22
+ count: number;
23
+ };
24
+ export type TypeAssertionKind = "bench" | "type";
25
+ export type TypeAssertionData<kind extends TypeAssertionKind = TypeAssertionKind> = kind extends "bench" ? TypeBenchmarkingAssertionData : TypeRelationshipAssertionData;
26
+ export type LinePositionRange = {
27
+ start: LinePosition;
28
+ end: LinePosition;
29
+ };
30
+ export type TypeRelationship = "subtype" | "supertype" | "equality" | "none";
31
+ export declare const isPositionWithinRange: ({ line, char }: LinePosition, { start, end }: LinePositionRange) => boolean;
32
+ export declare const getTypeAssertionAtPosition: (position: SourcePosition) => TypeAssertionData<"type">;
33
+ export declare const getBenchAssertionAtPosition: (position: SourcePosition) => TypeAssertionData<"bench">;
@@ -1,40 +1,20 @@
1
1
  import { readJson } from "@ark/fs";
2
- import { existsSync, readdirSync } from "node:fs";
3
- import { join } from "node:path";
2
+ import { existsSync } from "node:fs";
4
3
  import { getConfig } from "../config.js";
5
4
  import { getFileKey } from "../utils.js";
6
- let assertionEntries;
7
- export const getCachedAssertionEntries = () => {
8
- if (!assertionEntries) {
9
- const config = getConfig();
10
- if (!existsSync(config.assertionCacheDir))
11
- throwMissingAssertionDataError(config.assertionCacheDir);
12
- const assertionFiles = readdirSync(config.assertionCacheDir);
13
- const relationshipAssertions = {};
14
- const benchAssertions = {};
15
- assertionEntries = assertionFiles.map(file => {
16
- const data = readJson(join(config.assertionCacheDir, file));
17
- for (const fileName of Object.keys(data)) {
18
- const relationshipAssertionData = data[fileName].filter((entry) => "args" in entry);
19
- const benchAssertionData = data[fileName].filter((entry) => "count" in entry);
20
- relationshipAssertions[fileName] = relationshipAssertionData;
21
- benchAssertions[fileName] = benchAssertionData;
22
- }
23
- return [
24
- // remove .json extension
25
- file.slice(0, -5),
26
- relationshipAssertions,
27
- benchAssertions
28
- ];
29
- });
5
+ let cachedAssertions;
6
+ const getCachedAssertions = () => {
7
+ if (!cachedAssertions) {
8
+ const { assertionCachePath } = getConfig();
9
+ if (!existsSync(assertionCachePath)) {
10
+ throw new Error(`Unable to find precached assertion data at '${assertionCachePath}'. ` +
11
+ `Ensure the 'setup' function from @ark/attest has been called before running your tests.`);
12
+ }
13
+ cachedAssertions = readJson(assertionCachePath);
30
14
  }
31
- return assertionEntries;
32
- };
33
- const throwMissingAssertionDataError = (location) => {
34
- throw new Error(`Unable to find precached assertion data at '${location}'. ` +
35
- `Ensure the 'setup' function from @ark/attest has been called before running your tests.`);
15
+ return cachedAssertions;
36
16
  };
37
- const isPositionWithinRange = ({ line, char }, { start, end }) => {
17
+ export const isPositionWithinRange = ({ line, char }, { start, end }) => {
38
18
  if (line < start.line || line > end.line)
39
19
  return false;
40
20
  if (line === start.line)
@@ -43,14 +23,12 @@ const isPositionWithinRange = ({ line, char }, { start, end }) => {
43
23
  return char <= end.char;
44
24
  return true;
45
25
  };
46
- const getAssertionsOfKindAtPosition = (position, kind) => {
26
+ const getAssertionOfKindAtPosition = (position, kind) => {
47
27
  const fileKey = getFileKey(position.file);
48
- return getCachedAssertionEntries().map(([version, typeRelationshipAssertions, BenchAssertionAssertions]) => {
49
- const assertions = kind === "type" ? typeRelationshipAssertions : BenchAssertionAssertions;
50
- if (!assertions[fileKey]) {
51
- throw new Error(`Found no assertion data for '${fileKey}' for TypeScript version ${version}.`);
52
- }
53
- const matchingAssertion = assertions[fileKey].find(assertion =>
28
+ const assertions = getCachedAssertions()[fileKey];
29
+ if (!assertions)
30
+ throw new Error(`Found no assertion data for '${fileKey}'.`);
31
+ const matchingAssertion = assertions.find(assertion => (kind === "type" ? "args" in assertion : "count" in assertion) &&
54
32
  /**
55
33
  * Depending on the environment, a trace can refer to any of these points
56
34
  * attest(...)
@@ -59,12 +37,11 @@ const getAssertionsOfKindAtPosition = (position, kind) => {
59
37
  *
60
38
  */
61
39
  isPositionWithinRange(position, assertion.location));
62
- if (!matchingAssertion) {
63
- throw new Error(`Found no assertion for TypeScript version ${version} at line ${position.line} char ${position.char} in '${fileKey}'.
40
+ if (!matchingAssertion) {
41
+ throw new Error(`Found no assertion at line ${position.line} char ${position.char} in '${fileKey}'.
64
42
  Are sourcemaps enabled and working properly?`);
65
- }
66
- return [version, matchingAssertion];
67
- });
43
+ }
44
+ return matchingAssertion;
68
45
  };
69
- export const getTypeAssertionsAtPosition = (position) => getAssertionsOfKindAtPosition(position, "type");
70
- export const getBenchAssertionsAtPosition = (position) => getAssertionsOfKindAtPosition(position, "bench");
46
+ export const getTypeAssertionAtPosition = (position) => getAssertionOfKindAtPosition(position, "type");
47
+ export const getBenchAssertionAtPosition = (position) => getAssertionOfKindAtPosition(position, "bench");