Open History to see the last commit
1import { IR } from '@tanstack/db'
2import type { LoadSubsetOptions } from '@tanstack/db'
3
4export type RemoteSubsetWirePrimitive =
5 undefined | null | boolean | string | number | bigint
6
7export type RemoteSubsetWireTypedArray =
8 | Int8Array
9 | Uint8Array
10 | Uint8ClampedArray
11 | Int16Array
12 | Uint16Array
13 | Int32Array
14 | Uint32Array
15 | Float32Array
16 | Float64Array
17 | BigInt64Array
18 | BigUint64Array
19
20export type RemoteSubsetWireRecord = {
21 [key: string]: RemoteSubsetWireValue
22}
23
24/** Values whose complete semantics survive a coordinator transport boundary. */
25export type RemoteSubsetWireValue =
26 | RemoteSubsetWirePrimitive
27 | Date
28 | RegExp
29 | ArrayBuffer
30 | DataView
31 | RemoteSubsetWireTypedArray
32 | Array<RemoteSubsetWireValue>
33 | Map<RemoteSubsetWireValue, RemoteSubsetWireValue>
34 | Set<RemoteSubsetWireValue>
35 | RemoteSubsetWireRecord
36
37export type RemoteSubsetWireExpression =
38 | { type: `ref`; path: Array<string>; sourceAlias?: string }
39 | { type: `val`; value: RemoteSubsetWireValue }
40 | {
41 type: `func`
42 name: string
43 args: Array<RemoteSubsetWireExpression>
44 }
45
46export type RemoteSubsetWireCompareOptions = {
47 direction: `asc` | `desc`
48 nulls: `first` | `last`
49} & (
50 | { stringSort?: `lexical` }
51 | {
52 stringSort?: `locale`
53 locale?: string
54 localeOptions?: RemoteSubsetWireRecord
55 }
56)
57
58export type RemoteSubsetWireOrderByClause = {
59 expression: RemoteSubsetWireExpression
60 compareOptions: RemoteSubsetWireCompareOptions
61}
62
63export type RemoteSubsetWireCursor = {
64 whereFrom: RemoteSubsetWireExpression
65 whereCurrent: RemoteSubsetWireExpression
66 lastKey?: string | number
67}
68
69/** The complete data portion transported by a remote-subset request. */
70export type TransportedLoadSubsetOptions = {
71 where?: RemoteSubsetWireExpression
72 orderBy?: Array<RemoteSubsetWireOrderByClause>
73 limit?: number
74 cursor?: RemoteSubsetWireCursor
75 offset?: number
76 refetch?: boolean
77}
78
79export class RemoteSubsetWireValueError extends TypeError {
80 override readonly name = `RemoteSubsetWireValueError`
81
82 constructor(
83 readonly path: string,
84 reason: string,
85 ) {
86 super(`Unsupported remote subset wire value at ${path}: ${reason}`)
87 }
88}
89
90type ProjectionState = {
91 validateOnly: boolean
92 expressions: WeakMap<object, RemoteSubsetWireExpression>
93 expressionArrays: WeakMap<object, Array<RemoteSubsetWireExpression>>
94 stringArrays: WeakMap<object, Array<string>>
95 orderByArrays: WeakMap<object, Array<RemoteSubsetWireOrderByClause>>
96 orderByClauses: WeakMap<object, RemoteSubsetWireOrderByClause>
97 compareOptions: WeakMap<object, RemoteSubsetWireCompareOptions>
98 cursors: WeakMap<object, RemoteSubsetWireCursor>
99 wireValues: WeakMap<object, RemoteSubsetWireValue>
100}
101
102type DataProperty = {
103 present: boolean
104 value?: unknown
105}
106
107type TypedArrayConstructor = {
108 readonly prototype: RemoteSubsetWireTypedArray
109 new (
110 buffer: ArrayBuffer,
111 byteOffset?: number,
112 length?: number,
113 ): RemoteSubsetWireTypedArray
114}
115
116const typedArrayConstructors: ReadonlyArray<TypedArrayConstructor> = [
117 Int8Array,
118 Uint8Array,
119 Uint8ClampedArray,
120 Int16Array,
121 Uint16Array,
122 Int32Array,
123 Uint32Array,
124 Float32Array,
125 Float64Array,
126 BigInt64Array,
127 BigUint64Array,
128]
129
130const NativeDate = Date
131const identifierPattern = /^[A-Za-z_$][A-Za-z0-9_$]*$/
132
133/**
134 * Projects one live subset request into the exact coordinator wire domain.
135 * Validation happens before callers choose a local-leader or transported path.
136 */
137export function toTransportedLoadSubsetOptions(
138 options: LoadSubsetOptions,
139): TransportedLoadSubsetOptions {
140 return visitLoadSubsetOptions(options, false)
141}
142
143/** Checks wire admission without constructing a detached request snapshot. */
144export function validateRemoteSubsetOptions(options: LoadSubsetOptions): void {
145 visitLoadSubsetOptions(options, true)
146}
147
148// Both modes run the same admission checks. Validation retains input nodes only
149// as cycle markers; it never writes to them or returns them to a caller.
150function visitLoadSubsetOptions(
151 options: LoadSubsetOptions,
152 validateOnly: boolean,
153): TransportedLoadSubsetOptions {
154 assertPlainContainer(options, `options`)
155 assertAllowedProperties(options, `options`, [
156 `where`,
157 `orderBy`,
158 `limit`,
159 `cursor`,
160 `offset`,
161 `refetch`,
162 `signal`,
163 `subscription`,
164 ])
165
166 const state: ProjectionState = {
167 validateOnly,
168 expressions: new WeakMap(),
169 expressionArrays: new WeakMap(),
170 stringArrays: new WeakMap(),
171 orderByArrays: new WeakMap(),
172 orderByClauses: new WeakMap(),
173 compareOptions: new WeakMap(),
174 cursors: new WeakMap(),
175 wireValues: new WeakMap(),
176 }
177 const projected: TransportedLoadSubsetOptions = validateOnly
178 ? (options as TransportedLoadSubsetOptions)
179 : {}
180 const where = readDataProperty(options, `where`, `options.where`)
181 const orderBy = readDataProperty(options, `orderBy`, `options.orderBy`)
182 const limit = readDataProperty(options, `limit`, `options.limit`)
183 const cursor = readDataProperty(options, `cursor`, `options.cursor`)
184 const offset = readDataProperty(options, `offset`, `options.offset`)
185 const refetch = readDataProperty(options, `refetch`, `options.refetch`)
186
187 if (where.present && where.value !== undefined) {
188 const result = projectExpression(where.value, `options.where`, state)
189 if (!state.validateOnly) projected.where = result
190 }
191 if (orderBy.present && orderBy.value !== undefined) {
192 const result = projectOrderBy(orderBy.value, `options.orderBy`, state)
193 if (!state.validateOnly) projected.orderBy = result
194 }
195 if (limit.present && limit.value !== undefined) {
196 const result = projectNumber(limit.value, `options.limit`)
197 if (!state.validateOnly) projected.limit = result
198 }
199 if (cursor.present && cursor.value !== undefined) {
200 const result = projectCursor(cursor.value, `options.cursor`, state)
201 if (!state.validateOnly) projected.cursor = result
202 }
203 if (offset.present && offset.value !== undefined) {
204 const result = projectNumber(offset.value, `options.offset`)
205 if (!state.validateOnly) projected.offset = result
206 }
207 if (refetch.present && refetch.value !== undefined) {
208 if (typeof refetch.value !== `boolean`) {
209 throw new RemoteSubsetWireValueError(
210 `options.refetch`,
211 `expected boolean`,
212 )
213 }
214 if (!state.validateOnly) projected.refetch = refetch.value
215 }
216
217 return projected
218}
219
220/** Adds live lifecycle references only to an already validated local request. */
221export function toProcessLocalLoadSubsetOptions(
222 options: LoadSubsetOptions,
223 transported = toTransportedLoadSubsetOptions(options),
224): TransportedLoadSubsetOptions &
225 Pick<LoadSubsetOptions, `signal` | `subscription`> {
226 const projected = {
227 ...transported,
228 } as TransportedLoadSubsetOptions &
229 Pick<LoadSubsetOptions, `signal` | `subscription`>
230 const signal = readDataProperty(options, `signal`, `options.signal`)
231 const subscription = readDataProperty(
232 options,
233 `subscription`,
234 `options.subscription`,
235 )
236
237 if (signal.present) {
238 projected.signal = signal.value as LoadSubsetOptions[`signal`]
239 }
240 if (subscription.present) {
241 projected.subscription =
242 subscription.value as LoadSubsetOptions[`subscription`]
243 }
244
245 return projected
246}
247
248function projectExpression(
249 value: unknown,
250 path: string,
251 state: ProjectionState,
252): RemoteSubsetWireExpression {
253 const object = requireObject(value, path)
254 const existing = state.expressions.get(object)
255 if (existing) return existing
256
257 const type = readDataProperty(object, `type`, `${path}.type`)
258 if (!type.present || typeof type.value !== `string`) {
259 throw new RemoteSubsetWireValueError(`${path}.type`, describe(type.value))
260 }
261
262 switch (type.value) {
263 case `ref`: {
264 assertExpressionPrototype(object, path, IR.PropRef.prototype)
265 assertAllowedProperties(object, path, [`type`, `path`, `sourceAlias`])
266 const projected: Extract<RemoteSubsetWireExpression, { type: `ref` }> =
267 state.validateOnly
268 ? (object as Extract<RemoteSubsetWireExpression, { type: `ref` }>)
269 : { type: `ref`, path: [] }
270 state.expressions.set(object, projected)
271 const sourcePath = readRequiredDataProperty(
272 object,
273 `path`,
274 `${path}.path`,
275 )
276 const result = projectStringArray(sourcePath, `${path}.path`, state)
277 if (!state.validateOnly) projected.path = result
278 const sourceAlias = readDataProperty(
279 object,
280 `sourceAlias`,
281 `${path}.sourceAlias`,
282 )
283 if (sourceAlias.present) {
284 if (
285 typeof sourceAlias.value !== `string` ||
286 result[0] !== sourceAlias.value
287 ) {
288 throw new RemoteSubsetWireValueError(
289 `${path}.sourceAlias`,
290 `source alias must match the first path segment`,
291 )
292 }
293 if (!state.validateOnly) projected.sourceAlias = sourceAlias.value
294 }
295 return projected
296 }
297 case `val`: {
298 assertExpressionPrototype(object, path, IR.Value.prototype)
299 assertAllowedProperties(object, path, [`type`, `value`])
300 const projected: Extract<RemoteSubsetWireExpression, { type: `val` }> =
301 state.validateOnly
302 ? (object as Extract<RemoteSubsetWireExpression, { type: `val` }>)
303 : { type: `val`, value: undefined }
304 state.expressions.set(object, projected)
305 const sourceValue = readRequiredDataProperty(
306 object,
307 `value`,
308 `${path}.value`,
309 )
310 const result = projectWireValue(sourceValue, `${path}.value`, state)
311 if (!state.validateOnly) projected.value = result
312 return projected
313 }
314 case `func`: {
315 assertExpressionPrototype(object, path, IR.Func.prototype)
316 assertAllowedProperties(object, path, [`type`, `name`, `args`])
317 const projected: Extract<RemoteSubsetWireExpression, { type: `func` }> =
318 state.validateOnly
319 ? (object as Extract<RemoteSubsetWireExpression, { type: `func` }>)
320 : { type: `func`, name: ``, args: [] }
321 state.expressions.set(object, projected)
322 const name = readRequiredDataProperty(object, `name`, `${path}.name`)
323 if (typeof name !== `string`) {
324 throw new RemoteSubsetWireValueError(`${path}.name`, describe(name))
325 }
326 if (!state.validateOnly) projected.name = name
327 const args = readRequiredDataProperty(object, `args`, `${path}.args`)
328 const result = projectExpressionArray(args, `${path}.args`, state)
329 if (!state.validateOnly) projected.args = result
330 return projected
331 }
332 default:
333 throw new RemoteSubsetWireValueError(`${path}.type`, String(type.value))
334 }
335}
336
337function projectExpressionArray(
338 value: unknown,
339 path: string,
340 state: ProjectionState,
341): Array<RemoteSubsetWireExpression> {
342 const array = requireArray(value, path)
343 const existing = state.expressionArrays.get(array)
344 if (existing) return existing
345 assertArrayShape(array, path)
346 const projected = state.validateOnly
347 ? (array as Array<RemoteSubsetWireExpression>)
348 : new Array<RemoteSubsetWireExpression>(array.length)
349 state.expressionArrays.set(array, projected)
350 for (let index = 0; index < array.length; index++) {
351 if (!(index in array)) {
352 throw new RemoteSubsetWireValueError(
353 `${path}[${index}]`,
354 `missing expression`,
355 )
356 }
357 const result = projectExpression(array[index], `${path}[${index}]`, state)
358 if (!state.validateOnly) projected[index] = result
359 }
360 return projected
361}
362
363function projectStringArray(
364 value: unknown,
365 path: string,
366 state: ProjectionState,
367): Array<string> {
368 const array = requireArray(value, path)
369 const existing = state.stringArrays.get(array)
370 if (existing) return existing
371 assertArrayShape(array, path)
372 const projected = state.validateOnly
373 ? (array as Array<string>)
374 : new Array<string>(array.length)
375 state.stringArrays.set(array, projected)
376 for (let index = 0; index < array.length; index++) {
377 const entry = array[index]
378 if (!(index in array) || typeof entry !== `string`) {
379 throw new RemoteSubsetWireValueError(`${path}[${index}]`, describe(entry))
380 }
381 if (!state.validateOnly) projected[index] = entry
382 }
383 return projected
384}
385
386function projectOrderBy(
387 value: unknown,
388 path: string,
389 state: ProjectionState,
390): Array<RemoteSubsetWireOrderByClause> {
391 const array = requireArray(value, path)
392 const existing = state.orderByArrays.get(array)
393 if (existing) return existing
394 assertArrayShape(array, path)
395 const projected = state.validateOnly
396 ? (array as Array<RemoteSubsetWireOrderByClause>)
397 : new Array<RemoteSubsetWireOrderByClause>(array.length)
398 state.orderByArrays.set(array, projected)
399
400 for (let index = 0; index < array.length; index++) {
401 const clausePath = `${path}[${index}]`
402 const clause = requirePlainRecord(array[index], clausePath)
403 const existingClause = state.orderByClauses.get(clause)
404 if (existingClause) {
405 if (!state.validateOnly) projected[index] = existingClause
406 continue
407 }
408 assertAllowedProperties(clause, clausePath, [
409 `expression`,
410 `compareOptions`,
411 ])
412 const projectedClause = state.validateOnly
413 ? (clause as RemoteSubsetWireOrderByClause)
414 : {
415 expression: undefined as unknown as RemoteSubsetWireExpression,
416 compareOptions:
417 undefined as unknown as RemoteSubsetWireCompareOptions,
418 }
419 if (!state.validateOnly) projected[index] = projectedClause
420 state.orderByClauses.set(clause, projectedClause)
421 const expression = projectExpression(
422 readRequiredDataProperty(
423 clause,
424 `expression`,
425 `${clausePath}.expression`,
426 ),
427 `${clausePath}.expression`,
428 state,
429 )
430 const compareOptions = projectCompareOptions(
431 readRequiredDataProperty(
432 clause,
433 `compareOptions`,
434 `${clausePath}.compareOptions`,
435 ),
436 `${clausePath}.compareOptions`,
437 state,
438 )
439 if (!state.validateOnly) {
440 projectedClause.expression = expression
441 projectedClause.compareOptions = compareOptions
442 }
443 }
444 return projected
445}
446
447function projectCompareOptions(
448 value: unknown,
449 path: string,
450 state: ProjectionState,
451): RemoteSubsetWireCompareOptions {
452 const source = requirePlainRecord(value, path)
453 const existing = state.compareOptions.get(source)
454 if (existing) return existing
455 assertAllowedProperties(source, path, [
456 `direction`,
457 `nulls`,
458 `stringSort`,
459 `locale`,
460 `localeOptions`,
461 ])
462 const projected: {
463 direction?: `asc` | `desc`
464 nulls?: `first` | `last`
465 stringSort?: `lexical` | `locale`
466 locale?: string
467 localeOptions?: RemoteSubsetWireRecord
468 } = state.validateOnly ? source : {}
469
470 const direction = readRequiredDataProperty(
471 source,
472 `direction`,
473 `${path}.direction`,
474 )
475 if (direction !== `asc` && direction !== `desc`) {
476 throw new RemoteSubsetWireValueError(
477 `${path}.direction`,
478 describe(direction),
479 )
480 }
481 if (!state.validateOnly) projected.direction = direction
482
483 const nulls = readRequiredDataProperty(source, `nulls`, `${path}.nulls`)
484 if (nulls !== `first` && nulls !== `last`) {
485 throw new RemoteSubsetWireValueError(`${path}.nulls`, describe(nulls))
486 }
487 if (!state.validateOnly) projected.nulls = nulls
488
489 const stringSort = readDataProperty(
490 source,
491 `stringSort`,
492 `${path}.stringSort`,
493 )
494 if (stringSort.present && stringSort.value !== undefined) {
495 if (stringSort.value !== `lexical` && stringSort.value !== `locale`) {
496 throw new RemoteSubsetWireValueError(
497 `${path}.stringSort`,
498 describe(stringSort.value),
499 )
500 }
501 if (!state.validateOnly) projected.stringSort = stringSort.value
502 }
503 if (projected.stringSort !== `lexical`) {
504 const locale = readDataProperty(source, `locale`, `${path}.locale`)
505 if (locale.present && locale.value !== undefined) {
506 if (typeof locale.value !== `string`) {
507 throw new RemoteSubsetWireValueError(
508 `${path}.locale`,
509 describe(locale.value),
510 )
511 }
512 if (!state.validateOnly) projected.locale = locale.value
513 }
514 const localeOptions = readDataProperty(
515 source,
516 `localeOptions`,
517 `${path}.localeOptions`,
518 )
519 if (localeOptions.present && localeOptions.value !== undefined) {
520 const result = projectWireRecord(
521 localeOptions.value,
522 `${path}.localeOptions`,
523 state,
524 )
525 if (!state.validateOnly) projected.localeOptions = result
526 }
527 }
528 const result = projected as RemoteSubsetWireCompareOptions
529 state.compareOptions.set(source, result)
530 return result
531}
532
533function projectCursor(
534 value: unknown,
535 path: string,
536 state: ProjectionState,
537): RemoteSubsetWireCursor {
538 const source = requirePlainRecord(value, path)
539 const existing = state.cursors.get(source)
540 if (existing) return existing
541 assertAllowedProperties(source, path, [
542 `whereFrom`,
543 `whereCurrent`,
544 `lastKey`,
545 ])
546 const projected: RemoteSubsetWireCursor = state.validateOnly
547 ? (source as RemoteSubsetWireCursor)
548 : {
549 whereFrom: undefined as unknown as RemoteSubsetWireExpression,
550 whereCurrent: undefined as unknown as RemoteSubsetWireExpression,
551 }
552 state.cursors.set(source, projected)
553 const whereFrom = projectExpression(
554 readRequiredDataProperty(source, `whereFrom`, `${path}.whereFrom`),
555 `${path}.whereFrom`,
556 state,
557 )
558 const whereCurrent = projectExpression(
559 readRequiredDataProperty(source, `whereCurrent`, `${path}.whereCurrent`),
560 `${path}.whereCurrent`,
561 state,
562 )
563 if (!state.validateOnly) {
564 projected.whereFrom = whereFrom
565 projected.whereCurrent = whereCurrent
566 }
567 const lastKey = readDataProperty(source, `lastKey`, `${path}.lastKey`)
568 if (lastKey.present && lastKey.value !== undefined) {
569 if (
570 typeof lastKey.value !== `string` &&
571 typeof lastKey.value !== `number`
572 ) {
573 throw new RemoteSubsetWireValueError(
574 `${path}.lastKey`,
575 describe(lastKey.value),
576 )
577 }
578 if (!state.validateOnly) projected.lastKey = lastKey.value
579 }
580 return projected
581}
582
583function projectWireValue(
584 value: unknown,
585 path: string,
586 state: ProjectionState,
587): RemoteSubsetWireValue {
588 if (
589 value === undefined ||
590 value === null ||
591 typeof value === `boolean` ||
592 typeof value === `string` ||
593 typeof value === `number` ||
594 typeof value === `bigint`
595 ) {
596 return value
597 }
598 if (typeof value !== `object`) {
599 throw new RemoteSubsetWireValueError(path, describe(value))
600 }
601
602 const existing = state.wireValues.get(value)
603 if (existing) return existing
604
605 if (
606 typeof SharedArrayBuffer !== `undefined` &&
607 value instanceof SharedArrayBuffer
608 ) {
609 throw new RemoteSubsetWireValueError(path, `SharedArrayBuffer`)
610 }
611 if (value instanceof NativeDate) {
612 assertExactPrototype(value, NativeDate.prototype, path)
613 assertNoOwnProperties(value, path)
614 const time = value.getTime()
615 const projected = state.validateOnly ? value : new NativeDate(time)
616 state.wireValues.set(value, projected)
617 return projected
618 }
619 if (value instanceof RegExp) {
620 assertExactPrototype(value, RegExp.prototype, path)
621 assertRegExpShape(value, path)
622 const { source, flags } = value
623 const projected = state.validateOnly ? value : new RegExp(source, flags)
624 state.wireValues.set(value, projected)
625 return projected
626 }
627 if (value instanceof ArrayBuffer) {
628 assertExactPrototype(value, ArrayBuffer.prototype, path)
629 assertNoOwnProperties(value, path)
630 assertFixedArrayBuffer(value, path)
631 let projected: ArrayBuffer
632 try {
633 if (state.validateOnly) {
634 // A zero-length view checks detachment without copying the backing bytes.
635 new Uint8Array(value, 0, 0)
636 projected = value
637 } else {
638 projected = value.slice(0)
639 }
640 } catch {
641 throw new RemoteSubsetWireValueError(path, `detached ArrayBuffer`)
642 }
643 state.wireValues.set(value, projected)
644 return projected
645 }
646 if (value instanceof DataView) {
647 assertExactPrototype(value, DataView.prototype, path)
648 assertNoOwnProperties(value, path)
649 let byteOffset: number
650 let byteLength: number
651 let buffer: ArrayBufferLike
652 try {
653 byteOffset = value.byteOffset
654 byteLength = value.byteLength
655 buffer = value.buffer
656 } catch {
657 throw new RemoteSubsetWireValueError(path, `detached DataView`)
658 }
659 const projectedBuffer = projectWireValue(buffer, path, state)
660 if (!(projectedBuffer instanceof ArrayBuffer)) {
661 throw new RemoteSubsetWireValueError(path, `shared DataView buffer`)
662 }
663 const projected = state.validateOnly
664 ? value
665 : new DataView(projectedBuffer, byteOffset, byteLength)
666 state.wireValues.set(value, projected)
667 return projected
668 }
669
670 const typedArrayConstructor = getTypedArrayConstructor(value)
671 if (typedArrayConstructor) {
672 const typedArray = value as RemoteSubsetWireTypedArray
673 assertTypedArrayShape(typedArray, path)
674 let byteOffset: number
675 let length: number
676 let buffer: ArrayBufferLike
677 try {
678 byteOffset = typedArray.byteOffset
679 length = typedArray.length
680 buffer = typedArray.buffer
681 } catch {
682 throw new RemoteSubsetWireValueError(path, `detached typed array`)
683 }
684 if (!(buffer instanceof ArrayBuffer)) {
685 throw new RemoteSubsetWireValueError(path, `shared typed-array buffer`)
686 }
687 const projectedBuffer = projectWireValue(buffer, path, state)
688 if (!(projectedBuffer instanceof ArrayBuffer)) {
689 throw new RemoteSubsetWireValueError(path, `shared typed-array buffer`)
690 }
691 let projected: RemoteSubsetWireTypedArray
692 try {
693 projected = state.validateOnly
694 ? typedArray
695 : new typedArrayConstructor(projectedBuffer, byteOffset, length)
696 } catch {
697 throw new RemoteSubsetWireValueError(path, `detached typed array`)
698 }
699 state.wireValues.set(value, projected)
700 return projected
701 }
702 if (ArrayBuffer.isView(value)) {
703 throw new RemoteSubsetWireValueError(path, describe(value))
704 }
705 if (Array.isArray(value)) return projectWireArray(value, path, state)
706 if (value instanceof Map) return projectWireMap(value, path, state)
707 if (value instanceof Set) return projectWireSet(value, path, state)
708 return projectWireRecord(value, path, state)
709}
710
711function projectWireArray(
712 value: Array<unknown>,
713 path: string,
714 state: ProjectionState,
715): Array<RemoteSubsetWireValue> {
716 assertArrayShape(value, path)
717 const projected = state.validateOnly
718 ? (value as Array<RemoteSubsetWireValue>)
719 : new Array<RemoteSubsetWireValue>(value.length)
720 state.wireValues.set(value, projected)
721 for (let index = 0; index < value.length; index++) {
722 if (index in value) {
723 const result = projectWireValue(value[index], `${path}[${index}]`, state)
724 if (!state.validateOnly) projected[index] = result
725 }
726 }
727 return projected
728}
729
730function projectWireMap(
731 value: Map<unknown, unknown>,
732 path: string,
733 state: ProjectionState,
734): Map<RemoteSubsetWireValue, RemoteSubsetWireValue> {
735 assertExactPrototype(value, Map.prototype, path)
736 assertNoOwnProperties(value, path)
737 const projected = state.validateOnly
738 ? (value as Map<RemoteSubsetWireValue, RemoteSubsetWireValue>)
739 : new Map<RemoteSubsetWireValue, RemoteSubsetWireValue>()
740 state.wireValues.set(value, projected)
741 let index = 0
742 for (const [key, entry] of value) {
743 const projectedKey = projectWireValue(
744 key,
745 `${path}.entries[${index}].key`,
746 state,
747 )
748 const projectedValue = projectWireValue(
749 entry,
750 `${path}.entries[${index}].value`,
751 state,
752 )
753 if (!state.validateOnly) projected.set(projectedKey, projectedValue)
754 index++
755 }
756 return projected
757}
758
759function projectWireSet(
760 value: Set<unknown>,
761 path: string,
762 state: ProjectionState,
763): Set<RemoteSubsetWireValue> {
764 assertExactPrototype(value, Set.prototype, path)
765 assertNoOwnProperties(value, path)
766 const projected = state.validateOnly
767 ? (value as Set<RemoteSubsetWireValue>)
768 : new Set<RemoteSubsetWireValue>()
769 state.wireValues.set(value, projected)
770 let index = 0
771 for (const entry of value) {
772 const result = projectWireValue(entry, `${path}.values[${index}]`, state)
773 if (!state.validateOnly) projected.add(result)
774 index++
775 }
776 return projected
777}
778
779function projectWireRecord(
780 value: unknown,
781 path: string,
782 state: ProjectionState,
783): RemoteSubsetWireRecord {
784 const source = requirePlainRecord(value, path)
785 const existing = state.wireValues.get(source)
786 if (existing) return existing as RemoteSubsetWireRecord
787 const projected: RemoteSubsetWireRecord = state.validateOnly
788 ? (source as RemoteSubsetWireRecord)
789 : {}
790 state.wireValues.set(source, projected)
791
792 for (const key of ownKeys(source, path)) {
793 const childPath = propertyPath(path, key)
794 if (typeof key === `symbol`) {
795 throw new RemoteSubsetWireValueError(childPath, `symbol property key`)
796 }
797 const descriptor = Object.getOwnPropertyDescriptor(source, key)
798 if (!descriptor || !descriptor.enumerable || !(`value` in descriptor)) {
799 throw new RemoteSubsetWireValueError(childPath, `non-data property`)
800 }
801 const result = projectWireValue(descriptor.value, childPath, state)
802 if (!state.validateOnly) {
803 Object.defineProperty(projected, key, {
804 value: result,
805 enumerable: true,
806 writable: true,
807 configurable: true,
808 })
809 }
810 }
811 return projected
812}
813
814function projectNumber(value: unknown, path: string): number {
815 if (typeof value !== `number` || !Number.isSafeInteger(value) || value < 0) {
816 throw new RemoteSubsetWireValueError(path, `non-negative safe integer`)
817 }
818 return value
819}
820
821function readRequiredDataProperty(
822 value: object,
823 key: string,
824 path: string,
825): unknown {
826 const property = readDataProperty(value, key, path)
827 if (!property.present) {
828 throw new RemoteSubsetWireValueError(path, `missing property`)
829 }
830 return property.value
831}
832
833function readDataProperty(
834 value: object,
835 key: string,
836 path: string,
837): DataProperty {
838 let descriptor: PropertyDescriptor | undefined
839 try {
840 descriptor = Object.getOwnPropertyDescriptor(value, key)
841 } catch {
842 throw new RemoteSubsetWireValueError(path, `unreadable property`)
843 }
844 if (!descriptor) return { present: false }
845 if (!descriptor.enumerable || !(`value` in descriptor)) {
846 throw new RemoteSubsetWireValueError(path, `non-data property`)
847 }
848 return { present: true, value: descriptor.value }
849}
850
851function assertAllowedProperties(
852 value: object,
853 path: string,
854 allowed: ReadonlyArray<string>,
855): void {
856 const allowedSet = new Set(allowed)
857 for (const key of ownKeys(value, path)) {
858 if (typeof key === `symbol` || !allowedSet.has(key)) {
859 throw new RemoteSubsetWireValueError(propertyPath(path, key), `property`)
860 }
861 readDataProperty(value, key, propertyPath(path, key))
862 }
863}
864
865function assertPlainContainer(value: object, path: string): void {
866 assertExactPrototype(value, Object.prototype, path)
867}
868
869function assertExpressionPrototype(
870 value: object,
871 path: string,
872 expressionPrototype: object,
873): void {
874 let prototype: object | null
875 try {
876 prototype = Object.getPrototypeOf(value)
877 } catch {
878 throw new RemoteSubsetWireValueError(path, `unreadable prototype`)
879 }
880 if (prototype !== Object.prototype && prototype !== expressionPrototype) {
881 throw new RemoteSubsetWireValueError(path, describe(value))
882 }
883}
884
885function assertExactPrototype(
886 value: object,
887 expected: object,
888 path: string,
889): void {
890 let prototype: object | null
891 try {
892 prototype = Object.getPrototypeOf(value)
893 } catch {
894 throw new RemoteSubsetWireValueError(path, `unreadable prototype`)
895 }
896 if (prototype !== expected) {
897 throw new RemoteSubsetWireValueError(path, describe(value))
898 }
899}
900
901function assertNoOwnProperties(value: object, path: string): void {
902 const keys = ownKeys(value, path)
903 if (keys.length > 0) {
904 throw new RemoteSubsetWireValueError(
905 propertyPath(path, keys[0]!),
906 `property`,
907 )
908 }
909}
910
911function assertFixedArrayBuffer(value: ArrayBuffer, path: string): void {
912 if ((value as ArrayBuffer & { readonly resizable?: boolean }).resizable) {
913 throw new RemoteSubsetWireValueError(path, `resizable ArrayBuffer`)
914 }
915}
916
917function assertRegExpShape(value: RegExp, path: string): void {
918 const keys = ownKeys(value, path)
919 for (const key of keys) {
920 if (key !== `lastIndex`) {
921 throw new RemoteSubsetWireValueError(propertyPath(path, key), `property`)
922 }
923 }
924 const descriptor = Object.getOwnPropertyDescriptor(value, `lastIndex`)
925 if (!descriptor || !(`value` in descriptor) || descriptor.value !== 0) {
926 throw new RemoteSubsetWireValueError(
927 `${path}.lastIndex`,
928 `RegExp lastIndex must be 0`,
929 )
930 }
931}
932
933function assertTypedArrayShape(
934 value: RemoteSubsetWireTypedArray,
935 path: string,
936): void {
937 const keys = ownKeys(value, path)
938 for (const key of keys) {
939 if (typeof key !== `string` || !isCanonicalArrayIndex(key, value.length)) {
940 throw new RemoteSubsetWireValueError(propertyPath(path, key), `property`)
941 }
942 }
943}
944
945function assertArrayShape(value: Array<unknown>, path: string): void {
946 assertExactPrototype(value, Array.prototype, path)
947 const keys = ownKeys(value, path)
948 for (const key of keys) {
949 if (
950 key !== `length` &&
951 (typeof key !== `string` || !isCanonicalArrayIndex(key, value.length))
952 ) {
953 throw new RemoteSubsetWireValueError(propertyPath(path, key), `property`)
954 }
955 if (key !== `length`) {
956 readDataProperty(value, key, propertyPath(path, key))
957 }
958 }
959}
960
961function isCanonicalArrayIndex(key: string, length: number): boolean {
962 if (!/^(0|[1-9][0-9]*)$/.test(key)) return false
963 const index = Number(key)
964 return Number.isSafeInteger(index) && index >= 0 && index < length
965}
966
967function getTypedArrayConstructor(
968 value: object,
969): TypedArrayConstructor | undefined {
970 let prototype: object | null
971 try {
972 prototype = Object.getPrototypeOf(value)
973 } catch {
974 return undefined
975 }
976 return typedArrayConstructors.find(
977 (constructor) => prototype === constructor.prototype,
978 )
979}
980
981function requireArray(value: unknown, path: string): Array<unknown> {
982 if (!Array.isArray(value)) {
983 throw new RemoteSubsetWireValueError(path, describe(value))
984 }
985 return value
986}
987
988function requireObject(value: unknown, path: string): object {
989 if (value === null || typeof value !== `object`) {
990 throw new RemoteSubsetWireValueError(path, describe(value))
991 }
992 return value
993}
994
995function requirePlainRecord(
996 value: unknown,
997 path: string,
998): Record<string, unknown> {
999 const object = requireObject(value, path)
1000 assertExactPrototype(object, Object.prototype, path)
1001 return object as Record<string, unknown>
1002}
1003
1004function ownKeys(value: object, path: string): Array<string | symbol> {
1005 try {
1006 return Reflect.ownKeys(value)
1007 } catch {
1008 throw new RemoteSubsetWireValueError(path, `unreadable properties`)
1009 }
1010}
1011
1012function propertyPath(path: string, key: string | symbol): string {
1013 if (typeof key === `symbol`) return `${path}[${String(key)}]`
1014 return identifierPattern.test(key)
1015 ? `${path}.${key}`
1016 : `${path}[${JSON.stringify(key)}]`
1017}
1018
1019function describe(value: unknown): string {
1020 if (value === null) return `null`
1021 if (typeof value !== `object`) return typeof value
1022 return `object`
1023}