@ark/attest 0.56.6 → 0.57.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.
Files changed (40) hide show
  1. package/README.md +11 -24
  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 +3 -1
  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 +4 -22
  22. package/out/config.js +4 -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 +2 -0
  37. package/out/utils.js +3 -0
  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
@@ -132,7 +132,7 @@ describe("attest features", () => {
132
132
  const numericArray = arrayOf("number | bigint")
133
133
  // flexibly combine runtime logic with type assertions to customize your
134
134
  // tests beyond what is possible from pure static-analysis based type testing tools
135
- if (getPrimaryTsVersionUnderTest().startsWith("5")) {
135
+ if (ts.version.startsWith("5")) {
136
136
  // this assertion will only occur when testing TypeScript 5+!
137
137
  attest<(number | bigint)[]>(numericArray.infer)
138
138
  }
@@ -185,7 +185,6 @@ export const getDefaultAttestConfig = (): BaseAttestConfig => ({
185
185
  updateSnapshots: false,
186
186
  skipTypes: false,
187
187
  skipInlineInstantiations: false,
188
- tsVersions: "typescript",
189
188
  benchPercentThreshold: 20,
190
189
  benchErrorOnThresholdExceeded: true,
191
190
  filter: undefined,
@@ -341,40 +340,28 @@ This ensures that type assertions can be made across processes without creating
341
340
 
342
341
  ### TS Versions
343
342
 
344
- There is a tsVersions setting that allows testing multiple TypeScript aliases at once.
343
+ Attest analyzes your project with whichever version of `typescript` is installed. To test multiple versions, run your suite once per version, e.g. via a CI matrix that installs each version before running tests.
345
344
 
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
- ````
345
+ TypeScript 7.1+ is supported via its native API. Type assertions, completions, JSDoc, benches and the CLI work the same way, with a few differences:
346
+
347
+ - Instantiation counts are measured by running `tsc --extendedDiagnostics --singleThreaded` per bench. Since `tsc` fully checks the bench's dependencies before measuring it, work a bench shares with them isn't attributed to the bench, so counts run lower than with TypeScript 5/6, by as much as most of the count for a bench whose cost is mostly shared with its dependencies, and baselines should be recorded separately.
348
+ - Type strings, union ordering and error elaboration can differ from earlier versions, so snapshots may need to be updated when switching.
349
+ - Benches write temporary copies beside their source files while measuring, so they need a writable source directory.
363
350
 
364
351
  ### APIs
365
352
 
366
- The most flexible attest APIs are `getTypeAssertionsAtPosition` and `caller`.
353
+ The most flexible attest APIs are `getTypeAssertionAtPosition` and `caller`.
367
354
 
368
355
  Here's an example of how you might use them in your own API:
369
356
 
370
357
  ```ts
371
- import { getTypeAssertionsAtPosition, caller } from "@ark/attest"
358
+ import { getTypeAssertionAtPosition, caller } from "@ark/attest"
372
359
 
373
360
  const yourCustomAssert = <expectedType>(actualValue: expectedType) => {
374
361
  const position = caller()
375
- const types = getTypeAssertionsAtPosition(position)
362
+ const types = getTypeAssertionAtPosition(position)
376
363
  // assert that the type of actualValue is the same as the type of expectedType
377
- const relationship = types[0].args[0].relationships.typeArgs[0]
364
+ const relationship = types.args[0].relationships.typeArgs[0]
378
365
  if (relationship === undefined) {
379
366
  throw new Error(
380
367
  `yourCustomAssert requires a type arg representing the expected type, e.g. 'yourCustomAssert<"foo">("foo")'`
@@ -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");
@@ -1,5 +1,4 @@
1
1
  import { type SourcePosition } from "@ark/fs";
2
- import type ts from "typescript";
3
2
  export type SnapshotArgs = {
4
3
  position: SourcePosition;
5
4
  serializedValue: unknown;
@@ -15,7 +14,7 @@ export declare const getSnapshotByName: (file: string, name: string, customPath:
15
14
  export declare const queueSnapshotUpdate: (args: SnapshotArgs) => void;
16
15
  export type QueuedUpdate = {
17
16
  position: SourcePosition;
18
- snapCall: ts.CallExpression;
17
+ snapCallArgs: SnapCallArgs;
19
18
  snapFunctionName: string;
20
19
  newArgText: string;
21
20
  baselinePath: string[] | undefined;
@@ -24,6 +23,11 @@ export type ExternalSnapshotArgs = SnapshotArgs & {
24
23
  name: string;
25
24
  customPath: string | undefined;
26
25
  };
26
+ export type SnapCallArgs = {
27
+ pos: number;
28
+ end: number;
29
+ firstArgText: string | undefined;
30
+ };
27
31
  export declare const updateExternalSnapshot: ({ serializedValue: value, position, name, customPath }: ExternalSnapshotArgs) => void;
28
32
  export declare const writeSnapshotUpdatesOnExit: () => void;
29
33
  export declare const writeUpdates: (queuedUpdates: QueuedUpdate[]) => void;
@@ -3,7 +3,8 @@ import { throwInternalError } from "@ark/util";
3
3
  import { existsSync } from "node:fs";
4
4
  import { basename, dirname, isAbsolute, join } from "node:path";
5
5
  import { getConfig } from "../config.js";
6
- import { getFileKey } from "../utils.js";
6
+ import { getSnapCallArgs as getSnapCallArgsTs7 } from "../ts7/snapshots.js";
7
+ import { getFileKey, isTs7 } from "../utils.js";
7
8
  import { TsServer, getAbsolutePosition, nearestCallExpressionChild } from "./ts.js";
8
9
  import { getCallExpressionsByName } from "./utils.js";
9
10
  export const resolveSnapshotPath = (testFile, customPath) => {
@@ -21,7 +22,7 @@ export const getSnapshotByName = (file, name, customPath) => {
21
22
  */
22
23
  export const queueSnapshotUpdate = (args) => {
23
24
  const config = getConfig();
24
- const path = config.defaultAssertionCachePath;
25
+ const path = config.assertionCachePath;
25
26
  if (existsSync(path)) {
26
27
  const existing = readJson(path);
27
28
  writeJson(path, {
@@ -32,15 +33,19 @@ export const queueSnapshotUpdate = (args) => {
32
33
  else
33
34
  writeJson(path, { updates: [args] });
34
35
  };
35
- const findCallExpressionAncestor = (position, functionName) => {
36
- const server = TsServer.instance;
37
- const file = server.getSourceFileOrThrow(position.file);
38
- const absolutePosition = getAbsolutePosition(file, position);
39
- const startNode = nearestCallExpressionChild(file, absolutePosition);
40
- const calls = getCallExpressionsByName(startNode, [functionName], true);
41
- if (calls.length)
42
- return startNode;
43
- throwInternalError(`Unable to locate expected inline ${functionName} call from assertion at ${positionToString(position)}.`);
36
+ const getSnapCallArgs = (position, functionName) => {
37
+ if (isTs7)
38
+ return getSnapCallArgsTs7(position, functionName);
39
+ const file = TsServer.instance.getSourceFileOrThrow(position.file);
40
+ const startNode = nearestCallExpressionChild(file, getAbsolutePosition(file, position));
41
+ if (!getCallExpressionsByName(startNode, [functionName], true).length) {
42
+ throwInternalError(`Unable to locate expected inline ${functionName} call from assertion at ${positionToString(position)}.`);
43
+ }
44
+ return {
45
+ pos: startNode.arguments.pos,
46
+ end: startNode.arguments.end,
47
+ firstArgText: startNode.arguments[0]?.getText()
48
+ };
44
49
  };
45
50
  export const updateExternalSnapshot = ({ serializedValue: value, position, name, customPath }) => {
46
51
  const snapshotPath = resolveSnapshotPath(position.file, customPath);
@@ -56,20 +61,21 @@ let snapshotsWillBeWritten = false;
56
61
  export const writeSnapshotUpdatesOnExit = () => {
57
62
  if (snapshotsWillBeWritten)
58
63
  return;
59
- process.on("exit", writeCachedInlineSnapshotUpdates);
64
+ // before TS 7's API stops its server on exit
65
+ process.prependListener("exit", writeCachedInlineSnapshotUpdates);
60
66
  snapshotsWillBeWritten = true;
61
67
  };
62
68
  const writeCachedInlineSnapshotUpdates = () => {
63
69
  const config = getConfig();
64
70
  let snapshotData;
65
- if (!existsSync(config.defaultAssertionCachePath))
71
+ if (!existsSync(config.assertionCachePath))
66
72
  return;
67
73
  try {
68
- snapshotData = readJson(config.defaultAssertionCachePath).updates;
74
+ snapshotData = readJson(config.assertionCachePath).updates;
69
75
  }
70
76
  catch {
71
77
  // If we can't read the snapshot, log an error and move onto the next update
72
- console.error(`Unable to read snapshot data from expected location ${config.defaultAssertionCachePath}.`);
78
+ console.error(`Unable to read snapshot data from expected location ${config.assertionCachePath}.`);
73
79
  }
74
80
  if (snapshotData) {
75
81
  try {
@@ -82,7 +88,7 @@ const writeCachedInlineSnapshotUpdates = () => {
82
88
  }
83
89
  };
84
90
  const snapshotArgsToQueuedUpdate = ({ position, serializedValue, snapFunctionName = "snap", baselinePath }) => {
85
- const snapCall = findCallExpressionAncestor(position, snapFunctionName);
91
+ const snapCallArgs = getSnapCallArgs(position, snapFunctionName);
86
92
  let newArgText = typeof serializedValue === "string" && serializedValue.includes("\n") ?
87
93
  "`" + serializedValue.replace(/`/g, "\\`").replace(/\${/g, "\\${") + "`"
88
94
  : JSON.stringify(serializedValue);
@@ -91,7 +97,7 @@ const snapshotArgsToQueuedUpdate = ({ position, serializedValue, snapFunctionNam
91
97
  .replace(/"\$ark.undefined"/g, "undefined");
92
98
  return {
93
99
  position,
94
- snapCall,
100
+ snapCallArgs,
95
101
  snapFunctionName,
96
102
  newArgText,
97
103
  baselinePath
@@ -119,7 +125,7 @@ const runFormatterIfAvailable = (queuedUpdates) => {
119
125
  return;
120
126
  try {
121
127
  const updatedPaths = [
122
- ...new Set(queuedUpdates.map(update => filePath(update.snapCall.getSourceFile().fileName)))
128
+ ...new Set(queuedUpdates.map(update => filePath(update.position.file)))
123
129
  ];
124
130
  shell(`${formatter} ${updatedPaths.join(" ")}`);
125
131
  }
@@ -131,23 +137,23 @@ const writeFileUpdates = (path, updates) => {
131
137
  let fileText = readFile(path);
132
138
  let offSet = 0;
133
139
  for (const update of updates) {
134
- const previousArgTextLength = update.snapCall.arguments.end - update.snapCall.arguments.pos;
140
+ const { pos, end } = update.snapCallArgs;
135
141
  fileText =
136
- fileText.slice(0, update.snapCall.arguments.pos + offSet) +
142
+ fileText.slice(0, pos + offSet) +
137
143
  update.newArgText +
138
- fileText.slice(update.snapCall.arguments.end + offSet);
139
- offSet += update.newArgText.length - previousArgTextLength;
140
- summarizeSnapUpdate(update.snapCall.arguments, update);
144
+ fileText.slice(end + offSet);
145
+ offSet += update.newArgText.length - (end - pos);
146
+ summarizeSnapUpdate(update);
141
147
  }
142
148
  writeFile(path, fileText);
143
149
  };
144
- const summarizeSnapUpdate = (originalArgs, update) => {
145
- let updateSummary = `${originalArgs.length ? "🆙 Updated" : "📸 Established"} `;
150
+ const summarizeSnapUpdate = (update) => {
151
+ const previousValue = update.snapCallArgs.firstArgText;
152
+ let updateSummary = `${previousValue ? "🆙 Updated" : "📸 Established"} `;
146
153
  updateSummary +=
147
154
  update.baselinePath ?
148
155
  `baseline '${update.baselinePath.join("/")}' `
149
156
  : `snap at ${getFileKey(update.position.file)}:${update.position.line} `;
150
- const previousValue = update.snapCall.arguments[0]?.getText();
151
157
  updateSummary +=
152
158
  previousValue ?
153
159
  `from ${previousValue} to `
package/out/cache/ts.js CHANGED
@@ -124,8 +124,10 @@ const defaultDiagnosticHost = {
124
124
  const throwConfigParseError = (error) => throwError(ts.formatDiagnostics([error], defaultDiagnosticHost));
125
125
  const throwConfigInstantiationError = (instantiatedConfig) => throwError(ts.formatDiagnostics(instantiatedConfig.errors, defaultDiagnosticHost));
126
126
  export const getTsLibFiles = (tsconfigOptions) => {
127
- const defaultMapFromNodeModules = tsvfs.createDefaultMapFromNodeModules(tsconfigOptions);
128
127
  const libPath = dirname(ts.getDefaultLibFilePath(tsconfigOptions));
128
+ // read libs from the typescript attest imported rather than letting
129
+ // tsvfs resolve its own
130
+ const defaultMapFromNodeModules = tsvfs.createDefaultMapFromNodeModules(tsconfigOptions, ts, libPath);
129
131
  return {
130
132
  defaultMapFromNodeModules,
131
133
  resolvedPaths: [...defaultMapFromNodeModules.keys()].map(path => join(libPath, path))
@@ -1,6 +1,6 @@
1
1
  import * as tsvfs from "@typescript/vfs";
2
2
  import ts from "typescript";
3
- import type { LinePositionRange } from "./writeAssertionCache.ts";
3
+ import type { LinePositionRange } from "./getCachedAssertions.ts";
4
4
  export declare const getCallLocationFromCallExpression: (callExpression: ts.CallExpression) => LinePositionRange;
5
5
  /**
6
6
  * Processes inline instantiations from an attest call
@@ -1,11 +1,9 @@
1
- import type { LinePosition } from "@ark/fs";
2
1
  import ts from "typescript";
2
+ import type { AssertionsByFile, TypeAssertionData, TypeRelationship } from "./getCachedAssertions.ts";
3
3
  import { type StringifiableType } from "./ts.ts";
4
- export type AssertionsByFile = Record<string, TypeAssertionData[]>;
5
4
  export declare const analyzeProjectAssertions: () => AssertionsByFile;
6
5
  export declare const getAssertionsInFile: (file: ts.SourceFile, diagnosticsByFile: DiagnosticsByFile, attestAliases: string[]) => TypeAssertionData[];
7
6
  export declare const analyzeAssertCall: (assertCall: ts.CallExpression, diagnosticsByFile: DiagnosticsByFile) => TypeAssertionData;
8
- export type Completions = Record<string, string[]> | string;
9
7
  export type DiagnosticData = {
10
8
  start: number;
11
9
  end: number;
@@ -13,32 +11,5 @@ export type DiagnosticData = {
13
11
  };
14
12
  export type DiagnosticsByFile = Record<string, DiagnosticData[]>;
15
13
  export declare const getDiagnosticsByFile: () => DiagnosticsByFile;
16
- export type ArgAssertionData = {
17
- type: string;
18
- relationships: {
19
- args: TypeRelationship[];
20
- typeArgs: TypeRelationship[];
21
- };
22
- };
23
- export type TypeRelationshipAssertionData = {
24
- location: LinePositionRange;
25
- args: ArgAssertionData[];
26
- typeArgs: ArgAssertionData[];
27
- errors: string[];
28
- completions: Completions;
29
- /** JSDoc comment for the first argument, if any */
30
- jsdoc?: string;
31
- };
32
- export type TypeBenchmarkingAssertionData = {
33
- location: LinePositionRange;
34
- count: number;
35
- };
36
- export type TypeAssertionKind = "bench" | "type";
37
- export type TypeAssertionData<kind extends TypeAssertionKind = TypeAssertionKind> = kind extends "bench" ? TypeBenchmarkingAssertionData : TypeRelationshipAssertionData;
38
- export type LinePositionRange = {
39
- start: LinePosition;
40
- end: LinePosition;
41
- };
42
- export type TypeRelationship = "subtype" | "supertype" | "equality" | "none";
43
14
  export declare const compareTsTypes: (l: StringifiableType, r: StringifiableType) => TypeRelationship;
44
15
  export declare const checkDiagnosticMessages: (attestCall: ts.CallExpression, diagnosticsByFile: DiagnosticsByFile) => string[];
@@ -127,7 +127,8 @@ const getCompletions = (attestCall) => {
127
127
  const descendants = getDescendants(arg);
128
128
  const file = attestCall.getSourceFile();
129
129
  const text = file.getFullText();
130
- const completions = {};
130
+ // null prototype so inherited names like "constructor" aren't seen as duplicates
131
+ const completions = Object.create(null);
131
132
  for (const descendant of descendants) {
132
133
  if (ts.isStringLiteral(descendant) || ts.isTemplateLiteral(descendant)) {
133
134
  // descendant.pos tends to be an open quote while d.end tends to be right after the closing quote.
@@ -1,7 +1,6 @@
1
- import { ensureDir } from "@ark/fs";
2
- import { join } from "node:path";
1
+ import { ensureCacheDirs, getConfig } from "../config.js";
3
2
  import { writeAssertionData } from "../fixtures.js";
4
3
  export const precache = (args) => {
5
- const cacheFileToWrite = args[0] ?? join(ensureDir(".attest"), "typescript.json");
6
- writeAssertionData(cacheFileToWrite);
4
+ ensureCacheDirs();
5
+ writeAssertionData(args[0] ?? getConfig().assertionCachePath);
7
6
  };
@@ -1 +1 @@
1
- export declare const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
1
+ export declare const baseDiagnosticTscCmd: string;
package/out/cli/shared.js CHANGED
@@ -1 +1,4 @@
1
- export const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null";
1
+ import { isTs7 } from "../utils.js";
2
+ export const baseDiagnosticTscCmd = "npm exec -- tsc --noEmit --extendedDiagnostics --incremental false --tsBuildInfoFile null" +
3
+ // parallel checkers each instantiate their own copies of types
4
+ (isTs7 ? " --singleThreaded" : "");