capnweb 0.0.0-8a47045 → 0.0.0-9e499e2

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.
@@ -23,15 +23,15 @@ function _interopNamespace(e) {
23
23
  var cfw__namespace = /*#__PURE__*/_interopNamespace(cfw);
24
24
 
25
25
  // src/symbols.ts
26
- var WORKERS_MODULE_SYMBOL = Symbol("workers-module");
26
+ var WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol("workers-module");
27
27
  globalThis[WORKERS_MODULE_SYMBOL] = cfw__namespace;
28
28
 
29
29
  // src/core.ts
30
30
  if (!Symbol.dispose) {
31
- Symbol.dispose = Symbol.for("dispose");
31
+ Symbol.dispose = /* @__PURE__ */ Symbol.for("dispose");
32
32
  }
33
33
  if (!Symbol.asyncDispose) {
34
- Symbol.asyncDispose = Symbol.for("asyncDispose");
34
+ Symbol.asyncDispose = /* @__PURE__ */ Symbol.for("asyncDispose");
35
35
  }
36
36
  if (!Promise.withResolvers) {
37
37
  Promise.withResolvers = function() {
@@ -47,6 +47,9 @@ if (!Promise.withResolvers) {
47
47
  var workersModule = globalThis[WORKERS_MODULE_SYMBOL];
48
48
  var RpcTarget = workersModule ? workersModule.RpcTarget : class {
49
49
  };
50
+ var AsyncFunction = (async function() {
51
+ }).constructor;
52
+ var BUFFER_PROTOTYPE = typeof Buffer !== "undefined" ? Buffer.prototype : void 0;
50
53
  function typeForRpc(value) {
51
54
  switch (typeof value) {
52
55
  case "boolean":
@@ -71,13 +74,27 @@ function typeForRpc(value) {
71
74
  case Object.prototype:
72
75
  return "object";
73
76
  case Function.prototype:
77
+ case AsyncFunction.prototype:
74
78
  return "function";
75
79
  case Array.prototype:
76
80
  return "array";
77
81
  case Date.prototype:
78
82
  return "date";
79
83
  case Uint8Array.prototype:
84
+ case BUFFER_PROTOTYPE:
80
85
  return "bytes";
86
+ case WritableStream.prototype:
87
+ return "writable";
88
+ case ReadableStream.prototype:
89
+ return "readable";
90
+ case Headers.prototype:
91
+ return "headers";
92
+ case Request.prototype:
93
+ return "request";
94
+ case Response.prototype:
95
+ return "response";
96
+ case Blob.prototype:
97
+ return "blob";
81
98
  // TODO: All other structured clone types.
82
99
  case RpcStub.prototype:
83
100
  return "stub";
@@ -105,7 +122,34 @@ function mapNotLoaded() {
105
122
  throw new Error("RPC map() implementation was not loaded.");
106
123
  }
107
124
  var mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded };
125
+ function streamNotLoaded() {
126
+ throw new Error("Stream implementation was not loaded.");
127
+ }
128
+ var streamImpl = {
129
+ createWritableStreamHook: streamNotLoaded,
130
+ createWritableStreamFromHook: streamNotLoaded,
131
+ createReadableStreamHook: streamNotLoaded
132
+ };
108
133
  var StubHook = class {
134
+ // Like call(), but designed for streaming calls (e.g. WritableStream writes). Returns:
135
+ // - promise: A Promise<void> for the completion of the call.
136
+ // - size: If the call was remote, the byte size of the serialized message. For local calls,
137
+ // undefined is returned, indicating the caller should await the promise to serialize writes
138
+ // (no overlapping).
139
+ stream(path, args) {
140
+ let hook = this.call(path, args);
141
+ let pulled = hook.pull();
142
+ let promise;
143
+ if (pulled instanceof Promise) {
144
+ promise = pulled.then((p) => {
145
+ p.dispose();
146
+ });
147
+ } else {
148
+ pulled.dispose();
149
+ promise = Promise.resolve();
150
+ }
151
+ return { promise };
152
+ }
109
153
  };
110
154
  var ErrorStubHook = class extends StubHook {
111
155
  constructor(error) {
@@ -154,7 +198,7 @@ function withCallInterceptor(interceptor, callback) {
154
198
  doCall = oldValue;
155
199
  }
156
200
  }
157
- var RAW_STUB = Symbol("realStub");
201
+ var RAW_STUB = /* @__PURE__ */ Symbol("realStub");
158
202
  var PROXY_HANDLERS = {
159
203
  apply(target, thisArg, argumentsList) {
160
204
  let stub = target.raw;
@@ -330,10 +374,10 @@ async function pullPromise(promise) {
330
374
  }
331
375
  var RpcPayload = class _RpcPayload {
332
376
  // Private constructor; use factory functions above to construct.
333
- constructor(value, source, stubs, promises) {
377
+ constructor(value, source, hooks, promises) {
334
378
  this.value = value;
335
379
  this.source = source;
336
- this.stubs = stubs;
380
+ this.hooks = hooks;
337
381
  this.promises = promises;
338
382
  }
339
383
  // Create a payload from a value passed as params to an RPC from the app.
@@ -358,13 +402,13 @@ var RpcPayload = class _RpcPayload {
358
402
  // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the
359
403
  // inputs should not be. (In case of exception, nothing is disposed, though.)
360
404
  static fromArray(array) {
361
- let stubs = [];
405
+ let hooks = [];
362
406
  let promises = [];
363
407
  let resultArray = [];
364
408
  for (let payload of array) {
365
409
  payload.ensureDeepCopied();
366
- for (let stub of payload.stubs) {
367
- stubs.push(stub);
410
+ for (let hook of payload.hooks) {
411
+ hooks.push(hook);
368
412
  }
369
413
  for (let promise of payload.promises) {
370
414
  if (promise.parent === payload) {
@@ -378,12 +422,12 @@ var RpcPayload = class _RpcPayload {
378
422
  }
379
423
  resultArray.push(payload.value);
380
424
  }
381
- return new _RpcPayload(resultArray, "owned", stubs, promises);
425
+ return new _RpcPayload(resultArray, "owned", hooks, promises);
382
426
  }
383
427
  // Create a payload from a value parsed off the wire using Evaluator.evaluate().
384
428
  //
385
- // A payload is constructed with a null value and the given stubs and promises arrays. The value
386
- // is expected to be filled in by the evaluator, and the stubs and promises arrays are expected
429
+ // A payload is constructed with a null value and the given hooks and promises arrays. The value
430
+ // is expected to be filled in by the evaluator, and the hooks and promises arrays are expected
387
431
  // to be extended with stubs found during parsing. (This weird usage model is necessary so that
388
432
  // if the root value turns out to be a promise, its `parent` in `promises` can be the payload
389
433
  // object itself.)
@@ -391,8 +435,8 @@ var RpcPayload = class _RpcPayload {
391
435
  // When done, the payload takes ownership of the final value and all the stubs within. It may
392
436
  // modify the value in preparation for delivery, and may deliver the value directly to the app
393
437
  // without copying.
394
- static forEvaluate(stubs, promises) {
395
- return new _RpcPayload(null, "owned", stubs, promises);
438
+ static forEvaluate(hooks, promises) {
439
+ return new _RpcPayload(null, "owned", hooks, promises);
396
440
  }
397
441
  // Deep-copy the given value, including dup()ing all stubs.
398
442
  //
@@ -414,14 +458,20 @@ var RpcPayload = class _RpcPayload {
414
458
  return result;
415
459
  }
416
460
  // For `source === "return"` payloads only, this tracks any StubHooks created around RpcTargets
417
- // found in the payload at the time that it is serialized (or deep-copied) for return, so that we
418
- // can make sure they are not disposed before the pipeline ends.
461
+ // or WritableStreams found in the payload at the time that it is serialized (or deep-copied) for
462
+ // return, so that we can make sure they are not disposed before the pipeline ends.
419
463
  //
420
464
  // This is initialized on first use.
421
465
  rpcTargets;
422
466
  // Get the StubHook representing the given RpcTarget found inside this payload.
423
467
  getHookForRpcTarget(target, parent, dupStubs = true) {
424
468
  if (this.source === "params") {
469
+ if (dupStubs) {
470
+ let dupable = target;
471
+ if (typeof dupable.dup === "function") {
472
+ target = dupable.dup();
473
+ }
474
+ }
425
475
  return TargetStubHook.create(target, parent);
426
476
  } else if (this.source === "return") {
427
477
  let hook = this.rpcTargets?.get(target);
@@ -448,6 +498,64 @@ var RpcPayload = class _RpcPayload {
448
498
  throw new Error("owned payload shouldn't contain raw RpcTargets");
449
499
  }
450
500
  }
501
+ // Get the StubHook representing the given WritableStream found inside this payload.
502
+ getHookForWritableStream(stream, parent, dupStubs = true) {
503
+ if (this.source === "params") {
504
+ return streamImpl.createWritableStreamHook(stream);
505
+ } else if (this.source === "return") {
506
+ let hook = this.rpcTargets?.get(stream);
507
+ if (hook) {
508
+ if (dupStubs) {
509
+ return hook.dup();
510
+ } else {
511
+ this.rpcTargets?.delete(stream);
512
+ return hook;
513
+ }
514
+ } else {
515
+ hook = streamImpl.createWritableStreamHook(stream);
516
+ if (dupStubs) {
517
+ if (!this.rpcTargets) {
518
+ this.rpcTargets = /* @__PURE__ */ new Map();
519
+ }
520
+ this.rpcTargets.set(stream, hook);
521
+ return hook.dup();
522
+ } else {
523
+ return hook;
524
+ }
525
+ }
526
+ } else {
527
+ throw new Error("owned payload shouldn't contain raw WritableStreams");
528
+ }
529
+ }
530
+ // Get the StubHook representing the given ReadableStream found inside this payload.
531
+ getHookForReadableStream(stream, parent, dupStubs = true) {
532
+ if (this.source === "params") {
533
+ return streamImpl.createReadableStreamHook(stream);
534
+ } else if (this.source === "return") {
535
+ let hook = this.rpcTargets?.get(stream);
536
+ if (hook) {
537
+ if (dupStubs) {
538
+ return hook.dup();
539
+ } else {
540
+ this.rpcTargets?.delete(stream);
541
+ return hook;
542
+ }
543
+ } else {
544
+ hook = streamImpl.createReadableStreamHook(stream);
545
+ if (dupStubs) {
546
+ if (!this.rpcTargets) {
547
+ this.rpcTargets = /* @__PURE__ */ new Map();
548
+ }
549
+ this.rpcTargets.set(stream, hook);
550
+ return hook.dup();
551
+ } else {
552
+ return hook;
553
+ }
554
+ }
555
+ } else {
556
+ throw new Error("owned payload shouldn't contain raw ReadableStreams");
557
+ }
558
+ }
451
559
  deepCopy(value, oldParent, property, parent, dupStubs, owner) {
452
560
  let kind = typeForRpc(value);
453
561
  switch (kind) {
@@ -457,6 +565,7 @@ var RpcPayload = class _RpcPayload {
457
565
  case "bigint":
458
566
  case "date":
459
567
  case "bytes":
568
+ case "blob":
460
569
  case "error":
461
570
  case "undefined":
462
571
  return value;
@@ -491,22 +600,21 @@ var RpcPayload = class _RpcPayload {
491
600
  this.promises.push({ parent, property, promise });
492
601
  return promise;
493
602
  } else {
494
- let newStub = new RpcStub(hook);
495
- this.stubs.push(newStub);
496
- return newStub;
603
+ this.hooks.push(hook);
604
+ return new RpcStub(hook);
497
605
  }
498
606
  }
499
607
  case "function":
500
608
  case "rpc-target": {
501
609
  let target = value;
502
- let stub;
610
+ let hook;
503
611
  if (owner) {
504
- stub = new RpcStub(owner.getHookForRpcTarget(target, oldParent, dupStubs));
612
+ hook = owner.getHookForRpcTarget(target, oldParent, dupStubs);
505
613
  } else {
506
- stub = new RpcStub(TargetStubHook.create(target, oldParent));
614
+ hook = TargetStubHook.create(target, oldParent);
507
615
  }
508
- this.stubs.push(stub);
509
- return stub;
616
+ this.hooks.push(hook);
617
+ return new RpcStub(hook);
510
618
  }
511
619
  case "rpc-thenable": {
512
620
  let target = value;
@@ -519,6 +627,44 @@ var RpcPayload = class _RpcPayload {
519
627
  this.promises.push({ parent, property, promise });
520
628
  return promise;
521
629
  }
630
+ case "writable": {
631
+ let stream = value;
632
+ let hook;
633
+ if (owner) {
634
+ hook = owner.getHookForWritableStream(stream, oldParent, dupStubs);
635
+ } else {
636
+ hook = streamImpl.createWritableStreamHook(stream);
637
+ }
638
+ this.hooks.push(hook);
639
+ return stream;
640
+ }
641
+ case "readable": {
642
+ let stream = value;
643
+ let hook;
644
+ if (owner) {
645
+ hook = owner.getHookForReadableStream(stream, oldParent, dupStubs);
646
+ } else {
647
+ hook = streamImpl.createReadableStreamHook(stream);
648
+ }
649
+ this.hooks.push(hook);
650
+ return stream;
651
+ }
652
+ case "headers":
653
+ return new Headers(value);
654
+ case "request": {
655
+ let req = value;
656
+ if (req.body) {
657
+ this.deepCopy(req.body, req, "body", req, dupStubs, owner);
658
+ }
659
+ return new Request(req);
660
+ }
661
+ case "response": {
662
+ let resp = value;
663
+ if (resp.body) {
664
+ this.deepCopy(resp.body, resp, "body", resp, dupStubs, owner);
665
+ }
666
+ return new Response(resp.body, resp);
667
+ }
522
668
  default:
523
669
  throw new Error("unreachable");
524
670
  }
@@ -528,12 +674,12 @@ var RpcPayload = class _RpcPayload {
528
674
  ensureDeepCopied() {
529
675
  if (this.source !== "owned") {
530
676
  let dupStubs = this.source === "params";
531
- this.stubs = [];
677
+ this.hooks = [];
532
678
  this.promises = [];
533
679
  try {
534
680
  this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
535
681
  } catch (err) {
536
- this.stubs = void 0;
682
+ this.hooks = void 0;
537
683
  this.promises = void 0;
538
684
  throw err;
539
685
  }
@@ -636,7 +782,7 @@ var RpcPayload = class _RpcPayload {
636
782
  }
637
783
  dispose() {
638
784
  if (this.source === "owned") {
639
- this.stubs.forEach((stub) => stub[Symbol.dispose]());
785
+ this.hooks.forEach((hook) => hook.dispose());
640
786
  this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
641
787
  } else if (this.source === "return") {
642
788
  this.disposeImpl(this.value, void 0);
@@ -645,7 +791,7 @@ var RpcPayload = class _RpcPayload {
645
791
  }
646
792
  } else ;
647
793
  this.source = "owned";
648
- this.stubs = [];
794
+ this.hooks = [];
649
795
  this.promises = [];
650
796
  }
651
797
  // Recursive dispose, called only when `source` is "return".
@@ -656,6 +802,7 @@ var RpcPayload = class _RpcPayload {
656
802
  case "primitive":
657
803
  case "bigint":
658
804
  case "bytes":
805
+ case "blob":
659
806
  case "date":
660
807
  case "error":
661
808
  case "undefined":
@@ -698,6 +845,40 @@ var RpcPayload = class _RpcPayload {
698
845
  }
699
846
  case "rpc-thenable":
700
847
  return;
848
+ case "headers":
849
+ return;
850
+ case "request": {
851
+ let req = value;
852
+ if (req.body) this.disposeImpl(req.body, req);
853
+ return;
854
+ }
855
+ case "response": {
856
+ let resp = value;
857
+ if (resp.body) this.disposeImpl(resp.body, resp);
858
+ return;
859
+ }
860
+ case "writable": {
861
+ let stream = value;
862
+ let hook = this.rpcTargets?.get(stream);
863
+ if (hook) {
864
+ this.rpcTargets.delete(stream);
865
+ } else {
866
+ hook = streamImpl.createWritableStreamHook(stream);
867
+ }
868
+ hook.dispose();
869
+ return;
870
+ }
871
+ case "readable": {
872
+ let stream = value;
873
+ let hook = this.rpcTargets?.get(stream);
874
+ if (hook) {
875
+ this.rpcTargets.delete(stream);
876
+ } else {
877
+ hook = streamImpl.createReadableStreamHook(stream);
878
+ }
879
+ hook.dispose();
880
+ return;
881
+ }
701
882
  default:
702
883
  return;
703
884
  }
@@ -706,9 +887,9 @@ var RpcPayload = class _RpcPayload {
706
887
  // *would* be awaited if this payload were to be delivered. See the similarly-named method of
707
888
  // StubHook for explanation.
708
889
  ignoreUnhandledRejections() {
709
- if (this.stubs) {
710
- this.stubs.forEach((stub) => {
711
- unwrapStubOrParent(stub).ignoreUnhandledRejections();
890
+ if (this.hooks) {
891
+ this.hooks.forEach((hook) => {
892
+ hook.ignoreUnhandledRejections();
712
893
  });
713
894
  this.promises.forEach(
714
895
  (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()
@@ -724,11 +905,17 @@ var RpcPayload = class _RpcPayload {
724
905
  case "primitive":
725
906
  case "bigint":
726
907
  case "bytes":
908
+ case "blob":
727
909
  case "date":
728
910
  case "error":
729
911
  case "undefined":
730
912
  case "function":
731
913
  case "rpc-target":
914
+ case "writable":
915
+ case "readable":
916
+ case "headers":
917
+ case "request":
918
+ case "response":
732
919
  return;
733
920
  case "array": {
734
921
  let array = value;
@@ -801,11 +988,21 @@ function followPath(value, parent, path, owner) {
801
988
  let { hook, pathIfPromise } = unwrapStubAndPath(value);
802
989
  return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };
803
990
  }
991
+ case "writable":
992
+ value = void 0;
993
+ break;
994
+ case "readable":
995
+ value = void 0;
996
+ break;
804
997
  case "primitive":
805
998
  case "bigint":
806
999
  case "bytes":
1000
+ case "blob":
807
1001
  case "date":
808
1002
  case "error":
1003
+ case "headers":
1004
+ case "request":
1005
+ case "response":
809
1006
  value = void 0;
810
1007
  break;
811
1008
  case "undefined":
@@ -1040,6 +1237,14 @@ var PromiseStubHook = class _PromiseStubHook extends StubHook {
1040
1237
  args.ensureDeepCopied();
1041
1238
  return new _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
1042
1239
  }
1240
+ stream(path, args) {
1241
+ args.ensureDeepCopied();
1242
+ let promise = this.promise.then((hook) => {
1243
+ let result = hook.stream(path, args);
1244
+ return result.promise;
1245
+ });
1246
+ return { promise };
1247
+ }
1043
1248
  map(path, captures, instructions) {
1044
1249
  return new _PromiseStubHook(this.promise.then(
1045
1250
  (hook) => hook.map(path, captures, instructions),
@@ -1112,10 +1317,17 @@ var NullExporter = class {
1112
1317
  }
1113
1318
  unexport(ids) {
1114
1319
  }
1320
+ createPipe(readable) {
1321
+ throw new Error("Cannot create pipes without an RPC session.");
1322
+ }
1115
1323
  onSendError(error) {
1116
1324
  }
1117
1325
  };
1118
1326
  var NULL_EXPORTER = new NullExporter();
1327
+ async function streamToBlob(stream, type) {
1328
+ let b = await new Response(stream).blob();
1329
+ return b.type === type ? b : b.slice(0, b.size, type);
1330
+ }
1119
1331
  var ERROR_TYPES = {
1120
1332
  Error,
1121
1333
  EvalError,
@@ -1203,18 +1415,101 @@ var Devaluator = class _Devaluator {
1203
1415
  }
1204
1416
  case "bigint":
1205
1417
  return ["bigint", value.toString()];
1206
- case "date":
1207
- return ["date", value.getTime()];
1418
+ case "date": {
1419
+ const time = value.getTime();
1420
+ return ["date", Number.isNaN(time) ? null : time];
1421
+ }
1208
1422
  case "bytes": {
1209
1423
  let bytes = value;
1210
1424
  if (bytes.toBase64) {
1211
1425
  return ["bytes", bytes.toBase64({ omitPadding: true })];
1426
+ }
1427
+ let b64;
1428
+ if (typeof Buffer !== "undefined") {
1429
+ let buf = bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1430
+ b64 = buf.toString("base64");
1212
1431
  } else {
1213
- return [
1214
- "bytes",
1215
- btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, ""))
1216
- ];
1432
+ let binary = "";
1433
+ for (let i = 0; i < bytes.length; i++) {
1434
+ binary += String.fromCharCode(bytes[i]);
1435
+ }
1436
+ b64 = btoa(binary);
1217
1437
  }
1438
+ return ["bytes", b64.replace(/=+$/, "")];
1439
+ }
1440
+ case "headers":
1441
+ return ["headers", [...value]];
1442
+ case "request": {
1443
+ let req = value;
1444
+ let init = {};
1445
+ if (req.method !== "GET") init.method = req.method;
1446
+ let headers = [...req.headers];
1447
+ if (headers.length > 0) {
1448
+ init.headers = headers;
1449
+ }
1450
+ if (req.body) {
1451
+ init.body = this.devaluateImpl(req.body, req, depth + 1);
1452
+ init.duplex = req.duplex || "half";
1453
+ } else if (req.body === void 0 && !["GET", "HEAD", "OPTIONS", "TRACE", "DELETE"].includes(req.method)) {
1454
+ let bodyPromise = req.arrayBuffer();
1455
+ let readable = new ReadableStream({
1456
+ async start(controller) {
1457
+ try {
1458
+ controller.enqueue(new Uint8Array(await bodyPromise));
1459
+ controller.close();
1460
+ } catch (err) {
1461
+ controller.error(err);
1462
+ }
1463
+ }
1464
+ });
1465
+ let hook = streamImpl.createReadableStreamHook(readable);
1466
+ let importId = this.exporter.createPipe(readable, hook);
1467
+ init.body = ["readable", importId];
1468
+ init.duplex = req.duplex || "half";
1469
+ }
1470
+ if (req.cache && req.cache !== "default") init.cache = req.cache;
1471
+ if (req.redirect !== "follow") init.redirect = req.redirect;
1472
+ if (req.integrity) init.integrity = req.integrity;
1473
+ if (req.mode && req.mode !== "cors") init.mode = req.mode;
1474
+ if (req.credentials && req.credentials !== "same-origin") {
1475
+ init.credentials = req.credentials;
1476
+ }
1477
+ if (req.referrer && req.referrer !== "about:client") init.referrer = req.referrer;
1478
+ if (req.referrerPolicy) init.referrerPolicy = req.referrerPolicy;
1479
+ if (req.keepalive) init.keepalive = req.keepalive;
1480
+ let cfReq = req;
1481
+ if (cfReq.cf) init.cf = cfReq.cf;
1482
+ if (cfReq.encodeResponseBody && cfReq.encodeResponseBody !== "automatic") {
1483
+ init.encodeResponseBody = cfReq.encodeResponseBody;
1484
+ }
1485
+ return ["request", req.url, init];
1486
+ }
1487
+ case "response": {
1488
+ let resp = value;
1489
+ let body = this.devaluateImpl(resp.body, resp, depth + 1);
1490
+ let init = {};
1491
+ if (resp.status !== 200) init.status = resp.status;
1492
+ if (resp.statusText) init.statusText = resp.statusText;
1493
+ let headers = [...resp.headers];
1494
+ if (headers.length > 0) {
1495
+ init.headers = headers;
1496
+ }
1497
+ let cfResp = resp;
1498
+ if (cfResp.cf) init.cf = cfResp.cf;
1499
+ if (cfResp.encodeBody && cfResp.encodeBody !== "automatic") {
1500
+ init.encodeBody = cfResp.encodeBody;
1501
+ }
1502
+ if (cfResp.webSocket) {
1503
+ throw new TypeError("Can't serialize a Response containing a webSocket.");
1504
+ }
1505
+ return ["response", body, init];
1506
+ }
1507
+ case "blob": {
1508
+ let blob = value;
1509
+ let readable = blob.stream();
1510
+ let hook = streamImpl.createReadableStreamHook(readable);
1511
+ let importId = this.exporter.createPipe(readable, hook);
1512
+ return ["blob", blob.type, ["readable", importId]];
1218
1513
  }
1219
1514
  case "error": {
1220
1515
  let e = value;
@@ -1270,6 +1565,22 @@ var Devaluator = class _Devaluator {
1270
1565
  let hook = this.source.getHookForRpcTarget(value, parent);
1271
1566
  return this.devaluateHook("promise", hook);
1272
1567
  }
1568
+ case "writable": {
1569
+ if (!this.source) {
1570
+ throw new Error("Can't serialize WritableStream in this context.");
1571
+ }
1572
+ let hook = this.source.getHookForWritableStream(value, parent);
1573
+ return this.devaluateHook("writable", hook);
1574
+ }
1575
+ case "readable": {
1576
+ if (!this.source) {
1577
+ throw new Error("Can't serialize ReadableStream in this context.");
1578
+ }
1579
+ let ws = value;
1580
+ let hook = this.source.getHookForReadableStream(ws, parent);
1581
+ let importId = this.exporter.createPipe(ws, hook);
1582
+ return ["readable", importId];
1583
+ }
1273
1584
  default:
1274
1585
  throw new Error("unreachable");
1275
1586
  }
@@ -1294,16 +1605,33 @@ var NullImporter = class {
1294
1605
  getExport(idx) {
1295
1606
  return void 0;
1296
1607
  }
1608
+ getPipeReadable(exportId) {
1609
+ throw new Error("Cannot retrieve pipe readable without an RPC session.");
1610
+ }
1297
1611
  };
1298
1612
  var NULL_IMPORTER = new NullImporter();
1613
+ function fixBrokenRequestBody(request, body) {
1614
+ let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {
1615
+ let bytes = new Uint8Array(arrayBuffer);
1616
+ let result = new Request(request, { body: bytes });
1617
+ return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1618
+ });
1619
+ return new RpcPromise(new PromiseStubHook(promise), []);
1620
+ }
1621
+ function streamToBlobPromise(stream, type) {
1622
+ let promise = streamToBlob(stream, type).then((blob) => {
1623
+ return new PayloadStubHook(RpcPayload.fromAppReturn(blob));
1624
+ });
1625
+ return new RpcPromise(new PromiseStubHook(promise), []);
1626
+ }
1299
1627
  var Evaluator = class _Evaluator {
1300
1628
  constructor(importer) {
1301
1629
  this.importer = importer;
1302
1630
  }
1303
- stubs = [];
1631
+ hooks = [];
1304
1632
  promises = [];
1305
1633
  evaluate(value) {
1306
- let payload = RpcPayload.forEvaluate(this.stubs, this.promises);
1634
+ let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1307
1635
  try {
1308
1636
  payload.value = this.evaluateImpl(value, payload, "value");
1309
1637
  return payload;
@@ -1331,15 +1659,19 @@ var Evaluator = class _Evaluator {
1331
1659
  }
1332
1660
  break;
1333
1661
  case "date":
1662
+ if (value[1] === null) {
1663
+ return /* @__PURE__ */ new Date(NaN);
1664
+ }
1334
1665
  if (typeof value[1] == "number") {
1335
1666
  return new Date(value[1]);
1336
1667
  }
1337
1668
  break;
1338
1669
  case "bytes": {
1339
- let b64 = Uint8Array;
1340
1670
  if (typeof value[1] == "string") {
1341
- if (b64.fromBase64) {
1342
- return b64.fromBase64(value[1]);
1671
+ if (typeof Buffer !== "undefined") {
1672
+ return Buffer.from(value[1], "base64");
1673
+ } else if (Uint8Array.fromBase64) {
1674
+ return Uint8Array.fromBase64(value[1]);
1343
1675
  } else {
1344
1676
  let bs = atob(value[1]);
1345
1677
  let len = bs.length;
@@ -1373,6 +1705,67 @@ var Evaluator = class _Evaluator {
1373
1705
  return -Infinity;
1374
1706
  case "nan":
1375
1707
  return NaN;
1708
+ case "headers":
1709
+ if (value.length === 2 && value[1] instanceof Array) {
1710
+ return new Headers(value[1]);
1711
+ }
1712
+ break;
1713
+ case "request": {
1714
+ if (value.length !== 3 || typeof value[1] !== "string") break;
1715
+ let url = value[1];
1716
+ let init = value[2];
1717
+ if (typeof init !== "object" || init === null) break;
1718
+ if (init.body) {
1719
+ init.body = this.evaluateImpl(init.body, init, "body");
1720
+ if (init.body === null || typeof init.body === "string" || init.body instanceof Uint8Array || init.body instanceof ReadableStream) ; else {
1721
+ throw new TypeError("Request body must be of type ReadableStream.");
1722
+ }
1723
+ }
1724
+ if (init.signal) {
1725
+ init.signal = this.evaluateImpl(init.signal, init, "signal");
1726
+ if (!(init.signal instanceof AbortSignal)) {
1727
+ throw new TypeError("Request siganl must be of type AbortSignal.");
1728
+ }
1729
+ }
1730
+ if (init.headers && !(init.headers instanceof Array)) {
1731
+ throw new TypeError("Request headers must be serialized as an array of pairs.");
1732
+ }
1733
+ let result = new Request(url, init);
1734
+ if (init.body instanceof ReadableStream && result.body === void 0) {
1735
+ let promise = fixBrokenRequestBody(result, init.body);
1736
+ this.promises.push({ promise, parent, property });
1737
+ return promise;
1738
+ } else {
1739
+ return result;
1740
+ }
1741
+ }
1742
+ case "response": {
1743
+ if (value.length !== 3) break;
1744
+ let body = this.evaluateImpl(value[1], parent, property);
1745
+ if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) ; else {
1746
+ throw new TypeError("Response body must be of type ReadableStream.");
1747
+ }
1748
+ let init = value[2];
1749
+ if (typeof init !== "object" || init === null) break;
1750
+ if (init.webSocket) {
1751
+ throw new TypeError("Can't deserialize a Response containing a webSocket.");
1752
+ }
1753
+ if (init.headers && !(init.headers instanceof Array)) {
1754
+ throw new TypeError("Request headers must be serialized as an array of pairs.");
1755
+ }
1756
+ return new Response(body, init);
1757
+ }
1758
+ case "blob": {
1759
+ if (value.length !== 3 || typeof value[1] !== "string") break;
1760
+ let contentType = value[1];
1761
+ let content = this.evaluateImpl(value[2], parent, property);
1762
+ if (!(content instanceof ReadableStream)) {
1763
+ throw new TypeError("Blob content must be serialized as a ReadableStream.");
1764
+ }
1765
+ let promise = streamToBlobPromise(content, contentType);
1766
+ this.promises.push({ promise, parent, property });
1767
+ return promise;
1768
+ }
1376
1769
  case "import":
1377
1770
  case "pipeline": {
1378
1771
  if (value.length < 2 || value.length > 4) {
@@ -1392,9 +1785,8 @@ var Evaluator = class _Evaluator {
1392
1785
  this.promises.push({ promise, parent, property });
1393
1786
  return promise;
1394
1787
  } else {
1395
- let stub = new RpcPromise(hook2, []);
1396
- this.stubs.push(stub);
1397
- return stub;
1788
+ this.hooks.push(hook2);
1789
+ return new RpcPromise(hook2, []);
1398
1790
  }
1399
1791
  };
1400
1792
  if (value.length == 2) {
@@ -1472,12 +1864,27 @@ var Evaluator = class _Evaluator {
1472
1864
  return promise;
1473
1865
  } else {
1474
1866
  let hook = this.importer.importStub(value[1]);
1475
- let stub = new RpcStub(hook);
1476
- this.stubs.push(stub);
1477
- return stub;
1867
+ this.hooks.push(hook);
1868
+ return new RpcStub(hook);
1478
1869
  }
1479
1870
  }
1480
1871
  break;
1872
+ case "writable":
1873
+ if (typeof value[1] == "number") {
1874
+ let hook = this.importer.importStub(value[1]);
1875
+ let stream = streamImpl.createWritableStreamFromHook(hook);
1876
+ this.hooks.push(hook);
1877
+ return stream;
1878
+ }
1879
+ break;
1880
+ case "readable":
1881
+ if (typeof value[1] == "number") {
1882
+ let stream = this.importer.getPipeReadable(value[1]);
1883
+ let hook = streamImpl.createReadableStreamHook(stream);
1884
+ this.hooks.push(hook);
1885
+ return stream;
1886
+ }
1887
+ break;
1481
1888
  }
1482
1889
  throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1483
1890
  } else if (value instanceof Object) {
@@ -1617,6 +2024,14 @@ var RpcImportHook = class _RpcImportHook extends StubHook {
1617
2024
  return entry.session.sendCall(entry.importId, path, args);
1618
2025
  }
1619
2026
  }
2027
+ stream(path, args) {
2028
+ let entry = this.getEntry();
2029
+ if (entry.resolution) {
2030
+ return entry.resolution.stream(path, args);
2031
+ } else {
2032
+ return entry.session.sendStream(entry.importId, path, args);
2033
+ }
2034
+ }
1620
2035
  map(path, captures, instructions) {
1621
2036
  let entry;
1622
2037
  try {
@@ -1789,19 +2204,23 @@ var RpcSessionImpl = class {
1789
2204
  return payload;
1790
2205
  }
1791
2206
  };
2207
+ let autoRelease = exp.autoRelease;
1792
2208
  ++this.pullCount;
1793
2209
  exp.pull = resolve().then(
1794
2210
  (payload) => {
1795
2211
  let value = Devaluator.devaluate(payload.value, void 0, this, payload);
1796
2212
  this.send(["resolve", exportId, value]);
2213
+ if (autoRelease) this.releaseExport(exportId, 1);
1797
2214
  },
1798
2215
  (error) => {
1799
2216
  this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);
2217
+ if (autoRelease) this.releaseExport(exportId, 1);
1800
2218
  }
1801
2219
  ).catch(
1802
2220
  (error) => {
1803
2221
  try {
1804
2222
  this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]);
2223
+ if (autoRelease) this.releaseExport(exportId, 1);
1805
2224
  } catch (error2) {
1806
2225
  this.abort(error2);
1807
2226
  }
@@ -1853,9 +2272,35 @@ var RpcSessionImpl = class {
1853
2272
  getExport(idx) {
1854
2273
  return this.exports[idx]?.hook;
1855
2274
  }
2275
+ getPipeReadable(exportId) {
2276
+ let entry = this.exports[exportId];
2277
+ if (!entry || !entry.pipeReadable) {
2278
+ throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);
2279
+ }
2280
+ let readable = entry.pipeReadable;
2281
+ entry.pipeReadable = void 0;
2282
+ return readable;
2283
+ }
2284
+ createPipe(readable, readableHook) {
2285
+ if (this.abortReason) throw this.abortReason;
2286
+ this.send(["pipe"]);
2287
+ let importId = this.imports.length;
2288
+ let entry = new ImportTableEntry(this, importId, false);
2289
+ this.imports.push(entry);
2290
+ let hook = new RpcImportHook(
2291
+ /*isPromise=*/
2292
+ false,
2293
+ entry
2294
+ );
2295
+ let writable = streamImpl.createWritableStreamFromHook(hook);
2296
+ readable.pipeTo(writable).catch(() => {
2297
+ }).finally(() => readableHook.dispose());
2298
+ return importId;
2299
+ }
2300
+ // Serializes and sends a message. Returns the byte length of the serialized message.
1856
2301
  send(msg) {
1857
2302
  if (this.abortReason !== void 0) {
1858
- return;
2303
+ return 0;
1859
2304
  }
1860
2305
  let msgText;
1861
2306
  try {
@@ -1868,6 +2313,7 @@ var RpcSessionImpl = class {
1868
2313
  throw err;
1869
2314
  }
1870
2315
  this.transport.send(msgText).catch((err) => this.abort(err, false));
2316
+ return msgText.length;
1871
2317
  }
1872
2318
  sendCall(id, path, args) {
1873
2319
  if (this.abortReason) throw this.abortReason;
@@ -1885,6 +2331,34 @@ var RpcSessionImpl = class {
1885
2331
  entry
1886
2332
  );
1887
2333
  }
2334
+ sendStream(id, path, args) {
2335
+ if (this.abortReason) throw this.abortReason;
2336
+ let value = ["pipeline", id, path];
2337
+ let devalue = Devaluator.devaluate(args.value, void 0, this, args);
2338
+ value.push(devalue[0]);
2339
+ let size = this.send(["stream", value]);
2340
+ let importId = this.imports.length;
2341
+ let entry = new ImportTableEntry(
2342
+ this,
2343
+ importId,
2344
+ /*pulling=*/
2345
+ true
2346
+ );
2347
+ entry.remoteRefcount = 0;
2348
+ entry.localRefcount = 1;
2349
+ this.imports.push(entry);
2350
+ let promise = entry.awaitResolution().then(
2351
+ (p) => {
2352
+ p.dispose();
2353
+ delete this.imports[importId];
2354
+ },
2355
+ (err) => {
2356
+ delete this.imports[importId];
2357
+ throw err;
2358
+ }
2359
+ );
2360
+ return { promise, size };
2361
+ }
1888
2362
  sendMap(id, path, captures, instructions) {
1889
2363
  if (this.abortReason) {
1890
2364
  for (let cap of captures) {
@@ -1972,6 +2446,24 @@ var RpcSessionImpl = class {
1972
2446
  continue;
1973
2447
  }
1974
2448
  break;
2449
+ case "stream": {
2450
+ if (msg.length > 1) {
2451
+ let payload = new Evaluator(this).evaluate(msg[1]);
2452
+ let hook = new PayloadStubHook(payload);
2453
+ hook.ignoreUnhandledRejections();
2454
+ let exportId = this.exports.length;
2455
+ this.exports.push({ hook, refcount: 1, autoRelease: true });
2456
+ this.ensureResolvingExport(exportId);
2457
+ continue;
2458
+ }
2459
+ break;
2460
+ }
2461
+ case "pipe": {
2462
+ let { readable, writable } = new TransformStream();
2463
+ let hook = streamImpl.createWritableStreamHook(writable);
2464
+ this.exports.push({ hook, refcount: 1, pipeReadable: readable });
2465
+ continue;
2466
+ }
1975
2467
  case "pull": {
1976
2468
  let exportId = msg[1];
1977
2469
  if (typeof exportId == "number") {
@@ -2467,6 +2959,9 @@ var MapBuilder = class {
2467
2959
  }
2468
2960
  unexport(ids) {
2469
2961
  }
2962
+ createPipe(readable) {
2963
+ throw new Error("Cannot send ReadableStream inside a mapper function.");
2964
+ }
2470
2965
  onSendError(error) {
2471
2966
  }
2472
2967
  };
@@ -2576,6 +3071,9 @@ var MapApplicator = class {
2576
3071
  return this.variables[idx];
2577
3072
  }
2578
3073
  }
3074
+ getPipeReadable(exportId) {
3075
+ throw new Error("A mapper function cannot use pipe readables.");
3076
+ }
2579
3077
  };
2580
3078
  function applyMapToElement(input, parent, owner, captures, instructions) {
2581
3079
  let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner));
@@ -2616,6 +3114,333 @@ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
2616
3114
  }
2617
3115
  }
2618
3116
  };
3117
+
3118
+ // src/streams.ts
3119
+ var WritableStreamStubHook = class _WritableStreamStubHook extends StubHook {
3120
+ state;
3121
+ // undefined when disposed
3122
+ // Creates a new WritableStreamStubHook that is not duplicated from an existing hook.
3123
+ static create(stream) {
3124
+ let writer = stream.getWriter();
3125
+ return new _WritableStreamStubHook({ refcount: 1, writer, closed: false });
3126
+ }
3127
+ constructor(state, dupFrom) {
3128
+ super();
3129
+ this.state = state;
3130
+ if (dupFrom) {
3131
+ ++state.refcount;
3132
+ }
3133
+ }
3134
+ getState() {
3135
+ if (this.state) {
3136
+ return this.state;
3137
+ } else {
3138
+ throw new Error("Attempted to use a WritableStreamStubHook after it was disposed.");
3139
+ }
3140
+ }
3141
+ call(path, args) {
3142
+ try {
3143
+ let state = this.getState();
3144
+ if (path.length !== 1 || typeof path[0] !== "string") {
3145
+ throw new Error("WritableStream stub only supports direct method calls");
3146
+ }
3147
+ const method = path[0];
3148
+ if (method !== "write" && method !== "close" && method !== "abort") {
3149
+ args.dispose();
3150
+ throw new Error(`Unknown WritableStream method: ${method}`);
3151
+ }
3152
+ if (method === "close" || method === "abort") {
3153
+ state.closed = true;
3154
+ }
3155
+ let func = state.writer[method];
3156
+ let promise = args.deliverCall(func, state.writer);
3157
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
3158
+ } catch (err) {
3159
+ return new ErrorStubHook(err);
3160
+ }
3161
+ }
3162
+ map(path, captures, instructions) {
3163
+ for (let cap of captures) {
3164
+ cap.dispose();
3165
+ }
3166
+ return new ErrorStubHook(new Error("Cannot use map() on a WritableStream"));
3167
+ }
3168
+ get(path) {
3169
+ return new ErrorStubHook(new Error("Cannot access properties on a WritableStream stub"));
3170
+ }
3171
+ dup() {
3172
+ let state = this.getState();
3173
+ return new _WritableStreamStubHook(state, this);
3174
+ }
3175
+ pull() {
3176
+ return Promise.reject(new Error("Cannot pull a WritableStream stub"));
3177
+ }
3178
+ ignoreUnhandledRejections() {
3179
+ }
3180
+ dispose() {
3181
+ let state = this.state;
3182
+ this.state = void 0;
3183
+ if (state) {
3184
+ if (--state.refcount === 0) {
3185
+ if (!state.closed) {
3186
+ state.writer.abort(new Error("WritableStream RPC stub was disposed without calling close()")).catch(() => {
3187
+ });
3188
+ }
3189
+ state.writer.releaseLock();
3190
+ }
3191
+ }
3192
+ }
3193
+ onBroken(callback) {
3194
+ }
3195
+ };
3196
+ var INITIAL_WINDOW = 256 * 1024;
3197
+ var MAX_WINDOW = 1024 * 1024 * 1024;
3198
+ var MIN_WINDOW = 64 * 1024;
3199
+ var STARTUP_GROWTH_FACTOR = 2;
3200
+ var STEADY_GROWTH_FACTOR = 1.25;
3201
+ var DECAY_FACTOR = 0.9;
3202
+ var STARTUP_EXIT_ROUNDS = 3;
3203
+ var FlowController = class {
3204
+ constructor(now) {
3205
+ this.now = now;
3206
+ }
3207
+ // The current window size in bytes. The sender blocks when bytesInFlight >= window.
3208
+ window = INITIAL_WINDOW;
3209
+ // Total bytes currently in flight (sent but not yet acked).
3210
+ bytesInFlight = 0;
3211
+ // Whether we're still in the startup phase.
3212
+ inStartupPhase = true;
3213
+ // ----- BDP estimation state (private) -----
3214
+ // Total bytes acked so far.
3215
+ delivered = 0;
3216
+ // Time of most recent ack.
3217
+ deliveredTime = 0;
3218
+ // Time when the very first ack was received.
3219
+ firstAckTime = 0;
3220
+ firstAckDelivered = 0;
3221
+ // Global minimum RTT observed (milliseconds).
3222
+ minRtt = Infinity;
3223
+ // For startup exit: count of consecutive RTT rounds where the window didn't meaningfully grow.
3224
+ roundsWithoutIncrease = 0;
3225
+ // Window size at the start of the current round, for startup exit detection.
3226
+ lastRoundWindow = 0;
3227
+ // Time when the current round started.
3228
+ roundStartTime = 0;
3229
+ // Called when a write of `size` bytes is about to be sent. Returns a token that must be
3230
+ // passed to onAck() when the ack arrives, and whether the sender should block (window full).
3231
+ onSend(size) {
3232
+ this.bytesInFlight += size;
3233
+ let token = {
3234
+ sentTime: this.now(),
3235
+ size,
3236
+ deliveredAtSend: this.delivered,
3237
+ deliveredTimeAtSend: this.deliveredTime,
3238
+ windowAtSend: this.window,
3239
+ windowFullAtSend: this.bytesInFlight >= this.window
3240
+ };
3241
+ return { token, shouldBlock: token.windowFullAtSend };
3242
+ }
3243
+ // Called when a previously-sent write fails. Restores bytesInFlight without updating
3244
+ // any BDP estimates.
3245
+ onError(token) {
3246
+ this.bytesInFlight -= token.size;
3247
+ }
3248
+ // Called when an ack is received for a previously-sent write. Updates BDP estimates and
3249
+ // the window. Returns whether a blocked sender should now unblock.
3250
+ onAck(token) {
3251
+ let ackTime = this.now();
3252
+ this.delivered += token.size;
3253
+ this.deliveredTime = ackTime;
3254
+ this.bytesInFlight -= token.size;
3255
+ let rtt = ackTime - token.sentTime;
3256
+ this.minRtt = Math.min(this.minRtt, rtt);
3257
+ if (this.firstAckTime === 0) {
3258
+ this.firstAckTime = ackTime;
3259
+ this.firstAckDelivered = this.delivered;
3260
+ } else {
3261
+ let baseTime;
3262
+ let baseDelivered;
3263
+ if (token.deliveredTimeAtSend === 0) {
3264
+ baseTime = this.firstAckTime;
3265
+ baseDelivered = this.firstAckDelivered;
3266
+ } else {
3267
+ baseTime = token.deliveredTimeAtSend;
3268
+ baseDelivered = token.deliveredAtSend;
3269
+ }
3270
+ let interval = ackTime - baseTime;
3271
+ let bytes = this.delivered - baseDelivered;
3272
+ let bandwidth = bytes / interval;
3273
+ let growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR;
3274
+ let newWindow = bandwidth * this.minRtt * growthFactor;
3275
+ newWindow = Math.min(newWindow, token.windowAtSend * growthFactor);
3276
+ if (token.windowFullAtSend) {
3277
+ newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR);
3278
+ } else {
3279
+ newWindow = Math.max(newWindow, this.window);
3280
+ }
3281
+ this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW);
3282
+ if (this.inStartupPhase && token.sentTime >= this.roundStartTime) {
3283
+ if (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR) {
3284
+ this.roundsWithoutIncrease = 0;
3285
+ } else {
3286
+ if (++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS) {
3287
+ this.inStartupPhase = false;
3288
+ }
3289
+ }
3290
+ this.roundStartTime = ackTime;
3291
+ this.lastRoundWindow = this.window;
3292
+ }
3293
+ }
3294
+ return this.bytesInFlight < this.window;
3295
+ }
3296
+ };
3297
+ function createWritableStreamFromHook(hook) {
3298
+ let pendingError = void 0;
3299
+ let hookDisposed = false;
3300
+ let fc = new FlowController(() => performance.now());
3301
+ let windowResolve;
3302
+ let windowReject;
3303
+ const disposeHook = () => {
3304
+ if (!hookDisposed) {
3305
+ hookDisposed = true;
3306
+ hook.dispose();
3307
+ }
3308
+ };
3309
+ return new WritableStream({
3310
+ write(chunk, controller) {
3311
+ if (pendingError !== void 0) {
3312
+ throw pendingError;
3313
+ }
3314
+ const payload = RpcPayload.fromAppParams([chunk]);
3315
+ const { promise, size } = hook.stream(["write"], payload);
3316
+ if (size === void 0) {
3317
+ return promise.catch((err) => {
3318
+ if (pendingError === void 0) {
3319
+ pendingError = err;
3320
+ }
3321
+ throw err;
3322
+ });
3323
+ } else {
3324
+ let { token, shouldBlock } = fc.onSend(size);
3325
+ promise.then(() => {
3326
+ let hasCapacity = fc.onAck(token);
3327
+ if (hasCapacity && windowResolve) {
3328
+ windowResolve();
3329
+ windowResolve = void 0;
3330
+ windowReject = void 0;
3331
+ }
3332
+ }, (err) => {
3333
+ fc.onError(token);
3334
+ if (pendingError === void 0) {
3335
+ pendingError = err;
3336
+ controller.error(err);
3337
+ disposeHook();
3338
+ }
3339
+ if (windowReject) {
3340
+ windowReject(err);
3341
+ windowResolve = void 0;
3342
+ windowReject = void 0;
3343
+ }
3344
+ });
3345
+ if (shouldBlock) {
3346
+ return new Promise((resolve, reject) => {
3347
+ windowResolve = resolve;
3348
+ windowReject = reject;
3349
+ });
3350
+ }
3351
+ }
3352
+ },
3353
+ async close() {
3354
+ if (pendingError !== void 0) {
3355
+ disposeHook();
3356
+ throw pendingError;
3357
+ }
3358
+ const { promise } = hook.stream(["close"], RpcPayload.fromAppParams([]));
3359
+ try {
3360
+ await promise;
3361
+ } catch (err) {
3362
+ throw pendingError ?? err;
3363
+ } finally {
3364
+ disposeHook();
3365
+ }
3366
+ },
3367
+ abort(reason) {
3368
+ if (pendingError !== void 0) {
3369
+ return;
3370
+ }
3371
+ pendingError = reason ?? new Error("WritableStream was aborted");
3372
+ if (windowReject) {
3373
+ windowReject(pendingError);
3374
+ windowResolve = void 0;
3375
+ windowReject = void 0;
3376
+ }
3377
+ const { promise } = hook.stream(["abort"], RpcPayload.fromAppParams([reason]));
3378
+ promise.then(() => disposeHook(), () => disposeHook());
3379
+ }
3380
+ });
3381
+ }
3382
+ var ReadableStreamStubHook = class _ReadableStreamStubHook extends StubHook {
3383
+ state;
3384
+ // undefined when disposed
3385
+ // Creates a new ReadableStreamStubHook.
3386
+ static create(stream) {
3387
+ return new _ReadableStreamStubHook({ refcount: 1, stream, canceled: false });
3388
+ }
3389
+ constructor(state, dupFrom) {
3390
+ super();
3391
+ this.state = state;
3392
+ if (dupFrom) {
3393
+ ++state.refcount;
3394
+ }
3395
+ }
3396
+ call(path, args) {
3397
+ args.dispose();
3398
+ return new ErrorStubHook(new Error("Cannot call methods on a ReadableStream stub"));
3399
+ }
3400
+ map(path, captures, instructions) {
3401
+ for (let cap of captures) {
3402
+ cap.dispose();
3403
+ }
3404
+ return new ErrorStubHook(new Error("Cannot use map() on a ReadableStream"));
3405
+ }
3406
+ get(path) {
3407
+ return new ErrorStubHook(new Error("Cannot access properties on a ReadableStream stub"));
3408
+ }
3409
+ dup() {
3410
+ let state = this.state;
3411
+ if (!state) {
3412
+ throw new Error("Attempted to dup a ReadableStreamStubHook after it was disposed.");
3413
+ }
3414
+ return new _ReadableStreamStubHook(state, this);
3415
+ }
3416
+ pull() {
3417
+ return Promise.reject(new Error("Cannot pull a ReadableStream stub"));
3418
+ }
3419
+ ignoreUnhandledRejections() {
3420
+ }
3421
+ dispose() {
3422
+ let state = this.state;
3423
+ this.state = void 0;
3424
+ if (state) {
3425
+ if (--state.refcount === 0) {
3426
+ if (!state.canceled) {
3427
+ state.canceled = true;
3428
+ if (!state.stream.locked) {
3429
+ state.stream.cancel(
3430
+ new Error("ReadableStream RPC stub was disposed without being consumed")
3431
+ ).catch(() => {
3432
+ });
3433
+ }
3434
+ }
3435
+ }
3436
+ }
3437
+ }
3438
+ onBroken(callback) {
3439
+ }
3440
+ };
3441
+ streamImpl.createWritableStreamHook = WritableStreamStubHook.create;
3442
+ streamImpl.createWritableStreamFromHook = createWritableStreamFromHook;
3443
+ streamImpl.createReadableStreamHook = ReadableStreamStubHook.create;
2619
3444
  var RpcStub2 = RpcStub;
2620
3445
  var RpcPromise2 = RpcPromise;
2621
3446
  var RpcSession2 = RpcSession;