Open History to see the last commit
1import { isTemporal } from './hashing/temporal.js'
2
3/**
4 * Simple assertion function for runtime checks.
5 * Throws an error if the condition is false.
6 */
7export function assert(
8 condition: unknown,
9 message?: string,
10): asserts condition {
11 if (!condition) {
12 throw new Error(message || `Assertion failed`)
13 }
14}
15
16/**
17 * A map that returns a default value for keys that are not present.
18 */
19export class DefaultMap<K, V> extends Map<K, V> {
20 constructor(
21 private defaultValue: () => V,
22 entries?: Iterable<[K, V]>,
23 ) {
24 super(entries)
25 }
26
27 get(key: K): V {
28 if (!this.has(key)) {
29 // this.set(key, this.defaultValue())
30 return this.defaultValue()
31 }
32 return super.get(key)!
33 }
34
35 /**
36 * Update the value for a key using a function.
37 */
38 update(key: K, updater: (value: V) => V): V {
39 const value = this.get(key)
40 const newValue = updater(value)
41 this.set(key, newValue)
42 return newValue
43 }
44}
45
46// JS engines have various limits on how many args can be passed to a function
47// with a spread operator, so we need to split the operation into chunks
48// 32767 is the max for Chrome 14, all others are higher
49// TODO: investigate the performance of this and other approaches
50const chunkSize = 30000
51export function chunkedArrayPush(array: Array<unknown>, other: Array<unknown>) {
52 if (other.length <= chunkSize) {
53 array.push(...other)
54 } else {
55 for (let i = 0; i < other.length; i += chunkSize) {
56 const chunk = other.slice(i, i + chunkSize)
57 array.push(...chunk)
58 }
59 }
60}
61
62export function binarySearch<T>(
63 array: Array<T>,
64 value: T,
65 comparator: (a: T, b: T) => number,
66): number {
67 let low = 0
68 let high = array.length
69 while (low < high) {
70 const mid = Math.floor((low + high) / 2)
71 const comparison = comparator(array[mid]!, value)
72 if (comparison < 0) {
73 low = mid + 1
74 } else if (comparison > 0) {
75 high = mid
76 } else {
77 return mid
78 }
79 }
80 return low
81}
82
83/**
84 * Utility for generating unique IDs for objects and values.
85 * Uses WeakMap for object reference tracking and consistent hashing for primitives.
86 */
87export class ObjectIdGenerator {
88 private objectIds = new WeakMap<object, number>()
89 private nextId = 0
90
91 /**
92 * Get a unique identifier for any value.
93 * - Objects: Uses WeakMap for reference-based identity
94 * - Primitives: Uses consistent string-based hashing
95 */
96 getId(value: any): number {
97 // For primitives, use a simple hash of their string representation
98 if (typeof value !== `object` || value === null) {
99 const str = String(value)
100 let hashValue = 0
101 for (let i = 0; i < str.length; i++) {
102 const char = str.charCodeAt(i)
103 hashValue = (hashValue << 5) - hashValue + char
104 hashValue = hashValue & hashValue // Convert to 32-bit integer
105 }
106 return hashValue
107 }
108
109 // For objects, use WeakMap to assign unique IDs
110 if (!this.objectIds.has(value)) {
111 this.objectIds.set(value, this.nextId++)
112 }
113 return this.objectIds.get(value)!
114 }
115
116 /**
117 * Get a string representation of the ID for use in composite keys.
118 */
119 getStringId(value: any): string {
120 if (value === null) return `null`
121 if (value === undefined) return `undefined`
122 if (typeof value !== `object`) return `str_${String(value)}`
123
124 return `obj_${this.getId(value)}`
125 }
126}
127
128/**
129 * Global instance for cases where a shared object ID space is needed.
130 */
131export const globalObjectIdGenerator = new ObjectIdGenerator()
132
133export function* concatIterable<T>(
134 ...iterables: Array<Iterable<T>>
135): Iterable<T> {
136 for (const iterable of iterables) {
137 yield* iterable
138 }
139}
140
141export function* mapIterable<T, U>(
142 it: Iterable<T>,
143 fn: (t: T) => U,
144): Iterable<U> {
145 for (const t of it) {
146 yield fn(t)
147 }
148}
149
150export type HRange = [number, number] // half-open [start, end[ i.e. end is exclusive
151
152/**
153 * Computes the difference between two half-open ranges.
154 * @param a - The first half-open range
155 * @param b - The second half-open range
156 * @returns The difference between the two ranges
157 */
158export function diffHalfOpen(a: HRange, b: HRange) {
159 const [a1, a2] = a
160 const [b1, b2] = b
161
162 // A \ B can be up to two segments (left and right of the overlap)
163 const onlyInA: Array<number> = [
164 ...range(a1, Math.min(a2, b1)), // left side of A outside B
165 ...range(Math.max(a1, b2), a2), // right side of A outside B
166 ]
167
168 // B \ A similarly
169 const onlyInB: Array<number> = [
170 ...range(b1, Math.min(b2, a1)),
171 ...range(Math.max(b1, a2), b2),
172 ]
173
174 return { onlyInA, onlyInB }
175}
176
177function range(start: number, end: number): Array<number> {
178 const out: Array<number> = []
179 for (let i = start; i < end; i++) out.push(i)
180 return out
181}
182
183/**
184 * Compares two keys (string | number) in a consistent, deterministic way.
185 * Handles mixed types by ordering strings before numbers.
186 */
187export function compareKeys(a: string | number, b: string | number): number {
188 // Same type: compare directly
189 if (typeof a === typeof b) {
190 if (typeof a === `number` && typeof b === `number`) {
191 const aIsNaN = Number.isNaN(a)
192 const bIsNaN = Number.isNaN(b)
193 if (aIsNaN || bIsNaN) {
194 if (aIsNaN && bIsNaN) return 0
195 return aIsNaN ? 1 : -1
196 }
197 }
198 if (a < b) return -1
199 if (a > b) return 1
200 return 0
201 }
202 // Different types: strings come before numbers
203 return typeof a === `string` ? -1 : 1
204}
205
206type CanonicalValue =
207 | readonly [`undefined`]
208 | readonly [`null`]
209 | readonly [`boolean`, boolean]
210 | readonly [`number`, number | `NaN` | `Infinity` | `-Infinity`]
211 | readonly [`bigint`, string]
212 | readonly [`string`, string]
213 | readonly [`date`, number | `Invalid`]
214 | readonly [`temporal`, string, string]
215 | readonly [`regexp`, string, string]
216 | readonly [`bytes`, Array<number>]
217 | readonly [`array`, Array<CanonicalValue>]
218 | readonly [`map`, Array<readonly [CanonicalValue, CanonicalValue]>]
219 | readonly [`set`, Array<CanonicalValue>]
220 | readonly [`object`, Array<readonly [string, CanonicalValue]>]
221
222/**
223 * Serializes a supported query value into one canonical key.
224 *
225 * JSON's native encoding is not suitable for relation keys: it merges BigInt
226 * with strings when a replacer is used, merges NaN with null, drops undefined,
227 * and depends on object insertion order. Ordinary JSON values keep their
228 * established wire form. Values that need richer types use a reserved prefix
229 * plus a structural, type-tagged encoding.
230 */
231export function serializeValue(value: unknown): string {
232 if (isJsonSafeStructuralValue(value, new Set())) {
233 return JSON.stringify(toStableJsonValue(value))
234 }
235
236 return `~${JSON.stringify(toCanonicalValue(value, new Set()))}`
237}
238
239type JsonValue =
240 | null
241 | boolean
242 | number
243 | string
244 | Array<JsonValue>
245 | { [key: string]: JsonValue }
246
247function isJsonSafeStructuralValue(
248 value: unknown,
249 ancestors: Set<object>,
250): boolean {
251 if (value === null) return true
252
253 switch (typeof value) {
254 case `boolean`:
255 case `string`:
256 return true
257 case `number`:
258 return Number.isFinite(value)
259 case `undefined`:
260 case `bigint`:
261 case `symbol`:
262 case `function`:
263 return false
264 }
265
266 return withAcyclicValue(value, ancestors, () => {
267 if (
268 value instanceof Date ||
269 value instanceof RegExp ||
270 value instanceof Uint8Array ||
271 isTemporal(value) ||
272 value instanceof Map ||
273 value instanceof Set
274 ) {
275 return false
276 }
277
278 return Array.isArray(value)
279 ? value.every((item) => isJsonSafeStructuralValue(item, ancestors))
280 : Object.keys(value).every((key) =>
281 isJsonSafeStructuralValue(
282 (value as Record<string, unknown>)[key],
283 ancestors,
284 ),
285 )
286 })
287}
288
289function toStableJsonValue(value: unknown): JsonValue {
290 if (
291 value === null ||
292 typeof value === `boolean` ||
293 typeof value === `number` ||
294 typeof value === `string`
295 ) {
296 return value
297 }
298
299 if (Array.isArray(value)) {
300 return value.map(toStableJsonValue)
301 }
302
303 return Object.fromEntries(
304 Object.keys(value as object)
305 .sort()
306 .map((key) => [
307 key,
308 toStableJsonValue((value as Record<string, unknown>)[key]),
309 ]),
310 )
311}
312
313function toCanonicalValue(
314 value: unknown,
315 ancestors: Set<object>,
316): CanonicalValue {
317 if (value === undefined) return [`undefined`]
318 if (value === null) return [`null`]
319
320 switch (typeof value) {
321 case `boolean`:
322 return [`boolean`, value]
323 case `number`:
324 if (Number.isNaN(value)) return [`number`, `NaN`]
325 if (value === Infinity) return [`number`, `Infinity`]
326 if (value === -Infinity) return [`number`, `-Infinity`]
327 return [`number`, value === 0 ? 0 : value]
328 case `bigint`:
329 return [`bigint`, value.toString()]
330 case `string`:
331 return [`string`, value]
332 case `symbol`:
333 case `function`:
334 throw new TypeError(
335 `Cannot serialize ${typeof value} as a structural relation key`,
336 )
337 }
338
339 return withAcyclicValue(value, ancestors, () => {
340 if (value instanceof Date) {
341 const timestamp = value.getTime()
342 return Number.isNaN(timestamp)
343 ? ([`date`, `Invalid`] as const)
344 : ([`date`, timestamp] as const)
345 }
346
347 if (value instanceof RegExp) {
348 return [`regexp`, value.source, value.flags]
349 }
350
351 if (value instanceof Uint8Array) {
352 return [`bytes`, Array.from(value)]
353 }
354
355 if (isTemporal(value)) {
356 return [`temporal`, value[Symbol.toStringTag], value.toString()]
357 }
358
359 if (Array.isArray(value)) {
360 return [`array`, value.map((item) => toCanonicalValue(item, ancestors))]
361 }
362
363 if (value instanceof Map) {
364 const entries = [...value.entries()].map(
365 ([key, entryValue]) =>
366 [
367 toCanonicalValue(key, ancestors),
368 toCanonicalValue(entryValue, ancestors),
369 ] as const,
370 )
371 entries.sort((left, right) =>
372 compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),
373 )
374 return [`map`, entries]
375 }
376
377 if (value instanceof Set) {
378 const entries = [...value].map((entry) =>
379 toCanonicalValue(entry, ancestors),
380 )
381 entries.sort((left, right) =>
382 compareSerializedValues(JSON.stringify(left), JSON.stringify(right)),
383 )
384 return [`set`, entries]
385 }
386
387 const entries = Object.keys(value)
388 .sort()
389 .map(
390 (key) =>
391 [
392 key,
393 toCanonicalValue(
394 (value as Record<string, unknown>)[key],
395 ancestors,
396 ),
397 ] as const,
398 )
399 return [`object`, entries]
400 })
401}
402
403function compareSerializedValues(left: string, right: string): number {
404 return left < right ? -1 : left > right ? 1 : 0
405}
406
407function withAcyclicValue<T>(
408 value: object,
409 ancestors: Set<object>,
410 encode: () => T,
411): T {
412 if (ancestors.has(value)) {
413 throw new TypeError(`Cannot serialize a cyclic structural relation key`)
414 }
415
416 ancestors.add(value)
417 try {
418 return encode()
419 } finally {
420 ancestors.delete(value)
421 }
422}