This repository was archived by the owner on Sep 23, 2026. It is now read-only.
Repository navigation
Expand file tree
/
Copy pathdigest.ts
More file actions
107 lines (101 loc) · 4.07 KB
/
Copy pathdigest.ts
File metadata and controls
107 lines (101 loc) · 4.07 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
/**
* CONTENT DIGESTS — the identity every cache key in this package is built from.
*
* Synchronous and dependency-free on purpose. `crypto.subtle.digest` is async and unavailable in some
* of the contexts this code runs in (a synchronous compile pass, a Worker's hot path), and an async
* digest would force every compiler in the package to become async for a hash. FNV-1a over a canonical
* serialization gives a 128-bit value with collision odds that are irrelevant for a cache — and a cache
* MISS on a collision is a slow render, not a wrong one, because the entry is re-derived from the same
* inputs anyway.
*
* The canonical serialization is the load-bearing half: object keys are sorted, so two structurally
* equal descriptions digest identically no matter what order they were built in. `undefined` members
* are dropped, so an optional field explicitly set to `undefined` and one never set are the same thing,
* which is what a caller means.
*/
/** A stable string for any JSON-shaped value: sorted keys, dropped `undefined`, typed array support. */
export function canonicalize(value: unknown): string {
if (value === null) return "null";
switch (typeof value) {
case "undefined":
return "";
case "number":
return Number.isFinite(value) ? String(value) : "null";
case "boolean":
return value ? "true" : "false";
case "string":
return JSON.stringify(value);
case "bigint":
return `${value}n`;
case "function":
case "symbol":
return '"[unserializable]"';
default:
break;
}
if (Array.isArray(value)) return `[${value.map(canonicalize).join(",")}]`;
if (ArrayBuffer.isView(value)) {
const view = value as unknown as { length: number; [i: number]: number };
// Digest the BYTES, not a stringified list — a megapixel buffer must not become a megabyte string.
return `#${value.constructor.name}:${view.length}:${hashBytes(value)}`;
}
if (value instanceof Map) {
return `Map{${[...value.entries()]
.map(([k, v]) => `${canonicalize(k)}:${canonicalize(v)}`)
.sort()
.join(",")}}`;
}
if (value instanceof Set) {
return `Set{${[...value].map(canonicalize).sort().join(",")}}`;
}
const obj = value as Record<string, unknown>;
const parts: string[] = [];
for (const key of Object.keys(obj).sort()) {
const v = obj[key];
if (v === undefined) continue;
parts.push(`${JSON.stringify(key)}:${canonicalize(v)}`);
}
return `{${parts.join(",")}}`;
}
const OFFSET_LO = 0x9dc5;
const OFFSET_HI = 0x811c;
const PRIME_LO = 0x0193;
const PRIME_HI = 0x0100;
/** FNV-1a over UTF-16 code units, run as two independent 32-bit lanes for a 64-bit result. */
function fnv1a(input: string, seed: number): string {
let lo = OFFSET_LO ^ seed;
let hi = OFFSET_HI;
for (let i = 0; i < input.length; i++) {
const c = input.charCodeAt(i);
lo ^= c & 0xff;
hi ^= (c >>> 8) & 0xff;
const nlo = Math.imul(lo, PRIME_LO) + Math.imul(hi, PRIME_HI) * 0x10000;
const nhi = Math.imul(hi, PRIME_LO) ^ Math.imul(lo, PRIME_HI);
lo = nlo >>> 0;
hi = nhi >>> 0;
}
return (lo >>> 0).toString(16).padStart(8, "0") + (hi >>> 0).toString(16).padStart(8, "0");
}
function hashBytes(view: ArrayBufferView): string {
const bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
let lo = OFFSET_LO;
let hi = OFFSET_HI;
for (let i = 0; i < bytes.length; i++) {
lo ^= bytes[i]!;
hi ^= (bytes[i]! << 3) & 0xff;
const nlo = Math.imul(lo, PRIME_LO) + Math.imul(hi, PRIME_HI) * 0x10000;
const nhi = Math.imul(hi, PRIME_LO) ^ Math.imul(lo, PRIME_HI);
lo = nlo >>> 0;
hi = nhi >>> 0;
}
return (lo >>> 0).toString(16).padStart(8, "0") + (hi >>> 0).toString(16).padStart(8, "0");
}
/** A 128-bit hex digest of any JSON-shaped value. Two different seeds halve the collision surface. */
export function digest(value: unknown): string {
const s = canonicalize(value);
return fnv1a(s, 0) + fnv1a(s, 0x5bf03635);
}
/** Combine several digests into one, order-sensitively. */
export function combineDigests(...parts: string[]): string {
return digest(parts);
}