capnweb 0.0.0-610ab3a → 0.0.0-667958e

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.
@@ -405,6 +439,8 @@ If anything happens to the stub that would cause all further method calls and pr
405
439
 
406
440
  * Cap'n Web's pipelining can make it easy for a malicious client to enqueue a large amount of work to occur on a server. To mitigate this, we recommend implementing rate limits on expensive operations. If using Cloudflare Workers, you may also consider configuring [per-request CPU limits](https://developers.cloudflare.com/workers/wrangler/configuration/#limits) to be lower than the default 30s. Note that in stateless Workers (i.e. not Durable Objects), the system considers an entire WebSocket session to be one "request" for CPU limits purposes.
407
441
 
442
+ * Cap'n Web applies receiver-side resource limits before expensive message processing, including a maximum incoming message size before `JSON.parse`. If your app is exposed to untrusted peers, also configure native transport or socket payload limits where available, such as `ws`'s `maxPayload`, Bun's `maxPayloadLength`, or the runtime's built-in WebSocket cap. Cap'n Web's own check runs after `RpcTransport.receive()` has returned a complete message string, so transport-level limits are still the first line of defense against buffering very large frames.
443
+
408
444
  * Cap'n Web currently does not provide any runtime type checking. When using TypeScript, keep in mind that types are checked only at compile time. A malicious client can send types you did not expect, and this could cause you application to behave in unexpected ways. For example, MongoDB uses special property names to express queries; placing attacker-provided values directly into queries can result in query injection vulnerabilities (similar to SQL injection). Of course, JSON has always had the same problem, and there exists tooling to solve it. You might consider using a runtime type-checking framework like Zod to check your inputs. In the future, we hope to explore auto-generating type-checking code based on TypeScript types.
409
445
 
410
446
  ## Setting up a session
@@ -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":
@@ -931,6 +972,77 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
931
972
 
932
973
  //#endregion
933
974
  //#region src/serialize.ts
975
+ const DEFAULT_MAX_DEPTH = 256;
976
+ const DEFAULT_LIMITS = {
977
+ maxBigIntDigits: 16384,
978
+ maxDepth: 256,
979
+ maxMessageSize: 32 * 1024 * 1024
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
+ }
934
1046
  var NullExporter = class {
935
1047
  exportStub(stub) {
936
1048
  throw new Error("Cannot serialize RPC stubs without an RPC session.");
@@ -951,6 +1063,7 @@ async function streamToBlob(stream, type) {
951
1063
  return b.type === type ? b : b.slice(0, b.size, type);
952
1064
  }
953
1065
  const ERROR_TYPES = {
1066
+ __proto__: null,
954
1067
  Error,
955
1068
  EvalError,
956
1069
  RangeError,
@@ -982,7 +1095,7 @@ var Devaluator = class Devaluator {
982
1095
  }
983
1096
  exports;
984
1097
  devaluateImpl(value, parent, depth) {
985
- if (depth >= 64) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
1098
+ if (depth >= 256) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
986
1099
  switch (typeForRpc(value)) {
987
1100
  case "unsupported": {
988
1101
  let msg;
@@ -1021,18 +1134,40 @@ var Devaluator = class Devaluator {
1021
1134
  return ["date", Number.isNaN(time) ? null : time];
1022
1135
  }
1023
1136
  case "bytes": {
1024
- let bytes = value;
1025
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return ["bytes", bytes];
1026
- 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
+ ];
1027
1155
  let b64;
1028
- 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");
1029
1158
  else {
1030
1159
  let binary = "";
1031
1160
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1032
1161
  b64 = btoa(binary);
1033
1162
  }
1034
- return ["bytes", b64.replace(/=+$/, "")];
1163
+ b64 = b64.replace(/=+$/, "");
1164
+ return alternateTypeName === void 0 ? ["bytes", b64] : [
1165
+ "bytes",
1166
+ b64,
1167
+ alternateTypeName
1168
+ ];
1035
1169
  }
1170
+ case "url": return ["url", value.href];
1036
1171
  case "headers": return ["headers", [...value]];
1037
1172
  case "request": {
1038
1173
  let req = value;
@@ -1216,6 +1351,9 @@ var NullImporter = class {
1216
1351
  getPipeReadable(exportId) {
1217
1352
  throw new Error("Cannot retrieve pipe readable without an RPC session.");
1218
1353
  }
1354
+ getLimits() {
1355
+ return DEFAULT_LIMITS;
1356
+ }
1219
1357
  };
1220
1358
  const NULL_IMPORTER = new NullImporter();
1221
1359
  function fixBrokenRequestBody(request, body) {
@@ -1233,16 +1371,21 @@ function streamToBlobPromise(stream, type) {
1233
1371
  var Evaluator = class Evaluator {
1234
1372
  importer;
1235
1373
  encodingLevel;
1374
+ limits;
1236
1375
  constructor(importer, encodingLevel = "string") {
1237
1376
  this.importer = importer;
1238
1377
  this.encodingLevel = encodingLevel;
1378
+ this.limits = importer.getLimits();
1239
1379
  }
1240
1380
  hooks = [];
1241
1381
  promises = [];
1242
1382
  evaluate(value) {
1383
+ return this.evaluateWithDepth(value, 0);
1384
+ }
1385
+ evaluateWithDepth(value, depth) {
1243
1386
  let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1244
1387
  try {
1245
- payload.value = this.evaluateImpl(value, payload, "value");
1388
+ payload.value = this.evaluateImpl(value, payload, "value", depth);
1246
1389
  return payload;
1247
1390
  } catch (err) {
1248
1391
  payload.dispose();
@@ -1252,35 +1395,70 @@ var Evaluator = class Evaluator {
1252
1395
  evaluateCopy(value) {
1253
1396
  return this.evaluate(structuredClone(value));
1254
1397
  }
1255
- evaluateImpl(value, parent, property) {
1398
+ evaluateImpl(value, parent, property, depth) {
1399
+ let maxDepth = this.limits.maxDepth;
1400
+ if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1256
1401
  if (this.encodingLevel === "structuredClonable") {
1257
1402
  if (value instanceof Date || typeof value === "bigint") return value;
1258
1403
  }
1259
1404
  if (value instanceof Array) {
1260
1405
  if (value.length == 1 && value[0] instanceof Array) {
1261
1406
  let result = value[0];
1262
- for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i);
1407
+ for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);
1263
1408
  return result;
1264
1409
  } else switch (value[0]) {
1265
1410
  case "bigint":
1266
- if (typeof value[1] == "string") return BigInt(value[1]);
1411
+ if (typeof value[1] == "string") {
1412
+ let digits = value[1];
1413
+ let maxBigIntDigits = this.limits.maxBigIntDigits;
1414
+ if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);
1415
+ return BigInt(digits);
1416
+ }
1267
1417
  break;
1268
1418
  case "date":
1269
1419
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1270
1420
  if (typeof value[1] == "number") return new Date(value[1]);
1271
1421
  break;
1272
- case "bytes":
1273
- if (value[1] instanceof Uint8Array) return value[1];
1274
- if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1275
- 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]);
1276
1427
  else {
1277
1428
  let bs = atob(value[1]);
1278
1429
  let len = bs.length;
1279
- let bytes = new Uint8Array(len);
1430
+ bytes = new Uint8Array(len);
1280
1431
  for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1281
- return bytes;
1282
1432
  }
1283
- 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
+ }
1284
1462
  case "error":
1285
1463
  if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1286
1464
  let cls = ERROR_TYPES[value[1]] || Error;
@@ -1293,7 +1471,11 @@ var Evaluator = class Evaluator {
1293
1471
  let propsObj = props;
1294
1472
  for (let key of Object.keys(propsObj)) {
1295
1473
  if (key === "name" || key === "message" || key === "stack") continue;
1296
- anyResult[key] = this.evaluateImpl(propsObj[key], result, key);
1474
+ if (key in Object.prototype || key === "toJSON") {
1475
+ this.evaluateImpl(propsObj[key], result, key, depth + 1);
1476
+ continue;
1477
+ }
1478
+ anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);
1297
1479
  }
1298
1480
  }
1299
1481
  return result;
@@ -1305,6 +1487,9 @@ var Evaluator = class Evaluator {
1305
1487
  case "inf": return Infinity;
1306
1488
  case "-inf": return -Infinity;
1307
1489
  case "nan": return NaN;
1490
+ case "url":
1491
+ if (value.length === 2 && typeof value[1] === "string") return new URL(value[1]);
1492
+ break;
1308
1493
  case "headers":
1309
1494
  if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);
1310
1495
  break;
@@ -1314,11 +1499,11 @@ var Evaluator = class Evaluator {
1314
1499
  let init = value[2];
1315
1500
  if (typeof init !== "object" || init === null) break;
1316
1501
  if (init.body) {
1317
- init.body = this.evaluateImpl(init.body, init, "body");
1502
+ init.body = this.evaluateImpl(init.body, init, "body", depth + 1);
1318
1503
  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.");
1319
1504
  }
1320
1505
  if (init.signal) {
1321
- init.signal = this.evaluateImpl(init.signal, init, "signal");
1506
+ init.signal = this.evaluateImpl(init.signal, init, "signal", depth + 1);
1322
1507
  if (!(init.signal instanceof AbortSignal)) throw new TypeError("Request siganl must be of type AbortSignal.");
1323
1508
  }
1324
1509
  if (init.headers && !(init.headers instanceof Array)) throw new TypeError("Request headers must be serialized as an array of pairs.");
@@ -1335,7 +1520,7 @@ var Evaluator = class Evaluator {
1335
1520
  }
1336
1521
  case "response": {
1337
1522
  if (value.length !== 3) break;
1338
- let body = this.evaluateImpl(value[1], parent, property);
1523
+ let body = this.evaluateImpl(value[1], parent, property, depth + 1);
1339
1524
  if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) {} else throw new TypeError("Response body must be of type ReadableStream.");
1340
1525
  let init = value[2];
1341
1526
  if (typeof init !== "object" || init === null) break;
@@ -1346,7 +1531,7 @@ var Evaluator = class Evaluator {
1346
1531
  case "blob": {
1347
1532
  if (value.length !== 3 || typeof value[1] !== "string") break;
1348
1533
  let contentType = value[1];
1349
- let content = this.evaluateImpl(value[2], parent, property);
1534
+ let content = this.evaluateImpl(value[2], parent, property, depth + 1);
1350
1535
  if (!(content instanceof ReadableStream)) throw new TypeError("Blob content must be serialized as a ReadableStream.");
1351
1536
  let promise = streamToBlobPromise(content, contentType);
1352
1537
  this.promises.push({
@@ -1387,7 +1572,7 @@ var Evaluator = class Evaluator {
1387
1572
  if (value.length == 3) return addStub(hook.get(path));
1388
1573
  let args = value[3];
1389
1574
  if (!(args instanceof Array)) break;
1390
- args = new Evaluator(this.importer).evaluate([args]);
1575
+ args = new Evaluator(this.importer).evaluateWithDepth([args], depth);
1391
1576
  return addStub(hook.call(path, args));
1392
1577
  }
1393
1578
  case "remap": {
@@ -1453,9 +1638,9 @@ var Evaluator = class Evaluator {
1453
1638
  } else if (value instanceof Object) {
1454
1639
  let result = value;
1455
1640
  for (let key in result) if (key in Object.prototype || key === "toJSON") {
1456
- this.evaluateImpl(result[key], result, key);
1641
+ this.evaluateImpl(result[key], result, key, depth + 1);
1457
1642
  delete result[key];
1458
- } else result[key] = this.evaluateImpl(result[key], result, key);
1643
+ } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);
1459
1644
  return result;
1460
1645
  } else return value;
1461
1646
  }
@@ -1678,6 +1863,7 @@ var RpcSessionImpl = class {
1678
1863
  pullCount = 0;
1679
1864
  onBrokenCallbacks = [];
1680
1865
  encodingLevel;
1866
+ limits;
1681
1867
  constructor(transport, mainHook, options) {
1682
1868
  this.transport = transport;
1683
1869
  this.options = options;
@@ -1690,6 +1876,10 @@ var RpcSessionImpl = class {
1690
1876
  }
1691
1877
  }
1692
1878
  this.encodingLevel = level;
1879
+ this.limits = {
1880
+ ...DEFAULT_LIMITS,
1881
+ ...options.limits
1882
+ };
1693
1883
  this.exports.push({
1694
1884
  hook: mainHook,
1695
1885
  refcount: 1
@@ -1832,6 +2022,9 @@ var RpcSessionImpl = class {
1832
2022
  entry.pipeReadable = void 0;
1833
2023
  return readable;
1834
2024
  }
2025
+ getLimits() {
2026
+ return this.limits;
2027
+ }
1835
2028
  createPipe(readable, readableHook) {
1836
2029
  if (this.abortReason) throw this.abortReason;
1837
2030
  this.send(["pipe"]);
@@ -1991,6 +2184,7 @@ var RpcSessionImpl = class {
1991
2184
  } finally {
1992
2185
  if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;
1993
2186
  }
2187
+ 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.`);
1994
2188
  if (this.abortReason) break;
1995
2189
  let msg = this.encodingLevel === "string" ? JSON.parse(raw) : raw;
1996
2190
  if (msg instanceof Array) switch (msg[0]) {
@@ -2065,7 +2259,7 @@ var RpcSessionImpl = class {
2065
2259
  case "abort": {
2066
2260
  let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2067
2261
  payload.dispose();
2068
- this.abort(payload, false);
2262
+ this.abort(payload.value, false);
2069
2263
  break;
2070
2264
  }
2071
2265
  }
@@ -2116,6 +2310,8 @@ var RpcSession$1 = class {
2116
2310
 
2117
2311
  //#endregion
2118
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;
2119
2315
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2120
2316
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2121
2317
  return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
@@ -2191,6 +2387,8 @@ var WebSocketTransport = class {
2191
2387
  let message;
2192
2388
  if (reason instanceof Error) message = reason.message;
2193
2389
  else message = `${reason}`;
2390
+ let reasonBytes = new TextEncoder().encode(message);
2391
+ if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });
2194
2392
  this.#webSocket.close(3e3, message);
2195
2393
  if (!this.#error) this.#error = reason;
2196
2394
  }
@@ -2208,6 +2406,7 @@ var WebSocketTransport = class {
2208
2406
 
2209
2407
  //#endregion
2210
2408
  //#region src/batch.ts
2409
+ const yieldToMacrotask = typeof setImmediate === "function" ? () => new Promise((resolve) => setImmediate(resolve)) : () => new Promise((resolve) => setTimeout(resolve, 0));
2211
2410
  var BatchClientTransport = class {
2212
2411
  constructor(sendBatch) {
2213
2412
  this.#promise = this.#scheduleBatch(sendBatch);
@@ -2229,7 +2428,7 @@ var BatchClientTransport = class {
2229
2428
  this.#aborted = reason;
2230
2429
  }
2231
2430
  async #scheduleBatch(sendBatch) {
2232
- await new Promise((resolve) => setTimeout(resolve, 0));
2431
+ await yieldToMacrotask();
2233
2432
  if (this.#aborted !== void 0) throw this.#aborted;
2234
2433
  let batch = this.#batchToSend;
2235
2434
  this.#batchToSend = null;
@@ -2576,6 +2775,9 @@ var MapApplicator = class {
2576
2775
  getPipeReadable(exportId) {
2577
2776
  throw new Error("A mapper function cannot use pipe readables.");
2578
2777
  }
2778
+ getLimits() {
2779
+ return DEFAULT_LIMITS;
2780
+ }
2579
2781
  };
2580
2782
  function applyMapToElement(input, parent, owner, captures, instructions) {
2581
2783
  let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
@@ -2636,8 +2838,7 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2636
2838
  throw new Error(`Unknown WritableStream method: ${method}`);
2637
2839
  }
2638
2840
  if (method === "close" || method === "abort") state.closed = true;
2639
- let func = state.writer[method];
2640
- 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)));
2641
2842
  } catch (err) {
2642
2843
  return new ErrorStubHook(err);
2643
2844
  }
@@ -2914,12 +3115,12 @@ let newMessagePortRpcSession = newMessagePortRpcSession$1;
2914
3115
  * credentials as parameters and returns the authorized API), then cross-origin requests should
2915
3116
  * be safe.
2916
3117
  */
2917
- async function newWorkersRpcResponse(request, localMain) {
3118
+ async function newWorkersRpcResponse(request, localMain, options) {
2918
3119
  if (request.method === "POST") {
2919
- let response = await newHttpBatchRpcResponse(request, localMain);
3120
+ let response = await newHttpBatchRpcResponse(request, localMain, options);
2920
3121
  response.headers.set("Access-Control-Allow-Origin", "*");
2921
3122
  return response;
2922
- } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain);
3123
+ } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain, options);
2923
3124
  else return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
2924
3125
  }
2925
3126
 
@@ -3041,6 +3242,8 @@ let newBunWebSocketRpcSession = newBunWebSocketRpcSession$1;
3041
3242
 
3042
3243
  //#endregion
3043
3244
  exports.BunWebSocketTransport = BunWebSocketTransport;
3245
+ exports.DEFAULT_LIMITS = DEFAULT_LIMITS;
3246
+ exports.DEFAULT_MAX_DEPTH = DEFAULT_MAX_DEPTH;
3044
3247
  exports.RpcPromise = RpcPromise;
3045
3248
  exports.RpcSession = RpcSession;
3046
3249
  exports.RpcStub = RpcStub;