@fungi.computer/capnweb 0.0.0-stage → 0.12.0

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