diff --git a/.changeset/equal-dom-reference.md b/.changeset/equal-dom-reference.md new file mode 100644 index 00000000000..5ac3f37c0e5 --- /dev/null +++ b/.changeset/equal-dom-reference.md @@ -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. diff --git a/packages/effect/src/Equal.ts b/packages/effect/src/Equal.ts index ce1fba395e8..716c0122f49 100644 --- a/packages/effect/src/Equal.ts +++ b/packages/effect/src/Equal.ts @@ -18,6 +18,7 @@ import { byReferenceInstances, getAllObjectKeys, hashCache, + isDomReference, objectKind, toBytes } from "./internal/equal.ts" @@ -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 @@ -300,7 +301,7 @@ function compareStructure(self: object, that: object): boolean { return (self as Set).size === (that as Set).size && compareHashed(self as Set, that as Set, 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, that: Array): boolean { diff --git a/packages/effect/src/Hash.ts b/packages/effect/src/Hash.ts index 491033dcff9..9c983573a12 100644 --- a/packages/effect/src/Hash.ts +++ b/packages/effect/src/Hash.ts @@ -18,6 +18,7 @@ import { combine as combineDataFirst, getAllObjectKeys, hashCache, + isDomReference, mix, objectKind, toBytes @@ -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** * @@ -165,7 +168,7 @@ export const hash: (self: A) => number = (self: A) => { } else if (kind === 4) { h = hashUnordered(setSeed, self as any as Set, hashSetElement) } else { - h = structure(self) + h = isDomReference(self) ? random(self) : structure(self) } } finally { visitedObjects.delete(self) diff --git a/packages/effect/src/internal/equal.ts b/packages/effect/src/internal/equal.ts index e456e463415..bb8d5bf5960 100644 --- a/packages/effect/src/internal/equal.ts +++ b/packages/effect/src/internal/equal.ts @@ -40,6 +40,27 @@ export const getAllObjectKeys = (obj: object): Array | Set() +/** + * 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) ? diff --git a/packages/effect/test/Equal.test.ts b/packages/effect/test/Equal.test.ts index 35f80ceb883..d23164b61ab 100644 --- a/packages/effect/test/Equal.test.ts +++ b/packages/effect/test/Equal.test.ts @@ -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 { @@ -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() + } + }) }) diff --git a/packages/effect/test/Hash.test.ts b/packages/effect/test/Hash.test.ts index 764744dc5fa..312e7665e8c 100644 --- a/packages/effect/test/Hash.test.ts +++ b/packages/effect/test/Hash.test.ts @@ -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 => Array.from({ length }, (_, index) => index) @@ -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 => {