Skip to content
5 changes: 5 additions & 0 deletions .changeset/equal-dom-reference.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
"effect": patch
---

`Equal.equals` and `Hash.hash` now compare and hash DOM nodes and ranges by reference instead of walking the document.
7 changes: 4 additions & 3 deletions packages/effect/src/Equal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
byReferenceInstances,
getAllObjectKeys,
hashCache,
isDomReference,
objectKind,
toBytes
} from "./internal/equal.ts"
Expand Down Expand Up @@ -138,8 +139,8 @@ export interface Equal extends Hash.Hash {
* Dates compare by ISO string, RegExps compare by string representation,
* arrays compare element-by-element, Maps and Sets compare entries
* order-independently, and plain objects compare enumerable keys recursively.
* Functions without an `Equal` implementation compare by reference. Circular
* structures use coinductive equality.
* Functions, DOM nodes, and DOM ranges without an `Equal` implementation
* compare by reference. Circular structures use coinductive equality.
*
* Custom `Hash` implementations and already-cached structural hashes are
* checked first as a fast-path rejection. The function also supports dual
Expand Down Expand Up @@ -300,7 +301,7 @@ function compareStructure(self: object, that: object): boolean {
return (self as Set<unknown>).size === (that as Set<unknown>).size &&
compareHashed(self as Set<unknown>, that as Set<unknown>, Hash.hash, compareBoth)
}
return compareRecords(self as any, that as any)
return !isDomReference(self) && !isDomReference(that) && compareRecords(self as any, that as any)
}

function compareArrays(self: Array<unknown>, that: Array<unknown>): boolean {
Expand Down
5 changes: 4 additions & 1 deletion packages/effect/src/Hash.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import {
combine as combineDataFirst,
getAllObjectKeys,
hashCache,
isDomReference,
mix,
objectKind,
toBytes
Expand Down Expand Up @@ -91,6 +92,8 @@ export interface Hash {
* This function can hash primitives (numbers, strings, booleans, etc.) as well as
* objects, arrays, and other complex data structures. It automatically handles
* different types and provides a consistent hash value for equivalent inputs.
* Functions, DOM nodes, and DOM ranges without a `Hash` implementation hash by
* reference.
*
* **Gotchas**
*
Expand Down Expand Up @@ -165,7 +168,7 @@ export const hash: <A>(self: A) => number = <A>(self: A) => {
} else if (kind === 4) {
h = hashUnordered(setSeed, self as any as Set<unknown>, hashSetElement)
} else {
h = structure(self)
h = isDomReference(self) ? random(self) : structure(self)
}
} finally {
visitedObjects.delete(self)
Expand Down
21 changes: 21 additions & 0 deletions packages/effect/src/internal/equal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,27 @@ export const getAllObjectKeys = (obj: object): Array<PropertyKey> | Set<Property
/** @internal */
export const byReferenceInstances = new WeakSet<object>()

/**
* DOM nodes and ranges compare and hash by reference: walking their properties
* traverses the document and can throw. `Node.prototype` owns `DOCUMENT_NODE`
* and `nodeType` in every realm. Browsers tag `AbstractRange.prototype` (the
* base of `Range` and `StaticRange`); happy-dom's `Range.prototype` instead owns
* `compareBoundaryPoints` and `startOffset`. Only own descriptors are read, so
* no getter runs.
*
* @internal
*/
export const isDomReference = (u: object): boolean => {
for (let p = Object.getPrototypeOf(u); p !== null; p = Object.getPrototypeOf(p)) {
if (
(Object.hasOwn(p, "DOCUMENT_NODE") && Object.hasOwn(p, "nodeType")) ||
Object.getOwnPropertyDescriptor(p, Symbol.toStringTag)?.value === "AbstractRange" ||
(Object.hasOwn(p, "compareBoundaryPoints") && Object.hasOwn(p, "startOffset"))
) return true
}
return false
}

/** @internal */
export const objectKind = (u: object): number =>
Array.isArray(u) ?
Expand Down
98 changes: 98 additions & 0 deletions packages/effect/test/Equal.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import * as Equal from "effect/Equal"
import * as Hash from "effect/Hash"
import * as HashMap from "effect/HashMap"
import * as Option from "effect/Option"
import { Window } from "happy-dom"
import { describe, expect, it, vi } from "vitest"

class Key implements Equal.Equal, Hash.Hash {
Expand Down Expand Up @@ -1665,4 +1666,101 @@ describe("Equal.equals", () => {
expect(Equal.equals(obj1, obj2)).toBe(false)
})
})

it("compares DOM nodes and ranges by reference while preserving ordinary objects", async () => {
const window = new Window()
const other = new Window()
try {
const { document } = window
const detached = document.implementation.createHTMLDocument()
const div = document.createElement("div")
class Bookmark {
constructor(readonly startContainer: unknown, readonly offset: number) {}
}
class FakeNode {
constructor(readonly nodeType: number, readonly ownerDocument: unknown) {}
}
class SelectionSnapshot {
#tag = "SelectionSnapshot"
constructor(readonly _start: unknown, readonly endContainer: unknown, readonly collapsed: boolean) {}
get startContainer() {
return this._start
}
get [Symbol.toStringTag]() {
return this.#tag
}
}
class GuardedNode {
#kind = 1
constructor(readonly ownerDocument: unknown) {}
get nodeType() {
return this.#kind
}
get ELEMENT_NODE() {
return this.#kind
}
}
class Interval {
constructor(readonly start: number) {}
compareBoundaryPoints() {
return 0
}
}
class SourceSpan {
constructor(readonly start: number, readonly length: number) {}
get startOffset() {
return this.start
}
get endOffset() {
return this.start + this.length
}
}
class NodeKinds {
constructor(readonly kind: number) {}
get DOCUMENT_NODE() {
return 9
}
}
const makeForeignRecord = window.eval(
"(node, doc) => ({ startContainer: node, nodeType: 1, ownerDocument: doc, offset: 0 })"
) as (node: unknown, doc: unknown) => object

const pairs = [
[document, other.document],
[document.createElement("div"), document.createElement("div")],
[detached.createElement("div"), detached.createElement("div")],
[document.createRange(), other.document.createRange()],
[detached.createRange(), detached.createRange()]
]
for (const [a, b] of pairs) {
assert.isTrue(Equal.equals({ a }, { a }))
assert.isFalse(Equal.equals({ a }, { a: b }))
}
assert.isTrue(Equal.equals(new Bookmark(div, 0), new Bookmark(div, 0)))
assert.isFalse(Equal.equals(new Bookmark(div, 0), new Bookmark(div, 1)))
assert.isTrue(Equal.equals(new FakeNode(1, document), new FakeNode(1, document)))
assert.isTrue(Equal.equals(new SelectionSnapshot(div, div, true), new SelectionSnapshot(div, div, true)))
assert.isTrue(Equal.equals(new GuardedNode(document), new GuardedNode(document)))
assert.isTrue(Equal.equals(makeForeignRecord(div, document), makeForeignRecord(div, document)))
assert.isTrue(Equal.equals(new Interval(0), new Interval(0)))
assert.isTrue(Equal.equals(new NodeKinds(1), new NodeKinds(1)))
assert.isTrue(Equal.equals(new SourceSpan(8, 3), new SourceSpan(8, 3)))

const custom = (tag: number) =>
Object.assign(document.createElement("div"), {
tag,
[Equal.symbol](that: any) {
return that?.tag === tag
},
[Hash.symbol]() {
return tag
}
})
assert.isTrue(Equal.equals(custom(1), custom(1)))
assert.isFalse(Equal.equals(custom(1), custom(2)))
} finally {
await window.happyDOM.close()
await other.happyDOM.close()
}
})
})
42 changes: 41 additions & 1 deletion packages/effect/test/Hash.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { assert, describe, it } from "@effect/vitest"
import { assert, describe, it, vi } from "@effect/vitest"
import { Chunk, Equal, Graph, Hash, HashMap, HashSet, Trie } from "effect"
import { Window } from "happy-dom"

const range = (length: number): ReadonlyArray<number> => Array.from({ length }, (_, index) => index)

Expand Down Expand Up @@ -257,6 +258,45 @@ describe("Hash", () => {
})
})

it("hashes DOM nodes and ranges by reference unless they implement Hash", async () => {
const window = new Window()
try {
const node = window.document.createElement("div")
const range = window.document.createRange()
const detached = window.document.implementation.createHTMLDocument().createElement("div")
const random = vi.spyOn(Math, "random").mockReturnValue(0)
try {
assert.strictEqual(Hash.hash(node), Hash.random(node))
assert.strictEqual(Hash.hash(range), Hash.random(range))
assert.strictEqual(Hash.hash(detached), Hash.random(detached))
assert.strictEqual(Hash.hash({ node }), Hash.hash({ node }))
} finally {
random.mockRestore()
}
class Bookmark {
constructor(readonly startContainer: unknown, readonly offset: number) {}
}
class SelectionSnapshot {
#tag = "SelectionSnapshot"
constructor(readonly _start: unknown, readonly endContainer: unknown, readonly collapsed: boolean) {}
get startContainer() {
return this._start
}
get [Symbol.toStringTag]() {
return this.#tag
}
}
const bookmark = new Bookmark(node, 0)
assert.strictEqual(Hash.hash(bookmark), Hash.structure(bookmark))
const snapshot = new SelectionSnapshot(node, node, true)
assert.strictEqual(Hash.hash(snapshot), Hash.structure(snapshot))
const custom = Object.assign(window.document.createElement("div"), { [Hash.symbol]: () => 42 })
assert.strictEqual(Hash.hash(custom), 42)
} finally {
await window.happyDOM.close()
}
})

describe("Error objects", () => {
it("ignores non-enumerable construction-site metadata (JavaScriptCore)", () => {
const withSiteMetadata = (line: number): Error => {
Expand Down
Loading