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