/** * Side-effecting polyfills module for happy-dom / jsdom / bare-Node test * environments on WSL2 or older toolchains. * * Import via vitest `setupFiles`: * * ```ts * // vitest.config.ts * export default defineConfig({ * test: { * setupFiles: ["@suaveplan/testing/polyfills"], * }, * }); * ``` * * Installs: * - `globalThis.crypto` (from `node:crypto`'s `webcrypto` export) if missing * - `globalThis.TextEncoder` / `TextDecoder` (usually present, covered defensively) * * Exports nothing. Safe to import multiple times; operations are idempotent. */ import { webcrypto } from "node:crypto"; import { TextDecoder as NodeTextDecoder, TextEncoder as NodeTextEncoder, } from "node:util"; type WritableGlobal = { crypto?: Crypto; TextEncoder?: typeof NodeTextEncoder; TextDecoder?: typeof NodeTextDecoder; }; const g = globalThis as unknown as WritableGlobal; if ( typeof g.crypto === "undefined" || typeof g.crypto.getRandomValues !== "function" ) { g.crypto = webcrypto as unknown as Crypto; } if (typeof g.TextEncoder === "undefined") { g.TextEncoder = NodeTextEncoder; } if (typeof g.TextDecoder === "undefined") { g.TextDecoder = NodeTextDecoder; }