Skip to content
Source
Sign inSign up
TanStack/db
Open History to see the last commit

utils.ts

362 lines9.4 KB

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