capnweb 0.0.0-78744ca → 0.0.0-7a6e5da

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.
@@ -76,9 +76,22 @@ function typeForRpc(value) {
76
76
  case Array.prototype: return "array";
77
77
  case Date.prototype: return "date";
78
78
  case Uint8Array.prototype:
79
- case BUFFER_PROTOTYPE: return "bytes";
79
+ case BUFFER_PROTOTYPE:
80
+ case ArrayBuffer.prototype:
81
+ case DataView.prototype:
82
+ case Int8Array.prototype:
83
+ case Uint8ClampedArray.prototype:
84
+ case Int16Array.prototype:
85
+ case Uint16Array.prototype:
86
+ case Int32Array.prototype:
87
+ case Uint32Array.prototype:
88
+ case BigInt64Array.prototype:
89
+ case BigUint64Array.prototype:
90
+ case Float32Array.prototype:
91
+ case Float64Array.prototype: return "bytes";
80
92
  case WritableStream.prototype: return "writable";
81
93
  case ReadableStream.prototype: return "readable";
94
+ case URL.prototype: return "url";
82
95
  case Headers.prototype: return "headers";
83
96
  case Request.prototype: return "request";
84
97
  case Response.prototype: return "response";
@@ -112,7 +125,14 @@ let streamImpl = {
112
125
  };
113
126
  var StubHook = class {
114
127
  stream(path, args) {
115
- let pulled = this.call(path, args).pull();
128
+ let hook = this.call(path, args);
129
+ let pulled;
130
+ try {
131
+ pulled = hook.pull();
132
+ } catch (err) {
133
+ hook.dispose();
134
+ throw err;
135
+ }
116
136
  let promise;
117
137
  if (pulled instanceof Promise) promise = pulled.then((p) => {
118
138
  p.dispose();
@@ -131,9 +151,11 @@ var ErrorStubHook = class extends StubHook {
131
151
  this.error = error;
132
152
  }
133
153
  call(path, args) {
154
+ args.dispose();
134
155
  return this;
135
156
  }
136
157
  map(path, captures, instructions) {
158
+ for (let cap of captures) cap.dispose();
137
159
  return this;
138
160
  }
139
161
  get(path) {
@@ -257,7 +279,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
257
279
  };
258
280
  var RpcPromise$1 = class extends RpcStub$1 {
259
281
  constructor(hook, pathIfPromise) {
260
- super(hook, pathIfPromise);
282
+ if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);
283
+ else {
284
+ if (pathIfPromise !== void 0) throw new TypeError("RpcPromise constructor expected one argument, received two.");
285
+ let kind = typeForRpc(hook);
286
+ if (kind === "rpc-promise") {
287
+ let raw = unwrapStubAndPath(hook);
288
+ if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);
289
+ else {
290
+ let adopted = raw.hook;
291
+ raw.hook = DISPOSED_HOOK;
292
+ super(adopted, []);
293
+ }
294
+ } else if (kind === "rpc-thenable") super(TargetStubHook.create(hook, void 0), []);
295
+ else {
296
+ let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));
297
+ promiseHook.ignoreUnhandledRejections();
298
+ super(promiseHook, []);
299
+ }
300
+ }
261
301
  }
262
302
  then(onfulfilled, onrejected) {
263
303
  return pullPromise(this).then(...arguments);
@@ -413,6 +453,7 @@ var RpcPayload = class RpcPayload {
413
453
  case "date":
414
454
  case "bytes":
415
455
  case "blob":
456
+ case "url":
416
457
  case "error":
417
458
  case "undefined": return value;
418
459
  case "array": {
@@ -546,6 +587,30 @@ var RpcPayload = class RpcPayload {
546
587
  this.dispose();
547
588
  }
548
589
  }
590
+ async deliverStreamWrite(writer) {
591
+ try {
592
+ let promises = [];
593
+ this.deliverTo(this, "value", promises);
594
+ if (promises.length > 0) await Promise.all(promises);
595
+ let chunk = this.value[0];
596
+ if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {
597
+ if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {
598
+ value: () => this.dispose(),
599
+ writable: true,
600
+ enumerable: false,
601
+ configurable: true
602
+ });
603
+ await writer.write(chunk);
604
+ return RpcPayload.fromAppReturn(void 0);
605
+ }
606
+ await writer.write(chunk);
607
+ this.dispose();
608
+ return RpcPayload.fromAppReturn(void 0);
609
+ } catch (err) {
610
+ this.dispose();
611
+ throw err;
612
+ }
613
+ }
549
614
  async deliverResolve() {
550
615
  try {
551
616
  let promises = [];
@@ -586,6 +651,7 @@ var RpcPayload = class RpcPayload {
586
651
  case "bytes":
587
652
  case "blob":
588
653
  case "date":
654
+ case "url":
589
655
  case "error":
590
656
  case "undefined": return;
591
657
  case "array": {
@@ -668,6 +734,7 @@ var RpcPayload = class RpcPayload {
668
734
  case "rpc-target":
669
735
  case "writable":
670
736
  case "readable":
737
+ case "url":
671
738
  case "headers":
672
739
  case "request":
673
740
  case "response": return;
@@ -737,6 +804,7 @@ function followPath(value, parent, path, owner) {
737
804
  case "blob":
738
805
  case "date":
739
806
  case "error":
807
+ case "url":
740
808
  case "headers":
741
809
  case "request":
742
810
  case "response":
@@ -769,17 +837,22 @@ function followPath(value, parent, path, owner) {
769
837
  }
770
838
  var ValueStubHook = class extends StubHook {
771
839
  call(path, args) {
840
+ let followResult;
772
841
  try {
773
842
  let { value, owner } = this.getValue();
774
- let followResult = followPath(value, void 0, path, owner);
775
- if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
776
- if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
777
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
778
- return new PayloadStubHook(payload);
779
- }));
843
+ followResult = followPath(value, void 0, path, owner);
780
844
  } catch (err) {
845
+ args.dispose();
781
846
  return new ErrorStubHook(err);
782
847
  }
848
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
849
+ if (typeof followResult.value != "function") {
850
+ args.dispose();
851
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
852
+ }
853
+ return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
854
+ return new PayloadStubHook(payload);
855
+ }));
783
856
  }
784
857
  map(path, captures, instructions) {
785
858
  try {
@@ -800,7 +873,10 @@ var ValueStubHook = class extends StubHook {
800
873
  get(path) {
801
874
  try {
802
875
  let { value, owner } = this.getValue();
803
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
876
+ if (path.length === 0 && owner === null) {
877
+ if (value instanceof Object && "then" in value) return this.dup();
878
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
879
+ }
804
880
  let followResult = followPath(value, void 0, path, owner);
805
881
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
806
882
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -903,7 +979,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
903
979
  this.target = void 0;
904
980
  }
905
981
  }
906
- onBroken(callback) {}
982
+ onBroken(callback) {
983
+ let target = this.target;
984
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
985
+ }
907
986
  };
908
987
  var PromiseStubHook = class PromiseStubHook extends StubHook {
909
988
  promise;
@@ -917,12 +996,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
917
996
  }
918
997
  call(path, args) {
919
998
  args.ensureDeepCopied();
920
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
999
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
1000
+ args.dispose();
1001
+ throw err;
1002
+ }));
921
1003
  }
922
1004
  stream(path, args) {
923
1005
  args.ensureDeepCopied();
924
- return { promise: this.promise.then((hook) => {
925
- return hook.stream(path, args).promise;
1006
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
1007
+ args.dispose();
1008
+ throw err;
926
1009
  }) };
927
1010
  }
928
1011
  map(path, captures, instructions) {
@@ -949,10 +1032,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
949
1032
  }, (err) => {});
950
1033
  }
951
1034
  dispose() {
952
- if (this.resolution) this.resolution.dispose();
953
- else this.promise.then((hook) => {
954
- hook.dispose();
955
- }, (err) => {});
1035
+ this.promise.then((hook) => hook.dispose(), () => {});
956
1036
  }
957
1037
  onBroken(callback) {
958
1038
  if (this.resolution) this.resolution.onBroken(callback);
@@ -964,6 +1044,77 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
964
1044
 
965
1045
  //#endregion
966
1046
  //#region src/serialize.ts
1047
+ const DEFAULT_MAX_DEPTH = 256;
1048
+ const DEFAULT_LIMITS = {
1049
+ maxBigIntDigits: 16384,
1050
+ maxDepth: 256,
1051
+ maxMessageSize: 32 * 1024 * 1024
1052
+ };
1053
+ const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
1054
+ const BYTE_CONTAINER_TYPE_NAMES = [
1055
+ "ArrayBuffer",
1056
+ "DataView",
1057
+ "Int8Array",
1058
+ "Uint8Array",
1059
+ "Uint8ClampedArray",
1060
+ "Int16Array",
1061
+ "Uint16Array",
1062
+ "Int32Array",
1063
+ "Uint32Array",
1064
+ "BigInt64Array",
1065
+ "BigUint64Array",
1066
+ "Float32Array",
1067
+ "Float64Array"
1068
+ ];
1069
+ function isValidByteContainerName(value) {
1070
+ return BYTE_CONTAINER_TYPE_NAMES.includes(value);
1071
+ }
1072
+ const TYPED_ARRAY_ELEMENT_SIZE = {
1073
+ ArrayBuffer: void 0,
1074
+ DataView: void 0,
1075
+ Int8Array: void 0,
1076
+ Uint8Array: void 0,
1077
+ Uint8ClampedArray: void 0,
1078
+ Int16Array: 2,
1079
+ Uint16Array: 2,
1080
+ Int32Array: 4,
1081
+ Uint32Array: 4,
1082
+ BigInt64Array: 8,
1083
+ BigUint64Array: 8,
1084
+ Float32Array: 4,
1085
+ Float64Array: 8
1086
+ };
1087
+ const BYTE_CONTAINER_PROTOTYPES = {
1088
+ ArrayBuffer: ArrayBuffer.prototype,
1089
+ DataView: DataView.prototype,
1090
+ Int8Array: Int8Array.prototype,
1091
+ Uint8ClampedArray: Uint8ClampedArray.prototype,
1092
+ Int16Array: Int16Array.prototype,
1093
+ Uint16Array: Uint16Array.prototype,
1094
+ Int32Array: Int32Array.prototype,
1095
+ Uint32Array: Uint32Array.prototype,
1096
+ BigInt64Array: BigInt64Array.prototype,
1097
+ BigUint64Array: BigUint64Array.prototype,
1098
+ Float32Array: Float32Array.prototype,
1099
+ Float64Array: Float64Array.prototype
1100
+ };
1101
+ const BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();
1102
+ for (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);
1103
+ function swapByteOrder(bytes, elementSize) {
1104
+ if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);
1105
+ let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1106
+ for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {
1107
+ case 2:
1108
+ view.setUint16(offset, view.getUint16(offset, false), true);
1109
+ break;
1110
+ case 4:
1111
+ view.setUint32(offset, view.getUint32(offset, false), true);
1112
+ break;
1113
+ case 8:
1114
+ view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1115
+ break;
1116
+ }
1117
+ }
967
1118
  var NullExporter = class {
968
1119
  exportStub(stub) {
969
1120
  throw new Error("Cannot serialize RPC stubs without an RPC session.");
@@ -984,6 +1135,7 @@ async function streamToBlob(stream, type) {
984
1135
  return b.type === type ? b : b.slice(0, b.size, type);
985
1136
  }
986
1137
  const ERROR_TYPES = {
1138
+ __proto__: null,
987
1139
  Error,
988
1140
  EvalError,
989
1141
  RangeError,
@@ -1015,7 +1167,7 @@ var Devaluator = class Devaluator {
1015
1167
  }
1016
1168
  exports;
1017
1169
  devaluateImpl(value, parent, depth) {
1018
- if (depth >= 64) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
1170
+ if (depth >= 256) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
1019
1171
  switch (typeForRpc(value)) {
1020
1172
  case "unsupported": {
1021
1173
  let msg;
@@ -1054,18 +1206,40 @@ var Devaluator = class Devaluator {
1054
1206
  return ["date", Number.isNaN(time) ? null : time];
1055
1207
  }
1056
1208
  case "bytes": {
1057
- let bytes = value;
1058
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return ["bytes", bytes];
1059
- if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
1209
+ let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1210
+ let bytes;
1211
+ if (alternateTypeName === "ArrayBuffer") bytes = new Uint8Array(value);
1212
+ else if (alternateTypeName === void 0) bytes = value;
1213
+ else {
1214
+ let view = value;
1215
+ bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1216
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];
1217
+ if (!NATIVE_LITTLE_ENDIAN && elementSize) {
1218
+ bytes = bytes.slice();
1219
+ swapByteOrder(bytes, elementSize);
1220
+ }
1221
+ }
1222
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1223
+ "bytes",
1224
+ bytes,
1225
+ alternateTypeName
1226
+ ];
1060
1227
  let b64;
1061
- if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1228
+ if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1229
+ else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1062
1230
  else {
1063
1231
  let binary = "";
1064
1232
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1065
1233
  b64 = btoa(binary);
1066
1234
  }
1067
- return ["bytes", b64.replace(/=+$/, "")];
1235
+ b64 = b64.replace(/=+$/, "");
1236
+ return alternateTypeName === void 0 ? ["bytes", b64] : [
1237
+ "bytes",
1238
+ b64,
1239
+ alternateTypeName
1240
+ ];
1068
1241
  }
1242
+ case "url": return ["url", value.href];
1069
1243
  case "headers": return ["headers", [...value]];
1070
1244
  case "request": {
1071
1245
  let req = value;
@@ -1249,6 +1423,9 @@ var NullImporter = class {
1249
1423
  getPipeReadable(exportId) {
1250
1424
  throw new Error("Cannot retrieve pipe readable without an RPC session.");
1251
1425
  }
1426
+ getLimits() {
1427
+ return DEFAULT_LIMITS;
1428
+ }
1252
1429
  };
1253
1430
  const NULL_IMPORTER = new NullImporter();
1254
1431
  function fixBrokenRequestBody(request, body) {
@@ -1266,16 +1443,21 @@ function streamToBlobPromise(stream, type) {
1266
1443
  var Evaluator = class Evaluator {
1267
1444
  importer;
1268
1445
  encodingLevel;
1446
+ limits;
1269
1447
  constructor(importer, encodingLevel = "string") {
1270
1448
  this.importer = importer;
1271
1449
  this.encodingLevel = encodingLevel;
1450
+ this.limits = importer.getLimits();
1272
1451
  }
1273
1452
  hooks = [];
1274
1453
  promises = [];
1275
1454
  evaluate(value) {
1455
+ return this.evaluateWithDepth(value, 0);
1456
+ }
1457
+ evaluateWithDepth(value, depth) {
1276
1458
  let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1277
1459
  try {
1278
- payload.value = this.evaluateImpl(value, payload, "value");
1460
+ payload.value = this.evaluateImpl(value, payload, "value", depth);
1279
1461
  return payload;
1280
1462
  } catch (err) {
1281
1463
  payload.dispose();
@@ -1285,35 +1467,70 @@ var Evaluator = class Evaluator {
1285
1467
  evaluateCopy(value) {
1286
1468
  return this.evaluate(structuredClone(value));
1287
1469
  }
1288
- evaluateImpl(value, parent, property) {
1470
+ evaluateImpl(value, parent, property, depth) {
1471
+ let maxDepth = this.limits.maxDepth;
1472
+ if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1289
1473
  if (this.encodingLevel === "structuredClonable") {
1290
1474
  if (value instanceof Date || typeof value === "bigint") return value;
1291
1475
  }
1292
1476
  if (value instanceof Array) {
1293
1477
  if (value.length == 1 && value[0] instanceof Array) {
1294
1478
  let result = value[0];
1295
- for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i);
1479
+ for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);
1296
1480
  return result;
1297
1481
  } else switch (value[0]) {
1298
1482
  case "bigint":
1299
- if (typeof value[1] == "string") return BigInt(value[1]);
1483
+ if (typeof value[1] == "string") {
1484
+ let digits = value[1];
1485
+ let maxBigIntDigits = this.limits.maxBigIntDigits;
1486
+ if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);
1487
+ return BigInt(digits);
1488
+ }
1300
1489
  break;
1301
1490
  case "date":
1302
1491
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1303
1492
  if (typeof value[1] == "number") return new Date(value[1]);
1304
1493
  break;
1305
- case "bytes":
1306
- if (value[1] instanceof Uint8Array) return value[1];
1307
- if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1308
- else if (Uint8Array.fromBase64) return Uint8Array.fromBase64(value[1]);
1494
+ case "bytes": {
1495
+ let bytes;
1496
+ if (value[1] instanceof Uint8Array) bytes = value[1];
1497
+ else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1498
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1309
1499
  else {
1310
1500
  let bs = atob(value[1]);
1311
1501
  let len = bs.length;
1312
- let bytes = new Uint8Array(len);
1502
+ bytes = new Uint8Array(len);
1313
1503
  for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1314
- return bytes;
1315
1504
  }
1316
- break;
1505
+ else break;
1506
+ if (value.length === 2) return bytes;
1507
+ if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1508
+ if (!isValidByteContainerName(value[2])) {
1509
+ let marker = value[2].slice(0, 64);
1510
+ throw new TypeError(`Unknown bytes type marker: ${marker}`);
1511
+ }
1512
+ let marker = value[2];
1513
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];
1514
+ if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);
1515
+ let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1516
+ if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);
1517
+ switch (marker) {
1518
+ case "ArrayBuffer": return buffer;
1519
+ case "DataView": return new DataView(buffer);
1520
+ case "Int8Array": return new Int8Array(buffer);
1521
+ case "Uint8Array": return new Uint8Array(buffer);
1522
+ case "Uint8ClampedArray": return new Uint8ClampedArray(buffer);
1523
+ case "Int16Array": return new Int16Array(buffer);
1524
+ case "Uint16Array": return new Uint16Array(buffer);
1525
+ case "Int32Array": return new Int32Array(buffer);
1526
+ case "Uint32Array": return new Uint32Array(buffer);
1527
+ case "BigInt64Array": return new BigInt64Array(buffer);
1528
+ case "BigUint64Array": return new BigUint64Array(buffer);
1529
+ case "Float32Array": return new Float32Array(buffer);
1530
+ case "Float64Array": return new Float64Array(buffer);
1531
+ default:
1532
+ }
1533
+ }
1317
1534
  case "error":
1318
1535
  if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1319
1536
  let cls = ERROR_TYPES[value[1]] || Error;
@@ -1326,7 +1543,11 @@ var Evaluator = class Evaluator {
1326
1543
  let propsObj = props;
1327
1544
  for (let key of Object.keys(propsObj)) {
1328
1545
  if (key === "name" || key === "message" || key === "stack") continue;
1329
- anyResult[key] = this.evaluateImpl(propsObj[key], result, key);
1546
+ if (key in Object.prototype || key === "toJSON") {
1547
+ this.evaluateImpl(propsObj[key], result, key, depth + 1);
1548
+ continue;
1549
+ }
1550
+ anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);
1330
1551
  }
1331
1552
  }
1332
1553
  return result;
@@ -1338,6 +1559,9 @@ var Evaluator = class Evaluator {
1338
1559
  case "inf": return Infinity;
1339
1560
  case "-inf": return -Infinity;
1340
1561
  case "nan": return NaN;
1562
+ case "url":
1563
+ if (value.length === 2 && typeof value[1] === "string") return new URL(value[1]);
1564
+ break;
1341
1565
  case "headers":
1342
1566
  if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);
1343
1567
  break;
@@ -1347,11 +1571,11 @@ var Evaluator = class Evaluator {
1347
1571
  let init = value[2];
1348
1572
  if (typeof init !== "object" || init === null) break;
1349
1573
  if (init.body) {
1350
- init.body = this.evaluateImpl(init.body, init, "body");
1574
+ init.body = this.evaluateImpl(init.body, init, "body", depth + 1);
1351
1575
  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.");
1352
1576
  }
1353
1577
  if (init.signal) {
1354
- init.signal = this.evaluateImpl(init.signal, init, "signal");
1578
+ init.signal = this.evaluateImpl(init.signal, init, "signal", depth + 1);
1355
1579
  if (!(init.signal instanceof AbortSignal)) throw new TypeError("Request siganl must be of type AbortSignal.");
1356
1580
  }
1357
1581
  if (init.headers && !(init.headers instanceof Array)) throw new TypeError("Request headers must be serialized as an array of pairs.");
@@ -1368,7 +1592,7 @@ var Evaluator = class Evaluator {
1368
1592
  }
1369
1593
  case "response": {
1370
1594
  if (value.length !== 3) break;
1371
- let body = this.evaluateImpl(value[1], parent, property);
1595
+ let body = this.evaluateImpl(value[1], parent, property, depth + 1);
1372
1596
  if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) {} else throw new TypeError("Response body must be of type ReadableStream.");
1373
1597
  let init = value[2];
1374
1598
  if (typeof init !== "object" || init === null) break;
@@ -1379,7 +1603,7 @@ var Evaluator = class Evaluator {
1379
1603
  case "blob": {
1380
1604
  if (value.length !== 3 || typeof value[1] !== "string") break;
1381
1605
  let contentType = value[1];
1382
- let content = this.evaluateImpl(value[2], parent, property);
1606
+ let content = this.evaluateImpl(value[2], parent, property, depth + 1);
1383
1607
  if (!(content instanceof ReadableStream)) throw new TypeError("Blob content must be serialized as a ReadableStream.");
1384
1608
  let promise = streamToBlobPromise(content, contentType);
1385
1609
  this.promises.push({
@@ -1420,7 +1644,7 @@ var Evaluator = class Evaluator {
1420
1644
  if (value.length == 3) return addStub(hook.get(path));
1421
1645
  let args = value[3];
1422
1646
  if (!(args instanceof Array)) break;
1423
- args = new Evaluator(this.importer).evaluate([args]);
1647
+ args = new Evaluator(this.importer).evaluateWithDepth([args], depth);
1424
1648
  return addStub(hook.call(path, args));
1425
1649
  }
1426
1650
  case "remap": {
@@ -1486,9 +1710,9 @@ var Evaluator = class Evaluator {
1486
1710
  } else if (value instanceof Object) {
1487
1711
  let result = value;
1488
1712
  for (let key in result) if (key in Object.prototype || key === "toJSON") {
1489
- this.evaluateImpl(result[key], result, key);
1713
+ this.evaluateImpl(result[key], result, key, depth + 1);
1490
1714
  delete result[key];
1491
- } else result[key] = this.evaluateImpl(result[key], result, key);
1715
+ } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);
1492
1716
  return result;
1493
1717
  } else return value;
1494
1718
  }
@@ -1637,24 +1861,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1637
1861
  if (this.entry) return this.entry;
1638
1862
  else throw new Error("This RpcImportHook was already disposed.");
1639
1863
  }
1864
+ getEntryTakingOwnership(disposeOwned) {
1865
+ try {
1866
+ return this.getEntry();
1867
+ } catch (err) {
1868
+ disposeOwned();
1869
+ throw err;
1870
+ }
1871
+ }
1640
1872
  call(path, args) {
1641
- let entry = this.getEntry();
1873
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1642
1874
  if (entry.resolution) return entry.resolution.call(path, args);
1643
1875
  else return entry.session.sendCall(entry.importId, path, args);
1644
1876
  }
1645
1877
  stream(path, args) {
1646
- let entry = this.getEntry();
1878
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1647
1879
  if (entry.resolution) return entry.resolution.stream(path, args);
1648
1880
  else return entry.session.sendStream(entry.importId, path, args);
1649
1881
  }
1650
1882
  map(path, captures, instructions) {
1651
- let entry;
1652
- try {
1653
- entry = this.getEntry();
1654
- } catch (err) {
1883
+ let entry = this.getEntryTakingOwnership(() => {
1655
1884
  for (let cap of captures) cap.dispose();
1656
- throw err;
1657
- }
1885
+ });
1658
1886
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1659
1887
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1660
1888
  }
@@ -1711,6 +1939,7 @@ var RpcSessionImpl = class {
1711
1939
  pullCount = 0;
1712
1940
  onBrokenCallbacks = [];
1713
1941
  encodingLevel;
1942
+ limits;
1714
1943
  constructor(transport, mainHook, options) {
1715
1944
  this.transport = transport;
1716
1945
  this.options = options;
@@ -1723,6 +1952,10 @@ var RpcSessionImpl = class {
1723
1952
  }
1724
1953
  }
1725
1954
  this.encodingLevel = level;
1955
+ this.limits = {
1956
+ ...DEFAULT_LIMITS,
1957
+ ...options.limits
1958
+ };
1726
1959
  this.exports.push({
1727
1960
  hook: mainHook,
1728
1961
  refcount: 1
@@ -1865,6 +2098,9 @@ var RpcSessionImpl = class {
1865
2098
  entry.pipeReadable = void 0;
1866
2099
  return readable;
1867
2100
  }
2101
+ getLimits() {
2102
+ return this.limits;
2103
+ }
1868
2104
  createPipe(readable, readableHook) {
1869
2105
  if (this.abortReason) throw this.abortReason;
1870
2106
  this.send(["pipe"]);
@@ -1907,14 +2143,23 @@ var RpcSessionImpl = class {
1907
2143
  }
1908
2144
  }
1909
2145
  sendCall(id, path, args) {
1910
- if (this.abortReason) throw this.abortReason;
2146
+ if (this.abortReason) {
2147
+ args?.dispose();
2148
+ throw this.abortReason;
2149
+ }
1911
2150
  let value = [
1912
2151
  "pipeline",
1913
2152
  id,
1914
2153
  path
1915
2154
  ];
1916
2155
  if (args) {
1917
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2156
+ let devalue;
2157
+ try {
2158
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2159
+ } catch (err) {
2160
+ args.dispose();
2161
+ throw err;
2162
+ }
1918
2163
  value.push(devalue[0]);
1919
2164
  }
1920
2165
  this.send(["push", value]);
@@ -1923,13 +2168,22 @@ var RpcSessionImpl = class {
1923
2168
  return new RpcImportHook(true, entry);
1924
2169
  }
1925
2170
  sendStream(id, path, args) {
1926
- if (this.abortReason) throw this.abortReason;
2171
+ if (this.abortReason) {
2172
+ args.dispose();
2173
+ throw this.abortReason;
2174
+ }
1927
2175
  let value = [
1928
2176
  "pipeline",
1929
2177
  id,
1930
2178
  path
1931
2179
  ];
1932
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2180
+ let devalue;
2181
+ try {
2182
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2183
+ } catch (err) {
2184
+ args.dispose();
2185
+ throw err;
2186
+ }
1933
2187
  value.push(devalue[0]);
1934
2188
  let msg = ["stream", value];
1935
2189
  let size = this.send(msg);
@@ -2024,6 +2278,7 @@ var RpcSessionImpl = class {
2024
2278
  } finally {
2025
2279
  if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;
2026
2280
  }
2281
+ if (this.encodingLevel === "string" && raw.length > this.limits.maxMessageSize) throw new TypeError(`Incoming message exceeds maximum size of ${this.limits.maxMessageSize} UTF-16 code units.`);
2027
2282
  if (this.abortReason) break;
2028
2283
  let msg = this.encodingLevel === "string" ? JSON.parse(raw) : raw;
2029
2284
  if (msg instanceof Array) switch (msg[0]) {
@@ -2098,7 +2353,7 @@ var RpcSessionImpl = class {
2098
2353
  case "abort": {
2099
2354
  let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2100
2355
  payload.dispose();
2101
- this.abort(payload, false);
2356
+ this.abort(payload.value, false);
2102
2357
  break;
2103
2358
  }
2104
2359
  }
@@ -2149,6 +2404,8 @@ var RpcSession$1 = class {
2149
2404
 
2150
2405
  //#endregion
2151
2406
  //#region src/websocket.ts
2407
+ /** Close-frame reason max UTF-8 bytes: 125 payload - 2-byte status (RFC 6455 section 5.5). */
2408
+ const MAX_CLOSE_REASON_BYTES = 123;
2152
2409
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2153
2410
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2154
2411
  return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
@@ -2224,6 +2481,8 @@ var WebSocketTransport = class {
2224
2481
  let message;
2225
2482
  if (reason instanceof Error) message = reason.message;
2226
2483
  else message = `${reason}`;
2484
+ let reasonBytes = new TextEncoder().encode(message);
2485
+ if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });
2227
2486
  this.#webSocket.close(3e3, message);
2228
2487
  if (!this.#error) this.#error = reason;
2229
2488
  }
@@ -2241,6 +2500,7 @@ var WebSocketTransport = class {
2241
2500
 
2242
2501
  //#endregion
2243
2502
  //#region src/batch.ts
2503
+ const yieldToMacrotask = typeof setImmediate === "function" ? () => new Promise((resolve) => setImmediate(resolve)) : () => new Promise((resolve) => setTimeout(resolve, 0));
2244
2504
  var BatchClientTransport = class {
2245
2505
  constructor(sendBatch) {
2246
2506
  this.#promise = this.#scheduleBatch(sendBatch);
@@ -2262,7 +2522,7 @@ var BatchClientTransport = class {
2262
2522
  this.#aborted = reason;
2263
2523
  }
2264
2524
  async #scheduleBatch(sendBatch) {
2265
- await new Promise((resolve) => setTimeout(resolve, 0));
2525
+ await yieldToMacrotask();
2266
2526
  if (this.#aborted !== void 0) throw this.#aborted;
2267
2527
  let batch = this.#batchToSend;
2268
2528
  this.#batchToSend = null;
@@ -2554,9 +2814,11 @@ var MapVariableHook = class extends StubHook {
2554
2814
  else throwMapperBuilderUseError();
2555
2815
  }
2556
2816
  call(path, args) {
2817
+ args.dispose();
2557
2818
  throwMapperBuilderUseError();
2558
2819
  }
2559
2820
  map(path, captures, instructions) {
2821
+ for (let cap of captures) cap.dispose();
2560
2822
  throwMapperBuilderUseError();
2561
2823
  }
2562
2824
  pull() {
@@ -2609,6 +2871,9 @@ var MapApplicator = class {
2609
2871
  getPipeReadable(exportId) {
2610
2872
  throw new Error("A mapper function cannot use pipe readables.");
2611
2873
  }
2874
+ getLimits() {
2875
+ return DEFAULT_LIMITS;
2876
+ }
2612
2877
  };
2613
2878
  function applyMapToElement(input, parent, owner, captures, instructions) {
2614
2879
  let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
@@ -2664,14 +2929,11 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2664
2929
  let state = this.getState();
2665
2930
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2666
2931
  const method = path[0];
2667
- if (method !== "write" && method !== "close" && method !== "abort") {
2668
- args.dispose();
2669
- throw new Error(`Unknown WritableStream method: ${method}`);
2670
- }
2932
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2671
2933
  if (method === "close" || method === "abort") state.closed = true;
2672
- let func = state.writer[method];
2673
- return new PromiseStubHook(args.deliverCall(func, state.writer).then((payload) => new PayloadStubHook(payload)));
2934
+ return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
2674
2935
  } catch (err) {
2936
+ args.dispose();
2675
2937
  return new ErrorStubHook(err);
2676
2938
  }
2677
2939
  }
@@ -2947,16 +3209,18 @@ let newMessagePortRpcSession = newMessagePortRpcSession$1;
2947
3209
  * credentials as parameters and returns the authorized API), then cross-origin requests should
2948
3210
  * be safe.
2949
3211
  */
2950
- async function newWorkersRpcResponse(request, localMain) {
3212
+ async function newWorkersRpcResponse(request, localMain, options) {
2951
3213
  if (request.method === "POST") {
2952
- let response = await newHttpBatchRpcResponse(request, localMain);
3214
+ let response = await newHttpBatchRpcResponse(request, localMain, options);
2953
3215
  response.headers.set("Access-Control-Allow-Origin", "*");
2954
3216
  return response;
2955
- } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain);
3217
+ } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain, options);
2956
3218
  else return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
2957
3219
  }
2958
3220
 
2959
3221
  //#endregion
3222
+ exports.DEFAULT_LIMITS = DEFAULT_LIMITS;
3223
+ exports.DEFAULT_MAX_DEPTH = DEFAULT_MAX_DEPTH;
2960
3224
  exports.RpcPromise = RpcPromise;
2961
3225
  exports.RpcSession = RpcSession;
2962
3226
  exports.RpcStub = RpcStub;