Open History to see the last commit
1import { describe, expect, it } from 'vitest'
2import { Temporal } from 'temporal-polyfill'
3import { DefaultMap, compareKeys, serializeValue } from '../src/utils.js'
4import { hash } from '../src/hashing/index.js'
5
6describe(`DefaultMap`, () => {
7 it(`should return default value for missing keys`, () => {
8 const map = new DefaultMap(() => 0)
9 expect(map.get(`missing`)).toBe(0)
10 })
11
12 it(`should store and retrieve values`, () => {
13 const map = new DefaultMap(() => 0)
14 map.set(`key`, 42)
15 expect(map.get(`key`)).toBe(42)
16 })
17
18 it(`should accept initial entries`, () => {
19 const map = new DefaultMap(() => 0, [[`key`, 1]])
20 expect(map.get(`key`)).toBe(1)
21 })
22
23 it(`should update values using the update method`, () => {
24 const map = new DefaultMap(() => 0)
25 map.update(`key`, (value) => value + 1)
26 expect(map.get(`key`)).toBe(1)
27
28 map.update(`key`, (value) => value * 2)
29 expect(map.get(`key`)).toBe(2)
30 })
31})
32
33describe(`compareKeys`, () => {
34 it(`orders finite numeric keys before NaN`, () => {
35 expect(compareKeys(1, Number.NaN)).toBeLessThan(0)
36 expect(compareKeys(Number.NaN, 1)).toBeGreaterThan(0)
37 expect(compareKeys(Number.NaN, Number.NaN)).toBe(0)
38 })
39})
40
41describe(`serializeValue`, () => {
42 it(`preserves the established JSON form for ordinary keys`, () => {
43 expect(serializeValue(`user1`)).toBe(`"user1"`)
44 expect(serializeValue([1, `completed`])).toBe(`[1,"completed"]`)
45 })
46
47 it(`keeps distinct primitive types and special numbers distinct`, () => {
48 expect(serializeValue(1n)).not.toBe(serializeValue(`1`))
49 expect(serializeValue(Number.NaN)).not.toBe(serializeValue(null))
50 expect(serializeValue(undefined)).not.toBe(serializeValue(null))
51 expect(serializeValue(new Date(0))).not.toBe(
52 serializeValue(`1970-01-01T00:00:00.000Z`),
53 )
54 expect(serializeValue(new Date(Number.NaN))).not.toBe(
55 serializeValue(Number.NaN),
56 )
57 })
58
59 it(`canonicalizes plain-object property order`, () => {
60 expect(serializeValue({ a: 1, b: 2 })).toBe(serializeValue({ b: 2, a: 1 }))
61 })
62})
63
64const hashType = `number`
65describe(`hash`, () => {
66 describe(`primitive types`, () => {
67 it(`should hash null`, () => {
68 const result = hash(null)
69 expect(typeof result).toBe(hashType)
70 })
71
72 it(`should hash undefined`, () => {
73 const result = hash(undefined)
74 expect(typeof result).toBe(hashType)
75 })
76
77 it(`should hash strings`, () => {
78 const result1 = hash(`hello`)
79 const result2 = hash(``)
80 const result3 = hash(`test with spaces`)
81 const result4 = hash(`special\nchars\t"`)
82
83 expect(typeof result1).toBe(hashType)
84 expect(typeof result2).toBe(hashType)
85 expect(typeof result3).toBe(hashType)
86 expect(typeof result4).toBe(hashType)
87
88 // Same strings should have same hash
89 expect(hash(`hello`)).toBe(result1)
90 })
91
92 it(`should hash numbers`, () => {
93 const result1 = hash(42)
94 const result2 = hash(0)
95 const result3 = hash(-1)
96 const result4 = hash(3.14159)
97 const result5 = hash(Infinity)
98 const result6 = hash(-Infinity)
99 const result7 = hash(NaN)
100
101 expect(typeof result1).toBe(hashType)
102 expect(typeof result2).toBe(hashType)
103 expect(typeof result3).toBe(hashType)
104 expect(typeof result4).toBe(hashType)
105 expect(typeof result5).toBe(hashType)
106 expect(typeof result6).toBe(hashType)
107 expect(typeof result7).toBe(hashType)
108
109 // Same numbers should have same hash
110 expect(hash(42)).toBe(result1)
111 expect(hash(2.0)).not.toBe(hash(2.5))
112 expect(hash(3.14159)).toBe(result4)
113 })
114
115 it(`should hash booleans`, () => {
116 const result1 = hash(true)
117 const result2 = hash(false)
118
119 expect(typeof result1).toBe(hashType)
120 expect(typeof result2).toBe(hashType)
121 expect(result1).not.toBe(result2)
122
123 // Same booleans should have same hash
124 expect(hash(true)).toBe(result1)
125 expect(hash(false)).toBe(result2)
126 })
127
128 it(`should hash bigint`, () => {
129 const result1 = hash(123n)
130 const result2 = hash(456n)
131 const result3 = hash(123n)
132
133 expect(typeof result1).toBe(hashType)
134 expect(typeof result2).toBe(hashType)
135 expect(typeof result3).toBe(hashType)
136 expect(result1).toBe(result3) // Same bigint should have same hash
137 expect(result1).not.toBe(result2) // Different bigints should have different hash
138 })
139
140 it(`should hash symbols`, () => {
141 const sym1 = Symbol(`test`)
142 const sym2 = Symbol(`test`)
143 const sym3 = Symbol(`different`)
144 const sym4 = Symbol()
145 const sym5 = Symbol()
146
147 const result1 = hash(sym1)
148 const result2 = hash(sym2)
149 const result3 = hash(sym3)
150 const result4 = hash(sym4)
151 const result5 = hash(sym5)
152
153 expect(typeof result1).toBe(hashType)
154 expect(typeof result2).toBe(hashType)
155 expect(typeof result3).toBe(hashType)
156 expect(result1).not.toBe(result2)
157 expect(result1).not.toBe(result3)
158 expect(result4).not.toBe(result5)
159 expect(result1).not.toBe(result4)
160 })
161
162 it(`should hash registered symbols`, () => {
163 const first = Symbol.for(`tanstack-db-ivm-hash-first`)
164 const same = Symbol.for(`tanstack-db-ivm-hash-first`)
165 const second = Symbol.for(`tanstack-db-ivm-hash-second`)
166
167 expect(hash(first)).toBe(hash(same))
168 expect(hash(first)).not.toBe(hash(second))
169 expect(hash({ [first]: 1 })).not.toBe(hash({ [second]: 1 }))
170 })
171 })
172
173 describe(`object types`, () => {
174 it(`should hash plain objects`, () => {
175 const obj1 = { a: 1, b: 2 }
176 const obj2 = { b: 2, a: 1 } // Different key order
177
178 const hash1 = hash(obj1)
179 const hash2 = hash(obj2)
180
181 expect(typeof hash1).toBe(hashType)
182 expect(typeof hash2).toBe(hashType)
183 // Note: Different key orders might produce different hashes depending on JSON.stringify behavior
184 })
185
186 it(`includes enumerable symbol keys and values`, () => {
187 const key = Symbol(`key`)
188
189 expect(hash({ [key]: `before` })).not.toBe(hash({ [key]: `after` }))
190 expect(hash({ [Symbol(`key`)]: `value` })).not.toBe(
191 hash({ [Symbol(`key`)]: `value` }),
192 )
193 })
194
195 it(`rejects self and mutual cycles through symbol keys`, () => {
196 const key = Symbol(`cycle`)
197 const first: Record<PropertyKey, unknown> = {}
198 const second: Record<PropertyKey, unknown> = {}
199 first[key] = first
200 second[key] = second
201
202 const firstPeer: Record<PropertyKey, unknown> = {}
203 const secondPeer: Record<PropertyKey, unknown> = {}
204 firstPeer[key] = secondPeer
205 secondPeer[key] = firstPeer
206
207 for (const input of [first, second, firstPeer, secondPeer]) {
208 expect(() => hash(input)).toThrow(
209 `Cannot hash cyclic structural values`,
210 )
211 expect(() => hash(input)).toThrow(
212 `Cannot hash cyclic structural values`,
213 )
214 }
215 })
216
217 it.each([`object`, `map`] as const)(
218 `rejects shared cyclic branches through %s with bounded work`,
219 (container) => {
220 const size = 14
221 let reads = 0
222 const nodes: Array<Record<string, unknown> | Map<string, unknown>> =
223 Array.from({ length: size }, (_, value) =>
224 container === `object`
225 ? { value }
226 : new Map<string, unknown>([[`value`, value]]),
227 )
228
229 for (let index = 0; index < size; index++) {
230 const node = nodes[index]!
231 const next = nodes[(index + 1) % size]!
232 for (const key of [`left`, `right`] as const) {
233 const wrapper = Object.defineProperty({}, `next`, {
234 enumerable: true,
235 get: () => {
236 reads++
237 return next
238 },
239 })
240 if (node instanceof Map) node.set(key, wrapper)
241 else node[key] = wrapper
242 }
243 }
244
245 expect(() => hash(nodes[0]!)).toThrow(
246 `Cannot hash cyclic structural values`,
247 )
248 const firstReads = reads
249 const copy = structuredClone(nodes[0]!)
250
251 expect(() => hash(copy)).toThrow(`Cannot hash cyclic structural values`)
252 expect(firstReads).toBeLessThanOrEqual(size * 2)
253 },
254 )
255
256 it(`rejects a shared child that cycles to either ancestor`, () => {
257 const createGraph = (backBranch: `left` | `right`) => {
258 const root: Record<string, unknown> = {}
259 const left: Record<string, unknown> = {}
260 const right: Record<string, unknown> = {}
261 const shared: Record<string, unknown> = {}
262 root.left = left
263 root.right = right
264 left.next = shared
265 right.next = shared
266 shared.back = backBranch === `left` ? left : right
267 return root
268 }
269
270 const left = createGraph(`left`)
271 const equalLeft = createGraph(`left`)
272 const right = createGraph(`right`)
273
274 for (const input of [left, equalLeft, right]) {
275 expect(() => hash(input)).toThrow(
276 `Cannot hash cyclic structural values`,
277 )
278 }
279 })
280
281 it(`rejects cyclic graphs with exponentially many ancestor contexts`, () => {
282 const depth = 11
283 const shared = Array.from(
284 { length: depth + 1 },
285 (_, level) => ({ level }) as Record<string, unknown>,
286 )
287 const left = Array.from({ length: depth }, (_, level) => ({
288 side: `left`,
289 level,
290 next: shared[level + 1],
291 }))
292 const right = Array.from({ length: depth }, (_, level) => ({
293 side: `right`,
294 level,
295 next: shared[level + 1],
296 }))
297 for (let level = 0; level < depth; level++) {
298 shared[level]!.left = left[level]
299 shared[level]!.right = right[level]
300 shared[depth]![`left${level}`] = left[level]
301 }
302
303 expect(() => hash(shared[0])).toThrow(TypeError)
304 expect(() => hash(shared[0])).toThrow(
305 `Cannot hash cyclic structural values`,
306 )
307
308 const ring = Array.from(
309 { length: 600 },
310 (_, value) => ({ value }) as { value: number; next?: unknown },
311 )
312 for (let index = 0; index < ring.length; index++) {
313 ring[index]!.next = ring[(index + 1) % ring.length]
314 }
315 expect(() => hash(structuredClone(ring[0]))).toThrow(
316 `Cannot hash cyclic structural values`,
317 )
318 expect(() => hash(ring[0])).toThrow(
319 `Cannot hash cyclic structural values`,
320 )
321
322 const independent: Record<string, { self?: unknown }> = {}
323 for (let index = 0; index < 600; index++) {
324 const cycle: { self?: unknown } = {}
325 cycle.self = cycle
326 independent[String(index)] = cycle
327 }
328 expect(() => hash(structuredClone(independent))).toThrow(
329 `Cannot hash cyclic structural values`,
330 )
331 expect(() => hash(independent)).toThrow(
332 `Cannot hash cyclic structural values`,
333 )
334
335 const independentDiamonds: Record<string, unknown> = {}
336 for (let index = 0; index < 600; index++) {
337 const diamondCenter: Record<string, unknown> = {}
338 const leftIngress = { next: diamondCenter }
339 const rightIngress = { next: diamondCenter }
340 diamondCenter.back = leftIngress
341 independentDiamonds[`left${index}`] = leftIngress
342 independentDiamonds[`right${index}`] = rightIngress
343 }
344 expect(() => hash(structuredClone(independentDiamonds))).toThrow(
345 `Cannot hash cyclic structural values`,
346 )
347 expect(() => hash(independentDiamonds)).toThrow(
348 `Cannot hash cyclic structural values`,
349 )
350
351 const small: { self?: unknown } = {}
352 small.self = small
353 expect(() => hash(structuredClone(small))).toThrow(
354 `Cannot hash cyclic structural values`,
355 )
356 expect(() => hash(small)).toThrow(`Cannot hash cyclic structural values`)
357 })
358
359 it(`rejects both small and large repeated cyclic traversals`, () => {
360 const createGraph = (size: number) => {
361 const nodes = Array.from(
362 { length: size },
363 (_, value) => ({ value }) as Record<string, unknown>,
364 )
365 for (let index = 0; index < size; index++) {
366 const next = nodes[(index + 1) % size]!
367 nodes[index]!.left = { next }
368 nodes[index]!.right = { next }
369 }
370 return nodes[0]
371 }
372
373 expect(() => hash(createGraph(20))).toThrow(
374 `Cannot hash cyclic structural values`,
375 )
376 expect(() => hash(createGraph(300))).toThrow(
377 `Cannot hash cyclic structural values`,
378 )
379 })
380
381 it(`does not warm structural caches when a hash is rejected`, () => {
382 let reads = 0
383 const sentinel = Object.defineProperty({}, `value`, {
384 enumerable: true,
385 get: () => ++reads,
386 })
387 const shared: Record<string, unknown> = {
388 payload: Array.from({ length: 66_000 }, (_, value) => ({ value })),
389 }
390 const left = { next: shared }
391 const right = { next: shared }
392 shared.back = left
393 const root = { aSentinel: sentinel, left, right }
394
395 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
396 expect(() => hash(root)).toThrow(`Cannot hash cyclic structural values`)
397 expect(reads).toBe(2)
398 })
399
400 it.each([
401 [`Buffer`, () => Buffer.alloc(129)],
402 [`Uint8Array`, () => new Uint8Array(129)],
403 [`File`, () => new File([`opaque`], `opaque.bin`)],
404 ])(
405 `treats a large %s as an opaque leaf before structural work`,
406 (_name, createLeaf) => {
407 const leaves = Array.from({ length: 700 }, () => createLeaf())
408 for (const leaf of leaves) Object.assign(leaf, { self: leaf })
409 const createChain = () => {
410 const ring = leaves.map((leaf, value) => ({
411 value,
412 leaf,
413 next: undefined as unknown,
414 }))
415 for (let index = 0; index < ring.length; index++) {
416 ring[index]!.next = ring[index + 1]
417 }
418 return ring[0]
419 }
420
421 const first = createChain()
422 const expectedHash = hash(first)
423 expect(hash(first)).toBe(expectedHash)
424 expect(hash(createChain())).toBe(expectedHash)
425
426 let atDepthBoundary: unknown = createLeaf()
427 for (let index = 0; index < 768; index++) {
428 atDepthBoundary = { next: atDepthBoundary }
429 }
430 expect(() => hash(atDepthBoundary)).not.toThrow()
431
432 const adoptionLeaves = Array.from({ length: 20 }, () => createLeaf())
433 const createAdoptionGraph = () => {
434 const nodes = adoptionLeaves.map((leaf, value) => ({
435 value,
436 leaf,
437 })) as Array<Record<string, unknown>>
438 for (let index = 0; index < nodes.length; index++) {
439 const next = nodes[index + 1]
440 nodes[index]!.left = { next }
441 nodes[index]!.right = { next }
442 }
443 return nodes[0]
444 }
445 expect(hash(createAdoptionGraph())).toBe(hash(createAdoptionGraph()))
446 },
447 )
448
449 it(`rejects deep structural recursion before the JavaScript stack overflows`, () => {
450 let reads = 0
451 const sentinel = Object.defineProperty({}, `value`, {
452 enumerable: true,
453 get: () => ++reads,
454 })
455 const ring = Array.from(
456 { length: 800 },
457 (_, value) => ({ value }) as { value: number; next?: unknown },
458 )
459 for (let index = 0; index < ring.length; index++) {
460 ring[index]!.next = ring[(index + 1) % ring.length]
461 }
462 Object.defineProperty(ring[0]!, `aSentinel`, {
463 enumerable: true,
464 value: sentinel,
465 })
466
467 expect(() => hash(ring[0])).toThrow(
468 `Value is too complex to hash safely: structural depth`,
469 )
470 expect(() => hash(ring[0])).toThrow(
471 `Value is too complex to hash safely: structural depth`,
472 )
473 expect(reads).toBe(2)
474
475 const createChain = (size: number) => {
476 const root: { next?: unknown } = {}
477 let tail = root
478 for (let index = 0; index < size; index++) {
479 const next: { next?: unknown } = {}
480 tail.next = next
481 tail = next
482 }
483 return root
484 }
485 const accepted = createChain(600)
486 expect(hash(structuredClone(accepted))).toBe(hash(accepted))
487
488 const root = createChain(800)
489 expect(() => hash(root)).toThrow(
490 `Value is too complex to hash safely: structural depth`,
491 )
492 })
493
494 it(`rejects dense ancestor back-references without warming siblings`, () => {
495 const createGraph = (size: number) => {
496 const nodes: Array<Record<string, unknown>> = []
497 for (let index = 0; index < size; index++) {
498 const node: Record<string, unknown> = { index }
499 if (index > 0) nodes[index - 1]!.next = node
500 for (let ancestor = 0; ancestor < index; ancestor++) {
501 node[`ancestor${ancestor}`] = nodes[ancestor]
502 }
503 nodes.push(node)
504 }
505 return nodes[0]!
506 }
507 const accepted = createGraph(50)
508 expect(() => hash(structuredClone(accepted))).toThrow(
509 `Cannot hash cyclic structural values`,
510 )
511 expect(() => hash(accepted)).toThrow(
512 `Cannot hash cyclic structural values`,
513 )
514
515 let reads = 0
516 const sentinel = Object.defineProperty({}, `value`, {
517 enumerable: true,
518 get: () => ++reads,
519 })
520 const rejected = createGraph(450)
521 Object.defineProperty(rejected, `aSentinel`, {
522 enumerable: true,
523 value: sentinel,
524 })
525
526 expect(() => hash(rejected)).toThrow(
527 `Cannot hash cyclic structural values`,
528 )
529 expect(() => hash(rejected)).toThrow(
530 `Cannot hash cyclic structural values`,
531 )
532 expect(reads).toBe(2)
533 })
534
535 it(`should hash arrays`, () => {
536 const arr1 = [1, 2, 3]
537 const arr2 = [1, 2, 3]
538 const arr3 = [3, 2, 1]
539
540 const hash1 = hash(arr1)
541 const hash2 = hash(arr2)
542 const hash3 = hash(arr3)
543
544 expect(typeof hash1).toBe(hashType)
545 expect(hash1).toBe(hash2) // Same content should have same hash
546 expect(hash1).not.toBe(hash3) // Different content should have different hash
547 })
548
549 it(`should hash Date objects`, () => {
550 const date1 = new Date(`2023-01-01`)
551 const date2 = new Date(`2023-01-01`)
552 const date3 = new Date(`2023-01-02`)
553
554 const hash1 = hash(date1)
555 const hash2 = hash(date2)
556 const hash3 = hash(date3)
557
558 expect(typeof hash1).toBe(hashType)
559 expect(hash1).toBe(hash2) // Same date should have same hash
560 expect(hash1).not.toBe(hash3) // Different dates should have different hash
561 })
562
563 it(`should hash Temporal objects by value`, () => {
564 const date1 = Temporal.PlainDate.from(`2024-01-15`)
565 const date2 = Temporal.PlainDate.from(`2024-01-15`)
566 const date3 = Temporal.PlainDate.from(`2024-06-15`)
567
568 const hash1 = hash(date1)
569 const hash2 = hash(date2)
570 const hash3 = hash(date3)
571
572 expect(typeof hash1).toBe(hashType)
573 expect(hash1).toBe(hash2) // Same Temporal date should have same hash
574 expect(hash1).not.toBe(hash3) // Different Temporal dates should have different hash
575
576 // Different Temporal types with overlapping string representations should differ
577 const plainDate = Temporal.PlainDate.from(`2024-01-15`)
578 const plainDateTime = Temporal.PlainDateTime.from(`2024-01-15T00:00:00`)
579
580 expect(hash(plainDate)).not.toBe(hash(plainDateTime))
581
582 // Other Temporal types should also hash correctly
583 const time1 = Temporal.PlainTime.from(`10:30:00`)
584 const time2 = Temporal.PlainTime.from(`10:30:00`)
585 const time3 = Temporal.PlainTime.from(`14:00:00`)
586
587 expect(hash(time1)).toBe(hash(time2))
588 expect(hash(time1)).not.toBe(hash(time3))
589
590 const instant1 = Temporal.Instant.from(`2024-01-15T00:00:00Z`)
591 const instant2 = Temporal.Instant.from(`2024-01-15T00:00:00Z`)
592 const instant3 = Temporal.Instant.from(`2024-06-15T00:00:00Z`)
593
594 expect(hash(instant1)).toBe(hash(instant2))
595 expect(hash(instant1)).not.toBe(hash(instant3))
596 })
597
598 it(`should hash RegExp objects`, () => {
599 const regex1 = /test/g
600 const regex2 = /test/g
601 const regex3 = /different/i
602 const regex4 = /test/g
603 regex4.lastIndex = 1
604
605 const hash1 = hash(regex1)
606 const hash2 = hash(regex2)
607 const hash3 = hash(regex3)
608 const hash4 = hash(regex4)
609
610 expect(typeof hash1).toBe(hashType)
611 expect(hash1).toBe(hash2) // Same regex should have same hash
612 expect(hash1).not.toBe(hash3)
613 expect(hash1).not.toBe(hash4)
614 })
615
616 it(`should include sparse array length in its hash`, () => {
617 expect(hash([])).not.toBe(hash(Array(1)))
618 expect(hash(Array(1))).not.toBe(hash(Array(2)))
619 expect(hash(Array(2))).toBe(hash(Array(2)))
620 })
621
622 it(`should hash nested objects`, () => {
623 const nested1 = { a: { b: { c: 1 } } }
624 const nested2 = { a: { b: { c: 1 } } }
625 const nested3 = { a: { b: { c: 2 } } }
626
627 const hash1 = hash(nested1)
628 const hash2 = hash(nested2)
629 const hash3 = hash(nested3)
630
631 expect(typeof hash1).toBe(hashType)
632 expect(hash1).toBe(hash2)
633 expect(hash1).not.toBe(hash3)
634 })
635
636 it(`should hash functions`, () => {
637 const func1 = function test() {
638 return 1
639 }
640 const func2 = function test() {
641 return 1
642 }
643 const func3 = function different() {
644 return 2
645 }
646
647 const hash1 = hash(func1)
648 const hash2 = hash(func2)
649 const hash3 = hash(func3)
650
651 expect(typeof hash1).toBe(hashType)
652 expect(typeof hash2).toBe(hashType)
653 expect(typeof hash3).toBe(hashType)
654 expect(hash1).not.toBe(hash2) // Different function should have different hash
655 expect(hash1).not.toBe(hash3) // Different function should have different hash
656 expect(hash1).toBe(hash(func1)) // hashing same function should return same hash
657 })
658
659 it(`should hash Set objects`, () => {
660 const set1 = new Set([1, 2, 3])
661 const set2 = new Set([1, 2, 3])
662 const set3 = new Set([1, 2, 3, 4])
663
664 const hash1 = hash(set1)
665 const hash2 = hash(set2)
666 const hash3 = hash(set3)
667
668 expect(typeof hash1).toBe(hashType)
669 expect(hash1).toBe(hash2) // Same content should have same hash
670 expect(hash1).not.toBe(hash3) // Different content should have different hash
671 })
672
673 it(`should hash Map objects`, () => {
674 const map1 = new Map([
675 [`a`, 1],
676 [`b`, 2],
677 ])
678 const map2 = new Map([
679 [`a`, 1],
680 [`b`, 2],
681 ])
682 const map3 = new Map([
683 [`a`, 1],
684 [`b`, 2],
685 [`c`, 3],
686 ])
687
688 const hash1 = hash(map1)
689 const hash2 = hash(map2)
690 const hash3 = hash(map3)
691
692 expect(typeof hash1).toBe(hashType)
693 expect(hash1).toBe(hash2) // Same content should have same hash
694 expect(hash1).not.toBe(hash3) // Different content should have different hash
695 })
696
697 it(`should hash Maps and Sets with unsupported types`, () => {
698 // Map with BigInt values
699 const mapWithBigInt1 = new Map([
700 [`a`, 123n],
701 [`b`, 456n],
702 ])
703 const mapWithBigInt2 = new Map([
704 [`a`, 123n],
705 [`b`, 456n],
706 ])
707 const mapWithBigInt3 = new Map([
708 [`a`, 123n],
709 [`b`, 789n],
710 ])
711
712 const hash1 = hash(mapWithBigInt1)
713 const hash2 = hash(mapWithBigInt2)
714 const hash3 = hash(mapWithBigInt3)
715
716 expect(typeof hash1).toBe(hashType)
717 expect(hash1).toBe(hash2) // Same BigInt content should have same hash
718 expect(hash1).not.toBe(hash3) // Different BigInt content should have different hash
719
720 // Set with Symbol values
721 const sym1 = Symbol(`test`)
722 const sym2 = Symbol(`different`)
723 const setWithSymbols1 = new Set([sym1, sym2])
724 const setWithSymbols2 = new Set([sym1, sym2])
725 const setWithSymbols3 = new Set([sym1])
726
727 const hash4 = hash(setWithSymbols1)
728 const hash5 = hash(setWithSymbols2)
729 const hash6 = hash(setWithSymbols3)
730
731 expect(typeof hash4).toBe(hashType)
732 expect(hash4).toBe(hash5) // Same Symbol content should have same hash
733 expect(hash4).not.toBe(hash6) // Different Symbol content should have different hash
734 })
735
736 it(`should hash small Buffers and Uint8Arrays by content`, () => {
737 // Small buffers (≤128 bytes) are hashed by content for proper equality comparisons
738 const buffer1 = Buffer.from([1, 2, 3])
739 const buffer2 = Buffer.from([1, 2, 3])
740 const buffer3 = Buffer.from([1, 2, 3, 4])
741
742 const hash1 = hash(buffer1)
743 const hash2 = hash(buffer2)
744 const hash3 = hash(buffer3)
745
746 expect(typeof hash1).toBe(hashType)
747 expect(hash1).toBe(hash2) // Same content = same hash for small buffers
748 expect(hash1).not.toBe(hash3) // Different Buffer content should have different hash
749 expect(hash1).toBe(hash(buffer1)) // Hashing same buffer should return same hash
750
751 const uint8Array1 = new Uint8Array([1, 2, 3])
752 const uint8Array2 = new Uint8Array([1, 2, 3])
753 const uint8Array3 = new Uint8Array([1, 2, 3, 4])
754
755 const hash4 = hash(uint8Array1)
756 const hash5 = hash(uint8Array2)
757 const hash6 = hash(uint8Array3)
758
759 expect(typeof hash4).toBe(hashType)
760 expect(hash4).toBe(hash5) // Same content = same hash for small Uint8Arrays
761 expect(hash4).not.toBe(hash6) // Different uint8Array content should have different hash
762 expect(hash4).toBe(hash(uint8Array1)) // Hashing same uint8Array should return same hash
763 })
764
765 it(`should hash large Buffers, Uint8Arrays and File objects by reference`, () => {
766 // Large buffers (>128 bytes) are hashed by reference to avoid performance costs
767 const largeBuffer1 = Buffer.alloc(300)
768 const largeBuffer2 = Buffer.alloc(300)
769
770 // Fill with same content
771 for (let i = 0; i < 300; i++) {
772 largeBuffer1[i] = i % 256
773 largeBuffer2[i] = i % 256
774 }
775
776 const hash1 = hash(largeBuffer1)
777 const hash2 = hash(largeBuffer2)
778
779 expect(typeof hash1).toBe(hashType)
780 expect(hash1).not.toBe(hash2) // Same content but different instances = different hash for large buffers
781 expect(hash1).toBe(hash(largeBuffer1)) // Hashing same buffer should return same hash
782
783 const largeUint8Array1 = new Uint8Array(300)
784 const largeUint8Array2 = new Uint8Array(300)
785
786 // Fill with same content
787 for (let i = 0; i < 300; i++) {
788 largeUint8Array1[i] = i % 256
789 largeUint8Array2[i] = i % 256
790 }
791
792 const hash3 = hash(largeUint8Array1)
793 const hash4 = hash(largeUint8Array2)
794
795 expect(typeof hash3).toBe(hashType)
796 expect(hash3).not.toBe(hash4) // Same content but different instances = different hash for large Uint8Arrays
797 expect(hash3).toBe(hash(largeUint8Array1)) // Hashing same uint8Array should return same hash
798
799 // Files are always hashed by reference regardless of size
800 const file1 = new File([`Hello, world!`], `test.txt`)
801 const file2 = new File([`Hello, world!`], `test.txt`)
802 const file3 = new File([`Hello, world!`], `test.txt`)
803
804 const hash7 = hash(file1)
805 const hash8 = hash(file2)
806 const hash9 = hash(file3)
807
808 expect(typeof hash7).toBe(hashType)
809 expect(hash7).not.toBe(hash8) // Same content but different file instances have a different hash because it would be too costly to deeply hash files
810 expect(hash7).not.toBe(hash9) // Different file content should have different hash
811 expect(hash7).toBe(hash(file1)) // Hashing same file should return same hash
812 })
813 })
814
815 describe(`caching behavior`, () => {
816 it(`should cache hash values for objects`, () => {
817 const obj = { test: `value` }
818
819 const hash1 = hash(obj)
820 const hash2 = hash(obj)
821
822 expect(hash1).toBe(hash2)
823 expect(typeof hash1).toBe(hashType)
824 })
825
826 it(`should return cached values on subsequent calls`, () => {
827 const obj = { complex: { nested: { data: [1, 2, 3] } } }
828
829 // First call should compute and cache
830 const hash1 = hash(obj)
831
832 // Second call should return cached value
833 const hash2 = hash(obj)
834
835 expect(hash1).toBe(hash2)
836 expect(typeof hash1).toBe(hashType)
837 })
838
839 it(`should not cache primitive values`, () => {
840 // Primitives should not be cached as they use JSON.stringify directly
841 const hash1 = hash(`test`)
842 const hash2 = hash(`test`)
843
844 expect(hash1).toBe(hash2)
845 expect(typeof hash1).toBe(hashType)
846 })
847 })
848
849 describe(`edge cases`, () => {
850 it(`should handle empty objects and arrays`, () => {
851 expect(typeof hash({})).toBe(hashType)
852 expect(typeof hash([])).toBe(hashType)
853 expect(hash({})).not.toBe(hash([]))
854 })
855
856 it(`should handle objects with null and undefined values`, () => {
857 const obj1 = { a: null, b: undefined }
858 const obj2 = { a: null, b: undefined }
859
860 const hash1 = hash(obj1)
861 const hash2 = hash(obj2)
862
863 expect(hash1).toBe(hash2)
864 expect(typeof hash1).toBe(hashType)
865 })
866
867 it(`should distinguish between arrays and maps`, () => {
868 const array = [
869 [1, 2],
870 [3, 4],
871 ] as const
872 const map = new Map(array)
873
874 const hash1 = hash(array)
875 const hash2 = hash(map)
876
877 expect(typeof hash1).toBe(hashType)
878 expect(typeof hash2).toBe(hashType)
879 expect(hash1).not.toBe(hash2)
880 })
881
882 it(`should handle mixed type arrays`, () => {
883 const mixedArray = [1, `string`, true, null, { key: `value` }]
884 const sameArray = [1, `string`, true, null, { key: `value` }]
885
886 const hash1 = hash(mixedArray)
887 const hash2 = hash(sameArray)
888
889 expect(hash1).toBe(hash2)
890 expect(typeof hash1).toBe(hashType)
891 })
892
893 it(`should produce consistent hashes for same content`, () => {
894 const obj = {
895 string: `test`,
896 number: 42,
897 boolean: true,
898 array: [1, 2, 3],
899 nested: { inner: `value` },
900 buffer: Buffer.from([1, 2, 3]),
901 uint8Array: new Uint8Array([1, 2, 3]),
902 file: new File([`Hello, world!`], `test.txt`),
903 }
904
905 // Multiple calls should return the same hash
906 const hashes = Array.from({ length: 5 }, () => hash(obj))
907 const firstHash = hashes[0]
908
909 expect(hashes.every((h) => h === firstHash)).toBe(true)
910 expect(typeof firstHash).toBe(hashType)
911 })
912 })
913})