Skip to content

Commit 62236b7

Browse files
committed
Compare and hash DOM nodes and ranges by reference in Equal and Hash
1 parent f116db0 commit 62236b7

5 files changed

Lines changed: 193 additions & 23 deletions

File tree

‎.changeset/equal-dom-reference.md‎

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"effect": patch
3+
---
4+
5+
Compare and hash DOM nodes and ranges by reference in `Equal.equals` and `Hash.hash` so structural comparisons do not traverse the DOM tree or invoke throwing platform getters.

‎packages/effect/src/Equal.ts‎

Lines changed: 5 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -138,8 +138,8 @@ export interface Equal extends Hash.Hash {
138138
* Dates compare by ISO string, RegExps compare by string representation,
139139
* arrays compare element-by-element, Maps and Sets compare entries
140140
* order-independently, and plain objects compare enumerable keys recursively.
141-
* Functions without an `Equal` implementation compare by reference. Circular
142-
* structures use coinductive equality.
141+
* Functions, DOM nodes, and DOM ranges without an `Equal` implementation
142+
* compare by reference. Circular structures use coinductive equality.
143143
*
144144
* Custom `Hash` implementations and already-cached structural hashes are
145145
* checked first as a fast-path rejection. The function also supports dual
@@ -284,6 +284,9 @@ function compareStructure(self: object, that: object): boolean {
284284
if (kind !== objectKind(that)) {
285285
return false
286286
}
287+
if (kind === 10) {
288+
return false
289+
}
287290
if (kind >= 7) {
288291
const selfBytes = toBytes(self as ArrayBufferLike | DataView, kind)
289292
const thatBytes = toBytes(that as ArrayBufferLike | DataView, kind)

‎packages/effect/src/Hash.ts‎

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -153,7 +153,7 @@ export const hash: <A>(self: A) => number = <A>(self: A) => {
153153
try {
154154
if (isHash(self)) {
155155
h = (self as Hash)[symbol]()
156-
} else if (typeof self === "function") {
156+
} else if (typeof self === "function" || kind === 10) {
157157
h = random(self)
158158
} else if (kind >= 7) {
159159
const bytes = toBytes(self as any, kind)

‎packages/effect/src/internal/equal.ts‎

Lines changed: 96 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -40,27 +40,103 @@ export const getAllObjectKeys = (obj: object): Array<PropertyKey> | Set<Property
4040
/** @internal */
4141
export const byReferenceInstances = new WeakSet<object>()
4242

43+
const isDomNode = (u: object): boolean => {
44+
const globalNode = (globalThis as { readonly Node?: unknown }).Node
45+
if (typeof globalNode === "function" && u instanceof (globalNode as new(...args: Array<any>) => object)) {
46+
return true
47+
}
48+
if (!("nodeType" in u)) return false
49+
const node = u as {
50+
readonly nodeType?: unknown
51+
readonly ownerDocument?: {
52+
readonly nodeType?: unknown
53+
readonly createElement?: unknown
54+
readonly defaultView?: { readonly Node?: unknown } | null
55+
} | null
56+
readonly defaultView?: { readonly Node?: unknown } | null
57+
readonly createElement?: unknown
58+
}
59+
if (typeof node.nodeType !== "number") return false
60+
const view = node.ownerDocument?.defaultView ?? node.defaultView
61+
if (typeof view?.Node === "function" && u instanceof (view.Node as new(...args: Array<any>) => object)) {
62+
return true
63+
}
64+
if (node.ownerDocument === null) {
65+
return node.nodeType === 9 && typeof node.createElement === "function"
66+
}
67+
return (
68+
node.ownerDocument !== undefined &&
69+
node.ownerDocument.nodeType === 9 &&
70+
typeof node.ownerDocument.createElement === "function"
71+
)
72+
}
73+
74+
const isDomRange = (u: object): boolean => {
75+
const globals = globalThis as {
76+
readonly AbstractRange?: unknown
77+
readonly Range?: unknown
78+
readonly StaticRange?: unknown
79+
}
80+
if (
81+
(typeof globals.AbstractRange === "function" &&
82+
u instanceof (globals.AbstractRange as new(...args: Array<any>) => object)) ||
83+
(typeof globals.Range === "function" && u instanceof (globals.Range as new(...args: Array<any>) => object)) ||
84+
(typeof globals.StaticRange === "function" &&
85+
u instanceof (globals.StaticRange as new(...args: Array<any>) => object))
86+
) {
87+
return true
88+
}
89+
if (!("startContainer" in u)) return false
90+
const range = u as {
91+
readonly startContainer?: unknown
92+
readonly startOffset?: unknown
93+
readonly endOffset?: unknown
94+
readonly collapsed?: unknown
95+
}
96+
const container = range.startContainer
97+
if (typeof container !== "object" || container === null) return false
98+
const view = (container as {
99+
readonly ownerDocument?: {
100+
readonly defaultView?: {
101+
readonly AbstractRange?: unknown
102+
readonly Range?: unknown
103+
readonly StaticRange?: unknown
104+
} | null
105+
} | null
106+
}).ownerDocument?.defaultView
107+
if (view != null) {
108+
if (
109+
(typeof view.AbstractRange === "function" &&
110+
u instanceof (view.AbstractRange as new(...args: Array<any>) => object)) ||
111+
(typeof view.Range === "function" && u instanceof (view.Range as new(...args: Array<any>) => object)) ||
112+
(typeof view.StaticRange === "function" && u instanceof (view.StaticRange as new(...args: Array<any>) => object))
113+
) {
114+
return true
115+
}
116+
}
117+
return (
118+
typeof range.collapsed === "boolean" &&
119+
typeof range.startOffset === "number" &&
120+
typeof range.endOffset === "number" &&
121+
isDomNode(container)
122+
)
123+
}
124+
43125
/** @internal */
44-
export const objectKind = (u: object): number =>
45-
Array.isArray(u) ?
46-
5 :
47-
ArrayBuffer.isView(u) ?
48-
(u instanceof DataView ? 7 : 6) :
49-
Object.getPrototypeOf(u) === Object.prototype ?
50-
0 :
51-
u instanceof Date ?
52-
1 :
53-
u instanceof RegExp ?
54-
2 :
55-
u instanceof Map ?
56-
3 :
57-
u instanceof Set ?
58-
4 :
59-
u instanceof ArrayBuffer ?
60-
8 :
61-
typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer ?
62-
9 :
63-
0
126+
export const objectKind = (u: object): number => {
127+
if (Array.isArray(u)) return 5
128+
if (ArrayBuffer.isView(u)) return u instanceof DataView ? 7 : 6
129+
const proto = Object.getPrototypeOf(u)
130+
if (proto === Object.prototype || proto === null) return 0
131+
if (u instanceof Date) return 1
132+
if (u instanceof RegExp) return 2
133+
if (u instanceof Map) return 3
134+
if (u instanceof Set) return 4
135+
if (u instanceof ArrayBuffer) return 8
136+
if (typeof SharedArrayBuffer !== "undefined" && u instanceof SharedArrayBuffer) return 9
137+
if (isDomNode(u) || isDomRange(u)) return 10
138+
return 0
139+
}
64140

65141
/**
66142
* Returns `undefined` for detached buffers, which can no longer be read.

‎packages/effect/test/Equal.test.ts‎

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1665,4 +1665,90 @@ describe("Equal.equals", () => {
16651665
expect(Equal.equals(obj1, obj2)).toBe(false)
16661666
})
16671667
})
1668+
1669+
describe("DOM nodes and ranges", () => {
1670+
it("compares DOM nodes and ranges by reference without reading throwing getters", async () => {
1671+
const { Window } = await import("happy-dom")
1672+
const win = new Window()
1673+
const doc = win.document
1674+
const a = doc.createElement("div")
1675+
const b = doc.createElement("div")
1676+
const svgA = doc.createElementNS("http://www.w3.org/2000/svg", "svg")
1677+
const svgB = doc.createElementNS("http://www.w3.org/2000/svg", "svg")
1678+
let getterCalls = 0
1679+
const installThrowingGetter = (node: object) =>
1680+
Object.defineProperty(node, "brokenSvgMetric", {
1681+
enumerable: true,
1682+
get() {
1683+
getterCalls++
1684+
throw new TypeError("Illegal invocation")
1685+
}
1686+
})
1687+
installThrowingGetter(svgA)
1688+
installThrowingGetter(svgB)
1689+
1690+
assert.isTrue(Equal.equals(a, a))
1691+
assert.isFalse(Equal.equals(a, b))
1692+
assert.isFalse(Equal.equals(a, {}))
1693+
assert.isFalse(Equal.equals({}, a))
1694+
const otherWin = new Window()
1695+
assert.isTrue(Equal.equals(doc, doc))
1696+
assert.isFalse(Equal.equals(doc, otherWin.document))
1697+
1698+
// Nested wrappers compare the same DOM node as equal and distinct nodes as unequal
1699+
// without invoking DOM getters (including during Hash.hash on shared references).
1700+
assert.isTrue(Equal.equals({ node: svgA }, { node: svgA }))
1701+
assert.isFalse(Equal.equals({ node: svgA }, { node: svgB }))
1702+
assert.strictEqual(Hash.hash({ node: svgA }), Hash.hash({ node: svgA }))
1703+
assert.strictEqual(getterCalls, 0)
1704+
1705+
// Detached documents (`defaultView === null`) and their elements.
1706+
const detached = doc.implementation.createHTMLDocument()
1707+
const detachedA = detached.createElement("span")
1708+
const detachedB = detached.createElement("span")
1709+
installThrowingGetter(detachedA)
1710+
installThrowingGetter(detachedB)
1711+
assert.isTrue(Equal.equals(detached, detached))
1712+
assert.isTrue(Equal.equals(detachedA, detachedA))
1713+
assert.isFalse(Equal.equals(detachedA, detachedB))
1714+
assert.strictEqual(getterCalls, 0)
1715+
1716+
// DOM ranges compare by reference without walking startContainer/endContainer.
1717+
doc.body.append(a, b)
1718+
const rangeA = doc.createRange()
1719+
rangeA.selectNode(a)
1720+
const rangeB = doc.createRange()
1721+
rangeB.selectNode(a)
1722+
assert.isTrue(Equal.equals(rangeA, rangeA))
1723+
assert.isFalse(Equal.equals(rangeA, rangeB))
1724+
assert.isTrue(Equal.equals({ range: rangeA }, { range: rangeA }))
1725+
assert.isFalse(Equal.equals({ range: rangeA }, { range: rangeB }))
1726+
assert.strictEqual(Hash.hash(rangeA), Hash.hash(rangeA))
1727+
1728+
// Custom Equal/Hash implementations on a DOM node still take precedence.
1729+
const customA = doc.createElement("span")
1730+
const customB = doc.createElement("span")
1731+
Object.assign(customA, {
1732+
[Equal.symbol](that: unknown) {
1733+
return that === customB || that === customA
1734+
},
1735+
[Hash.symbol]() {
1736+
return 42
1737+
}
1738+
})
1739+
Object.assign(customB, {
1740+
[Equal.symbol](that: unknown) {
1741+
return that === customA || that === customB
1742+
},
1743+
[Hash.symbol]() {
1744+
return 42
1745+
}
1746+
})
1747+
assert.isTrue(Equal.equals(customA, customB))
1748+
assert.strictEqual(Hash.hash(customA), 42)
1749+
1750+
await win.happyDOM.close()
1751+
await otherWin.happyDOM.close()
1752+
})
1753+
})
16681754
})

0 commit comments

Comments
 (0)