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

remote-subset-wire.ts

941 lines27.3 KB

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