Open History to see the last commit
1import { MurmurHashStream, getSymbolIdentity, randomHash } from './murmur.js'
2import { isTemporal } from './temporal.js'
3import type { Hasher } from './murmur.js'
4
5/*
6 * Implementation of structural hashing based on the Composites polyfill implementation:
7 * https://github.com/tc39/proposal-composites
8 */
9
10const TRUE = randomHash()
11const FALSE = randomHash()
12const NULL = randomHash()
13const UNDEFINED = randomHash()
14const KEY = randomHash()
15const FUNCTIONS = randomHash()
16// Identity is distinct even if two random hash values happen to collide.
17const DATE_MARKER = { hash: randomHash() }
18const REGEXP_MARKER = { hash: randomHash() }
19const OBJECT_MARKER = { hash: randomHash() }
20const ARRAY_MARKER = { hash: randomHash() }
21const MAP_MARKER = { hash: randomHash() }
22const SET_MARKER = { hash: randomHash() }
23const UINT8ARRAY_MARKER = { hash: randomHash() }
24const TEMPORAL_MARKER = { hash: randomHash() }
25// Bound structural recursion and value visits. Shared acyclic subtrees are
26// cached; cycles are rejected rather than given context-dependent hashes.
27const MAX_STRUCTURAL_HASH_WORK = 1_000_000
28const MAX_STRUCTURAL_HASH_DEPTH = 768
29
30// Maximum byte length for Uint8Arrays to hash by content instead of reference
31// Arrays smaller than this will be hashed by content, allowing proper equality comparisons
32// for small arrays like ULIDs (16 bytes) while still avoiding performance costs for large arrays
33const UINT8ARRAY_CONTENT_HASH_THRESHOLD = 128
34
35const hashCache = new WeakMap<object, number>()
36const referenceValues = new WeakSet<object>()
37
38/** @internal Register a mutable handle before it enters a structural value. */
39export function registerOpaqueHash(value: object): void {
40 cachedReferenceHash(value)
41}
42
43type HashContext = {
44 activeObjects: Set<object>
45 work: number
46 pendingHashes: Map<object, number>
47}
48
49export function hash(input: any): number {
50 const hasher = new MurmurHashStream()
51 updateHasher(hasher, input)
52 return hasher.digest()
53}
54
55function hashObject(input: object, context: HashContext): number {
56 if (context.activeObjects.size >= MAX_STRUCTURAL_HASH_DEPTH) {
57 throw new RangeError(
58 `Value is too complex to hash safely: structural depth`,
59 )
60 }
61
62 context.activeObjects.add(input)
63
64 let valueHash: number | undefined
65 try {
66 const [marker, header, body] = objectParts(input)
67 const hasher = new MurmurHashStream()
68 hasher.update(marker.hash)
69 // Header values of a type with a body (array length, RegExp fields)
70 // count toward the work cap; Date, binary, and Temporal headers do not.
71 for (const value of header)
72 if (body) updateHasher(hasher, value, context)
73 else hasher.update(value as string | number)
74 if (body) {
75 // String keys in UTF-16 code-unit order, then enumerable symbol keys by
76 // identity. Code-unit order is total; locale collation can rank two
77 // distinct keys as equal and leave their insertion order in the hash.
78 const keys: Array<string | symbol> = Object.keys(body)
79 // A dense array with no other keys lists its indices in one order for
80 // every equal array: integer keys come first, so the last key is the
81 // last index. Anything else sorts.
82 const denseArray =
83 Array.isArray(body) &&
84 keys.length === body.length &&
85 (keys.length === 0 || keys[keys.length - 1] === String(body.length - 1))
86 if (!denseArray) keys.sort()
87 keys.push(
88 ...Object.getOwnPropertySymbols(body)
89 .filter((key) =>
90 Object.prototype.propertyIsEnumerable.call(body, key),
91 )
92 .sort(
93 (left, right) => getSymbolIdentity(left) - getSymbolIdentity(right),
94 ),
95 )
96 for (const key of keys) {
97 hasher.update(KEY)
98 hasher.update(key)
99 updateHasher(hasher, body[key as keyof typeof body], context)
100 }
101 }
102 valueHash = hasher.digest()
103 } finally {
104 context.activeObjects.delete(input)
105 }
106
107 context.pendingHashes.set(input, valueHash)
108 return valueHash
109}
110
111/**
112 * The one type dispatch shared by structural hashing and equality: a type
113 * marker, primitive header values, and an optional object whose enumerable
114 * own properties are compared structurally.
115 */
116type ObjectParts = [
117 marker: Readonly<{ hash: number }>,
118 // A RegExp `lastIndex` can hold any value; the other headers are strings
119 // or numbers.
120 header: ReadonlyArray<unknown>,
121 body?: object,
122]
123
124function objectParts(input: object): ObjectParts {
125 if (input instanceof Date) {
126 const time = input.getTime()
127 // Invalid dates are equal to each other; headers compare with `===`.
128 return [DATE_MARKER, [Number.isNaN(time) ? `invalid` : time]]
129 }
130 if (isBinaryValue(input))
131 return [
132 UINT8ARRAY_MARKER,
133 [String.fromCharCode.apply(null, input as unknown as Array<number>)],
134 ]
135 if (isTemporal(input))
136 return [TEMPORAL_MARKER, [input[Symbol.toStringTag], input.toString()]]
137 if (input instanceof RegExp)
138 return [REGEXP_MARKER, [input.source, input.flags, input.lastIndex], input]
139 if (input instanceof Map) return [MAP_MARKER, [], [...input.entries()]]
140 if (input instanceof Set) return [SET_MARKER, [], [...input.values()]]
141 return input instanceof Array
142 ? [ARRAY_MARKER, [input.length], input]
143 : [OBJECT_MARKER, [], input]
144}
145
146function updateHasher(
147 hasher: Hasher,
148 input: unknown,
149 context?: HashContext,
150): void {
151 if (context && ++context.work > MAX_STRUCTURAL_HASH_WORK) {
152 throw new RangeError(`Value is too complex to hash safely: structural work`)
153 }
154 if (input === null) {
155 hasher.update(NULL)
156 return
157 }
158 switch (typeof input) {
159 case `undefined`:
160 hasher.update(UNDEFINED)
161 return
162 case `boolean`:
163 hasher.update(input ? TRUE : FALSE)
164 return
165 case `number`:
166 // Normalize NaNs and -0
167 hasher.update(isNaN(input) ? NaN : input === 0 ? 0 : input)
168 return
169 case `bigint`:
170 case `string`:
171 case `symbol`:
172 hasher.update(input)
173 return
174 case `object`:
175 hasher.update(getCachedHash(input, context))
176 return
177 case `function`:
178 // Functions are assigned a globally unique ID
179 // and that ID is cached in the weak map
180 hasher.update(cachedReferenceHash(input))
181 }
182}
183
184function getCachedHash(input: object, context?: HashContext): number {
185 // Active objects are neither cached nor pending, so the cycle check below
186 // still sees every back-reference.
187 const cached = hashCache.get(input) ?? context?.pendingHashes.get(input)
188 if (cached !== undefined) return cached
189
190 // Opaque leaves cannot contain structural back-references. Resolve them
191 // before entering structural recursion, even when they have user properties.
192 if (isReferenceHashedObject(input)) return cachedReferenceHash(input)
193
194 if (context) {
195 if (context.activeObjects.has(input)) {
196 throw new TypeError(`Cannot hash cyclic structural values`)
197 }
198 return hashObject(input, context)
199 }
200
201 // Only an uncached structural root needs graph traversal state. Commit its
202 // cache entries after success so a failed traversal cannot poison retries.
203 const root: HashContext = {
204 activeObjects: new Set(),
205 work: 0,
206 pendingHashes: new Map(),
207 }
208 const result = hashObject(input, root)
209 for (const [object, valueHash] of root.pendingHashes) {
210 hashCache.set(object, valueHash)
211 }
212 return result
213}
214
215function isReferenceHashedObject(input: object): boolean {
216 return (
217 referenceValues.has(input) ||
218 (typeof File !== `undefined` && input instanceof File) ||
219 (isBinaryValue(input) &&
220 input.byteLength > UINT8ARRAY_CONTENT_HASH_THRESHOLD)
221 )
222}
223
224// Buffer can come from another realm than Uint8Array (for example under jsdom).
225function isBinaryValue(input: object): input is Uint8Array {
226 return (
227 (typeof Buffer !== `undefined` && input instanceof Buffer) ||
228 input instanceof Uint8Array
229 )
230}
231
232/** @internal Compare immutable structural values without computing a digest.
233 * Pair memoization also permits cyclic values that structural hashing rejects.
234 * Reference-valued leaves remain opaque, including registered mutable handles.
235 */
236export function equalHashValues(left: unknown, right: unknown): boolean {
237 return compareHashValues(left, right)
238}
239
240function enumerableKeys(value: object): Array<PropertyKey> {
241 return Reflect.ownKeys(value).filter((key) =>
242 Object.prototype.propertyIsEnumerable.call(value, key),
243 )
244}
245
246// Allocate pair memoization only when structural bodies need comparison. A
247// module-level recursion also avoids rebuilding the worker for every call.
248function compareHashValues(
249 a: unknown,
250 b: unknown,
251 compared?: Map<object, Set<object>>,
252): boolean {
253 if (a === b || (Number.isNaN(a) && Number.isNaN(b))) return true
254 if (
255 a === null ||
256 b === null ||
257 typeof a !== `object` ||
258 typeof b !== `object` ||
259 isReferenceHashedObject(a) ||
260 isReferenceHashedObject(b)
261 )
262 return false
263 // Arrays from another realm take the object marker but keep this check.
264 if (Array.isArray(a) && Array.isArray(b) && a.length !== b.length)
265 return false
266
267 // Revisited pairs close cycles and avoid expanding shared subtrees. Check
268 // before objectParts copies Map or Set entries; record only pairs with a
269 // body, after their markers and headers match.
270 const peers = compared?.get(a)
271 if (peers?.has(b)) return true
272 const [aMarker, aHeader, aBody] = objectParts(a)
273 const [bMarker, bHeader, bBody] = objectParts(b)
274 if (
275 aMarker !== bMarker ||
276 !aHeader.every((value, index) => value === bHeader[index])
277 )
278 return false
279 if (!aBody || !bBody) return true
280 if (peers) peers.add(b)
281 else (compared ??= new Map()).set(a, new Set([b]))
282 const aKeys = enumerableKeys(aBody)
283 return (
284 aKeys.length === enumerableKeys(bBody).length &&
285 aKeys.every(
286 (key) =>
287 Object.prototype.propertyIsEnumerable.call(bBody, key) &&
288 compareHashValues(
289 aBody[key as keyof object],
290 bBody[key as keyof object],
291 compared,
292 ),
293 )
294 )
295}
296
297let nextRefId = 1
298function cachedReferenceHash(fn: object): number {
299 let valueHash = hashCache.get(fn)
300 if (valueHash === undefined) {
301 valueHash = nextRefId ^ FUNCTIONS
302 nextRefId++
303 hashCache.set(fn, valueHash)
304 referenceValues.add(fn)
305 }
306 return valueHash
307}
308
309// One punctuation tag per objectParts marker, so values of different kinds
310// never share an identity (and no tag reads as an identifier in this source).
311const MARKER_TAGS = new Map<{ hash: number }, string>([
312 [ARRAY_MARKER, `[`],
313 [OBJECT_MARKER, `{`],
314 [DATE_MARKER, `<`],
315 [REGEXP_MARKER, `/`],
316 [MAP_MARKER, `&`],
317 [SET_MARKER, `*`],
318 [UINT8ARRAY_MARKER, `^`],
319 [TEMPORAL_MARKER, `?`],
320])
321
322// Nesting a structural identity follows: a min or max input is an array of
323// exact keys, and an exact key can hold a reference tuple.
324const MAX_IDENTITY_DEPTH = 4
325
326/**
327 * @internal An exact identity string for a value, or undefined when it has
328 * no cheap one. Two values that `equalHashValues` treats as equal get the
329 * same result, both undefined or one string; two that it treats as different
330 * never share a string. The decision uses only what equalHashValues reads:
331 * the type, the `objectParts` marker and headers, and enumerable own keys. groupBy uses it
332 * to merge equal contributions without hashing them.
333 */
334export function structuralIdentity(
335 value: unknown,
336 depth = 0,
337): string | undefined {
338 switch (typeof value) {
339 case `number`:
340 // The hash treats -0 as 0 and every NaN as one value.
341 return `#${value === 0 ? 0 : value}`
342 case `string`:
343 return `"${value.length}:${value}`
344 case `boolean`:
345 return value ? `+` : `-`
346 case `undefined`:
347 return `~`
348 case `bigint`:
349 return `%${value}`
350 case `symbol`:
351 return `$${getSymbolIdentity(value)}`
352 case `object`: {
353 if (value === null) return `!`
354 if (depth >= MAX_IDENTITY_DEPTH || isReferenceHashedObject(value))
355 return undefined
356 const [marker, header, body] = objectParts(value)
357 // equalHashValues compares headers with ===, so a NaN header is never
358 // equal to another value's, and gets no identity.
359 let head = MARKER_TAGS.get(marker)!
360 for (const part of header) {
361 if (Number.isNaN(part)) return undefined
362 head += structuralIdentity(part, depth + 1)
363 }
364 if (!body) return head
365 if (
366 Object.getOwnPropertySymbols(body).some((key) =>
367 Object.prototype.propertyIsEnumerable.call(body, key),
368 )
369 )
370 return undefined
371 let parts = ``
372 for (const key of Object.keys(body).sort()) {
373 const part = structuralIdentity(
374 (body as Record<string, unknown>)[key],
375 depth + 1,
376 )
377 if (part === undefined) return undefined
378 parts += `${key.length}:${key}=${part}|`
379 }
380 // An array's header is its length, so a hole differs from undefined.
381 return `${head}:${parts.length}:${parts}`
382 }
383 default:
384 return undefined
385 }
386}