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