Open History to see the last commit
1import { isTemporal } from './hashing/temporal.js'
2
3// JS engines have various limits on how many args can be passed to a function
4// with a spread operator, so we need to split the operation into chunks
5// 32767 is the max for Chrome 14, all others are higher
6// TODO: investigate the performance of this and other approaches
7const chunkSize = 30000
8export function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {
9 if (other.length <= chunkSize) {
10 array.push(...other)
11 } else {
12 for (let i = 0; i < other.length; i += chunkSize) {
13 const chunk = other.slice(i, i + chunkSize)
14 array.push(...chunk)
15 }
16 }
17}
18
19export function binarySearch<T>(
20 array: Array<T>,
21 value: T,
22 comparator: (a: T, b: T) => number,
23): number {
24 let low = 0
25 let high = array.length
26 while (low < high) {
27 const mid = Math.floor((low + high) / 2)
28 const comparison = comparator(array[mid]!, value)
29 if (comparison < 0) {
30 low = mid + 1
31 } else if (comparison > 0) {
32 high = mid
33 } else {
34 return mid
35 }
36 }
37 return low
38}
39
40export type HRange = [number, number] // half-open [start, end[ i.e. end is exclusive
41
42/**
43 * Computes the difference between two half-open ranges.
44 * @param a - The first half-open range
45 * @param b - The second half-open range
46 * @returns The difference between the two ranges
47 */
48export function diffHalfOpen(a: HRange, b: HRange) {
49 const [a1, a2] = a
50 const [b1, b2] = b
51
52 // A \ B can be up to two segments (left and right of the overlap)
53 const onlyInA: Array<number> = [
54 ...range(a1, Math.min(a2, b1)), // left side of A outside B
55 ...range(Math.max(a1, b2), a2), // right side of A outside B
56 ]
57
58 // B \ A similarly
59 const onlyInB: Array<number> = [
60 ...range(b1, Math.min(b2, a1)),
61 ...range(Math.max(b1, a2), b2),
62 ]
63
64 return { onlyInA, onlyInB }
65}
66
67function range(start: number, end: number): Array<number> {
68 const out: Array<number> = []
69 for (let i = start; i < end; i++) out.push(i)
70 return out
71}
72
73/**
74 * Compares two keys (string | number) in a consistent, deterministic way.
75 * Handles mixed types by ordering strings before numbers.
76 */
77export function compareKeys(a: string | number, b: string | number): number {
78 // Same type: compare directly
79 if (typeof a === typeof b) {
80 if (typeof a === `number` && typeof b === `number`) {
81 const aIsNaN = Number.isNaN(a)
82 const bIsNaN = Number.isNaN(b)
83 if (aIsNaN || bIsNaN) {
84 if (aIsNaN && bIsNaN) return 0
85 return aIsNaN ? 1 : -1
86 }
87 }
88 if (a < b) return -1
89 if (a > b) return 1
90 return 0
91 }
92 // Different types: strings come before numbers
93 return typeof a === `string` ? -1 : 1
94}
95
96type CanonicalValue =
97 | readonly [`undefined`]
98 | readonly [`null`]
99 | readonly [`boolean`, boolean]
100 | readonly [`number`, number | `NaN` | `Infinity` | `-Infinity`]
101 | readonly [`bigint`, string]
102 | readonly [`string`, string]
103 | readonly [`date`, number | `Invalid`]
104 | readonly [`temporal`, string, string]
105 | readonly [`regexp`, string, string]
106 | readonly [`bytes`, Array<number>]
107 | readonly [`array`, Array<CanonicalValue>]
108 | readonly [`map`, Array<readonly [CanonicalValue, CanonicalValue]>]
109 | readonly [`set`, Array<CanonicalValue>]
110 | readonly [`object`, Array<readonly [string, CanonicalValue]>]
111
112/**
113 * Serializes a supported query value into one canonical key.
114 *
115 * JSON's native encoding is not suitable for relation keys: it merges BigInt
116 * with strings when a replacer is used, merges NaN with null, drops undefined,
117 * and depends on object insertion order. Ordinary JSON values keep their
118 * established wire form. Values that need richer types use a reserved prefix
119 * plus a structural, type-tagged encoding.
120 */
121export function serializeValue(value: unknown): string {
122 if (isJsonSafeStructuralValue(value, new Set())) {
123 return JSON.stringify(toStableJsonValue(value))
124 }
125
126 return `~${JSON.stringify(toCanonicalValue(value, new Set()))}`
127}
128
129type JsonValue =
130 | null
131 | boolean
132 | number
133 | string
134 | Array<JsonValue>
135 | { [key: string]: JsonValue }
136
137function isJsonSafeStructuralValue(
138 value: unknown,
139 ancestors: Set<object>,
140): boolean {
141 if (value === null) return true
142
143 switch (typeof value) {
144 case `boolean`:
145 case `string`:
146 return true
147 case `number`:
148 return Number.isFinite(value)
149 case `undefined`:
150 case `bigint`:
151 case `symbol`:
152 case `function`:
153 return false
154 }
155
156 return withAcyclicValue(value, ancestors, () => {
157 if (
158 value instanceof Date ||
159 value instanceof RegExp ||
160 value instanceof Uint8Array ||
161 isTemporal(value) ||
162 value instanceof Map ||
163 value instanceof Set
164 ) {
165 return false
166 }
167
168 return Array.isArray(value)
169 ? value.every((item) => isJsonSafeStructuralValue(item, ancestors))
170 : Object.keys(value).every((key) =>
171 isJsonSafeStructuralValue(
172 (value as Record<string, unknown>)[key],
173 ancestors,
174 ),
175 )
176 })
177}
178
179function toStableJsonValue(value: unknown): JsonValue {
180 if (
181 value === null ||
182 typeof value === `boolean` ||
183 typeof value === `number` ||
184 typeof value === `string`
185 ) {
186 return value
187 }
188
189 if (Array.isArray(value)) {
190 return value.map(toStableJsonValue)
191 }
192
193 return Object.fromEntries(
194 Object.keys(value as object)
195 .sort()
196 .map((key) => [
197 key,
198 toStableJsonValue((value as Record<string, unknown>)[key]),
199 ]),
200 )
201}
202
203function toCanonicalValue(
204 value: unknown,
205 ancestors: Set<object>,
206): CanonicalValue {
207 if (value === undefined) return [`undefined`]
208 if (value === null) return [`null`]
209
210 switch (typeof value) {
211 case `boolean`:
212 return [`boolean`, value]
213 case `number`:
214 if (Number.isNaN(value)) return [`number`, `NaN`]
215 if (value === Infinity) return [`number`, `Infinity`]
216 if (value === -Infinity) return [`number`, `-Infinity`]
217 return [`number`, value === 0 ? 0 : value]
218 case `bigint`:
219 return [`bigint`, value.toString()]
220 case `string`:
221 return [`string`, value]
222 case `symbol`:
223 case `function`:
224 throw new TypeError(
225 `Cannot serialize ${typeof value} as a structural relation key`,
226 )
227 }
228
229 return withAcyclicValue(value, ancestors, () => {
230 if (value instanceof Date) {
231 const timestamp = value.getTime()
232 return Number.isNaN(timestamp)
233 ? ([`date`, `Invalid`] as const)
234 : ([`date`, timestamp] as const)
235 }
236
237 if (value instanceof RegExp) {
238 return [`regexp`, value.source, value.flags]
239 }
240
241 if (value instanceof Uint8Array) {
242 return [`bytes`, Array.from(value)]
243 }
244
245 if (isTemporal(value)) {
246 return [`temporal`, value[Symbol.toStringTag], value.toString()]
247 }
248
249 if (Array.isArray(value)) {
250 return [`array`, value.map((item) => toCanonicalValue(item, ancestors))]
251 }
252
253 if (value instanceof Map) {
254 const entries = [...value.entries()].map(
255 ([key, entryValue]) =>
256 [
257 toCanonicalValue(key, ancestors),
258 toCanonicalValue(entryValue, ancestors),
259 ] as const,
260 )
261 entries.sort((left, right) =>
262 compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),
263 )
264 return [`map`, entries]
265 }
266
267 if (value instanceof Set) {
268 const entries = [...value].map((entry) =>
269 toCanonicalValue(entry, ancestors),
270 )
271 entries.sort((left, right) =>
272 compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),
273 )
274 return [`set`, entries]
275 }
276
277 const entries = Object.keys(value)
278 .sort()
279 .map(
280 (key) =>
281 [
282 key,
283 toCanonicalValue(
284 (value as Record<string, unknown>)[key],
285 ancestors,
286 ),
287 ] as const,
288 )
289 return [`object`, entries]
290 })
291}
292
293function compareSerializedValues(left: string, right: string): number {
294 return left < right ? -1 : left > right ? 1 : 0
295}
296
297function withAcyclicValue<T>(
298 value: object,
299 ancestors: Set<object>,
300 encode: () => T,
301): T {
302 if (ancestors.has(value)) {
303 throw new TypeError(`Cannot serialize a cyclic structural relation key`)
304 }
305
306 ancestors.add(value)
307 try {
308 return encode()
309 } finally {
310 ancestors.delete(value)
311 }
312}