Open History to see the last commit
1import { createHash } from 'node:crypto'
2import { readFileSync } from 'node:fs'
3import { dirname, resolve } from 'node:path'
4import { fileURLToPath } from 'node:url'
5import { vi } from 'vitest'
6import { fc } from '@fast-check/vitest'
7import vitestPackage from 'vitest/package.json'
8import type * as HashModuleExports from '../src/hashing/hash'
9
10type HashModule = Pick<typeof HashModuleExports, `hash` | `registerOpaqueHash`>
11
12const sourceDirectory = resolve(
13 dirname(fileURLToPath(import.meta.url)),
14 `../src/hashing`,
15)
16const sourceDigest = createHash(`sha256`)
17 .update(readFileSync(resolve(sourceDirectory, `hash.ts`)))
18 .update(readFileSync(resolve(sourceDirectory, `murmur.ts`)))
19 .digest(`hex`)
20
21export type HashSession = HashModule & {
22 readonly tape: ReadonlyArray<number>
23 readonly environment: Readonly<{
24 node: string
25 platform: string
26 arch: string
27 fastCheck: string
28 vitest: string
29 hashSources: string
30 }>
31}
32
33// Only module initialization is recorded/replayed. Hash calls and fast-check
34// generation run after the spy has been restored. Call serially within a file.
35export async function captureHashSession(
36 tape?: ReadonlyArray<number>,
37 load: () => Promise<HashModule> = () => import('../src/hashing/hash'),
38): Promise<HashSession> {
39 vi.resetModules()
40 const replayTape = tape?.slice()
41 const nativeRandom = Math.random
42 const draws: Array<number> = []
43 let cursor = 0
44 const random = vi.spyOn(Math, `random`).mockImplementation(() => {
45 if (replayTape && cursor >= replayTape.length)
46 throw new Error(`Hash replay tape exhausted`)
47 const value = replayTape ? replayTape[cursor++]! : nativeRandom()
48 if (!Number.isFinite(value) || value < 0 || value >= 1) {
49 throw new Error(`Invalid hash initialization draw`)
50 }
51 draws.push(value)
52 return value
53 })
54 try {
55 const module = await load()
56 if (replayTape && cursor !== replayTape.length)
57 throw new Error(`Unused hash replay draws`)
58 return {
59 ...module,
60 tape: Object.freeze(draws),
61 environment: Object.freeze({
62 node: process.version,
63 platform: process.platform,
64 arch: process.arch,
65 fastCheck: fc.__version,
66 vitest: vitestPackage.version,
67 hashSources: sourceDigest,
68 }),
69 }
70 } finally {
71 random.mockRestore()
72 }
73}
74
75export class HashReplayError extends Error {
76 constructor(
77 readonly replay: {
78 law: string
79 input: unknown
80 observed: ReadonlyArray<number>
81 tape: ReadonlyArray<number>
82 environment: HashSession[`environment`]
83 },
84 cause: unknown,
85 ) {
86 // The outer native fast-check runner retains its own seed/path/minimized
87 // inputs. Do not replace its reporter or stringify away the original cause.
88 super(`Hash law replay: ${JSON.stringify(replay)}`, { cause })
89 this.name = `HashReplayError`
90 }
91}