Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 9 additions & 1 deletion ark/attest/__tests__/externalSnapshots.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -49,13 +49,21 @@ contextualize(() => {
"kt"
)
attest(1337).snap.toFile("toFileNew")
attest({} as { b: "b" | "a"; a: 1 }).type.toString.normalizedSnap.toFile(
"normalized"
)
const contents = readJson(defaultSnapPath)
attest(contents).equals({
[testFile]: {
...defaultSnapFileContents[testFile],
toFileNew: 1337
toFileNew: 1337,
normalized: '{ a: 1; b: "a" | "b" }'
}
})

attest({} as { a: 1; b: "a" | "b" }).type.toString.normalizedSnap.toFile(
"normalized"
)
})

it("update existing", () => {
Expand Down
60 changes: 60 additions & 0 deletions ark/attest/__tests__/normalizedSnap.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { attest, contextualize } from "@ark/attest"
import * as assert from "node:assert/strict"

contextualize(() => {
it("normalizes nested properties and unions without hiding type changes", () => {
const first = {} as {
z: { b: "b" | "a"; a: 1 } | { d: 4; c: 3 }
readonly a?: [string, number]
}
const reordered = {} as {
readonly a?: [string, number]
z: { c: 3; d: 4 } | { a: 1; b: "a" | "b" }
}
const expected = `{
readonly a?: [string, number]
z: { a: 1; b: "a" | "b" } | { c: 3; d: 4 }
}`
attest(first).type.toString.normalizedSnap(expected)
attest(reordered).type.toString.normalizedSnap(expected)
assert.throws(
() =>
attest(
{} as { a: [number, string]; z: { a: 1; b: "a" | "b" } }
).type.toString.normalizedSnap(expected),
assert.AssertionError
)
attest({} as { b: 2; a: 1 }).type.toString.snap("{ b: 2; a: 1 }")
})

it("preserves literal text, tuple positions and overload order", () => {
const value = {} as {
z: "red|blue" | "green"
b: (value: string, count: number) => "z" | "a"
(value: "special"): 1
readonly "a-key"?: [string, number]
(value: string): 2
[Symbol.toStringTag]: "value"
}
attest(value).type.toString.normalizedSnap(`{
(value: "special"): 1
(value: string): 2
readonly "a-key"?: [string, number]
b: (value: string, count: number) => "a" | "z"
z: "green" | "red|blue"
[Symbol.toStringTag]: "value"
}`)
attest({} as (() => "z" | "a") | "literal").type.toString.normalizedSnap(
'"literal" | (() => "a" | "z")'
)
attest({} as { z: 1 } & { a: 2 }).type.toString.normalizedSnap(
"{ z: 1 } & { a: 2 }"
)
attest({} as { 2: 2; readonly "a|b": `z${string}` | `a${string}`; 10: 10 })
.type.toString.normalizedSnap(`{
10: 10
2: 2
readonly "a|b": \`a\${string}\` | \`z\${string}\`
}`)
})
})
9 changes: 9 additions & 0 deletions ark/attest/__tests__/snapExpectedOutput.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { attest, cleanup, setup } from "@ark/attest"
import { attestInternal } from "@ark/attest/internal/assert/attest.ts"
import type { makeComplexType } from "./utils.ts"

setup({ typeToStringFormat: { useTabs: true } })
Expand Down Expand Up @@ -69,6 +70,14 @@ attest({

attest({ [Symbol("mySymbol")]: 1 }).snap({ "Symbol(mySymbol)": 1 })

attest({} as { b: "b" | "a"; a: 1 }).type.toString.normalizedSnap(
'{ a: 1; b: "a" | "b" }'
)

attestInternal({} as { b: "b" | "a"; a: 1 }, {
cfg: { updateSnapshots: true }
}).type.toString.normalizedSnap('{ a: 1; b: "a" | "b" }')

const it = (name: string, fn: () => void) => fn()

it("can snap instantiations", () => {
Expand Down
7 changes: 7 additions & 0 deletions ark/attest/__tests__/snapTemplate.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { attest, cleanup, setup } from "@ark/attest"
import { attestInternal } from "@ark/attest/internal/assert/attest.ts"
import type { makeComplexType } from "./utils.ts"

setup({ typeToStringFormat: { useTabs: true } })
Expand Down Expand Up @@ -51,6 +52,12 @@ attest({

attest({ [Symbol("mySymbol")]: 1 }).snap()

attest({} as { b: "b" | "a"; a: 1 }).type.toString.normalizedSnap()

attestInternal({} as { b: "b" | "a"; a: 1 }, {
cfg: { updateSnapshots: true }
}).type.toString.normalizedSnap("old type")

const it = (name: string, fn: () => void) => fn()

it("can snap instantiations", () => {
Expand Down
25 changes: 22 additions & 3 deletions ark/attest/assert/chainableAssertions.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import {
throwAssertionError
} from "./assertions.ts"
import type { AssertionContext, VersionableActual } from "./attest.ts"
import { normalizedTypePlugin } from "./normalizedType.ts"

export type ChainableAssertionOptions = {
allowRegex?: boolean
Expand Down Expand Up @@ -172,6 +173,14 @@ export class ChainableAssertions implements AssertionRecord {
})
}

get normalizedSnap(): snapProperty<unknown, AssertionKind> {
this.ctx.versionableActual = new TypeAssertionMapping(data => ({
actual: formatTypeString(data.args[0].type, true)
}))
this.ctx.lastSnapName = "normalizedSnap"
return this.snap
}

private immediateOrChained() {
const immediateAssertion = (...args: [expected: unknown]) => {
let expected
Expand Down Expand Up @@ -278,14 +287,21 @@ export class ChainableAssertions implements AssertionRecord {

const declarationPrefix = "type T = "

const formatTypeString = (typeString: string) =>
const formatTypeString = (typeString: string, normalized = false) =>
prettier
.format(`${declarationPrefix}${typeString}`, {
semi: false,
printWidth: 60,
trailingComma: "none",
parser: "typescript",
...getConfig().typeToStringFormat
...getConfig().typeToStringFormat,
...(normalized && {
parser: "attest-normalized-type",
plugins: [
...(getConfig().typeToStringFormat.plugins ?? []),
normalizedTypePlugin
]
})
})
.slice(declarationPrefix.length)
.trimEnd()
Expand Down Expand Up @@ -380,7 +396,10 @@ export type TypeAssertionsRoot = {
}

export type TypeAssertionProps = {
toString: valueFromTypeAssertion<string | RegExp>
toString: valueFromTypeAssertion<string | RegExp> & {
/** Snapshot with properties and union members sorted alphabetically. */
normalizedSnap: snapProperty<string, "value">
}
errors: valueFromTypeAssertion<string | RegExp, string>
completions: CompletionsSnap
}
Expand Down
94 changes: 94 additions & 0 deletions ark/attest/assert/normalizedType.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,94 @@
import type { Parser } from "prettier"
import { parsers as typescriptParsers } from "prettier/plugins/typescript"

// A module path lets @prettier/sync load the plugin in its worker, in both
// source and built packages. The parser is independent of the type checker.
export const normalizedTypePlugin = import.meta.url

type TypeNode = {
type: string
range: [number, number]
[key: string]: unknown
}

const isNode = (value: unknown): value is TypeNode =>
typeof value === "object" &&
value !== null &&
"type" in value &&
typeof value.type === "string" &&
"range" in value &&
Array.isArray(value.range)

const nodesIn = (value: unknown): TypeNode[] =>
Array.isArray(value) ? value.filter(isNode)
: isNode(value) ? [value]
: []

const compare = (l: string, r: string): number =>
l < r ? -1
: l > r ? 1
: 0

const propertyName = (node: TypeNode): string | undefined => {
if (node.type !== "TSPropertySignature" || node.computed) return
const key = node.key
if (!isNode(key)) return
if (typeof key.name === "string") return key.name
if (typeof key.value === "string" || typeof key.value === "number")
return String(key.value)
}

// Normalize children first so unions of object types sort by their normalized
// contents. Returned text is only a sort key; Prettier prints the actual AST.
const normalize = (node: TypeNode, source: string): string => {
const children = Object.entries(node)
.filter(([key]) => key !== "comments" && key !== "tokens")
.flatMap(([, value]) => nodesIn(value))
.sort((l, r) => l.range[0] - r.range[0])
const text = new Map(children.map(child => [child, normalize(child, source)]))

if (node.type === "TSUnionType") {
const types = nodesIn(node.types).sort((l, r) =>
compare(text.get(l)!, text.get(r)!)
)
node.types = types
return types.map(type => text.get(type)).join(" | ")
}
if (node.type === "TSTypeLiteral") {
const members = nodesIn(node.members)
const properties = members
.filter(member => propertyName(member) !== undefined)
.sort((l, r) => compare(propertyName(l)!, propertyName(r)!))
let index = 0
// Keep overloads, index signatures and computed keys in their slots.
node.members = members.map(member =>
propertyName(member) === undefined ? member : properties[index++]
)
return `{ ${nodesIn(node.members)
.map(member => text.get(member))
.join(" ")} }`
}

let result = ""
let start = node.range[0]
for (const child of children) {
result += source.slice(start, child.range[0]) + text.get(child)
start = child.range[1]
}
return result + source.slice(start, node.range[1])
}

export const parsers: Record<string, Parser<unknown>> = {
"attest-normalized-type": {
...typescriptParsers.typescript,
parse: async (text, options) => {
const ast: unknown = await typescriptParsers.typescript.parse(
text,
options
)
if (!isNode(ast)) throw new Error("Expected a TypeScript syntax tree")
normalize(ast, text)
return ast
}
}
}
16 changes: 16 additions & 0 deletions ark/docs/content/docs/attest/assertions.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,22 @@ attest(Even.json).snap({
})
```

### Normalized type snapshots

Use `.type.toString.normalizedSnap()` to sort object properties and union members alphabetically before snapshotting. This avoids failures caused only by a type checker's printing order.

```ts
import { attest } from "@ark/attest"

const value = {} as { b: "b" | "a"; a: 1 }

attest(value).type.toString.normalizedSnap('{ a: 1; b: "a" | "b" }')
```

Omit the argument to generate the snapshot, or use `updateSnapshots` to refresh it. Normalization includes nested types and uses your `typeToStringFormat` settings. The saved expectation is compared exactly against the normalized output.

Tuple elements, function parameters and intersection members retain their order. Method signatures, overloads, index signatures and computed properties retain their positions. Type aliases are not expanded, so normalization does not make every equivalent type print identically.

### Errors

```ts
Expand Down
16 changes: 16 additions & 0 deletions ark/docs/public/docs/attest/llms.txt
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,22 @@ attest(Even.json).snap({
})
```

### Normalized type snapshots

Use `.type.toString.normalizedSnap()` to sort object properties and union members alphabetically before snapshotting. This avoids failures caused only by a type checker's printing order.

```ts
import { attest } from "@ark/attest"

const value = {} as { b: "b" | "a"; a: 1 }

attest(value).type.toString.normalizedSnap('{ a: 1; b: "a" | "b" }')
```

Omit the argument to generate the snapshot, or use `updateSnapshots` to refresh it. Normalization includes nested types and uses your `typeToStringFormat` settings. The saved expectation is compared exactly against the normalized output.

Tuple elements, function parameters and intersection members retain their order. Method signatures, overloads, index signatures and computed properties retain their positions. Type aliases are not expanded, so normalization does not make every equivalent type print identically.

### Errors

```ts
Expand Down
Loading