capnweb 0.0.0-e3fa093 → 0.0.0-ee7ca6f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,3084 @@
1
+ //#region src/symbols.ts
2
+ let WORKERS_MODULE_SYMBOL = Symbol("workers-module");
3
+
4
+ //#endregion
5
+ //#region src/core.ts
6
+ if (!Symbol.dispose) Symbol.dispose = Symbol.for("dispose");
7
+ if (!Symbol.asyncDispose) Symbol.asyncDispose = Symbol.for("asyncDispose");
8
+ if (!Promise.withResolvers) Promise.withResolvers = function() {
9
+ let resolve;
10
+ let reject;
11
+ return {
12
+ promise: new Promise((res, rej) => {
13
+ resolve = res;
14
+ reject = rej;
15
+ }),
16
+ resolve,
17
+ reject
18
+ };
19
+ };
20
+ let workersModule = globalThis[WORKERS_MODULE_SYMBOL];
21
+ let RpcTarget$1 = workersModule ? workersModule.RpcTarget : class {};
22
+ const AsyncFunction = (async function() {}).constructor;
23
+ let BUFFER_PROTOTYPE = typeof Buffer !== "undefined" ? Buffer.prototype : void 0;
24
+ function typeForRpc(value) {
25
+ switch (typeof value) {
26
+ case "boolean":
27
+ case "number":
28
+ case "string": return "primitive";
29
+ case "undefined": return "undefined";
30
+ case "object":
31
+ case "function": break;
32
+ case "bigint": return "bigint";
33
+ default: return "unsupported";
34
+ }
35
+ if (value === null) return "primitive";
36
+ let prototype = Object.getPrototypeOf(value);
37
+ switch (prototype) {
38
+ case Object.prototype: return "object";
39
+ case Function.prototype:
40
+ case AsyncFunction.prototype: return "function";
41
+ case Array.prototype: return "array";
42
+ case Date.prototype: return "date";
43
+ case Uint8Array.prototype:
44
+ case BUFFER_PROTOTYPE: return "bytes";
45
+ case WritableStream.prototype: return "writable";
46
+ case ReadableStream.prototype: return "readable";
47
+ case Headers.prototype: return "headers";
48
+ case Request.prototype: return "request";
49
+ case Response.prototype: return "response";
50
+ case Blob.prototype: return "blob";
51
+ case RpcStub$1.prototype: return "stub";
52
+ case RpcPromise$1.prototype: return "rpc-promise";
53
+ default:
54
+ if (workersModule) {
55
+ if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub) return "rpc-target";
56
+ else if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype) return "rpc-thenable";
57
+ }
58
+ if (value instanceof RpcTarget$1) return "rpc-target";
59
+ if (value instanceof Error) return "error";
60
+ return "unsupported";
61
+ }
62
+ }
63
+ function mapNotLoaded() {
64
+ throw new Error("RPC map() implementation was not loaded.");
65
+ }
66
+ let mapImpl = {
67
+ applyMap: mapNotLoaded,
68
+ sendMap: mapNotLoaded
69
+ };
70
+ function streamNotLoaded() {
71
+ throw new Error("Stream implementation was not loaded.");
72
+ }
73
+ let streamImpl = {
74
+ createWritableStreamHook: streamNotLoaded,
75
+ createWritableStreamFromHook: streamNotLoaded,
76
+ createReadableStreamHook: streamNotLoaded
77
+ };
78
+ var StubHook = class {
79
+ stream(path, args) {
80
+ let pulled = this.call(path, args).pull();
81
+ let promise;
82
+ if (pulled instanceof Promise) promise = pulled.then((p) => {
83
+ p.dispose();
84
+ });
85
+ else {
86
+ pulled.dispose();
87
+ promise = Promise.resolve();
88
+ }
89
+ return { promise };
90
+ }
91
+ };
92
+ var ErrorStubHook = class extends StubHook {
93
+ error;
94
+ constructor(error) {
95
+ super();
96
+ this.error = error;
97
+ }
98
+ call(path, args) {
99
+ return this;
100
+ }
101
+ map(path, captures, instructions) {
102
+ return this;
103
+ }
104
+ get(path) {
105
+ return this;
106
+ }
107
+ dup() {
108
+ return this;
109
+ }
110
+ pull() {
111
+ return Promise.reject(this.error);
112
+ }
113
+ ignoreUnhandledRejections() {}
114
+ dispose() {}
115
+ onBroken(callback) {
116
+ try {
117
+ callback(this.error);
118
+ } catch (err) {
119
+ Promise.resolve(err);
120
+ }
121
+ }
122
+ };
123
+ const DISPOSED_HOOK = new ErrorStubHook(/* @__PURE__ */ new Error("Attempted to use RPC stub after it has been disposed."));
124
+ let doCall = (hook, path, params) => {
125
+ return hook.call(path, params);
126
+ };
127
+ function withCallInterceptor(interceptor, callback) {
128
+ let oldValue = doCall;
129
+ doCall = interceptor;
130
+ try {
131
+ return callback();
132
+ } finally {
133
+ doCall = oldValue;
134
+ }
135
+ }
136
+ let RAW_STUB = Symbol("realStub");
137
+ const PROXY_HANDLERS = {
138
+ apply(target, thisArg, argumentsList) {
139
+ let stub = target.raw;
140
+ return new RpcPromise$1(doCall(stub.hook, stub.pathIfPromise || [], RpcPayload.fromAppParams(argumentsList)), []);
141
+ },
142
+ get(target, prop, receiver) {
143
+ let stub = target.raw;
144
+ if (prop === RAW_STUB) return stub;
145
+ else if (prop in RpcPromise$1.prototype) return stub[prop];
146
+ else if (typeof prop === "string") return new RpcPromise$1(stub.hook, stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]);
147
+ else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return () => {
148
+ stub.hook.dispose();
149
+ stub.hook = DISPOSED_HOOK;
150
+ };
151
+ else return;
152
+ },
153
+ has(target, prop) {
154
+ let stub = target.raw;
155
+ if (prop === RAW_STUB) return true;
156
+ else if (prop in RpcPromise$1.prototype) return prop in stub;
157
+ else if (typeof prop === "string") return true;
158
+ else if (prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0)) return true;
159
+ else return false;
160
+ },
161
+ construct(target, args) {
162
+ throw new Error("An RPC stub cannot be used as a constructor.");
163
+ },
164
+ defineProperty(target, property, attributes) {
165
+ throw new Error("Can't define properties on RPC stubs.");
166
+ },
167
+ deleteProperty(target, p) {
168
+ throw new Error("Can't delete properties on RPC stubs.");
169
+ },
170
+ getOwnPropertyDescriptor(target, p) {},
171
+ getPrototypeOf(target) {
172
+ return Object.getPrototypeOf(target.raw);
173
+ },
174
+ isExtensible(target) {
175
+ return false;
176
+ },
177
+ ownKeys(target) {
178
+ return [];
179
+ },
180
+ preventExtensions(target) {
181
+ return true;
182
+ },
183
+ set(target, p, newValue, receiver) {
184
+ throw new Error("Can't assign properties on RPC stubs.");
185
+ },
186
+ setPrototypeOf(target, v) {
187
+ throw new Error("Can't override prototype of RPC stubs.");
188
+ }
189
+ };
190
+ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
191
+ constructor(hook, pathIfPromise) {
192
+ super();
193
+ if (!(hook instanceof StubHook)) {
194
+ let value = hook;
195
+ if (value instanceof RpcTarget$1 || value instanceof Function) hook = TargetStubHook.create(value, void 0);
196
+ else hook = new PayloadStubHook(RpcPayload.fromAppReturn(value));
197
+ if (pathIfPromise) throw new TypeError("RpcStub constructor expected one argument, received two.");
198
+ }
199
+ this.hook = hook;
200
+ this.pathIfPromise = pathIfPromise;
201
+ let func = () => {};
202
+ func.raw = this;
203
+ return new Proxy(func, PROXY_HANDLERS);
204
+ }
205
+ hook;
206
+ pathIfPromise;
207
+ dup() {
208
+ let target = this[RAW_STUB];
209
+ if (target.pathIfPromise) return new RpcStub$1(target.hook.get(target.pathIfPromise));
210
+ else return new RpcStub$1(target.hook.dup());
211
+ }
212
+ onRpcBroken(callback) {
213
+ this[RAW_STUB].hook.onBroken(callback);
214
+ }
215
+ map(func) {
216
+ let { hook, pathIfPromise } = this[RAW_STUB];
217
+ return mapImpl.sendMap(hook, pathIfPromise || [], func);
218
+ }
219
+ toString() {
220
+ return "[object RpcStub]";
221
+ }
222
+ };
223
+ var RpcPromise$1 = class extends RpcStub$1 {
224
+ constructor(hook, pathIfPromise) {
225
+ super(hook, pathIfPromise);
226
+ }
227
+ then(onfulfilled, onrejected) {
228
+ return pullPromise(this).then(...arguments);
229
+ }
230
+ catch(onrejected) {
231
+ return pullPromise(this).catch(...arguments);
232
+ }
233
+ finally(onfinally) {
234
+ return pullPromise(this).finally(...arguments);
235
+ }
236
+ toString() {
237
+ return "[object RpcPromise]";
238
+ }
239
+ };
240
+ function unwrapStubTakingOwnership(stub) {
241
+ let { hook, pathIfPromise } = stub[RAW_STUB];
242
+ if (pathIfPromise && pathIfPromise.length > 0) return hook.get(pathIfPromise);
243
+ else return hook;
244
+ }
245
+ function unwrapStubAndDup(stub) {
246
+ let { hook, pathIfPromise } = stub[RAW_STUB];
247
+ if (pathIfPromise) return hook.get(pathIfPromise);
248
+ else return hook.dup();
249
+ }
250
+ function unwrapStubNoProperties(stub) {
251
+ let { hook, pathIfPromise } = stub[RAW_STUB];
252
+ if (pathIfPromise && pathIfPromise.length > 0) return;
253
+ return hook;
254
+ }
255
+ function unwrapStubOrParent(stub) {
256
+ return stub[RAW_STUB].hook;
257
+ }
258
+ function unwrapStubAndPath(stub) {
259
+ return stub[RAW_STUB];
260
+ }
261
+ async function pullPromise(promise) {
262
+ let { hook, pathIfPromise } = promise[RAW_STUB];
263
+ if (pathIfPromise.length > 0) hook = hook.get(pathIfPromise);
264
+ return (await hook.pull()).deliverResolve();
265
+ }
266
+ var RpcPayload = class RpcPayload {
267
+ value;
268
+ source;
269
+ hooks;
270
+ promises;
271
+ static fromAppParams(value) {
272
+ return new RpcPayload(value, "params");
273
+ }
274
+ static fromAppReturn(value) {
275
+ return new RpcPayload(value, "return");
276
+ }
277
+ static fromArray(array) {
278
+ let hooks = [];
279
+ let promises = [];
280
+ let resultArray = [];
281
+ for (let payload of array) {
282
+ payload.ensureDeepCopied();
283
+ for (let hook of payload.hooks) hooks.push(hook);
284
+ for (let promise of payload.promises) {
285
+ if (promise.parent === payload) promise = {
286
+ parent: resultArray,
287
+ property: resultArray.length,
288
+ promise: promise.promise
289
+ };
290
+ promises.push(promise);
291
+ }
292
+ resultArray.push(payload.value);
293
+ }
294
+ return new RpcPayload(resultArray, "owned", hooks, promises);
295
+ }
296
+ static forEvaluate(hooks, promises) {
297
+ return new RpcPayload(null, "owned", hooks, promises);
298
+ }
299
+ static deepCopyFrom(value, oldParent, owner) {
300
+ let result = new RpcPayload(null, "owned", [], []);
301
+ result.value = result.deepCopy(value, oldParent, "value", result, true, owner);
302
+ return result;
303
+ }
304
+ constructor(value, source, hooks, promises) {
305
+ this.value = value;
306
+ this.source = source;
307
+ this.hooks = hooks;
308
+ this.promises = promises;
309
+ }
310
+ rpcTargets;
311
+ getHookForRpcTarget(target, parent, dupStubs = true) {
312
+ if (this.source === "params") {
313
+ if (dupStubs) {
314
+ let dupable = target;
315
+ if (typeof dupable.dup === "function") target = dupable.dup();
316
+ }
317
+ return TargetStubHook.create(target, parent);
318
+ } else if (this.source === "return") {
319
+ let hook = this.rpcTargets?.get(target);
320
+ if (hook) if (dupStubs) return hook.dup();
321
+ else {
322
+ this.rpcTargets?.delete(target);
323
+ return hook;
324
+ }
325
+ else {
326
+ hook = TargetStubHook.create(target, parent);
327
+ if (dupStubs) {
328
+ if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
329
+ this.rpcTargets.set(target, hook);
330
+ return hook.dup();
331
+ } else return hook;
332
+ }
333
+ } else throw new Error("owned payload shouldn't contain raw RpcTargets");
334
+ }
335
+ getHookForWritableStream(stream, parent, dupStubs = true) {
336
+ if (this.source === "params") return streamImpl.createWritableStreamHook(stream);
337
+ else if (this.source === "return") {
338
+ let hook = this.rpcTargets?.get(stream);
339
+ if (hook) if (dupStubs) return hook.dup();
340
+ else {
341
+ this.rpcTargets?.delete(stream);
342
+ return hook;
343
+ }
344
+ else {
345
+ hook = streamImpl.createWritableStreamHook(stream);
346
+ if (dupStubs) {
347
+ if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
348
+ this.rpcTargets.set(stream, hook);
349
+ return hook.dup();
350
+ } else return hook;
351
+ }
352
+ } else throw new Error("owned payload shouldn't contain raw WritableStreams");
353
+ }
354
+ getHookForReadableStream(stream, parent, dupStubs = true) {
355
+ if (this.source === "params") return streamImpl.createReadableStreamHook(stream);
356
+ else if (this.source === "return") {
357
+ let hook = this.rpcTargets?.get(stream);
358
+ if (hook) if (dupStubs) return hook.dup();
359
+ else {
360
+ this.rpcTargets?.delete(stream);
361
+ return hook;
362
+ }
363
+ else {
364
+ hook = streamImpl.createReadableStreamHook(stream);
365
+ if (dupStubs) {
366
+ if (!this.rpcTargets) this.rpcTargets = /* @__PURE__ */ new Map();
367
+ this.rpcTargets.set(stream, hook);
368
+ return hook.dup();
369
+ } else return hook;
370
+ }
371
+ } else throw new Error("owned payload shouldn't contain raw ReadableStreams");
372
+ }
373
+ deepCopy(value, oldParent, property, parent, dupStubs, owner) {
374
+ switch (typeForRpc(value)) {
375
+ case "unsupported": return value;
376
+ case "primitive":
377
+ case "bigint":
378
+ case "date":
379
+ case "bytes":
380
+ case "blob":
381
+ case "error":
382
+ case "undefined": return value;
383
+ case "array": {
384
+ let array = value;
385
+ let len = array.length;
386
+ let result = new Array(len);
387
+ for (let i = 0; i < len; i++) result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
388
+ return result;
389
+ }
390
+ case "object": {
391
+ let result = {};
392
+ let object = value;
393
+ for (let i in object) result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);
394
+ return result;
395
+ }
396
+ case "stub":
397
+ case "rpc-promise": {
398
+ let stub = value;
399
+ let hook;
400
+ if (dupStubs) hook = unwrapStubAndDup(stub);
401
+ else hook = unwrapStubTakingOwnership(stub);
402
+ if (stub instanceof RpcPromise$1) {
403
+ let promise = new RpcPromise$1(hook, []);
404
+ this.promises.push({
405
+ parent,
406
+ property,
407
+ promise
408
+ });
409
+ return promise;
410
+ } else {
411
+ this.hooks.push(hook);
412
+ return new RpcStub$1(hook);
413
+ }
414
+ }
415
+ case "function":
416
+ case "rpc-target": {
417
+ let target = value;
418
+ let hook;
419
+ if (owner) hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);
420
+ else hook = TargetStubHook.create(target, oldParent);
421
+ this.hooks.push(hook);
422
+ return new RpcStub$1(hook);
423
+ }
424
+ case "rpc-thenable": {
425
+ let target = value;
426
+ let promise;
427
+ if (owner) promise = new RpcPromise$1(owner.getHookForRpcTarget(target, oldParent, dupStubs), []);
428
+ else promise = new RpcPromise$1(TargetStubHook.create(target, oldParent), []);
429
+ this.promises.push({
430
+ parent,
431
+ property,
432
+ promise
433
+ });
434
+ return promise;
435
+ }
436
+ case "writable": {
437
+ let stream = value;
438
+ let hook;
439
+ if (owner) hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);
440
+ else hook = streamImpl.createWritableStreamHook(stream);
441
+ this.hooks.push(hook);
442
+ return stream;
443
+ }
444
+ case "readable": {
445
+ let stream = value;
446
+ let hook;
447
+ if (owner) hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
448
+ else hook = streamImpl.createReadableStreamHook(stream);
449
+ this.hooks.push(hook);
450
+ return stream;
451
+ }
452
+ case "headers": return new Headers(value);
453
+ case "request": {
454
+ let req = value;
455
+ if (req.body) this.deepCopy(req.body, req, "body", req, dupStubs, owner);
456
+ return new Request(req);
457
+ }
458
+ case "response": {
459
+ let resp = value;
460
+ if (resp.body) this.deepCopy(resp.body, resp, "body", resp, dupStubs, owner);
461
+ return new Response(resp.body, resp);
462
+ }
463
+ default: throw new Error("unreachable");
464
+ }
465
+ }
466
+ ensureDeepCopied() {
467
+ if (this.source !== "owned") {
468
+ let dupStubs = this.source === "params";
469
+ this.hooks = [];
470
+ this.promises = [];
471
+ try {
472
+ this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
473
+ } catch (err) {
474
+ this.hooks = void 0;
475
+ this.promises = void 0;
476
+ throw err;
477
+ }
478
+ this.source = "owned";
479
+ if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error("Not all rpcTargets were accounted for in deep-copy?");
480
+ this.rpcTargets = void 0;
481
+ }
482
+ }
483
+ deliverTo(parent, property, promises) {
484
+ this.ensureDeepCopied();
485
+ if (this.value instanceof RpcPromise$1) RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);
486
+ else {
487
+ parent[property] = this.value;
488
+ for (let record of this.promises) RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);
489
+ }
490
+ }
491
+ static deliverRpcPromiseTo(promise, parent, property, promises) {
492
+ let hook = unwrapStubNoProperties(promise);
493
+ if (!hook) throw new Error("property promises should have been resolved earlier");
494
+ let inner = hook.pull();
495
+ if (inner instanceof RpcPayload) inner.deliverTo(parent, property, promises);
496
+ else promises.push(inner.then((payload) => {
497
+ let subPromises = [];
498
+ payload.deliverTo(parent, property, subPromises);
499
+ if (subPromises.length > 0) return Promise.all(subPromises);
500
+ }));
501
+ }
502
+ async deliverCall(func, thisArg) {
503
+ try {
504
+ let promises = [];
505
+ this.deliverTo(this, "value", promises);
506
+ if (promises.length > 0) await Promise.all(promises);
507
+ let result = Function.prototype.apply.call(func, thisArg, this.value);
508
+ if (result instanceof RpcPromise$1) return RpcPayload.fromAppReturn(result);
509
+ else return RpcPayload.fromAppReturn(await result);
510
+ } finally {
511
+ this.dispose();
512
+ }
513
+ }
514
+ async deliverResolve() {
515
+ try {
516
+ let promises = [];
517
+ this.deliverTo(this, "value", promises);
518
+ if (promises.length > 0) await Promise.all(promises);
519
+ let result = this.value;
520
+ if (result instanceof Object) {
521
+ if (!(Symbol.dispose in result)) Object.defineProperty(result, Symbol.dispose, {
522
+ value: () => this.dispose(),
523
+ writable: true,
524
+ enumerable: false,
525
+ configurable: true
526
+ });
527
+ }
528
+ return result;
529
+ } catch (err) {
530
+ this.dispose();
531
+ throw err;
532
+ }
533
+ }
534
+ dispose() {
535
+ if (this.source === "owned") {
536
+ this.hooks.forEach((hook) => hook.dispose());
537
+ this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
538
+ } else if (this.source === "return") {
539
+ this.disposeImpl(this.value, void 0);
540
+ if (this.rpcTargets && this.rpcTargets.size > 0) throw new Error("Not all rpcTargets were accounted for in disposeImpl()?");
541
+ }
542
+ this.source = "owned";
543
+ this.hooks = [];
544
+ this.promises = [];
545
+ }
546
+ disposeImpl(value, parent) {
547
+ switch (typeForRpc(value)) {
548
+ case "unsupported":
549
+ case "primitive":
550
+ case "bigint":
551
+ case "bytes":
552
+ case "blob":
553
+ case "date":
554
+ case "error":
555
+ case "undefined": return;
556
+ case "array": {
557
+ let array = value;
558
+ let len = array.length;
559
+ for (let i = 0; i < len; i++) this.disposeImpl(array[i], array);
560
+ return;
561
+ }
562
+ case "object": {
563
+ let object = value;
564
+ for (let i in object) this.disposeImpl(object[i], object);
565
+ return;
566
+ }
567
+ case "stub":
568
+ case "rpc-promise": {
569
+ let hook = unwrapStubNoProperties(value);
570
+ if (hook) hook.dispose();
571
+ return;
572
+ }
573
+ case "function":
574
+ case "rpc-target": {
575
+ let target = value;
576
+ let hook = this.rpcTargets?.get(target);
577
+ if (hook) {
578
+ hook.dispose();
579
+ this.rpcTargets.delete(target);
580
+ } else disposeRpcTarget(target);
581
+ return;
582
+ }
583
+ case "rpc-thenable": return;
584
+ case "headers": return;
585
+ case "request": {
586
+ let req = value;
587
+ if (req.body) this.disposeImpl(req.body, req);
588
+ return;
589
+ }
590
+ case "response": {
591
+ let resp = value;
592
+ if (resp.body) this.disposeImpl(resp.body, resp);
593
+ return;
594
+ }
595
+ case "writable": {
596
+ let stream = value;
597
+ let hook = this.rpcTargets?.get(stream);
598
+ if (hook) this.rpcTargets.delete(stream);
599
+ else hook = streamImpl.createWritableStreamHook(stream);
600
+ hook.dispose();
601
+ return;
602
+ }
603
+ case "readable": {
604
+ let stream = value;
605
+ let hook = this.rpcTargets?.get(stream);
606
+ if (hook) this.rpcTargets.delete(stream);
607
+ else hook = streamImpl.createReadableStreamHook(stream);
608
+ hook.dispose();
609
+ return;
610
+ }
611
+ default: return;
612
+ }
613
+ }
614
+ ignoreUnhandledRejections() {
615
+ if (this.hooks) {
616
+ this.hooks.forEach((hook) => {
617
+ hook.ignoreUnhandledRejections();
618
+ });
619
+ this.promises.forEach((promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections());
620
+ } else this.ignoreUnhandledRejectionsImpl(this.value);
621
+ }
622
+ ignoreUnhandledRejectionsImpl(value) {
623
+ switch (typeForRpc(value)) {
624
+ case "unsupported":
625
+ case "primitive":
626
+ case "bigint":
627
+ case "bytes":
628
+ case "blob":
629
+ case "date":
630
+ case "error":
631
+ case "undefined":
632
+ case "function":
633
+ case "rpc-target":
634
+ case "writable":
635
+ case "readable":
636
+ case "headers":
637
+ case "request":
638
+ case "response": return;
639
+ case "array": {
640
+ let array = value;
641
+ let len = array.length;
642
+ for (let i = 0; i < len; i++) this.ignoreUnhandledRejectionsImpl(array[i]);
643
+ return;
644
+ }
645
+ case "object": {
646
+ let object = value;
647
+ for (let i in object) this.ignoreUnhandledRejectionsImpl(object[i]);
648
+ return;
649
+ }
650
+ case "stub":
651
+ case "rpc-promise":
652
+ unwrapStubOrParent(value).ignoreUnhandledRejections();
653
+ return;
654
+ case "rpc-thenable":
655
+ value.then((_) => {}, (_) => {});
656
+ return;
657
+ default: return;
658
+ }
659
+ }
660
+ };
661
+ function followPath(value, parent, path, owner) {
662
+ for (let i = 0; i < path.length; i++) {
663
+ parent = value;
664
+ let part = path[i];
665
+ if (part in Object.prototype) {
666
+ value = void 0;
667
+ continue;
668
+ }
669
+ switch (typeForRpc(value)) {
670
+ case "object":
671
+ case "function":
672
+ if (Object.hasOwn(value, part)) value = value[part];
673
+ else value = void 0;
674
+ break;
675
+ case "array":
676
+ if (Number.isInteger(part) && part >= 0) value = value[part];
677
+ else value = void 0;
678
+ break;
679
+ case "rpc-target":
680
+ case "rpc-thenable":
681
+ if (Object.hasOwn(value, part)) throw new TypeError(`Attempted to access property '${part}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`);
682
+ else value = value[part];
683
+ owner = null;
684
+ break;
685
+ case "stub":
686
+ case "rpc-promise": {
687
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
688
+ return {
689
+ hook,
690
+ remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i)
691
+ };
692
+ }
693
+ case "writable":
694
+ value = void 0;
695
+ break;
696
+ case "readable":
697
+ value = void 0;
698
+ break;
699
+ case "primitive":
700
+ case "bigint":
701
+ case "bytes":
702
+ case "blob":
703
+ case "date":
704
+ case "error":
705
+ case "headers":
706
+ case "request":
707
+ case "response":
708
+ value = void 0;
709
+ break;
710
+ case "undefined":
711
+ value = value[part];
712
+ break;
713
+ case "unsupported": if (i === 0) throw new TypeError(`RPC stub points at a non-serializable type.`);
714
+ else {
715
+ let prefix = path.slice(0, i).join(".");
716
+ let remainder = path.slice(0, i).join(".");
717
+ throw new TypeError(`'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`);
718
+ }
719
+ default: throw new TypeError("unreachable");
720
+ }
721
+ }
722
+ if (value instanceof RpcPromise$1) {
723
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
724
+ return {
725
+ hook,
726
+ remainingPath: pathIfPromise || []
727
+ };
728
+ }
729
+ return {
730
+ value,
731
+ parent,
732
+ owner
733
+ };
734
+ }
735
+ var ValueStubHook = class extends StubHook {
736
+ call(path, args) {
737
+ try {
738
+ let { value, owner } = this.getValue();
739
+ let followResult = followPath(value, void 0, path, owner);
740
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
741
+ if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
742
+ return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
743
+ return new PayloadStubHook(payload);
744
+ }));
745
+ } catch (err) {
746
+ return new ErrorStubHook(err);
747
+ }
748
+ }
749
+ map(path, captures, instructions) {
750
+ try {
751
+ let followResult;
752
+ try {
753
+ let { value, owner } = this.getValue();
754
+ followResult = followPath(value, void 0, path, owner);
755
+ } catch (err) {
756
+ for (let cap of captures) cap.dispose();
757
+ throw err;
758
+ }
759
+ if (followResult.hook) return followResult.hook.map(followResult.remainingPath, captures, instructions);
760
+ return mapImpl.applyMap(followResult.value, followResult.parent, followResult.owner, captures, instructions);
761
+ } catch (err) {
762
+ return new ErrorStubHook(err);
763
+ }
764
+ }
765
+ get(path) {
766
+ try {
767
+ let { value, owner } = this.getValue();
768
+ if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
769
+ let followResult = followPath(value, void 0, path, owner);
770
+ if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
771
+ return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
772
+ } catch (err) {
773
+ return new ErrorStubHook(err);
774
+ }
775
+ }
776
+ };
777
+ var PayloadStubHook = class PayloadStubHook extends ValueStubHook {
778
+ constructor(payload) {
779
+ super();
780
+ this.payload = payload;
781
+ }
782
+ payload;
783
+ getPayload() {
784
+ if (this.payload) return this.payload;
785
+ else throw new Error("Attempted to use an RPC StubHook after it was disposed.");
786
+ }
787
+ getValue() {
788
+ let payload = this.getPayload();
789
+ return {
790
+ value: payload.value,
791
+ owner: payload
792
+ };
793
+ }
794
+ dup() {
795
+ let thisPayload = this.getPayload();
796
+ return new PayloadStubHook(RpcPayload.deepCopyFrom(thisPayload.value, void 0, thisPayload));
797
+ }
798
+ pull() {
799
+ return this.getPayload();
800
+ }
801
+ ignoreUnhandledRejections() {
802
+ if (this.payload) this.payload.ignoreUnhandledRejections();
803
+ }
804
+ dispose() {
805
+ if (this.payload) {
806
+ this.payload.dispose();
807
+ this.payload = void 0;
808
+ }
809
+ }
810
+ onBroken(callback) {
811
+ if (this.payload) {
812
+ if (this.payload.value instanceof RpcStub$1) this.payload.value.onRpcBroken(callback);
813
+ }
814
+ }
815
+ };
816
+ function disposeRpcTarget(target) {
817
+ if (Symbol.dispose in target) try {
818
+ target[Symbol.dispose]();
819
+ } catch (err) {
820
+ Promise.reject(err);
821
+ }
822
+ }
823
+ var TargetStubHook = class TargetStubHook extends ValueStubHook {
824
+ static create(value, parent) {
825
+ if (typeof value !== "function") parent = void 0;
826
+ return new TargetStubHook(value, parent);
827
+ }
828
+ constructor(target, parent, dupFrom) {
829
+ super();
830
+ this.target = target;
831
+ this.parent = parent;
832
+ if (dupFrom) {
833
+ if (dupFrom.refcount) {
834
+ this.refcount = dupFrom.refcount;
835
+ ++this.refcount.count;
836
+ }
837
+ } else if (Symbol.dispose in target) this.refcount = { count: 1 };
838
+ }
839
+ target;
840
+ parent;
841
+ refcount;
842
+ getTarget() {
843
+ if (this.target) return this.target;
844
+ else throw new Error("Attempted to use an RPC StubHook after it was disposed.");
845
+ }
846
+ getValue() {
847
+ return {
848
+ value: this.getTarget(),
849
+ owner: null
850
+ };
851
+ }
852
+ dup() {
853
+ return new TargetStubHook(this.getTarget(), this.parent, this);
854
+ }
855
+ pull() {
856
+ let target = this.getTarget();
857
+ if ("then" in target) return Promise.resolve(target).then((resolution) => {
858
+ return RpcPayload.fromAppReturn(resolution);
859
+ });
860
+ else return Promise.reject(/* @__PURE__ */ new Error("Tried to resolve a non-promise stub."));
861
+ }
862
+ ignoreUnhandledRejections() {}
863
+ dispose() {
864
+ if (this.target) {
865
+ if (this.refcount) {
866
+ if (--this.refcount.count == 0) disposeRpcTarget(this.target);
867
+ }
868
+ this.target = void 0;
869
+ }
870
+ }
871
+ onBroken(callback) {}
872
+ };
873
+ var PromiseStubHook = class PromiseStubHook extends StubHook {
874
+ promise;
875
+ resolution;
876
+ constructor(promise) {
877
+ super();
878
+ this.promise = promise.then((res) => {
879
+ this.resolution = res;
880
+ return res;
881
+ });
882
+ }
883
+ call(path, args) {
884
+ args.ensureDeepCopied();
885
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
886
+ }
887
+ stream(path, args) {
888
+ args.ensureDeepCopied();
889
+ return { promise: this.promise.then((hook) => {
890
+ return hook.stream(path, args).promise;
891
+ }) };
892
+ }
893
+ map(path, captures, instructions) {
894
+ return new PromiseStubHook(this.promise.then((hook) => hook.map(path, captures, instructions), (err) => {
895
+ for (let cap of captures) cap.dispose();
896
+ throw err;
897
+ }));
898
+ }
899
+ get(path) {
900
+ return new PromiseStubHook(this.promise.then((hook) => hook.get(path)));
901
+ }
902
+ dup() {
903
+ if (this.resolution) return this.resolution.dup();
904
+ else return new PromiseStubHook(this.promise.then((hook) => hook.dup()));
905
+ }
906
+ pull() {
907
+ if (this.resolution) return this.resolution.pull();
908
+ else return this.promise.then((hook) => hook.pull());
909
+ }
910
+ ignoreUnhandledRejections() {
911
+ if (this.resolution) this.resolution.ignoreUnhandledRejections();
912
+ else this.promise.then((res) => {
913
+ res.ignoreUnhandledRejections();
914
+ }, (err) => {});
915
+ }
916
+ dispose() {
917
+ if (this.resolution) this.resolution.dispose();
918
+ else this.promise.then((hook) => {
919
+ hook.dispose();
920
+ }, (err) => {});
921
+ }
922
+ onBroken(callback) {
923
+ if (this.resolution) this.resolution.onBroken(callback);
924
+ else this.promise.then((hook) => {
925
+ hook.onBroken(callback);
926
+ }, callback);
927
+ }
928
+ };
929
+
930
+ //#endregion
931
+ //#region src/serialize.ts
932
+ const DEFAULT_MAX_DEPTH = 256;
933
+ const DEFAULT_LIMITS = {
934
+ maxBigIntDigits: 16384,
935
+ maxDepth: 256,
936
+ maxMessageSize: 32 * 1024 * 1024
937
+ };
938
+ var NullExporter = class {
939
+ exportStub(stub) {
940
+ throw new Error("Cannot serialize RPC stubs without an RPC session.");
941
+ }
942
+ exportPromise(stub) {
943
+ throw new Error("Cannot serialize RPC stubs without an RPC session.");
944
+ }
945
+ getImport(hook) {}
946
+ unexport(ids) {}
947
+ createPipe(readable) {
948
+ throw new Error("Cannot create pipes without an RPC session.");
949
+ }
950
+ onSendError(error) {}
951
+ };
952
+ const NULL_EXPORTER = new NullExporter();
953
+ async function streamToBlob(stream, type) {
954
+ let b = await new Response(stream).blob();
955
+ return b.type === type ? b : b.slice(0, b.size, type);
956
+ }
957
+ const ERROR_TYPES = {
958
+ __proto__: null,
959
+ Error,
960
+ EvalError,
961
+ RangeError,
962
+ ReferenceError,
963
+ SyntaxError,
964
+ TypeError,
965
+ URIError,
966
+ AggregateError
967
+ };
968
+ var Devaluator = class Devaluator {
969
+ exporter;
970
+ source;
971
+ encodingLevel;
972
+ constructor(exporter, source, encodingLevel) {
973
+ this.exporter = exporter;
974
+ this.source = source;
975
+ this.encodingLevel = encodingLevel;
976
+ }
977
+ static devaluate(value, parent, exporter = NULL_EXPORTER, source, encodingLevel = "string") {
978
+ let devaluator = new Devaluator(exporter, source, encodingLevel);
979
+ try {
980
+ return devaluator.devaluateImpl(value, parent, 0);
981
+ } catch (err) {
982
+ if (devaluator.exports) try {
983
+ exporter.unexport(devaluator.exports);
984
+ } catch (err) {}
985
+ throw err;
986
+ }
987
+ }
988
+ exports;
989
+ devaluateImpl(value, parent, depth) {
990
+ if (depth >= 256) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
991
+ switch (typeForRpc(value)) {
992
+ case "unsupported": {
993
+ let msg;
994
+ try {
995
+ msg = `Cannot serialize value: ${value}`;
996
+ } catch (err) {
997
+ msg = "Cannot serialize value: (couldn't stringify value)";
998
+ }
999
+ throw new TypeError(msg);
1000
+ }
1001
+ case "primitive": if (typeof value === "number" && !isFinite(value)) {
1002
+ if (this.encodingLevel === "structuredClonable") return value;
1003
+ if (value === Infinity) return ["inf"];
1004
+ else if (value === -Infinity) return ["-inf"];
1005
+ else return ["nan"];
1006
+ } else return value;
1007
+ case "object": {
1008
+ let object = value;
1009
+ let result = {};
1010
+ for (let key in object) result[key] = this.devaluateImpl(object[key], object, depth + 1);
1011
+ return result;
1012
+ }
1013
+ case "array": {
1014
+ let array = value;
1015
+ let len = array.length;
1016
+ let result = new Array(len);
1017
+ for (let i = 0; i < len; i++) result[i] = this.devaluateImpl(array[i], array, depth + 1);
1018
+ return [result];
1019
+ }
1020
+ case "bigint":
1021
+ if (this.encodingLevel === "structuredClonable") return value;
1022
+ return ["bigint", value.toString()];
1023
+ case "date": {
1024
+ if (this.encodingLevel === "structuredClonable") return value;
1025
+ const time = value.getTime();
1026
+ return ["date", Number.isNaN(time) ? null : time];
1027
+ }
1028
+ case "bytes": {
1029
+ let bytes = value;
1030
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return ["bytes", bytes];
1031
+ if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
1032
+ let b64;
1033
+ if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1034
+ else {
1035
+ let binary = "";
1036
+ for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1037
+ b64 = btoa(binary);
1038
+ }
1039
+ return ["bytes", b64.replace(/=+$/, "")];
1040
+ }
1041
+ case "headers": return ["headers", [...value]];
1042
+ case "request": {
1043
+ let req = value;
1044
+ let init = {};
1045
+ if (req.method !== "GET") init.method = req.method;
1046
+ let headers = [...req.headers];
1047
+ if (headers.length > 0) init.headers = headers;
1048
+ if (req.body) {
1049
+ init.body = this.devaluateImpl(req.body, req, depth + 1);
1050
+ init.duplex = req.duplex || "half";
1051
+ } else if (req.body === void 0 && ![
1052
+ "GET",
1053
+ "HEAD",
1054
+ "OPTIONS",
1055
+ "TRACE",
1056
+ "DELETE"
1057
+ ].includes(req.method)) {
1058
+ let bodyPromise = req.arrayBuffer();
1059
+ let readable = new ReadableStream({ async start(controller) {
1060
+ try {
1061
+ controller.enqueue(new Uint8Array(await bodyPromise));
1062
+ controller.close();
1063
+ } catch (err) {
1064
+ controller.error(err);
1065
+ }
1066
+ } });
1067
+ let hook = streamImpl.createReadableStreamHook(readable);
1068
+ init.body = ["readable", this.exporter.createPipe(readable, hook)];
1069
+ init.duplex = req.duplex || "half";
1070
+ }
1071
+ if (req.cache && req.cache !== "default") init.cache = req.cache;
1072
+ if (req.redirect !== "follow") init.redirect = req.redirect;
1073
+ if (req.integrity) init.integrity = req.integrity;
1074
+ if (req.mode && req.mode !== "cors") init.mode = req.mode;
1075
+ if (req.credentials && req.credentials !== "same-origin") init.credentials = req.credentials;
1076
+ if (req.referrer && req.referrer !== "about:client") init.referrer = req.referrer;
1077
+ if (req.referrerPolicy) init.referrerPolicy = req.referrerPolicy;
1078
+ if (req.keepalive) init.keepalive = req.keepalive;
1079
+ let cfReq = req;
1080
+ if (cfReq.cf) init.cf = cfReq.cf;
1081
+ if (cfReq.encodeResponseBody && cfReq.encodeResponseBody !== "automatic") init.encodeResponseBody = cfReq.encodeResponseBody;
1082
+ return [
1083
+ "request",
1084
+ req.url,
1085
+ init
1086
+ ];
1087
+ }
1088
+ case "response": {
1089
+ let resp = value;
1090
+ let body = this.devaluateImpl(resp.body, resp, depth + 1);
1091
+ let init = {};
1092
+ if (resp.status !== 200) init.status = resp.status;
1093
+ if (resp.statusText) init.statusText = resp.statusText;
1094
+ let headers = [...resp.headers];
1095
+ if (headers.length > 0) init.headers = headers;
1096
+ let cfResp = resp;
1097
+ if (cfResp.cf) init.cf = cfResp.cf;
1098
+ if (cfResp.encodeBody && cfResp.encodeBody !== "automatic") init.encodeBody = cfResp.encodeBody;
1099
+ if (cfResp.webSocket) throw new TypeError("Can't serialize a Response containing a webSocket.");
1100
+ return [
1101
+ "response",
1102
+ body,
1103
+ init
1104
+ ];
1105
+ }
1106
+ case "blob": {
1107
+ let blob = value;
1108
+ let readable = blob.stream();
1109
+ let hook = streamImpl.createReadableStreamHook(readable);
1110
+ let importId = this.exporter.createPipe(readable, hook);
1111
+ return [
1112
+ "blob",
1113
+ blob.type,
1114
+ ["readable", importId]
1115
+ ];
1116
+ }
1117
+ case "error": {
1118
+ let e = value;
1119
+ let rewritten = this.exporter.onSendError(e);
1120
+ if (rewritten) e = rewritten;
1121
+ let anyE = e;
1122
+ let props;
1123
+ let captureProp = (key, val) => {
1124
+ let exportsBefore = this.exports?.length ?? 0;
1125
+ try {
1126
+ let encoded = this.devaluateImpl(val, e, depth + 1);
1127
+ if (!props) props = {};
1128
+ props[key] = encoded;
1129
+ } catch (err) {
1130
+ if (this.exports && this.exports.length > exportsBefore) {
1131
+ let tail = this.exports.splice(exportsBefore);
1132
+ try {
1133
+ this.exporter.unexport(tail);
1134
+ } catch (err2) {}
1135
+ }
1136
+ }
1137
+ };
1138
+ for (let key of Object.keys(e)) {
1139
+ if (key === "name" || key === "message" || key === "stack") continue;
1140
+ captureProp(key, anyE[key]);
1141
+ }
1142
+ if ("cause" in e) captureProp("cause", anyE.cause);
1143
+ if (e instanceof AggregateError) captureProp("errors", e.errors);
1144
+ let result = [
1145
+ "error",
1146
+ e.name,
1147
+ e.message
1148
+ ];
1149
+ if (props) {
1150
+ result.push(rewritten && rewritten.stack ? rewritten.stack : null);
1151
+ result.push(props);
1152
+ } else if (rewritten && rewritten.stack) result.push(rewritten.stack);
1153
+ return result;
1154
+ }
1155
+ case "undefined":
1156
+ if (this.encodingLevel === "structuredClonable") return;
1157
+ return ["undefined"];
1158
+ case "stub":
1159
+ case "rpc-promise": {
1160
+ if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1161
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
1162
+ let importId = this.exporter.getImport(hook);
1163
+ if (importId !== void 0) if (pathIfPromise) if (pathIfPromise.length > 0) return [
1164
+ "pipeline",
1165
+ importId,
1166
+ pathIfPromise
1167
+ ];
1168
+ else return ["pipeline", importId];
1169
+ else return ["import", importId];
1170
+ if (pathIfPromise) hook = hook.get(pathIfPromise);
1171
+ else hook = hook.dup();
1172
+ return this.devaluateHook(pathIfPromise ? "promise" : "export", hook);
1173
+ }
1174
+ case "function":
1175
+ case "rpc-target": {
1176
+ if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1177
+ let hook = this.source.getHookForRpcTarget(value, parent);
1178
+ return this.devaluateHook("export", hook);
1179
+ }
1180
+ case "rpc-thenable": {
1181
+ if (!this.source) throw new Error("Can't serialize RPC stubs in this context.");
1182
+ let hook = this.source.getHookForRpcTarget(value, parent);
1183
+ return this.devaluateHook("promise", hook);
1184
+ }
1185
+ case "writable": {
1186
+ if (!this.source) throw new Error("Can't serialize WritableStream in this context.");
1187
+ let hook = this.source.getHookForWritableStream(value, parent);
1188
+ return this.devaluateHook("writable", hook);
1189
+ }
1190
+ case "readable": {
1191
+ if (!this.source) throw new Error("Can't serialize ReadableStream in this context.");
1192
+ let ws = value;
1193
+ let hook = this.source.getHookForReadableStream(ws, parent);
1194
+ return ["readable", this.exporter.createPipe(ws, hook)];
1195
+ }
1196
+ default: throw new Error("unreachable");
1197
+ }
1198
+ }
1199
+ devaluateHook(type, hook) {
1200
+ if (!this.exports) this.exports = [];
1201
+ let exportId = type === "promise" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);
1202
+ this.exports.push(exportId);
1203
+ return [type, exportId];
1204
+ }
1205
+ };
1206
+ /**
1207
+ * Serialize a value, using Cap'n Web's underlying serialization. This won't be able to serialize
1208
+ * RPC stubs, but it will support basic data types.
1209
+ */
1210
+ function serialize(value) {
1211
+ return JSON.stringify(Devaluator.devaluate(value));
1212
+ }
1213
+ var NullImporter = class {
1214
+ importStub(idx) {
1215
+ throw new Error("Cannot deserialize RPC stubs without an RPC session.");
1216
+ }
1217
+ importPromise(idx) {
1218
+ throw new Error("Cannot deserialize RPC stubs without an RPC session.");
1219
+ }
1220
+ getExport(idx) {}
1221
+ getPipeReadable(exportId) {
1222
+ throw new Error("Cannot retrieve pipe readable without an RPC session.");
1223
+ }
1224
+ getLimits() {
1225
+ return DEFAULT_LIMITS;
1226
+ }
1227
+ };
1228
+ const NULL_IMPORTER = new NullImporter();
1229
+ function fixBrokenRequestBody(request, body) {
1230
+ return new RpcPromise$1(new PromiseStubHook(new Response(body).arrayBuffer().then((arrayBuffer) => {
1231
+ let bytes = new Uint8Array(arrayBuffer);
1232
+ let result = new Request(request, { body: bytes });
1233
+ return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1234
+ })), []);
1235
+ }
1236
+ function streamToBlobPromise(stream, type) {
1237
+ return new RpcPromise$1(new PromiseStubHook(streamToBlob(stream, type).then((blob) => {
1238
+ return new PayloadStubHook(RpcPayload.fromAppReturn(blob));
1239
+ })), []);
1240
+ }
1241
+ var Evaluator = class Evaluator {
1242
+ importer;
1243
+ encodingLevel;
1244
+ limits;
1245
+ constructor(importer, encodingLevel = "string") {
1246
+ this.importer = importer;
1247
+ this.encodingLevel = encodingLevel;
1248
+ this.limits = importer.getLimits();
1249
+ }
1250
+ hooks = [];
1251
+ promises = [];
1252
+ evaluate(value) {
1253
+ return this.evaluateWithDepth(value, 0);
1254
+ }
1255
+ evaluateWithDepth(value, depth) {
1256
+ let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1257
+ try {
1258
+ payload.value = this.evaluateImpl(value, payload, "value", depth);
1259
+ return payload;
1260
+ } catch (err) {
1261
+ payload.dispose();
1262
+ throw err;
1263
+ }
1264
+ }
1265
+ evaluateCopy(value) {
1266
+ return this.evaluate(structuredClone(value));
1267
+ }
1268
+ evaluateImpl(value, parent, property, depth) {
1269
+ let maxDepth = this.limits.maxDepth;
1270
+ if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1271
+ if (this.encodingLevel === "structuredClonable") {
1272
+ if (value instanceof Date || typeof value === "bigint") return value;
1273
+ }
1274
+ if (value instanceof Array) {
1275
+ if (value.length == 1 && value[0] instanceof Array) {
1276
+ let result = value[0];
1277
+ for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);
1278
+ return result;
1279
+ } else switch (value[0]) {
1280
+ case "bigint":
1281
+ if (typeof value[1] == "string") {
1282
+ let digits = value[1];
1283
+ let maxBigIntDigits = this.limits.maxBigIntDigits;
1284
+ if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);
1285
+ return BigInt(digits);
1286
+ }
1287
+ break;
1288
+ case "date":
1289
+ if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1290
+ if (typeof value[1] == "number") return new Date(value[1]);
1291
+ break;
1292
+ case "bytes":
1293
+ if (value[1] instanceof Uint8Array) return value[1];
1294
+ if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1295
+ else if (Uint8Array.fromBase64) return Uint8Array.fromBase64(value[1]);
1296
+ else {
1297
+ let bs = atob(value[1]);
1298
+ let len = bs.length;
1299
+ let bytes = new Uint8Array(len);
1300
+ for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1301
+ return bytes;
1302
+ }
1303
+ break;
1304
+ case "error":
1305
+ if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1306
+ let cls = ERROR_TYPES[value[1]] || Error;
1307
+ let result = cls === AggregateError ? new cls([], value[2]) : new cls(value[2]);
1308
+ if (typeof value[3] === "string") result.stack = value[3];
1309
+ if (value.length >= 5) {
1310
+ let props = value[4];
1311
+ if (!props || typeof props !== "object" || Array.isArray(props)) break;
1312
+ let anyResult = result;
1313
+ let propsObj = props;
1314
+ for (let key of Object.keys(propsObj)) {
1315
+ if (key === "name" || key === "message" || key === "stack") continue;
1316
+ if (key in Object.prototype || key === "toJSON") {
1317
+ this.evaluateImpl(propsObj[key], result, key, depth + 1);
1318
+ continue;
1319
+ }
1320
+ anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);
1321
+ }
1322
+ }
1323
+ return result;
1324
+ }
1325
+ break;
1326
+ case "undefined":
1327
+ if (value.length === 1) return;
1328
+ break;
1329
+ case "inf": return Infinity;
1330
+ case "-inf": return -Infinity;
1331
+ case "nan": return NaN;
1332
+ case "headers":
1333
+ if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);
1334
+ break;
1335
+ case "request": {
1336
+ if (value.length !== 3 || typeof value[1] !== "string") break;
1337
+ let url = value[1];
1338
+ let init = value[2];
1339
+ if (typeof init !== "object" || init === null) break;
1340
+ if (init.body) {
1341
+ init.body = this.evaluateImpl(init.body, init, "body", depth + 1);
1342
+ if (init.body === null || typeof init.body === "string" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) {} else throw new TypeError("Request body must be of type ReadableStream.");
1343
+ }
1344
+ if (init.signal) {
1345
+ init.signal = this.evaluateImpl(init.signal, init, "signal", depth + 1);
1346
+ if (!(init.signal instanceof AbortSignal)) throw new TypeError("Request siganl must be of type AbortSignal.");
1347
+ }
1348
+ if (init.headers && !(init.headers instanceof Array)) throw new TypeError("Request headers must be serialized as an array of pairs.");
1349
+ let result = new Request(url, init);
1350
+ if (init.body instanceof ReadableStream && result.body === void 0) {
1351
+ let promise = fixBrokenRequestBody(result, init.body);
1352
+ this.promises.push({
1353
+ promise,
1354
+ parent,
1355
+ property
1356
+ });
1357
+ return promise;
1358
+ } else return result;
1359
+ }
1360
+ case "response": {
1361
+ if (value.length !== 3) break;
1362
+ let body = this.evaluateImpl(value[1], parent, property, depth + 1);
1363
+ if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) {} else throw new TypeError("Response body must be of type ReadableStream.");
1364
+ let init = value[2];
1365
+ if (typeof init !== "object" || init === null) break;
1366
+ if (init.webSocket) throw new TypeError("Can't deserialize a Response containing a webSocket.");
1367
+ if (init.headers && !(init.headers instanceof Array)) throw new TypeError("Request headers must be serialized as an array of pairs.");
1368
+ return new Response(body, init);
1369
+ }
1370
+ case "blob": {
1371
+ if (value.length !== 3 || typeof value[1] !== "string") break;
1372
+ let contentType = value[1];
1373
+ let content = this.evaluateImpl(value[2], parent, property, depth + 1);
1374
+ if (!(content instanceof ReadableStream)) throw new TypeError("Blob content must be serialized as a ReadableStream.");
1375
+ let promise = streamToBlobPromise(content, contentType);
1376
+ this.promises.push({
1377
+ promise,
1378
+ parent,
1379
+ property
1380
+ });
1381
+ return promise;
1382
+ }
1383
+ case "import":
1384
+ case "pipeline": {
1385
+ if (value.length < 2 || value.length > 4) break;
1386
+ if (typeof value[1] != "number") break;
1387
+ let hook = this.importer.getExport(value[1]);
1388
+ if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);
1389
+ let isPromise = value[0] == "pipeline";
1390
+ let addStub = (hook) => {
1391
+ if (isPromise) {
1392
+ let promise = new RpcPromise$1(hook, []);
1393
+ this.promises.push({
1394
+ promise,
1395
+ parent,
1396
+ property
1397
+ });
1398
+ return promise;
1399
+ } else {
1400
+ this.hooks.push(hook);
1401
+ return new RpcPromise$1(hook, []);
1402
+ }
1403
+ };
1404
+ if (value.length == 2) if (isPromise) return addStub(hook.get([]));
1405
+ else return addStub(hook.dup());
1406
+ let path = value[2];
1407
+ if (!(path instanceof Array)) break;
1408
+ if (!path.every((part) => {
1409
+ return typeof part == "string" || typeof part == "number";
1410
+ })) break;
1411
+ if (value.length == 3) return addStub(hook.get(path));
1412
+ let args = value[3];
1413
+ if (!(args instanceof Array)) break;
1414
+ args = new Evaluator(this.importer).evaluateWithDepth([args], depth);
1415
+ return addStub(hook.call(path, args));
1416
+ }
1417
+ case "remap": {
1418
+ if (value.length !== 5 || typeof value[1] !== "number" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array)) break;
1419
+ let hook = this.importer.getExport(value[1]);
1420
+ if (!hook) throw new Error(`no such entry on exports table: ${value[1]}`);
1421
+ let path = value[2];
1422
+ if (!path.every((part) => {
1423
+ return typeof part == "string" || typeof part == "number";
1424
+ })) break;
1425
+ let captures = value[3].map((cap) => {
1426
+ if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== "import" && cap[0] !== "export" || typeof cap[1] !== "number") throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);
1427
+ if (cap[0] === "export") return this.importer.importStub(cap[1]);
1428
+ else {
1429
+ let exp = this.importer.getExport(cap[1]);
1430
+ if (!exp) throw new Error(`no such entry on exports table: ${cap[1]}`);
1431
+ return exp.dup();
1432
+ }
1433
+ });
1434
+ let instructions = value[4];
1435
+ let promise = new RpcPromise$1(hook.map(path, captures, instructions), []);
1436
+ this.promises.push({
1437
+ promise,
1438
+ parent,
1439
+ property
1440
+ });
1441
+ return promise;
1442
+ }
1443
+ case "export":
1444
+ case "promise":
1445
+ if (typeof value[1] == "number") if (value[0] == "promise") {
1446
+ let promise = new RpcPromise$1(this.importer.importPromise(value[1]), []);
1447
+ this.promises.push({
1448
+ parent,
1449
+ property,
1450
+ promise
1451
+ });
1452
+ return promise;
1453
+ } else {
1454
+ let hook = this.importer.importStub(value[1]);
1455
+ this.hooks.push(hook);
1456
+ return new RpcStub$1(hook);
1457
+ }
1458
+ break;
1459
+ case "writable":
1460
+ if (typeof value[1] == "number") {
1461
+ let hook = this.importer.importStub(value[1]);
1462
+ let stream = streamImpl.createWritableStreamFromHook(hook);
1463
+ this.hooks.push(hook);
1464
+ return stream;
1465
+ }
1466
+ break;
1467
+ case "readable":
1468
+ if (typeof value[1] == "number") {
1469
+ let stream = this.importer.getPipeReadable(value[1]);
1470
+ let hook = streamImpl.createReadableStreamHook(stream);
1471
+ this.hooks.push(hook);
1472
+ return stream;
1473
+ }
1474
+ break;
1475
+ }
1476
+ throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1477
+ } else if (value instanceof Object) {
1478
+ let result = value;
1479
+ for (let key in result) if (key in Object.prototype || key === "toJSON") {
1480
+ this.evaluateImpl(result[key], result, key, depth + 1);
1481
+ delete result[key];
1482
+ } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);
1483
+ return result;
1484
+ } else return value;
1485
+ }
1486
+ };
1487
+ /**
1488
+ * Deserialize a value serialized using serialize().
1489
+ */
1490
+ function deserialize(value) {
1491
+ let payload = new Evaluator(NULL_IMPORTER).evaluate(JSON.parse(value));
1492
+ payload.dispose();
1493
+ return payload.value;
1494
+ }
1495
+
1496
+ //#endregion
1497
+ //#region src/rpc.ts
1498
+ const ESTIMATED_OBJECT_OVERHEAD = 16;
1499
+ const ESTIMATED_ENTRY_OVERHEAD = 8;
1500
+ const ESTIMATED_BINARY_OVERHEAD = 16;
1501
+ const MAX_ESTIMATE_DEPTH = 64;
1502
+ function estimateStringSize(value) {
1503
+ return 2 + value.length * 3;
1504
+ }
1505
+ function estimateEncodedSize(value, seen, depth = 0) {
1506
+ if (depth >= MAX_ESTIMATE_DEPTH) return ESTIMATED_ENTRY_OVERHEAD;
1507
+ switch (typeof value) {
1508
+ case "string": return estimateStringSize(value);
1509
+ case "number": return 16;
1510
+ case "bigint": return 16;
1511
+ case "boolean": return 8;
1512
+ case "undefined": return 16;
1513
+ case "object": {
1514
+ if (value === null) return 8;
1515
+ if (ArrayBuffer.isView(value)) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1516
+ if (value instanceof ArrayBuffer) return ESTIMATED_BINARY_OVERHEAD + value.byteLength;
1517
+ if (typeof Blob !== "undefined" && value instanceof Blob) return ESTIMATED_BINARY_OVERHEAD + value.size;
1518
+ if (value instanceof Date) return 16;
1519
+ seen ??= /* @__PURE__ */ new WeakSet();
1520
+ if (seen.has(value)) return ESTIMATED_ENTRY_OVERHEAD;
1521
+ seen.add(value);
1522
+ if (value instanceof Array) {
1523
+ let size = ESTIMATED_OBJECT_OVERHEAD;
1524
+ for (let item of value) size += ESTIMATED_ENTRY_OVERHEAD + estimateEncodedSize(item, seen, depth + 1);
1525
+ return size;
1526
+ }
1527
+ if (value instanceof Error) {
1528
+ let size = ESTIMATED_OBJECT_OVERHEAD + estimateStringSize(value.name) + estimateStringSize(value.message) + estimateStringSize(value.stack ?? "");
1529
+ for (let key of Object.keys(value)) size += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);
1530
+ return size;
1531
+ }
1532
+ let size = ESTIMATED_OBJECT_OVERHEAD;
1533
+ for (let key of Object.keys(value)) size += ESTIMATED_ENTRY_OVERHEAD + estimateStringSize(key) + estimateEncodedSize(value[key], seen, depth + 1);
1534
+ return size;
1535
+ }
1536
+ default: return 16;
1537
+ }
1538
+ }
1539
+ var ImportTableEntry = class {
1540
+ session;
1541
+ importId;
1542
+ constructor(session, importId, pulling) {
1543
+ this.session = session;
1544
+ this.importId = importId;
1545
+ if (pulling) this.activePull = Promise.withResolvers();
1546
+ }
1547
+ localRefcount = 0;
1548
+ remoteRefcount = 1;
1549
+ activePull;
1550
+ resolution;
1551
+ onBrokenRegistrations;
1552
+ resolve(resolution) {
1553
+ if (this.localRefcount == 0) {
1554
+ resolution.dispose();
1555
+ return;
1556
+ }
1557
+ this.resolution = resolution;
1558
+ this.sendRelease();
1559
+ if (this.onBrokenRegistrations) {
1560
+ for (let i of this.onBrokenRegistrations) {
1561
+ let callback = this.session.onBrokenCallbacks[i];
1562
+ let endIndex = this.session.onBrokenCallbacks.length;
1563
+ resolution.onBroken(callback);
1564
+ if (this.session.onBrokenCallbacks[endIndex] === callback) delete this.session.onBrokenCallbacks[endIndex];
1565
+ else delete this.session.onBrokenCallbacks[i];
1566
+ }
1567
+ this.onBrokenRegistrations = void 0;
1568
+ }
1569
+ if (this.activePull) {
1570
+ this.activePull.resolve();
1571
+ this.activePull = void 0;
1572
+ }
1573
+ }
1574
+ async awaitResolution() {
1575
+ if (!this.activePull) {
1576
+ this.session.sendPull(this.importId);
1577
+ this.activePull = Promise.withResolvers();
1578
+ }
1579
+ await this.activePull.promise;
1580
+ return this.resolution.pull();
1581
+ }
1582
+ dispose() {
1583
+ if (this.resolution) this.resolution.dispose();
1584
+ else {
1585
+ this.abort(/* @__PURE__ */ new Error("RPC was canceled because the RpcPromise was disposed."));
1586
+ this.sendRelease();
1587
+ }
1588
+ }
1589
+ abort(error) {
1590
+ if (!this.resolution) {
1591
+ this.resolution = new ErrorStubHook(error);
1592
+ if (this.activePull) {
1593
+ this.activePull.reject(error);
1594
+ this.activePull = void 0;
1595
+ }
1596
+ this.onBrokenRegistrations = void 0;
1597
+ }
1598
+ }
1599
+ onBroken(callback) {
1600
+ if (this.resolution) this.resolution.onBroken(callback);
1601
+ else {
1602
+ let index = this.session.onBrokenCallbacks.length;
1603
+ this.session.onBrokenCallbacks.push(callback);
1604
+ if (!this.onBrokenRegistrations) this.onBrokenRegistrations = [];
1605
+ this.onBrokenRegistrations.push(index);
1606
+ }
1607
+ }
1608
+ sendRelease() {
1609
+ if (this.remoteRefcount > 0) {
1610
+ this.session.sendRelease(this.importId, this.remoteRefcount);
1611
+ this.remoteRefcount = 0;
1612
+ }
1613
+ }
1614
+ };
1615
+ var RpcImportHook = class RpcImportHook extends StubHook {
1616
+ isPromise;
1617
+ entry;
1618
+ constructor(isPromise, entry) {
1619
+ super();
1620
+ this.isPromise = isPromise;
1621
+ ++entry.localRefcount;
1622
+ this.entry = entry;
1623
+ }
1624
+ collectPath(path) {
1625
+ return this;
1626
+ }
1627
+ getEntry() {
1628
+ if (this.entry) return this.entry;
1629
+ else throw new Error("This RpcImportHook was already disposed.");
1630
+ }
1631
+ call(path, args) {
1632
+ let entry = this.getEntry();
1633
+ if (entry.resolution) return entry.resolution.call(path, args);
1634
+ else return entry.session.sendCall(entry.importId, path, args);
1635
+ }
1636
+ stream(path, args) {
1637
+ let entry = this.getEntry();
1638
+ if (entry.resolution) return entry.resolution.stream(path, args);
1639
+ else return entry.session.sendStream(entry.importId, path, args);
1640
+ }
1641
+ map(path, captures, instructions) {
1642
+ let entry;
1643
+ try {
1644
+ entry = this.getEntry();
1645
+ } catch (err) {
1646
+ for (let cap of captures) cap.dispose();
1647
+ throw err;
1648
+ }
1649
+ if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1650
+ else return entry.session.sendMap(entry.importId, path, captures, instructions);
1651
+ }
1652
+ get(path) {
1653
+ let entry = this.getEntry();
1654
+ if (entry.resolution) return entry.resolution.get(path);
1655
+ else return entry.session.sendCall(entry.importId, path);
1656
+ }
1657
+ dup() {
1658
+ return new RpcImportHook(false, this.getEntry());
1659
+ }
1660
+ pull() {
1661
+ let entry = this.getEntry();
1662
+ if (!this.isPromise) throw new Error("Can't pull this hook because it's not a promise hook.");
1663
+ if (entry.resolution) return entry.resolution.pull();
1664
+ return entry.awaitResolution();
1665
+ }
1666
+ ignoreUnhandledRejections() {}
1667
+ dispose() {
1668
+ let entry = this.entry;
1669
+ this.entry = void 0;
1670
+ if (entry) {
1671
+ if (--entry.localRefcount === 0) entry.dispose();
1672
+ }
1673
+ }
1674
+ onBroken(callback) {
1675
+ if (this.entry) this.entry.onBroken(callback);
1676
+ }
1677
+ };
1678
+ var RpcMainHook = class extends RpcImportHook {
1679
+ session;
1680
+ constructor(entry) {
1681
+ super(false, entry);
1682
+ this.session = entry.session;
1683
+ }
1684
+ dispose() {
1685
+ if (this.session) {
1686
+ let session = this.session;
1687
+ this.session = void 0;
1688
+ session.shutdown();
1689
+ }
1690
+ }
1691
+ };
1692
+ var RpcSessionImpl = class {
1693
+ transport;
1694
+ options;
1695
+ exports = [];
1696
+ reverseExports = /* @__PURE__ */ new Map();
1697
+ imports = [];
1698
+ abortReason;
1699
+ cancelReadLoop;
1700
+ nextExportId = -1;
1701
+ onBatchDone;
1702
+ pullCount = 0;
1703
+ onBrokenCallbacks = [];
1704
+ encodingLevel;
1705
+ limits;
1706
+ constructor(transport, mainHook, options) {
1707
+ this.transport = transport;
1708
+ this.options = options;
1709
+ let level = "string";
1710
+ if ("encodingLevel" in transport) {
1711
+ let raw = transport.encodingLevel;
1712
+ if (raw !== void 0) {
1713
+ if (raw !== "string" && raw !== "jsonCompatible" && raw !== "jsonCompatibleWithBytes" && raw !== "structuredClonable") throw new TypeError(`Unknown transport encodingLevel: ${String(raw)}`);
1714
+ level = raw;
1715
+ }
1716
+ }
1717
+ this.encodingLevel = level;
1718
+ this.limits = {
1719
+ ...DEFAULT_LIMITS,
1720
+ ...options.limits
1721
+ };
1722
+ this.exports.push({
1723
+ hook: mainHook,
1724
+ refcount: 1
1725
+ });
1726
+ this.imports.push(new ImportTableEntry(this, 0, false));
1727
+ this.readLoop().catch((err) => this.abort(err));
1728
+ }
1729
+ getMainImport() {
1730
+ return new RpcMainHook(this.imports[0]);
1731
+ }
1732
+ shutdown() {
1733
+ this.abort(/* @__PURE__ */ new Error("RPC session was shut down by disposing the main stub"), false);
1734
+ }
1735
+ exportStub(hook) {
1736
+ if (this.abortReason) throw this.abortReason;
1737
+ let existingExportId = this.reverseExports.get(hook);
1738
+ if (existingExportId !== void 0) {
1739
+ ++this.exports[existingExportId].refcount;
1740
+ return existingExportId;
1741
+ } else {
1742
+ let exportId = this.nextExportId--;
1743
+ this.exports[exportId] = {
1744
+ hook,
1745
+ refcount: 1
1746
+ };
1747
+ this.reverseExports.set(hook, exportId);
1748
+ return exportId;
1749
+ }
1750
+ }
1751
+ exportPromise(hook) {
1752
+ if (this.abortReason) throw this.abortReason;
1753
+ let exportId = this.nextExportId--;
1754
+ this.exports[exportId] = {
1755
+ hook,
1756
+ refcount: 1
1757
+ };
1758
+ this.reverseExports.set(hook, exportId);
1759
+ this.ensureResolvingExport(exportId);
1760
+ return exportId;
1761
+ }
1762
+ unexport(ids) {
1763
+ for (let id of ids) this.releaseExport(id, 1);
1764
+ }
1765
+ releaseExport(exportId, refcount) {
1766
+ let entry = this.exports[exportId];
1767
+ if (!entry) throw new Error(`no such export ID: ${exportId}`);
1768
+ if (entry.refcount < refcount) throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);
1769
+ entry.refcount -= refcount;
1770
+ if (entry.refcount === 0) {
1771
+ delete this.exports[exportId];
1772
+ this.reverseExports.delete(entry.hook);
1773
+ entry.hook.dispose();
1774
+ }
1775
+ }
1776
+ onSendError(error) {
1777
+ if (this.options.onSendError) return this.options.onSendError(error);
1778
+ }
1779
+ ensureResolvingExport(exportId) {
1780
+ let exp = this.exports[exportId];
1781
+ if (!exp) throw new Error(`no such export ID: ${exportId}`);
1782
+ if (!exp.pull) {
1783
+ let resolve = async () => {
1784
+ let hook = exp.hook;
1785
+ for (;;) {
1786
+ let payload = await hook.pull();
1787
+ if (payload.value instanceof RpcStub$1) {
1788
+ let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);
1789
+ if (pathIfPromise && pathIfPromise.length == 0) {
1790
+ if (this.getImport(hook) === void 0) {
1791
+ hook = inner;
1792
+ continue;
1793
+ }
1794
+ }
1795
+ }
1796
+ return payload;
1797
+ }
1798
+ };
1799
+ let autoRelease = exp.autoRelease;
1800
+ ++this.pullCount;
1801
+ exp.pull = resolve().then((payload) => {
1802
+ let value = Devaluator.devaluate(payload.value, void 0, this, payload, this.encodingLevel);
1803
+ this.send([
1804
+ "resolve",
1805
+ exportId,
1806
+ value
1807
+ ]);
1808
+ if (autoRelease) this.releaseExport(exportId, 1);
1809
+ }, (error) => {
1810
+ this.send([
1811
+ "reject",
1812
+ exportId,
1813
+ Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)
1814
+ ]);
1815
+ if (autoRelease) this.releaseExport(exportId, 1);
1816
+ }).catch((error) => {
1817
+ try {
1818
+ this.send([
1819
+ "reject",
1820
+ exportId,
1821
+ Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)
1822
+ ]);
1823
+ if (autoRelease) this.releaseExport(exportId, 1);
1824
+ } catch (error2) {
1825
+ this.abort(error2);
1826
+ }
1827
+ }).finally(() => {
1828
+ if (--this.pullCount === 0) {
1829
+ if (this.onBatchDone) this.onBatchDone.resolve();
1830
+ }
1831
+ });
1832
+ }
1833
+ }
1834
+ getImport(hook) {
1835
+ if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this) return hook.entry.importId;
1836
+ else return;
1837
+ }
1838
+ importStub(idx) {
1839
+ if (this.abortReason) throw this.abortReason;
1840
+ let entry = this.imports[idx];
1841
+ if (!entry) {
1842
+ entry = new ImportTableEntry(this, idx, false);
1843
+ this.imports[idx] = entry;
1844
+ }
1845
+ return new RpcImportHook(false, entry);
1846
+ }
1847
+ importPromise(idx) {
1848
+ if (this.abortReason) throw this.abortReason;
1849
+ if (this.imports[idx]) return new ErrorStubHook(/* @__PURE__ */ new Error("Bug in RPC system: The peer sent a promise reusing an existing export ID."));
1850
+ let entry = new ImportTableEntry(this, idx, true);
1851
+ this.imports[idx] = entry;
1852
+ return new RpcImportHook(true, entry);
1853
+ }
1854
+ getExport(idx) {
1855
+ return this.exports[idx]?.hook;
1856
+ }
1857
+ getPipeReadable(exportId) {
1858
+ let entry = this.exports[exportId];
1859
+ if (!entry || !entry.pipeReadable) throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);
1860
+ let readable = entry.pipeReadable;
1861
+ entry.pipeReadable = void 0;
1862
+ return readable;
1863
+ }
1864
+ getLimits() {
1865
+ return this.limits;
1866
+ }
1867
+ createPipe(readable, readableHook) {
1868
+ if (this.abortReason) throw this.abortReason;
1869
+ this.send(["pipe"]);
1870
+ let importId = this.imports.length;
1871
+ let entry = new ImportTableEntry(this, importId, false);
1872
+ this.imports.push(entry);
1873
+ let hook = new RpcImportHook(false, entry);
1874
+ let writable = streamImpl.createWritableStreamFromHook(hook);
1875
+ readable.pipeTo(writable).catch(() => {}).finally(() => readableHook.dispose());
1876
+ return importId;
1877
+ }
1878
+ send(msg) {
1879
+ if (this.abortReason !== void 0) return 0;
1880
+ if (this.encodingLevel === "string") {
1881
+ let msgText;
1882
+ try {
1883
+ msgText = JSON.stringify(msg);
1884
+ } catch (err) {
1885
+ try {
1886
+ this.abort(err);
1887
+ } catch (err2) {}
1888
+ throw err;
1889
+ }
1890
+ try {
1891
+ let sent = this.transport.send(msgText);
1892
+ if (sent !== void 0 && typeof sent.catch === "function") sent.catch((err) => this.abort(err, false));
1893
+ } catch (err) {
1894
+ queueMicrotask(() => this.abort(err, false));
1895
+ }
1896
+ return msgText.length;
1897
+ } else try {
1898
+ let size = this.transport.send(msg);
1899
+ if (typeof size === "number") return size;
1900
+ let thenable = size;
1901
+ if (thenable && typeof thenable.then === "function") Promise.resolve(thenable).catch((err) => this.abort(err, false));
1902
+ return;
1903
+ } catch (err) {
1904
+ queueMicrotask(() => this.abort(err, false));
1905
+ return;
1906
+ }
1907
+ }
1908
+ sendCall(id, path, args) {
1909
+ if (this.abortReason) throw this.abortReason;
1910
+ let value = [
1911
+ "pipeline",
1912
+ id,
1913
+ path
1914
+ ];
1915
+ if (args) {
1916
+ let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
1917
+ value.push(devalue[0]);
1918
+ }
1919
+ this.send(["push", value]);
1920
+ let entry = new ImportTableEntry(this, this.imports.length, false);
1921
+ this.imports.push(entry);
1922
+ return new RpcImportHook(true, entry);
1923
+ }
1924
+ sendStream(id, path, args) {
1925
+ if (this.abortReason) throw this.abortReason;
1926
+ let value = [
1927
+ "pipeline",
1928
+ id,
1929
+ path
1930
+ ];
1931
+ let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
1932
+ value.push(devalue[0]);
1933
+ let msg = ["stream", value];
1934
+ let size = this.send(msg);
1935
+ if (size === void 0) size = estimateEncodedSize(msg);
1936
+ let importId = this.imports.length;
1937
+ let entry = new ImportTableEntry(this, importId, true);
1938
+ entry.remoteRefcount = 0;
1939
+ entry.localRefcount = 1;
1940
+ this.imports.push(entry);
1941
+ return {
1942
+ promise: entry.awaitResolution().then((p) => {
1943
+ p.dispose();
1944
+ delete this.imports[importId];
1945
+ }, (err) => {
1946
+ delete this.imports[importId];
1947
+ throw err;
1948
+ }),
1949
+ size
1950
+ };
1951
+ }
1952
+ sendMap(id, path, captures, instructions) {
1953
+ if (this.abortReason) {
1954
+ for (let cap of captures) cap.dispose();
1955
+ throw this.abortReason;
1956
+ }
1957
+ let value = [
1958
+ "remap",
1959
+ id,
1960
+ path,
1961
+ captures.map((hook) => {
1962
+ let importId = this.getImport(hook);
1963
+ if (importId !== void 0) return ["import", importId];
1964
+ else return ["export", this.exportStub(hook)];
1965
+ }),
1966
+ instructions
1967
+ ];
1968
+ this.send(["push", value]);
1969
+ let entry = new ImportTableEntry(this, this.imports.length, false);
1970
+ this.imports.push(entry);
1971
+ return new RpcImportHook(true, entry);
1972
+ }
1973
+ sendPull(id) {
1974
+ if (this.abortReason) throw this.abortReason;
1975
+ this.send(["pull", id]);
1976
+ }
1977
+ sendRelease(id, remoteRefcount) {
1978
+ if (this.abortReason) return;
1979
+ this.send([
1980
+ "release",
1981
+ id,
1982
+ remoteRefcount
1983
+ ]);
1984
+ delete this.imports[id];
1985
+ }
1986
+ abort(error, trySendAbortMessage = true) {
1987
+ if (this.abortReason !== void 0) return;
1988
+ this.cancelReadLoop?.(error);
1989
+ this.cancelReadLoop = void 0;
1990
+ if (trySendAbortMessage) try {
1991
+ let abortMsg = ["abort", Devaluator.devaluate(error, void 0, this, void 0, this.encodingLevel)];
1992
+ if (this.encodingLevel === "string") {
1993
+ let sent = this.transport.send(JSON.stringify(abortMsg));
1994
+ if (sent !== void 0 && typeof sent.catch === "function") sent.catch((err) => {});
1995
+ } else {
1996
+ let result = this.transport.send(abortMsg);
1997
+ if (result && typeof result.then === "function") Promise.resolve(result).catch((err) => {});
1998
+ }
1999
+ } catch (err) {}
2000
+ if (error === void 0) error = "undefined";
2001
+ this.abortReason = error;
2002
+ if (this.onBatchDone) this.onBatchDone.reject(error);
2003
+ if (this.transport.abort) try {
2004
+ this.transport.abort(error);
2005
+ } catch (err) {
2006
+ Promise.resolve(err);
2007
+ }
2008
+ for (let i in this.onBrokenCallbacks) try {
2009
+ this.onBrokenCallbacks[i](error);
2010
+ } catch (err) {
2011
+ Promise.resolve(err);
2012
+ }
2013
+ for (let i in this.imports) this.imports[i].abort(error);
2014
+ for (let i in this.exports) this.exports[i].hook.dispose();
2015
+ }
2016
+ async readLoop() {
2017
+ while (!this.abortReason) {
2018
+ let readCanceled = Promise.withResolvers();
2019
+ this.cancelReadLoop = readCanceled.reject;
2020
+ let raw;
2021
+ try {
2022
+ raw = await Promise.race([this.transport.receive(), readCanceled.promise]);
2023
+ } finally {
2024
+ if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;
2025
+ }
2026
+ if (this.encodingLevel === "string" && raw.length > this.limits.maxMessageSize) throw new TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);
2027
+ if (this.abortReason) break;
2028
+ let msg = this.encodingLevel === "string" ? JSON.parse(raw) : raw;
2029
+ if (msg instanceof Array) switch (msg[0]) {
2030
+ case "push":
2031
+ if (msg.length > 1) {
2032
+ let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2033
+ hook.ignoreUnhandledRejections();
2034
+ this.exports.push({
2035
+ hook,
2036
+ refcount: 1
2037
+ });
2038
+ continue;
2039
+ }
2040
+ break;
2041
+ case "stream":
2042
+ if (msg.length > 1) {
2043
+ let hook = new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[1]));
2044
+ hook.ignoreUnhandledRejections();
2045
+ let exportId = this.exports.length;
2046
+ this.exports.push({
2047
+ hook,
2048
+ refcount: 1,
2049
+ autoRelease: true
2050
+ });
2051
+ this.ensureResolvingExport(exportId);
2052
+ continue;
2053
+ }
2054
+ break;
2055
+ case "pipe": {
2056
+ let { readable, writable } = new TransformStream();
2057
+ let hook = streamImpl.createWritableStreamHook(writable);
2058
+ this.exports.push({
2059
+ hook,
2060
+ refcount: 1,
2061
+ pipeReadable: readable
2062
+ });
2063
+ continue;
2064
+ }
2065
+ case "pull": {
2066
+ let exportId = msg[1];
2067
+ if (typeof exportId == "number") {
2068
+ this.ensureResolvingExport(exportId);
2069
+ continue;
2070
+ }
2071
+ break;
2072
+ }
2073
+ case "resolve":
2074
+ case "reject": {
2075
+ let importId = msg[1];
2076
+ if (typeof importId == "number" && msg.length > 2) {
2077
+ let imp = this.imports[importId];
2078
+ if (imp) if (msg[0] == "resolve") imp.resolve(new PayloadStubHook(new Evaluator(this, this.encodingLevel).evaluate(msg[2])));
2079
+ else {
2080
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[2]);
2081
+ payload.dispose();
2082
+ imp.resolve(new ErrorStubHook(payload.value));
2083
+ }
2084
+ else if (msg[0] == "resolve") new Evaluator(this, this.encodingLevel).evaluate(msg[2]).dispose();
2085
+ continue;
2086
+ }
2087
+ break;
2088
+ }
2089
+ case "release": {
2090
+ let exportId = msg[1];
2091
+ let refcount = msg[2];
2092
+ if (typeof exportId == "number" && typeof refcount == "number") {
2093
+ this.releaseExport(exportId, refcount);
2094
+ continue;
2095
+ }
2096
+ break;
2097
+ }
2098
+ case "abort": {
2099
+ let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2100
+ payload.dispose();
2101
+ this.abort(payload.value, false);
2102
+ break;
2103
+ }
2104
+ }
2105
+ throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);
2106
+ }
2107
+ }
2108
+ async drain() {
2109
+ if (this.abortReason) throw this.abortReason;
2110
+ if (this.pullCount > 0) {
2111
+ let { promise, resolve, reject } = Promise.withResolvers();
2112
+ this.onBatchDone = {
2113
+ resolve,
2114
+ reject
2115
+ };
2116
+ await promise;
2117
+ }
2118
+ }
2119
+ getStats() {
2120
+ let result = {
2121
+ imports: 0,
2122
+ exports: 0
2123
+ };
2124
+ for (let i in this.imports) ++result.imports;
2125
+ for (let i in this.exports) ++result.exports;
2126
+ return result;
2127
+ }
2128
+ };
2129
+ var RpcSession$1 = class {
2130
+ #session;
2131
+ #mainStub;
2132
+ constructor(transport, localMain, options = {}) {
2133
+ let mainHook;
2134
+ if (localMain) mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain));
2135
+ else mainHook = new ErrorStubHook(/* @__PURE__ */ new Error("This connection has no main object."));
2136
+ this.#session = new RpcSessionImpl(transport, mainHook, options);
2137
+ this.#mainStub = new RpcStub$1(this.#session.getMainImport());
2138
+ }
2139
+ getRemoteMain() {
2140
+ return this.#mainStub;
2141
+ }
2142
+ getStats() {
2143
+ return this.#session.getStats();
2144
+ }
2145
+ drain() {
2146
+ return this.#session.drain();
2147
+ }
2148
+ };
2149
+
2150
+ //#endregion
2151
+ //#region src/websocket.ts
2152
+ /** Close-frame reason max UTF-8 bytes: 125 payload − 2-byte status (RFC 6455 §5.5). */
2153
+ const MAX_CLOSE_REASON_BYTES = 123;
2154
+ function newWebSocketRpcSession$1(webSocket, localMain, options) {
2155
+ if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2156
+ return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
2157
+ }
2158
+ /**
2159
+ * For use in Cloudflare Workers: Construct an HTTP response that starts a WebSocket RPC session
2160
+ * with the given `localMain`.
2161
+ */
2162
+ function newWorkersWebSocketRpcResponse(request, localMain, options) {
2163
+ if (request.headers.get("Upgrade")?.toLowerCase() !== "websocket") return new Response("This endpoint only accepts WebSocket requests.", { status: 400 });
2164
+ let pair = new WebSocketPair();
2165
+ let server = pair[0];
2166
+ server.accept();
2167
+ newWebSocketRpcSession$1(server, localMain, options);
2168
+ return new Response(null, {
2169
+ status: 101,
2170
+ webSocket: pair[1]
2171
+ });
2172
+ }
2173
+ /**
2174
+ * Generic WebSocket transport. Default `T = string` is backward-compatible and satisfies
2175
+ * `RpcTransport`. Use `T = ArrayBuffer` as a building block for binary transports.
2176
+ */
2177
+ var WebSocketTransport = class {
2178
+ constructor(webSocket) {
2179
+ this.#webSocket = webSocket;
2180
+ webSocket.binaryType = "arraybuffer";
2181
+ if (webSocket.readyState === WebSocket.CONNECTING) {
2182
+ this.#sendQueue = [];
2183
+ webSocket.addEventListener("open", (event) => {
2184
+ try {
2185
+ for (let message of this.#sendQueue) webSocket.send(message);
2186
+ } catch (err) {
2187
+ this.#receivedError(err);
2188
+ }
2189
+ this.#sendQueue = void 0;
2190
+ });
2191
+ }
2192
+ webSocket.addEventListener("message", (event) => {
2193
+ if (this.#error) {} else if (typeof event.data === "string" || event.data instanceof ArrayBuffer) if (this.#receiveResolver) {
2194
+ this.#receiveResolver(event.data);
2195
+ this.#receiveResolver = void 0;
2196
+ this.#receiveRejecter = void 0;
2197
+ } else this.#receiveQueue.push(event.data);
2198
+ else this.#receivedError(/* @__PURE__ */ new TypeError("Received unexpected message type from WebSocket."));
2199
+ });
2200
+ webSocket.addEventListener("close", (event) => {
2201
+ this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
2202
+ });
2203
+ webSocket.addEventListener("error", (event) => {
2204
+ this.#receivedError(/* @__PURE__ */ new Error(`WebSocket connection failed.`));
2205
+ });
2206
+ }
2207
+ #webSocket;
2208
+ #sendQueue;
2209
+ #receiveResolver;
2210
+ #receiveRejecter;
2211
+ #receiveQueue = [];
2212
+ #error;
2213
+ send(message) {
2214
+ if (this.#sendQueue === void 0) this.#webSocket.send(message);
2215
+ else this.#sendQueue.push(message);
2216
+ }
2217
+ receive() {
2218
+ if (this.#receiveQueue.length > 0) return Promise.resolve(this.#receiveQueue.shift());
2219
+ else if (this.#error) return Promise.reject(this.#error);
2220
+ else return new Promise((resolve, reject) => {
2221
+ this.#receiveResolver = resolve;
2222
+ this.#receiveRejecter = reject;
2223
+ });
2224
+ }
2225
+ abort(reason) {
2226
+ let message;
2227
+ if (reason instanceof Error) message = reason.message;
2228
+ else message = `${reason}`;
2229
+ let reasonBytes = new TextEncoder().encode(message);
2230
+ if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });
2231
+ this.#webSocket.close(3e3, message);
2232
+ if (!this.#error) this.#error = reason;
2233
+ }
2234
+ #receivedError(reason) {
2235
+ if (!this.#error) {
2236
+ this.#error = reason;
2237
+ if (this.#receiveRejecter) {
2238
+ this.#receiveRejecter(reason);
2239
+ this.#receiveResolver = void 0;
2240
+ this.#receiveRejecter = void 0;
2241
+ }
2242
+ }
2243
+ }
2244
+ };
2245
+
2246
+ //#endregion
2247
+ //#region src/batch.ts
2248
+ var BatchClientTransport = class {
2249
+ constructor(sendBatch) {
2250
+ this.#promise = this.#scheduleBatch(sendBatch);
2251
+ }
2252
+ #promise;
2253
+ #aborted;
2254
+ #batchToSend = [];
2255
+ #batchToReceive = null;
2256
+ send(message) {
2257
+ if (this.#batchToSend !== null) this.#batchToSend.push(message);
2258
+ }
2259
+ async receive() {
2260
+ if (!this.#batchToReceive) await this.#promise;
2261
+ let msg = this.#batchToReceive.shift();
2262
+ if (msg !== void 0) return msg;
2263
+ else throw new Error("Batch RPC request ended.");
2264
+ }
2265
+ abort(reason) {
2266
+ this.#aborted = reason;
2267
+ }
2268
+ async #scheduleBatch(sendBatch) {
2269
+ await new Promise((resolve) => setTimeout(resolve, 0));
2270
+ if (this.#aborted !== void 0) throw this.#aborted;
2271
+ let batch = this.#batchToSend;
2272
+ this.#batchToSend = null;
2273
+ this.#batchToReceive = await sendBatch(batch);
2274
+ }
2275
+ };
2276
+ function newHttpBatchRpcSession$1(urlOrRequest, options) {
2277
+ let sendBatch = async (batch) => {
2278
+ let response = await fetch(urlOrRequest, {
2279
+ method: "POST",
2280
+ body: batch.join("\n")
2281
+ });
2282
+ if (!response.ok) {
2283
+ response.body?.cancel();
2284
+ throw new Error(`RPC request failed: ${response.status} ${response.statusText}`);
2285
+ }
2286
+ let body = await response.text();
2287
+ return body == "" ? [] : body.split("\n");
2288
+ };
2289
+ return new RpcSession$1(new BatchClientTransport(sendBatch), void 0, options).getRemoteMain();
2290
+ }
2291
+ var BatchServerTransport = class {
2292
+ constructor(batch) {
2293
+ this.#batchToReceive = batch;
2294
+ }
2295
+ #batchToSend = [];
2296
+ #batchToReceive;
2297
+ #allReceived = Promise.withResolvers();
2298
+ send(message) {
2299
+ this.#batchToSend.push(message);
2300
+ }
2301
+ async receive() {
2302
+ let msg = this.#batchToReceive.shift();
2303
+ if (msg !== void 0) return msg;
2304
+ else {
2305
+ this.#allReceived.resolve();
2306
+ return new Promise((r) => {});
2307
+ }
2308
+ }
2309
+ abort(reason) {
2310
+ this.#allReceived.reject(reason);
2311
+ }
2312
+ whenAllReceived() {
2313
+ return this.#allReceived.promise;
2314
+ }
2315
+ getResponseBody() {
2316
+ return this.#batchToSend.join("\n");
2317
+ }
2318
+ };
2319
+ /**
2320
+ * Implements the server end of an HTTP batch session, using standard Fetch API types to represent
2321
+ * HTTP requests and responses.
2322
+ *
2323
+ * @param request The request received from the client initiating the session.
2324
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
2325
+ * @param options Optional RPC session options.
2326
+ * @returns The HTTP response to return to the client. Note that the returned object has mutable
2327
+ * headers, so you can modify them using e.g. `response.headers.set("Foo", "bar")`.
2328
+ */
2329
+ async function newHttpBatchRpcResponse(request, localMain, options) {
2330
+ if (request.method !== "POST") return new Response("This endpoint only accepts POST requests.", { status: 405 });
2331
+ let body = await request.text();
2332
+ let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2333
+ let rpc = new RpcSession$1(transport, localMain, options);
2334
+ await transport.whenAllReceived();
2335
+ await rpc.drain();
2336
+ return new Response(transport.getResponseBody());
2337
+ }
2338
+ /**
2339
+ * Implements the server end of an HTTP batch session using traditional Node.js HTTP APIs.
2340
+ *
2341
+ * @param request The request received from the client initiating the session.
2342
+ * @param response The response object, to which the response should be written.
2343
+ * @param localMain The main stub or RpcTarget which the server wishes to expose to the client.
2344
+ * @param options Optional RPC session options. You can also pass headers to set on the response.
2345
+ */
2346
+ async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2347
+ if (request.method !== "POST") {
2348
+ response.writeHead(405, "This endpoint only accepts POST requests.", options?.headers);
2349
+ response.end();
2350
+ return;
2351
+ }
2352
+ let body = await new Promise((resolve, reject) => {
2353
+ let chunks = [];
2354
+ request.on("data", (chunk) => {
2355
+ chunks.push(chunk);
2356
+ });
2357
+ request.on("end", () => {
2358
+ resolve(Buffer.concat(chunks).toString());
2359
+ });
2360
+ request.on("error", reject);
2361
+ });
2362
+ let transport = new BatchServerTransport(body === "" ? [] : body.split("\n"));
2363
+ let rpc = new RpcSession$1(transport, localMain, options);
2364
+ await transport.whenAllReceived();
2365
+ await rpc.drain();
2366
+ response.writeHead(200, options?.headers);
2367
+ response.end(transport.getResponseBody());
2368
+ }
2369
+
2370
+ //#endregion
2371
+ //#region src/messageport.ts
2372
+ function newMessagePortRpcSession$1(port, localMain, options) {
2373
+ return new RpcSession$1(new MessagePortTransport(port), localMain, options).getRemoteMain();
2374
+ }
2375
+ var MessagePortTransport = class {
2376
+ encodingLevel = "structuredClonable";
2377
+ constructor(port) {
2378
+ this.#port = port;
2379
+ port.start();
2380
+ port.addEventListener("message", (event) => {
2381
+ if (this.#error) {} else if (event.data === null) this.#receivedError(/* @__PURE__ */ new Error("Peer closed MessagePort connection."));
2382
+ else if (this.#receiveResolver) {
2383
+ this.#receiveResolver(event.data);
2384
+ this.#receiveResolver = void 0;
2385
+ this.#receiveRejecter = void 0;
2386
+ } else this.#receiveQueue.push(event.data);
2387
+ });
2388
+ port.addEventListener("messageerror", (event) => {
2389
+ this.#receivedError(/* @__PURE__ */ new Error("MessagePort message error."));
2390
+ });
2391
+ }
2392
+ #port;
2393
+ #receiveResolver;
2394
+ #receiveRejecter;
2395
+ #receiveQueue = [];
2396
+ #error;
2397
+ send(message) {
2398
+ if (this.#error) throw this.#error;
2399
+ this.#port.postMessage(message);
2400
+ }
2401
+ async receive() {
2402
+ if (this.#receiveQueue.length > 0) return this.#receiveQueue.shift();
2403
+ else if (this.#error) throw this.#error;
2404
+ else return new Promise((resolve, reject) => {
2405
+ this.#receiveResolver = resolve;
2406
+ this.#receiveRejecter = reject;
2407
+ });
2408
+ }
2409
+ abort(reason) {
2410
+ try {
2411
+ this.#port.postMessage(null);
2412
+ } catch (err) {}
2413
+ this.#port.close();
2414
+ if (!this.#error) this.#error = reason;
2415
+ }
2416
+ #receivedError(reason) {
2417
+ if (!this.#error) {
2418
+ this.#error = reason;
2419
+ if (this.#receiveRejecter) {
2420
+ this.#receiveRejecter(reason);
2421
+ this.#receiveResolver = void 0;
2422
+ this.#receiveRejecter = void 0;
2423
+ }
2424
+ }
2425
+ }
2426
+ };
2427
+
2428
+ //#endregion
2429
+ //#region src/map.ts
2430
+ let currentMapBuilder;
2431
+ var MapBuilder = class {
2432
+ context;
2433
+ captureMap = /* @__PURE__ */ new Map();
2434
+ instructions = [];
2435
+ constructor(subject, path) {
2436
+ if (currentMapBuilder) this.context = {
2437
+ parent: currentMapBuilder,
2438
+ captures: [],
2439
+ subject: currentMapBuilder.capture(subject),
2440
+ path
2441
+ };
2442
+ else this.context = {
2443
+ parent: void 0,
2444
+ captures: [],
2445
+ subject,
2446
+ path
2447
+ };
2448
+ currentMapBuilder = this;
2449
+ }
2450
+ unregister() {
2451
+ currentMapBuilder = this.context.parent;
2452
+ }
2453
+ makeInput() {
2454
+ return new MapVariableHook(this, 0);
2455
+ }
2456
+ makeOutput(result) {
2457
+ let devalued;
2458
+ try {
2459
+ devalued = Devaluator.devaluate(result.value, void 0, this, result);
2460
+ } finally {
2461
+ result.dispose();
2462
+ }
2463
+ this.instructions.push(devalued);
2464
+ if (this.context.parent) {
2465
+ this.context.parent.instructions.push([
2466
+ "remap",
2467
+ this.context.subject,
2468
+ this.context.path,
2469
+ this.context.captures.map((cap) => ["import", cap]),
2470
+ this.instructions
2471
+ ]);
2472
+ return new MapVariableHook(this.context.parent, this.context.parent.instructions.length);
2473
+ } else return this.context.subject.map(this.context.path, this.context.captures, this.instructions);
2474
+ }
2475
+ pushCall(hook, path, params) {
2476
+ let devalued = Devaluator.devaluate(params.value, void 0, this, params);
2477
+ devalued = devalued[0];
2478
+ let subject = this.capture(hook.dup());
2479
+ this.instructions.push([
2480
+ "pipeline",
2481
+ subject,
2482
+ path,
2483
+ devalued
2484
+ ]);
2485
+ return new MapVariableHook(this, this.instructions.length);
2486
+ }
2487
+ pushGet(hook, path) {
2488
+ let subject = this.capture(hook.dup());
2489
+ this.instructions.push([
2490
+ "pipeline",
2491
+ subject,
2492
+ path
2493
+ ]);
2494
+ return new MapVariableHook(this, this.instructions.length);
2495
+ }
2496
+ capture(hook) {
2497
+ if (hook instanceof MapVariableHook && hook.mapper === this) return hook.idx;
2498
+ let result = this.captureMap.get(hook);
2499
+ if (result === void 0) {
2500
+ if (this.context.parent) {
2501
+ let parentIdx = this.context.parent.capture(hook);
2502
+ this.context.captures.push(parentIdx);
2503
+ } else this.context.captures.push(hook);
2504
+ result = -this.context.captures.length;
2505
+ this.captureMap.set(hook, result);
2506
+ }
2507
+ return result;
2508
+ }
2509
+ exportStub(hook) {
2510
+ throw new Error("Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback.");
2511
+ }
2512
+ exportPromise(hook) {
2513
+ return this.exportStub(hook);
2514
+ }
2515
+ getImport(hook) {
2516
+ return this.capture(hook);
2517
+ }
2518
+ unexport(ids) {}
2519
+ createPipe(readable) {
2520
+ throw new Error("Cannot send ReadableStream inside a mapper function.");
2521
+ }
2522
+ onSendError(error) {}
2523
+ };
2524
+ mapImpl.sendMap = (hook, path, func) => {
2525
+ let builder = new MapBuilder(hook, path);
2526
+ let result;
2527
+ try {
2528
+ result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => {
2529
+ return func(new RpcPromise$1(builder.makeInput(), []));
2530
+ }));
2531
+ } finally {
2532
+ builder.unregister();
2533
+ }
2534
+ if (result instanceof Promise) {
2535
+ result.catch((err) => {});
2536
+ throw new Error("RPC map() callbacks cannot be async.");
2537
+ }
2538
+ return new RpcPromise$1(builder.makeOutput(result), []);
2539
+ };
2540
+ function throwMapperBuilderUseError() {
2541
+ throw new Error("Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects.");
2542
+ }
2543
+ var MapVariableHook = class extends StubHook {
2544
+ mapper;
2545
+ idx;
2546
+ constructor(mapper, idx) {
2547
+ super();
2548
+ this.mapper = mapper;
2549
+ this.idx = idx;
2550
+ }
2551
+ dup() {
2552
+ return this;
2553
+ }
2554
+ dispose() {}
2555
+ get(path) {
2556
+ if (path.length == 0) return this;
2557
+ else if (currentMapBuilder) return currentMapBuilder.pushGet(this, path);
2558
+ else throwMapperBuilderUseError();
2559
+ }
2560
+ call(path, args) {
2561
+ throwMapperBuilderUseError();
2562
+ }
2563
+ map(path, captures, instructions) {
2564
+ throwMapperBuilderUseError();
2565
+ }
2566
+ pull() {
2567
+ throwMapperBuilderUseError();
2568
+ }
2569
+ ignoreUnhandledRejections() {}
2570
+ onBroken(callback) {
2571
+ throwMapperBuilderUseError();
2572
+ }
2573
+ };
2574
+ var MapApplicator = class {
2575
+ captures;
2576
+ variables;
2577
+ constructor(captures, input) {
2578
+ this.captures = captures;
2579
+ this.variables = [input];
2580
+ }
2581
+ dispose() {
2582
+ for (let variable of this.variables) variable.dispose();
2583
+ }
2584
+ apply(instructions) {
2585
+ try {
2586
+ if (instructions.length < 1) throw new Error("Invalid empty mapper function.");
2587
+ for (let instruction of instructions.slice(0, -1)) {
2588
+ let payload = new Evaluator(this).evaluateCopy(instruction);
2589
+ if (payload.value instanceof RpcStub$1) {
2590
+ let hook = unwrapStubNoProperties(payload.value);
2591
+ if (hook) {
2592
+ this.variables.push(hook);
2593
+ continue;
2594
+ }
2595
+ }
2596
+ this.variables.push(new PayloadStubHook(payload));
2597
+ }
2598
+ return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);
2599
+ } finally {
2600
+ for (let variable of this.variables) variable.dispose();
2601
+ }
2602
+ }
2603
+ importStub(idx) {
2604
+ throw new Error("A mapper function cannot refer to exports.");
2605
+ }
2606
+ importPromise(idx) {
2607
+ return this.importStub(idx);
2608
+ }
2609
+ getExport(idx) {
2610
+ if (idx < 0) return this.captures[-idx - 1];
2611
+ else return this.variables[idx];
2612
+ }
2613
+ getPipeReadable(exportId) {
2614
+ throw new Error("A mapper function cannot use pipe readables.");
2615
+ }
2616
+ getLimits() {
2617
+ return DEFAULT_LIMITS;
2618
+ }
2619
+ };
2620
+ function applyMapToElement(input, parent, owner, captures, instructions) {
2621
+ let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
2622
+ try {
2623
+ return mapper.apply(instructions);
2624
+ } finally {
2625
+ mapper.dispose();
2626
+ }
2627
+ }
2628
+ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2629
+ try {
2630
+ let result;
2631
+ if (input instanceof RpcPromise$1) throw new Error("applyMap() can't be called on RpcPromise");
2632
+ else if (input instanceof Array) {
2633
+ let payloads = [];
2634
+ try {
2635
+ for (let elem of input) payloads.push(applyMapToElement(elem, input, owner, captures, instructions));
2636
+ } catch (err) {
2637
+ for (let payload of payloads) payload.dispose();
2638
+ throw err;
2639
+ }
2640
+ result = RpcPayload.fromArray(payloads);
2641
+ } else if (input === null || input === void 0) result = RpcPayload.fromAppReturn(input);
2642
+ else result = applyMapToElement(input, parent, owner, captures, instructions);
2643
+ return new PayloadStubHook(result);
2644
+ } finally {
2645
+ for (let cap of captures) cap.dispose();
2646
+ }
2647
+ };
2648
+
2649
+ //#endregion
2650
+ //#region src/streams.ts
2651
+ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2652
+ state;
2653
+ static create(stream) {
2654
+ return new WritableStreamStubHook({
2655
+ refcount: 1,
2656
+ writer: stream.getWriter(),
2657
+ closed: false
2658
+ });
2659
+ }
2660
+ constructor(state, dupFrom) {
2661
+ super();
2662
+ this.state = state;
2663
+ if (dupFrom) ++state.refcount;
2664
+ }
2665
+ getState() {
2666
+ if (this.state) return this.state;
2667
+ else throw new Error("Attempted to use a WritableStreamStubHook after it was disposed.");
2668
+ }
2669
+ call(path, args) {
2670
+ try {
2671
+ let state = this.getState();
2672
+ if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2673
+ const method = path[0];
2674
+ if (method !== "write" && method !== "close" && method !== "abort") {
2675
+ args.dispose();
2676
+ throw new Error(`Unknown WritableStream method: ${method}`);
2677
+ }
2678
+ if (method === "close" || method === "abort") state.closed = true;
2679
+ let func = state.writer[method];
2680
+ return new PromiseStubHook(args.deliverCall(func, state.writer).then((payload) => new PayloadStubHook(payload)));
2681
+ } catch (err) {
2682
+ return new ErrorStubHook(err);
2683
+ }
2684
+ }
2685
+ map(path, captures, instructions) {
2686
+ for (let cap of captures) cap.dispose();
2687
+ return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot use map() on a WritableStream"));
2688
+ }
2689
+ get(path) {
2690
+ return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot access properties on a WritableStream stub"));
2691
+ }
2692
+ dup() {
2693
+ return new WritableStreamStubHook(this.getState(), this);
2694
+ }
2695
+ pull() {
2696
+ return Promise.reject(/* @__PURE__ */ new Error("Cannot pull a WritableStream stub"));
2697
+ }
2698
+ ignoreUnhandledRejections() {}
2699
+ dispose() {
2700
+ let state = this.state;
2701
+ this.state = void 0;
2702
+ if (state) {
2703
+ if (--state.refcount === 0) {
2704
+ if (!state.closed) state.writer.abort(/* @__PURE__ */ new Error("WritableStream RPC stub was disposed without calling close()")).catch(() => {});
2705
+ state.writer.releaseLock();
2706
+ }
2707
+ }
2708
+ }
2709
+ onBroken(callback) {}
2710
+ };
2711
+ const INITIAL_WINDOW = 256 * 1024;
2712
+ const MAX_WINDOW = 1024 * 1024 * 1024;
2713
+ const MIN_WINDOW = 64 * 1024;
2714
+ const STARTUP_GROWTH_FACTOR = 2;
2715
+ const STEADY_GROWTH_FACTOR = 1.25;
2716
+ const DECAY_FACTOR = .9;
2717
+ const STARTUP_EXIT_ROUNDS = 3;
2718
+ var FlowController = class {
2719
+ now;
2720
+ window = INITIAL_WINDOW;
2721
+ bytesInFlight = 0;
2722
+ inStartupPhase = true;
2723
+ delivered = 0;
2724
+ deliveredTime = 0;
2725
+ firstAckTime = 0;
2726
+ firstAckDelivered = 0;
2727
+ minRtt = Infinity;
2728
+ roundsWithoutIncrease = 0;
2729
+ lastRoundWindow = 0;
2730
+ roundStartTime = 0;
2731
+ constructor(now) {
2732
+ this.now = now;
2733
+ }
2734
+ onSend(size) {
2735
+ this.bytesInFlight += size;
2736
+ let token = {
2737
+ sentTime: this.now(),
2738
+ size,
2739
+ deliveredAtSend: this.delivered,
2740
+ deliveredTimeAtSend: this.deliveredTime,
2741
+ windowAtSend: this.window,
2742
+ windowFullAtSend: this.bytesInFlight >= this.window
2743
+ };
2744
+ return {
2745
+ token,
2746
+ shouldBlock: token.windowFullAtSend
2747
+ };
2748
+ }
2749
+ onError(token) {
2750
+ this.bytesInFlight -= token.size;
2751
+ }
2752
+ onAck(token) {
2753
+ let ackTime = this.now();
2754
+ this.delivered += token.size;
2755
+ this.deliveredTime = ackTime;
2756
+ this.bytesInFlight -= token.size;
2757
+ let rtt = ackTime - token.sentTime;
2758
+ this.minRtt = Math.min(this.minRtt, rtt);
2759
+ if (this.firstAckTime === 0) {
2760
+ this.firstAckTime = ackTime;
2761
+ this.firstAckDelivered = this.delivered;
2762
+ } else {
2763
+ let baseTime;
2764
+ let baseDelivered;
2765
+ if (token.deliveredTimeAtSend === 0) {
2766
+ baseTime = this.firstAckTime;
2767
+ baseDelivered = this.firstAckDelivered;
2768
+ } else {
2769
+ baseTime = token.deliveredTimeAtSend;
2770
+ baseDelivered = token.deliveredAtSend;
2771
+ }
2772
+ let interval = ackTime - baseTime;
2773
+ let bandwidth = (this.delivered - baseDelivered) / interval;
2774
+ let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;
2775
+ let newWindow = bandwidth * this.minRtt * growthFactor;
2776
+ newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);
2777
+ if (token.windowFullAtSend) newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);
2778
+ else newWindow = Math.max(newWindow, this.window);
2779
+ this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);
2780
+ if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {
2781
+ if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) this.roundsWithoutIncrease = 0;
2782
+ else if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) this.inStartupPhase = false;
2783
+ this.roundStartTime = ackTime;
2784
+ this.lastRoundWindow = this.window;
2785
+ }
2786
+ }
2787
+ return this.bytesInFlight < this.window;
2788
+ }
2789
+ };
2790
+ function createWritableStreamFromHook(hook) {
2791
+ let pendingError = void 0;
2792
+ let hookDisposed = false;
2793
+ let fc = new FlowController(() => performance.now());
2794
+ let windowResolve;
2795
+ let windowReject;
2796
+ const disposeHook = () => {
2797
+ if (!hookDisposed) {
2798
+ hookDisposed = true;
2799
+ hook.dispose();
2800
+ }
2801
+ };
2802
+ return new WritableStream({
2803
+ write(chunk, controller) {
2804
+ if (pendingError !== void 0) throw pendingError;
2805
+ const payload = RpcPayload.fromAppParams([chunk]);
2806
+ const { promise, size } = hook.stream(["write"], payload);
2807
+ if (size === void 0) return promise.catch((err) => {
2808
+ if (pendingError === void 0) pendingError = err;
2809
+ throw err;
2810
+ });
2811
+ else {
2812
+ let { token, shouldBlock } = fc.onSend(size);
2813
+ promise.then(() => {
2814
+ if (fc.onAck(token) && windowResolve) {
2815
+ windowResolve();
2816
+ windowResolve = void 0;
2817
+ windowReject = void 0;
2818
+ }
2819
+ }, (err) => {
2820
+ fc.onError(token);
2821
+ if (pendingError === void 0) {
2822
+ pendingError = err;
2823
+ controller.error(err);
2824
+ disposeHook();
2825
+ }
2826
+ if (windowReject) {
2827
+ windowReject(err);
2828
+ windowResolve = void 0;
2829
+ windowReject = void 0;
2830
+ }
2831
+ });
2832
+ if (shouldBlock) return new Promise((resolve, reject) => {
2833
+ windowResolve = resolve;
2834
+ windowReject = reject;
2835
+ });
2836
+ }
2837
+ },
2838
+ async close() {
2839
+ if (pendingError !== void 0) {
2840
+ disposeHook();
2841
+ throw pendingError;
2842
+ }
2843
+ const { promise } = hook.stream(["close"], RpcPayload.fromAppParams([]));
2844
+ try {
2845
+ await promise;
2846
+ } catch (err) {
2847
+ throw pendingError ?? err;
2848
+ } finally {
2849
+ disposeHook();
2850
+ }
2851
+ },
2852
+ abort(reason) {
2853
+ if (pendingError !== void 0) return;
2854
+ pendingError = reason ?? /* @__PURE__ */ new Error("WritableStream was aborted");
2855
+ if (windowReject) {
2856
+ windowReject(pendingError);
2857
+ windowResolve = void 0;
2858
+ windowReject = void 0;
2859
+ }
2860
+ const { promise } = hook.stream(["abort"], RpcPayload.fromAppParams([reason]));
2861
+ promise.then(() => disposeHook(), () => disposeHook());
2862
+ }
2863
+ });
2864
+ }
2865
+ var ReadableStreamStubHook = class ReadableStreamStubHook extends StubHook {
2866
+ state;
2867
+ static create(stream) {
2868
+ return new ReadableStreamStubHook({
2869
+ refcount: 1,
2870
+ stream,
2871
+ canceled: false
2872
+ });
2873
+ }
2874
+ constructor(state, dupFrom) {
2875
+ super();
2876
+ this.state = state;
2877
+ if (dupFrom) ++state.refcount;
2878
+ }
2879
+ call(path, args) {
2880
+ args.dispose();
2881
+ return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot call methods on a ReadableStream stub"));
2882
+ }
2883
+ map(path, captures, instructions) {
2884
+ for (let cap of captures) cap.dispose();
2885
+ return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot use map() on a ReadableStream"));
2886
+ }
2887
+ get(path) {
2888
+ return new ErrorStubHook(/* @__PURE__ */ new Error("Cannot access properties on a ReadableStream stub"));
2889
+ }
2890
+ dup() {
2891
+ let state = this.state;
2892
+ if (!state) throw new Error("Attempted to dup a ReadableStreamStubHook after it was disposed.");
2893
+ return new ReadableStreamStubHook(state, this);
2894
+ }
2895
+ pull() {
2896
+ return Promise.reject(/* @__PURE__ */ new Error("Cannot pull a ReadableStream stub"));
2897
+ }
2898
+ ignoreUnhandledRejections() {}
2899
+ dispose() {
2900
+ let state = this.state;
2901
+ this.state = void 0;
2902
+ if (state) {
2903
+ if (--state.refcount === 0) {
2904
+ if (!state.canceled) {
2905
+ state.canceled = true;
2906
+ if (!state.stream.locked) state.stream.cancel(/* @__PURE__ */ new Error("ReadableStream RPC stub was disposed without being consumed")).catch(() => {});
2907
+ }
2908
+ }
2909
+ }
2910
+ }
2911
+ onBroken(callback) {}
2912
+ };
2913
+ streamImpl.createWritableStreamHook = WritableStreamStubHook.create;
2914
+ streamImpl.createWritableStreamFromHook = createWritableStreamFromHook;
2915
+ streamImpl.createReadableStreamHook = ReadableStreamStubHook.create;
2916
+
2917
+ //#endregion
2918
+ //#region src/index.ts
2919
+ const RpcStub = RpcStub$1;
2920
+ const RpcPromise = RpcPromise$1;
2921
+ const RpcSession = RpcSession$1;
2922
+ const RpcTarget = RpcTarget$1;
2923
+ /**
2924
+ * Start a WebSocket session given either an already-open WebSocket or a URL.
2925
+ *
2926
+ * @param webSocket Either the `wss://` URL to connect to, or an already-open WebSocket object to
2927
+ * use.
2928
+ * @param localMain The main RPC interface to expose to the peer. Returns a stub for the main
2929
+ * interface exposed from the peer.
2930
+ */
2931
+ let newWebSocketRpcSession = newWebSocketRpcSession$1;
2932
+ /**
2933
+ * Initiate an HTTP batch session from the client side.
2934
+ *
2935
+ * The parameters to this method have exactly the same signature as `fetch()`, but the return
2936
+ * value is an RpcStub. You can customize anything about the request except for the method
2937
+ * (it will always be set to POST) and the body (which the RPC system will fill in).
2938
+ */
2939
+ let newHttpBatchRpcSession = newHttpBatchRpcSession$1;
2940
+ /**
2941
+ * Initiate an RPC session over a MessagePort, which is particularly useful for communicating
2942
+ * between an iframe and its parent frame in a browser context. Each side should call this function
2943
+ * on its own end of the MessageChannel.
2944
+ */
2945
+ let newMessagePortRpcSession = newMessagePortRpcSession$1;
2946
+ /**
2947
+ * Implements unified handling of HTTP-batch and WebSocket responses for the Cloudflare Workers
2948
+ * Runtime.
2949
+ *
2950
+ * SECURITY WARNING: This function accepts cross-origin requests. If you do not want this, you
2951
+ * should validate the `Origin` header before calling this, or use `newHttpBatchRpcSession()` and
2952
+ * `newWebSocketRpcSession()` directly with appropriate security measures for each type of request.
2953
+ * But if your API uses in-band authorization (i.e. it has an RPC method that takes the user's
2954
+ * credentials as parameters and returns the authorized API), then cross-origin requests should
2955
+ * be safe.
2956
+ */
2957
+ async function newWorkersRpcResponse(request, localMain, options) {
2958
+ if (request.method === "POST") {
2959
+ let response = await newHttpBatchRpcResponse(request, localMain, options);
2960
+ response.headers.set("Access-Control-Allow-Origin", "*");
2961
+ return response;
2962
+ } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain, options);
2963
+ else return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
2964
+ }
2965
+
2966
+ //#endregion
2967
+ //#region src/bun.ts
2968
+ /**
2969
+ * Start an RPC session over a Bun ServerWebSocket.
2970
+ *
2971
+ * Returns both the stub and the transport. The transport must be wired to Bun's
2972
+ * `WebSocketHandler` callbacks (`message`, `close`, `error`) by calling its
2973
+ * `dispatchMessage`, `dispatchClose`, and `dispatchError` methods.
2974
+ *
2975
+ * For a zero-wiring alternative, see `newBunWebSocketRpcHandler`.
2976
+ */
2977
+ function newBunWebSocketRpcSession$1(ws, localMain, options) {
2978
+ let transport = new BunWebSocketTransport(ws);
2979
+ return {
2980
+ stub: new RpcSession$1(transport, localMain, options).getRemoteMain(),
2981
+ transport
2982
+ };
2983
+ }
2984
+ /**
2985
+ * Create a Bun `WebSocketHandler` object that manages RPC sessions automatically.
2986
+ *
2987
+ * The returned object can be passed directly as the `websocket` option to `Bun.serve()`.
2988
+ * A fresh `localMain` is created for each connection via the `createMain` callback.
2989
+ * The transport is stored on `ws.data.__capnwebTransport`.
2990
+ *
2991
+ * @param createMain Called once per connection to create the main RPC interface for that client.
2992
+ * @param options Optional RPC session options applied to every connection.
2993
+ */
2994
+ function newBunWebSocketRpcHandler(createMain, options) {
2995
+ return {
2996
+ open(ws) {
2997
+ let transport = new BunWebSocketTransport(ws);
2998
+ ws.data = {
2999
+ __capnwebTransport: transport,
3000
+ __capnwebStub: new RpcSession$1(transport, createMain(), options).getRemoteMain()
3001
+ };
3002
+ },
3003
+ message(ws, message) {
3004
+ ws.data.__capnwebTransport.dispatchMessage(message);
3005
+ },
3006
+ close(ws, code, reason) {
3007
+ ws.data.__capnwebTransport.dispatchClose(code, reason);
3008
+ },
3009
+ error(ws, error) {
3010
+ ws.data.__capnwebTransport.dispatchError(error);
3011
+ }
3012
+ };
3013
+ }
3014
+ var BunWebSocketTransport = class {
3015
+ constructor(ws) {
3016
+ this.#ws = ws;
3017
+ }
3018
+ #ws;
3019
+ #receiveResolver;
3020
+ #receiveRejecter;
3021
+ #receiveQueue = [];
3022
+ #error;
3023
+ async send(message) {
3024
+ this.#ws.send(message);
3025
+ }
3026
+ async receive() {
3027
+ if (this.#receiveQueue.length > 0) return this.#receiveQueue.shift();
3028
+ else if (this.#error) throw this.#error;
3029
+ else return new Promise((resolve, reject) => {
3030
+ this.#receiveResolver = resolve;
3031
+ this.#receiveRejecter = reject;
3032
+ });
3033
+ }
3034
+ abort(reason) {
3035
+ let message;
3036
+ if (reason instanceof Error) message = reason.message;
3037
+ else message = `${reason}`;
3038
+ this.#ws.close(3e3, message);
3039
+ if (!this.#error) this.#error = reason;
3040
+ }
3041
+ dispatchMessage(data) {
3042
+ if (this.#error) return;
3043
+ let strData = typeof data === "string" ? data : data.toString("utf-8");
3044
+ if (this.#receiveResolver) {
3045
+ this.#receiveResolver(strData);
3046
+ this.#receiveResolver = void 0;
3047
+ this.#receiveRejecter = void 0;
3048
+ } else this.#receiveQueue.push(strData);
3049
+ }
3050
+ dispatchClose(code, reason) {
3051
+ this.#receivedError(/* @__PURE__ */ new Error(`Peer closed WebSocket: ${code} ${reason}`));
3052
+ }
3053
+ dispatchError(error) {
3054
+ this.#receivedError(/* @__PURE__ */ new Error(`WebSocket connection failed.`));
3055
+ }
3056
+ #receivedError(reason) {
3057
+ if (!this.#error) {
3058
+ this.#error = reason;
3059
+ if (this.#receiveRejecter) {
3060
+ this.#receiveRejecter(reason);
3061
+ this.#receiveResolver = void 0;
3062
+ this.#receiveRejecter = void 0;
3063
+ }
3064
+ }
3065
+ }
3066
+ };
3067
+
3068
+ //#endregion
3069
+ //#region src/index-bun.ts
3070
+ /**
3071
+ * Start an RPC session over a Bun ServerWebSocket.
3072
+ *
3073
+ * Returns both the RPC stub and the transport. The transport exposes `dispatchMessage`,
3074
+ * `dispatchClose`, and `dispatchError` methods that must be wired to Bun's `WebSocketHandler`
3075
+ * callbacks. For a zero-wiring alternative, use `newBunWebSocketRpcHandler` instead.
3076
+ *
3077
+ * @param ws The Bun ServerWebSocket from the `open` callback.
3078
+ * @param localMain The main RPC interface to expose to the peer.
3079
+ */
3080
+ let newBunWebSocketRpcSession = newBunWebSocketRpcSession$1;
3081
+
3082
+ //#endregion
3083
+ export { BunWebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, RpcPromise, RpcSession, RpcStub, RpcTarget, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
3084
+ //# sourceMappingURL=index-bun.js.map