capnweb 0.10.0 → 0.11.1

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.
package/README.md CHANGED
@@ -199,15 +199,15 @@ The following types can be passed over RPC (in arguments or return values), and
199
199
  * Arrays
200
200
  * `bigint`
201
201
  * `Date`
202
- * `Uint8Array`
202
+ * `ArrayBuffer`, `DataView`, and typed arrays
203
203
  * `Error` and its well-known subclasses
204
204
  * `Blob`
205
205
  * `ReadableStream` and `WritableStream`, with automatic flow control.
206
+ * `URL`
206
207
  * `Headers`, `Request`, and `Response` from the Fetch API.
207
208
 
208
209
  The following types are not supported as of this writing, but may be added in the future:
209
210
  * `Map` and `Set`
210
- * `ArrayBuffer` and typed arrays other than `Uint8Array`
211
211
  * `RegExp`
212
212
 
213
213
  The following are intentionally NOT supported:
@@ -379,6 +379,40 @@ Sometimes you need to pass a stub somewhere where it will be disposed, but also
379
379
 
380
380
  Hint: You can call `.dup()` on a property of a stub or promise, in order to create a stub backed by that property. This is particularly useful when you know in advance that the property is going to resolve to a stub: calling `.dup()` on it gives you a stub you can start using immediately, that otherwise behaves exactly the same as the eventual stub would if you awaited it.
381
381
 
382
+ #### Holding on to a callback past the call that delivered it
383
+
384
+ A common bidirectional-calling pattern is for the client to pass a callback to the server, which the server then invokes later (for example from a timer, an event handler, or a subsequent RPC). Because the callback parameter is a stub, and stubs in params are implicitly disposed when the call returns, the server must duplicate the stub with `.dup()` if it wants to invoke the callback after the call completes:
385
+
386
+ ```ts
387
+ import { type RpcStub, RpcTarget } from 'capnweb';
388
+
389
+ // A callback the client passes in: a stub wrapping a function.
390
+ type Listener = RpcStub<(msg: string) => void>;
391
+
392
+ class Api extends RpcTarget {
393
+ #listener?: Listener;
394
+
395
+ // Stubs passed as params are disposed when the call returns, so `.dup()`
396
+ // to keep a reference that outlives registerListener().
397
+ registerListener(listener: Listener) {
398
+ this.#listener?.[Symbol.dispose](); // release any previous listener
399
+ this.#listener = listener.dup();
400
+ }
401
+
402
+ // A *later* call can invoke the retained callback -- still valid thanks to .dup().
403
+ notify(msg: string) {
404
+ this.#listener?.(msg);
405
+ }
406
+
407
+ // Dispose our duplicate when done so the client-side stub can be freed.
408
+ [Symbol.dispose]() {
409
+ this.#listener?.[Symbol.dispose]();
410
+ }
411
+ }
412
+ ```
413
+
414
+ The same rule applies in the other direction: if the server returns a stub to the client and the client wants to keep using it after disposing the result, the client should `.dup()` the stub before the result is disposed.
415
+
382
416
  ### Listening for disposal
383
417
 
384
418
  An `RpcTarget` may declare a `Symbol.dispose` method. If it does, the RPC system will automatically invoke it when a stub pointing at it (and all its duplicates) has been disposed.
@@ -43,9 +43,22 @@ function typeForRpc(value) {
43
43
  case Array.prototype: return "array";
44
44
  case Date.prototype: return "date";
45
45
  case Uint8Array.prototype:
46
- case BUFFER_PROTOTYPE: return "bytes";
46
+ case BUFFER_PROTOTYPE:
47
+ case ArrayBuffer.prototype:
48
+ case DataView.prototype:
49
+ case Int8Array.prototype:
50
+ case Uint8ClampedArray.prototype:
51
+ case Int16Array.prototype:
52
+ case Uint16Array.prototype:
53
+ case Int32Array.prototype:
54
+ case Uint32Array.prototype:
55
+ case BigInt64Array.prototype:
56
+ case BigUint64Array.prototype:
57
+ case Float32Array.prototype:
58
+ case Float64Array.prototype: return "bytes";
47
59
  case WritableStream.prototype: return "writable";
48
60
  case ReadableStream.prototype: return "readable";
61
+ case URL.prototype: return "url";
49
62
  case Headers.prototype: return "headers";
50
63
  case Request.prototype: return "request";
51
64
  case Response.prototype: return "response";
@@ -380,6 +393,7 @@ var RpcPayload = class RpcPayload {
380
393
  case "date":
381
394
  case "bytes":
382
395
  case "blob":
396
+ case "url":
383
397
  case "error":
384
398
  case "undefined": return value;
385
399
  case "array": {
@@ -513,6 +527,30 @@ var RpcPayload = class RpcPayload {
513
527
  this.dispose();
514
528
  }
515
529
  }
530
+ async deliverStreamWrite(writer) {
531
+ try {
532
+ let promises = [];
533
+ this.deliverTo(this, "value", promises);
534
+ if (promises.length > 0) await Promise.all(promises);
535
+ let chunk = this.value[0];
536
+ if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {
537
+ if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {
538
+ value: () => this.dispose(),
539
+ writable: true,
540
+ enumerable: false,
541
+ configurable: true
542
+ });
543
+ await writer.write(chunk);
544
+ return RpcPayload.fromAppReturn(void 0);
545
+ }
546
+ await writer.write(chunk);
547
+ this.dispose();
548
+ return RpcPayload.fromAppReturn(void 0);
549
+ } catch (err) {
550
+ this.dispose();
551
+ throw err;
552
+ }
553
+ }
516
554
  async deliverResolve() {
517
555
  try {
518
556
  let promises = [];
@@ -553,6 +591,7 @@ var RpcPayload = class RpcPayload {
553
591
  case "bytes":
554
592
  case "blob":
555
593
  case "date":
594
+ case "url":
556
595
  case "error":
557
596
  case "undefined": return;
558
597
  case "array": {
@@ -635,6 +674,7 @@ var RpcPayload = class RpcPayload {
635
674
  case "rpc-target":
636
675
  case "writable":
637
676
  case "readable":
677
+ case "url":
638
678
  case "headers":
639
679
  case "request":
640
680
  case "response": return;
@@ -704,6 +744,7 @@ function followPath(value, parent, path, owner) {
704
744
  case "blob":
705
745
  case "date":
706
746
  case "error":
747
+ case "url":
707
748
  case "headers":
708
749
  case "request":
709
750
  case "response":
@@ -937,6 +978,71 @@ const DEFAULT_LIMITS = {
937
978
  maxDepth: 256,
938
979
  maxMessageSize: 32 * 1024 * 1024
939
980
  };
981
+ const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
982
+ const BYTE_CONTAINER_TYPE_NAMES = [
983
+ "ArrayBuffer",
984
+ "DataView",
985
+ "Int8Array",
986
+ "Uint8Array",
987
+ "Uint8ClampedArray",
988
+ "Int16Array",
989
+ "Uint16Array",
990
+ "Int32Array",
991
+ "Uint32Array",
992
+ "BigInt64Array",
993
+ "BigUint64Array",
994
+ "Float32Array",
995
+ "Float64Array"
996
+ ];
997
+ function isValidByteContainerName(value) {
998
+ return BYTE_CONTAINER_TYPE_NAMES.includes(value);
999
+ }
1000
+ const TYPED_ARRAY_ELEMENT_SIZE = {
1001
+ ArrayBuffer: void 0,
1002
+ DataView: void 0,
1003
+ Int8Array: void 0,
1004
+ Uint8Array: void 0,
1005
+ Uint8ClampedArray: void 0,
1006
+ Int16Array: 2,
1007
+ Uint16Array: 2,
1008
+ Int32Array: 4,
1009
+ Uint32Array: 4,
1010
+ BigInt64Array: 8,
1011
+ BigUint64Array: 8,
1012
+ Float32Array: 4,
1013
+ Float64Array: 8
1014
+ };
1015
+ const BYTE_CONTAINER_PROTOTYPES = {
1016
+ ArrayBuffer: ArrayBuffer.prototype,
1017
+ DataView: DataView.prototype,
1018
+ Int8Array: Int8Array.prototype,
1019
+ Uint8ClampedArray: Uint8ClampedArray.prototype,
1020
+ Int16Array: Int16Array.prototype,
1021
+ Uint16Array: Uint16Array.prototype,
1022
+ Int32Array: Int32Array.prototype,
1023
+ Uint32Array: Uint32Array.prototype,
1024
+ BigInt64Array: BigInt64Array.prototype,
1025
+ BigUint64Array: BigUint64Array.prototype,
1026
+ Float32Array: Float32Array.prototype,
1027
+ Float64Array: Float64Array.prototype
1028
+ };
1029
+ const BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();
1030
+ for (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);
1031
+ function swapByteOrder(bytes, elementSize) {
1032
+ if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);
1033
+ let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1034
+ for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {
1035
+ case 2:
1036
+ view.setUint16(offset, view.getUint16(offset, false), true);
1037
+ break;
1038
+ case 4:
1039
+ view.setUint32(offset, view.getUint32(offset, false), true);
1040
+ break;
1041
+ case 8:
1042
+ view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1043
+ break;
1044
+ }
1045
+ }
940
1046
  var NullExporter = class {
941
1047
  exportStub(stub) {
942
1048
  throw new Error("Cannot serialize RPC stubs without an RPC session.");
@@ -956,7 +1062,8 @@ async function streamToBlob(stream, type) {
956
1062
  let b = await new Response(stream).blob();
957
1063
  return b.type === type ? b : b.slice(0, b.size, type);
958
1064
  }
959
- const ERROR_TYPES = Object.assign(Object.create(null), {
1065
+ const ERROR_TYPES = {
1066
+ __proto__: null,
960
1067
  Error,
961
1068
  EvalError,
962
1069
  RangeError,
@@ -965,7 +1072,7 @@ const ERROR_TYPES = Object.assign(Object.create(null), {
965
1072
  TypeError,
966
1073
  URIError,
967
1074
  AggregateError
968
- });
1075
+ };
969
1076
  var Devaluator = class Devaluator {
970
1077
  exporter;
971
1078
  source;
@@ -1027,18 +1134,40 @@ var Devaluator = class Devaluator {
1027
1134
  return ["date", Number.isNaN(time) ? null : time];
1028
1135
  }
1029
1136
  case "bytes": {
1030
- let bytes = value;
1031
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return ["bytes", bytes];
1032
- if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
1137
+ let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1138
+ let bytes;
1139
+ if (alternateTypeName === "ArrayBuffer") bytes = new Uint8Array(value);
1140
+ else if (alternateTypeName === void 0) bytes = value;
1141
+ else {
1142
+ let view = value;
1143
+ bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1144
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];
1145
+ if (!NATIVE_LITTLE_ENDIAN && elementSize) {
1146
+ bytes = bytes.slice();
1147
+ swapByteOrder(bytes, elementSize);
1148
+ }
1149
+ }
1150
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1151
+ "bytes",
1152
+ bytes,
1153
+ alternateTypeName
1154
+ ];
1033
1155
  let b64;
1034
- if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1156
+ if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1157
+ else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1035
1158
  else {
1036
1159
  let binary = "";
1037
1160
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1038
1161
  b64 = btoa(binary);
1039
1162
  }
1040
- return ["bytes", b64.replace(/=+$/, "")];
1163
+ b64 = b64.replace(/=+$/, "");
1164
+ return alternateTypeName === void 0 ? ["bytes", b64] : [
1165
+ "bytes",
1166
+ b64,
1167
+ alternateTypeName
1168
+ ];
1041
1169
  }
1170
+ case "url": return ["url", value.href];
1042
1171
  case "headers": return ["headers", [...value]];
1043
1172
  case "request": {
1044
1173
  let req = value;
@@ -1290,18 +1419,46 @@ var Evaluator = class Evaluator {
1290
1419
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1291
1420
  if (typeof value[1] == "number") return new Date(value[1]);
1292
1421
  break;
1293
- case "bytes":
1294
- if (value[1] instanceof Uint8Array) return value[1];
1295
- if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1296
- else if (Uint8Array.fromBase64) return Uint8Array.fromBase64(value[1]);
1422
+ case "bytes": {
1423
+ let bytes;
1424
+ if (value[1] instanceof Uint8Array) bytes = value[1];
1425
+ else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1426
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1297
1427
  else {
1298
1428
  let bs = atob(value[1]);
1299
1429
  let len = bs.length;
1300
- let bytes = new Uint8Array(len);
1430
+ bytes = new Uint8Array(len);
1301
1431
  for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1302
- return bytes;
1303
1432
  }
1304
- break;
1433
+ else break;
1434
+ if (value.length === 2) return bytes;
1435
+ if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1436
+ if (!isValidByteContainerName(value[2])) {
1437
+ let marker = value[2].slice(0, 64);
1438
+ throw new TypeError(`Unknown bytes type marker: ${marker}`);
1439
+ }
1440
+ let marker = value[2];
1441
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];
1442
+ if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);
1443
+ let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1444
+ if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);
1445
+ switch (marker) {
1446
+ case "ArrayBuffer": return buffer;
1447
+ case "DataView": return new DataView(buffer);
1448
+ case "Int8Array": return new Int8Array(buffer);
1449
+ case "Uint8Array": return new Uint8Array(buffer);
1450
+ case "Uint8ClampedArray": return new Uint8ClampedArray(buffer);
1451
+ case "Int16Array": return new Int16Array(buffer);
1452
+ case "Uint16Array": return new Uint16Array(buffer);
1453
+ case "Int32Array": return new Int32Array(buffer);
1454
+ case "Uint32Array": return new Uint32Array(buffer);
1455
+ case "BigInt64Array": return new BigInt64Array(buffer);
1456
+ case "BigUint64Array": return new BigUint64Array(buffer);
1457
+ case "Float32Array": return new Float32Array(buffer);
1458
+ case "Float64Array": return new Float64Array(buffer);
1459
+ default:
1460
+ }
1461
+ }
1305
1462
  case "error":
1306
1463
  if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1307
1464
  let cls = ERROR_TYPES[value[1]] || Error;
@@ -1330,6 +1487,9 @@ var Evaluator = class Evaluator {
1330
1487
  case "inf": return Infinity;
1331
1488
  case "-inf": return -Infinity;
1332
1489
  case "nan": return NaN;
1490
+ case "url":
1491
+ if (value.length === 2 && typeof value[1] === "string") return new URL(value[1]);
1492
+ break;
1333
1493
  case "headers":
1334
1494
  if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);
1335
1495
  break;
@@ -1551,10 +1711,6 @@ var ImportTableEntry = class {
1551
1711
  resolution;
1552
1712
  onBrokenRegistrations;
1553
1713
  resolve(resolution) {
1554
- if (this.resolution) {
1555
- resolution.dispose();
1556
- return;
1557
- }
1558
1714
  if (this.localRefcount == 0) {
1559
1715
  resolution.dispose();
1560
1716
  return;
@@ -2154,6 +2310,8 @@ var RpcSession$1 = class {
2154
2310
 
2155
2311
  //#endregion
2156
2312
  //#region src/websocket.ts
2313
+ /** Close-frame reason max UTF-8 bytes: 125 payload - 2-byte status (RFC 6455 section 5.5). */
2314
+ const MAX_CLOSE_REASON_BYTES = 123;
2157
2315
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2158
2316
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2159
2317
  return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
@@ -2248,6 +2406,7 @@ var WebSocketTransport = class {
2248
2406
 
2249
2407
  //#endregion
2250
2408
  //#region src/batch.ts
2409
+ const yieldToMacrotask = typeof setImmediate === "function" ? () => new Promise((resolve) => setImmediate(resolve)) : () => new Promise((resolve) => setTimeout(resolve, 0));
2251
2410
  var BatchClientTransport = class {
2252
2411
  constructor(sendBatch) {
2253
2412
  this.#promise = this.#scheduleBatch(sendBatch);
@@ -2269,7 +2428,7 @@ var BatchClientTransport = class {
2269
2428
  this.#aborted = reason;
2270
2429
  }
2271
2430
  async #scheduleBatch(sendBatch) {
2272
- await new Promise((resolve) => setTimeout(resolve, 0));
2431
+ await yieldToMacrotask();
2273
2432
  if (this.#aborted !== void 0) throw this.#aborted;
2274
2433
  let batch = this.#batchToSend;
2275
2434
  this.#batchToSend = null;
@@ -2679,8 +2838,7 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2679
2838
  throw new Error(`Unknown WritableStream method: ${method}`);
2680
2839
  }
2681
2840
  if (method === "close" || method === "abort") state.closed = true;
2682
- let func = state.writer[method];
2683
- return new PromiseStubHook(args.deliverCall(func, state.writer).then((payload) => new PayloadStubHook(payload)));
2841
+ return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
2684
2842
  } catch (err) {
2685
2843
  return new ErrorStubHook(err);
2686
2844
  }