capnweb 0.0.0-79bc296 → 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.
package/dist/index-bun.js CHANGED
@@ -41,9 +41,22 @@ function typeForRpc(value) {
41
41
  case Array.prototype: return "array";
42
42
  case Date.prototype: return "date";
43
43
  case Uint8Array.prototype:
44
- case BUFFER_PROTOTYPE: return "bytes";
44
+ case BUFFER_PROTOTYPE:
45
+ case ArrayBuffer.prototype:
46
+ case DataView.prototype:
47
+ case Int8Array.prototype:
48
+ case Uint8ClampedArray.prototype:
49
+ case Int16Array.prototype:
50
+ case Uint16Array.prototype:
51
+ case Int32Array.prototype:
52
+ case Uint32Array.prototype:
53
+ case BigInt64Array.prototype:
54
+ case BigUint64Array.prototype:
55
+ case Float32Array.prototype:
56
+ case Float64Array.prototype: return "bytes";
45
57
  case WritableStream.prototype: return "writable";
46
58
  case ReadableStream.prototype: return "readable";
59
+ case URL.prototype: return "url";
47
60
  case Headers.prototype: return "headers";
48
61
  case Request.prototype: return "request";
49
62
  case Response.prototype: return "response";
@@ -77,7 +90,14 @@ let streamImpl = {
77
90
  };
78
91
  var StubHook = class {
79
92
  stream(path, args) {
80
- let pulled = this.call(path, args).pull();
93
+ let hook = this.call(path, args);
94
+ let pulled;
95
+ try {
96
+ pulled = hook.pull();
97
+ } catch (err) {
98
+ hook.dispose();
99
+ throw err;
100
+ }
81
101
  let promise;
82
102
  if (pulled instanceof Promise) promise = pulled.then((p) => {
83
103
  p.dispose();
@@ -96,9 +116,11 @@ var ErrorStubHook = class extends StubHook {
96
116
  this.error = error;
97
117
  }
98
118
  call(path, args) {
119
+ args.dispose();
99
120
  return this;
100
121
  }
101
122
  map(path, captures, instructions) {
123
+ for (let cap of captures) cap.dispose();
102
124
  return this;
103
125
  }
104
126
  get(path) {
@@ -222,7 +244,25 @@ var RpcStub$1 = class RpcStub$1 extends RpcTarget$1 {
222
244
  };
223
245
  var RpcPromise$1 = class extends RpcStub$1 {
224
246
  constructor(hook, pathIfPromise) {
225
- super(hook, pathIfPromise);
247
+ if (hook instanceof StubHook) super(hook, pathIfPromise ?? []);
248
+ else {
249
+ if (pathIfPromise !== void 0) throw new TypeError("RpcPromise constructor expected one argument, received two.");
250
+ let kind = typeForRpc(hook);
251
+ if (kind === "rpc-promise") {
252
+ let raw = unwrapStubAndPath(hook);
253
+ if (raw.pathIfPromise.length > 0) super(raw.hook, raw.pathIfPromise);
254
+ else {
255
+ let adopted = raw.hook;
256
+ raw.hook = DISPOSED_HOOK;
257
+ super(adopted, []);
258
+ }
259
+ } else if (kind === "rpc-thenable") super(TargetStubHook.create(hook, void 0), []);
260
+ else {
261
+ let promiseHook = new PromiseStubHook(Promise.resolve(hook).then((value) => new PayloadStubHook(RpcPayload.fromAppReturn(value))));
262
+ promiseHook.ignoreUnhandledRejections();
263
+ super(promiseHook, []);
264
+ }
265
+ }
226
266
  }
227
267
  then(onfulfilled, onrejected) {
228
268
  return pullPromise(this).then(...arguments);
@@ -378,6 +418,7 @@ var RpcPayload = class RpcPayload {
378
418
  case "date":
379
419
  case "bytes":
380
420
  case "blob":
421
+ case "url":
381
422
  case "error":
382
423
  case "undefined": return value;
383
424
  case "array": {
@@ -511,6 +552,30 @@ var RpcPayload = class RpcPayload {
511
552
  this.dispose();
512
553
  }
513
554
  }
555
+ async deliverStreamWrite(writer) {
556
+ try {
557
+ let promises = [];
558
+ this.deliverTo(this, "value", promises);
559
+ if (promises.length > 0) await Promise.all(promises);
560
+ let chunk = this.value[0];
561
+ if ((this.hooks.length > 0 || this.promises.length > 0) && chunk instanceof Object) {
562
+ if (!(Symbol.dispose in chunk)) Object.defineProperty(chunk, Symbol.dispose, {
563
+ value: () => this.dispose(),
564
+ writable: true,
565
+ enumerable: false,
566
+ configurable: true
567
+ });
568
+ await writer.write(chunk);
569
+ return RpcPayload.fromAppReturn(void 0);
570
+ }
571
+ await writer.write(chunk);
572
+ this.dispose();
573
+ return RpcPayload.fromAppReturn(void 0);
574
+ } catch (err) {
575
+ this.dispose();
576
+ throw err;
577
+ }
578
+ }
514
579
  async deliverResolve() {
515
580
  try {
516
581
  let promises = [];
@@ -551,6 +616,7 @@ var RpcPayload = class RpcPayload {
551
616
  case "bytes":
552
617
  case "blob":
553
618
  case "date":
619
+ case "url":
554
620
  case "error":
555
621
  case "undefined": return;
556
622
  case "array": {
@@ -633,6 +699,7 @@ var RpcPayload = class RpcPayload {
633
699
  case "rpc-target":
634
700
  case "writable":
635
701
  case "readable":
702
+ case "url":
636
703
  case "headers":
637
704
  case "request":
638
705
  case "response": return;
@@ -702,6 +769,7 @@ function followPath(value, parent, path, owner) {
702
769
  case "blob":
703
770
  case "date":
704
771
  case "error":
772
+ case "url":
705
773
  case "headers":
706
774
  case "request":
707
775
  case "response":
@@ -734,17 +802,22 @@ function followPath(value, parent, path, owner) {
734
802
  }
735
803
  var ValueStubHook = class extends StubHook {
736
804
  call(path, args) {
805
+ let followResult;
737
806
  try {
738
807
  let { value, owner } = this.getValue();
739
- let followResult = followPath(value, void 0, path, owner);
740
- if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
741
- if (typeof followResult.value != "function") throw new TypeError(`'${path.join(".")}' is not a function.`);
742
- return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
743
- return new PayloadStubHook(payload);
744
- }));
808
+ followResult = followPath(value, void 0, path, owner);
745
809
  } catch (err) {
810
+ args.dispose();
746
811
  return new ErrorStubHook(err);
747
812
  }
813
+ if (followResult.hook) return followResult.hook.call(followResult.remainingPath, args);
814
+ if (typeof followResult.value != "function") {
815
+ args.dispose();
816
+ return new ErrorStubHook(/* @__PURE__ */ new TypeError(`'${path.join(".")}' is not a function.`));
817
+ }
818
+ return new PromiseStubHook(args.deliverCall(followResult.value, followResult.parent).then((payload) => {
819
+ return new PayloadStubHook(payload);
820
+ }));
748
821
  }
749
822
  map(path, captures, instructions) {
750
823
  try {
@@ -765,7 +838,10 @@ var ValueStubHook = class extends StubHook {
765
838
  get(path) {
766
839
  try {
767
840
  let { value, owner } = this.getValue();
768
- if (path.length === 0 && owner === null) throw new Error("Can't dup an RpcTarget stub as a promise.");
841
+ if (path.length === 0 && owner === null) {
842
+ if (value instanceof Object && "then" in value) return this.dup();
843
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
844
+ }
769
845
  let followResult = followPath(value, void 0, path, owner);
770
846
  if (followResult.hook) return followResult.hook.get(followResult.remainingPath);
771
847
  return new PayloadStubHook(RpcPayload.deepCopyFrom(followResult.value, followResult.parent, followResult.owner));
@@ -868,7 +944,10 @@ var TargetStubHook = class TargetStubHook extends ValueStubHook {
868
944
  this.target = void 0;
869
945
  }
870
946
  }
871
- onBroken(callback) {}
947
+ onBroken(callback) {
948
+ let target = this.target;
949
+ if (target && "then" in target) Promise.resolve(target).then(() => {}, callback);
950
+ }
872
951
  };
873
952
  var PromiseStubHook = class PromiseStubHook extends StubHook {
874
953
  promise;
@@ -882,12 +961,16 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
882
961
  }
883
962
  call(path, args) {
884
963
  args.ensureDeepCopied();
885
- return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
964
+ return new PromiseStubHook(this.promise.then((hook) => hook.call(path, args), (err) => {
965
+ args.dispose();
966
+ throw err;
967
+ }));
886
968
  }
887
969
  stream(path, args) {
888
970
  args.ensureDeepCopied();
889
- return { promise: this.promise.then((hook) => {
890
- return hook.stream(path, args).promise;
971
+ return { promise: this.promise.then((hook) => hook.stream(path, args).promise, (err) => {
972
+ args.dispose();
973
+ throw err;
891
974
  }) };
892
975
  }
893
976
  map(path, captures, instructions) {
@@ -914,10 +997,7 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
914
997
  }, (err) => {});
915
998
  }
916
999
  dispose() {
917
- if (this.resolution) this.resolution.dispose();
918
- else this.promise.then((hook) => {
919
- hook.dispose();
920
- }, (err) => {});
1000
+ this.promise.then((hook) => hook.dispose(), () => {});
921
1001
  }
922
1002
  onBroken(callback) {
923
1003
  if (this.resolution) this.resolution.onBroken(callback);
@@ -929,6 +1009,77 @@ var PromiseStubHook = class PromiseStubHook extends StubHook {
929
1009
 
930
1010
  //#endregion
931
1011
  //#region src/serialize.ts
1012
+ const DEFAULT_MAX_DEPTH = 256;
1013
+ const DEFAULT_LIMITS = {
1014
+ maxBigIntDigits: 16384,
1015
+ maxDepth: 256,
1016
+ maxMessageSize: 32 * 1024 * 1024
1017
+ };
1018
+ const NATIVE_LITTLE_ENDIAN = new Uint8Array(new Uint16Array([1]).buffer)[0] === 1;
1019
+ const BYTE_CONTAINER_TYPE_NAMES = [
1020
+ "ArrayBuffer",
1021
+ "DataView",
1022
+ "Int8Array",
1023
+ "Uint8Array",
1024
+ "Uint8ClampedArray",
1025
+ "Int16Array",
1026
+ "Uint16Array",
1027
+ "Int32Array",
1028
+ "Uint32Array",
1029
+ "BigInt64Array",
1030
+ "BigUint64Array",
1031
+ "Float32Array",
1032
+ "Float64Array"
1033
+ ];
1034
+ function isValidByteContainerName(value) {
1035
+ return BYTE_CONTAINER_TYPE_NAMES.includes(value);
1036
+ }
1037
+ const TYPED_ARRAY_ELEMENT_SIZE = {
1038
+ ArrayBuffer: void 0,
1039
+ DataView: void 0,
1040
+ Int8Array: void 0,
1041
+ Uint8Array: void 0,
1042
+ Uint8ClampedArray: void 0,
1043
+ Int16Array: 2,
1044
+ Uint16Array: 2,
1045
+ Int32Array: 4,
1046
+ Uint32Array: 4,
1047
+ BigInt64Array: 8,
1048
+ BigUint64Array: 8,
1049
+ Float32Array: 4,
1050
+ Float64Array: 8
1051
+ };
1052
+ const BYTE_CONTAINER_PROTOTYPES = {
1053
+ ArrayBuffer: ArrayBuffer.prototype,
1054
+ DataView: DataView.prototype,
1055
+ Int8Array: Int8Array.prototype,
1056
+ Uint8ClampedArray: Uint8ClampedArray.prototype,
1057
+ Int16Array: Int16Array.prototype,
1058
+ Uint16Array: Uint16Array.prototype,
1059
+ Int32Array: Int32Array.prototype,
1060
+ Uint32Array: Uint32Array.prototype,
1061
+ BigInt64Array: BigInt64Array.prototype,
1062
+ BigUint64Array: BigUint64Array.prototype,
1063
+ Float32Array: Float32Array.prototype,
1064
+ Float64Array: Float64Array.prototype
1065
+ };
1066
+ const BYTE_CONTAINER_TYPE_BY_PROTOTYPE = /* @__PURE__ */ new Map();
1067
+ for (let type of Object.keys(BYTE_CONTAINER_PROTOTYPES)) BYTE_CONTAINER_TYPE_BY_PROTOTYPE.set(BYTE_CONTAINER_PROTOTYPES[type], type);
1068
+ function swapByteOrder(bytes, elementSize) {
1069
+ if (elementSize !== 2 && elementSize !== 4 && elementSize !== 8) throw new RangeError(`Unsupported element size: ${elementSize}`);
1070
+ let view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
1071
+ for (let offset = 0; offset < bytes.byteLength; offset += elementSize) switch (elementSize) {
1072
+ case 2:
1073
+ view.setUint16(offset, view.getUint16(offset, false), true);
1074
+ break;
1075
+ case 4:
1076
+ view.setUint32(offset, view.getUint32(offset, false), true);
1077
+ break;
1078
+ case 8:
1079
+ view.setBigUint64(offset, view.getBigUint64(offset, false), true);
1080
+ break;
1081
+ }
1082
+ }
932
1083
  var NullExporter = class {
933
1084
  exportStub(stub) {
934
1085
  throw new Error("Cannot serialize RPC stubs without an RPC session.");
@@ -949,6 +1100,7 @@ async function streamToBlob(stream, type) {
949
1100
  return b.type === type ? b : b.slice(0, b.size, type);
950
1101
  }
951
1102
  const ERROR_TYPES = {
1103
+ __proto__: null,
952
1104
  Error,
953
1105
  EvalError,
954
1106
  RangeError,
@@ -980,7 +1132,7 @@ var Devaluator = class Devaluator {
980
1132
  }
981
1133
  exports;
982
1134
  devaluateImpl(value, parent, depth) {
983
- if (depth >= 64) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
1135
+ if (depth >= 256) throw new Error("Serialization exceeded maximum allowed depth. (Does the message contain cycles?)");
984
1136
  switch (typeForRpc(value)) {
985
1137
  case "unsupported": {
986
1138
  let msg;
@@ -1019,18 +1171,40 @@ var Devaluator = class Devaluator {
1019
1171
  return ["date", Number.isNaN(time) ? null : time];
1020
1172
  }
1021
1173
  case "bytes": {
1022
- let bytes = value;
1023
- if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return ["bytes", bytes];
1024
- if (bytes.toBase64) return ["bytes", bytes.toBase64({ omitPadding: true })];
1174
+ let alternateTypeName = BYTE_CONTAINER_TYPE_BY_PROTOTYPE.get(Object.getPrototypeOf(value));
1175
+ let bytes;
1176
+ if (alternateTypeName === "ArrayBuffer") bytes = new Uint8Array(value);
1177
+ else if (alternateTypeName === void 0) bytes = value;
1178
+ else {
1179
+ let view = value;
1180
+ bytes = new Uint8Array(view.buffer, view.byteOffset, view.byteLength);
1181
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[alternateTypeName];
1182
+ if (!NATIVE_LITTLE_ENDIAN && elementSize) {
1183
+ bytes = bytes.slice();
1184
+ swapByteOrder(bytes, elementSize);
1185
+ }
1186
+ }
1187
+ if (this.encodingLevel === "structuredClonable" || this.encodingLevel === "jsonCompatibleWithBytes") return alternateTypeName === void 0 ? ["bytes", bytes] : [
1188
+ "bytes",
1189
+ bytes,
1190
+ alternateTypeName
1191
+ ];
1025
1192
  let b64;
1026
- if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1193
+ if (bytes.toBase64) b64 = bytes.toBase64({ omitPadding: true });
1194
+ else if (typeof Buffer !== "undefined") b64 = (bytes instanceof Buffer ? bytes : Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)).toString("base64");
1027
1195
  else {
1028
1196
  let binary = "";
1029
1197
  for (let i = 0; i < bytes.length; i++) binary += String.fromCharCode(bytes[i]);
1030
1198
  b64 = btoa(binary);
1031
1199
  }
1032
- return ["bytes", b64.replace(/=+$/, "")];
1200
+ b64 = b64.replace(/=+$/, "");
1201
+ return alternateTypeName === void 0 ? ["bytes", b64] : [
1202
+ "bytes",
1203
+ b64,
1204
+ alternateTypeName
1205
+ ];
1033
1206
  }
1207
+ case "url": return ["url", value.href];
1034
1208
  case "headers": return ["headers", [...value]];
1035
1209
  case "request": {
1036
1210
  let req = value;
@@ -1214,6 +1388,9 @@ var NullImporter = class {
1214
1388
  getPipeReadable(exportId) {
1215
1389
  throw new Error("Cannot retrieve pipe readable without an RPC session.");
1216
1390
  }
1391
+ getLimits() {
1392
+ return DEFAULT_LIMITS;
1393
+ }
1217
1394
  };
1218
1395
  const NULL_IMPORTER = new NullImporter();
1219
1396
  function fixBrokenRequestBody(request, body) {
@@ -1231,16 +1408,21 @@ function streamToBlobPromise(stream, type) {
1231
1408
  var Evaluator = class Evaluator {
1232
1409
  importer;
1233
1410
  encodingLevel;
1411
+ limits;
1234
1412
  constructor(importer, encodingLevel = "string") {
1235
1413
  this.importer = importer;
1236
1414
  this.encodingLevel = encodingLevel;
1415
+ this.limits = importer.getLimits();
1237
1416
  }
1238
1417
  hooks = [];
1239
1418
  promises = [];
1240
1419
  evaluate(value) {
1420
+ return this.evaluateWithDepth(value, 0);
1421
+ }
1422
+ evaluateWithDepth(value, depth) {
1241
1423
  let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1242
1424
  try {
1243
- payload.value = this.evaluateImpl(value, payload, "value");
1425
+ payload.value = this.evaluateImpl(value, payload, "value", depth);
1244
1426
  return payload;
1245
1427
  } catch (err) {
1246
1428
  payload.dispose();
@@ -1250,35 +1432,70 @@ var Evaluator = class Evaluator {
1250
1432
  evaluateCopy(value) {
1251
1433
  return this.evaluate(structuredClone(value));
1252
1434
  }
1253
- evaluateImpl(value, parent, property) {
1435
+ evaluateImpl(value, parent, property, depth) {
1436
+ let maxDepth = this.limits.maxDepth;
1437
+ if (depth >= maxDepth) throw new TypeError(`Deserialization exceeded maximum allowed message depth of ${maxDepth}.`);
1254
1438
  if (this.encodingLevel === "structuredClonable") {
1255
1439
  if (value instanceof Date || typeof value === "bigint") return value;
1256
1440
  }
1257
1441
  if (value instanceof Array) {
1258
1442
  if (value.length == 1 && value[0] instanceof Array) {
1259
1443
  let result = value[0];
1260
- for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i);
1444
+ for (let i = 0; i < result.length; i++) result[i] = this.evaluateImpl(result[i], result, i, depth + 1);
1261
1445
  return result;
1262
1446
  } else switch (value[0]) {
1263
1447
  case "bigint":
1264
- if (typeof value[1] == "string") return BigInt(value[1]);
1448
+ if (typeof value[1] == "string") {
1449
+ let digits = value[1];
1450
+ let maxBigIntDigits = this.limits.maxBigIntDigits;
1451
+ if (digits.length > maxBigIntDigits) throw new TypeError(`Deserialized bigint exceeds maximum length of ${maxBigIntDigits} digits.`);
1452
+ return BigInt(digits);
1453
+ }
1265
1454
  break;
1266
1455
  case "date":
1267
1456
  if (value[1] === null) return /* @__PURE__ */ new Date(NaN);
1268
1457
  if (typeof value[1] == "number") return new Date(value[1]);
1269
1458
  break;
1270
- case "bytes":
1271
- if (value[1] instanceof Uint8Array) return value[1];
1272
- if (typeof value[1] == "string") if (typeof Buffer !== "undefined") return Buffer.from(value[1], "base64");
1273
- else if (Uint8Array.fromBase64) return Uint8Array.fromBase64(value[1]);
1459
+ case "bytes": {
1460
+ let bytes;
1461
+ if (value[1] instanceof Uint8Array) bytes = value[1];
1462
+ else if (typeof value[1] == "string") if (typeof Buffer !== "undefined") bytes = Buffer.from(value[1], "base64");
1463
+ else if (Uint8Array.fromBase64) bytes = Uint8Array.fromBase64(value[1]);
1274
1464
  else {
1275
1465
  let bs = atob(value[1]);
1276
1466
  let len = bs.length;
1277
- let bytes = new Uint8Array(len);
1467
+ bytes = new Uint8Array(len);
1278
1468
  for (let i = 0; i < len; i++) bytes[i] = bs.charCodeAt(i);
1279
- return bytes;
1280
1469
  }
1281
- break;
1470
+ else break;
1471
+ if (value.length === 2) return bytes;
1472
+ if (typeof value[2] !== "string") throw new TypeError(`Unknown bytes type marker type: ${typeof value[2]}`);
1473
+ if (!isValidByteContainerName(value[2])) {
1474
+ let marker = value[2].slice(0, 64);
1475
+ throw new TypeError(`Unknown bytes type marker: ${marker}`);
1476
+ }
1477
+ let marker = value[2];
1478
+ let elementSize = TYPED_ARRAY_ELEMENT_SIZE[marker];
1479
+ if (elementSize !== void 0 && bytes.byteLength % elementSize !== 0) throw new TypeError(`Invalid byte length ${bytes.byteLength} for ${marker}; expected a multiple of ${elementSize}`);
1480
+ let buffer = bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength);
1481
+ if (!NATIVE_LITTLE_ENDIAN && elementSize !== void 0) swapByteOrder(new Uint8Array(buffer), elementSize);
1482
+ switch (marker) {
1483
+ case "ArrayBuffer": return buffer;
1484
+ case "DataView": return new DataView(buffer);
1485
+ case "Int8Array": return new Int8Array(buffer);
1486
+ case "Uint8Array": return new Uint8Array(buffer);
1487
+ case "Uint8ClampedArray": return new Uint8ClampedArray(buffer);
1488
+ case "Int16Array": return new Int16Array(buffer);
1489
+ case "Uint16Array": return new Uint16Array(buffer);
1490
+ case "Int32Array": return new Int32Array(buffer);
1491
+ case "Uint32Array": return new Uint32Array(buffer);
1492
+ case "BigInt64Array": return new BigInt64Array(buffer);
1493
+ case "BigUint64Array": return new BigUint64Array(buffer);
1494
+ case "Float32Array": return new Float32Array(buffer);
1495
+ case "Float64Array": return new Float64Array(buffer);
1496
+ default:
1497
+ }
1498
+ }
1282
1499
  case "error":
1283
1500
  if (value.length >= 3 && typeof value[1] === "string" && typeof value[2] === "string") {
1284
1501
  let cls = ERROR_TYPES[value[1]] || Error;
@@ -1291,7 +1508,11 @@ var Evaluator = class Evaluator {
1291
1508
  let propsObj = props;
1292
1509
  for (let key of Object.keys(propsObj)) {
1293
1510
  if (key === "name" || key === "message" || key === "stack") continue;
1294
- anyResult[key] = this.evaluateImpl(propsObj[key], result, key);
1511
+ if (key in Object.prototype || key === "toJSON") {
1512
+ this.evaluateImpl(propsObj[key], result, key, depth + 1);
1513
+ continue;
1514
+ }
1515
+ anyResult[key] = this.evaluateImpl(propsObj[key], result, key, depth + 1);
1295
1516
  }
1296
1517
  }
1297
1518
  return result;
@@ -1303,6 +1524,9 @@ var Evaluator = class Evaluator {
1303
1524
  case "inf": return Infinity;
1304
1525
  case "-inf": return -Infinity;
1305
1526
  case "nan": return NaN;
1527
+ case "url":
1528
+ if (value.length === 2 && typeof value[1] === "string") return new URL(value[1]);
1529
+ break;
1306
1530
  case "headers":
1307
1531
  if (value.length === 2 && value[1] instanceof Array) return new Headers(value[1]);
1308
1532
  break;
@@ -1312,11 +1536,11 @@ var Evaluator = class Evaluator {
1312
1536
  let init = value[2];
1313
1537
  if (typeof init !== "object" || init === null) break;
1314
1538
  if (init.body) {
1315
- init.body = this.evaluateImpl(init.body, init, "body");
1539
+ init.body = this.evaluateImpl(init.body, init, "body", depth + 1);
1316
1540
  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.");
1317
1541
  }
1318
1542
  if (init.signal) {
1319
- init.signal = this.evaluateImpl(init.signal, init, "signal");
1543
+ init.signal = this.evaluateImpl(init.signal, init, "signal", depth + 1);
1320
1544
  if (!(init.signal instanceof AbortSignal)) throw new TypeError("Request siganl must be of type AbortSignal.");
1321
1545
  }
1322
1546
  if (init.headers && !(init.headers instanceof Array)) throw new TypeError("Request headers must be serialized as an array of pairs.");
@@ -1333,7 +1557,7 @@ var Evaluator = class Evaluator {
1333
1557
  }
1334
1558
  case "response": {
1335
1559
  if (value.length !== 3) break;
1336
- let body = this.evaluateImpl(value[1], parent, property);
1560
+ let body = this.evaluateImpl(value[1], parent, property, depth + 1);
1337
1561
  if (body === null || typeof body === "string" || body instanceof Uint8Array || body instanceof ReadableStream) {} else throw new TypeError("Response body must be of type ReadableStream.");
1338
1562
  let init = value[2];
1339
1563
  if (typeof init !== "object" || init === null) break;
@@ -1344,7 +1568,7 @@ var Evaluator = class Evaluator {
1344
1568
  case "blob": {
1345
1569
  if (value.length !== 3 || typeof value[1] !== "string") break;
1346
1570
  let contentType = value[1];
1347
- let content = this.evaluateImpl(value[2], parent, property);
1571
+ let content = this.evaluateImpl(value[2], parent, property, depth + 1);
1348
1572
  if (!(content instanceof ReadableStream)) throw new TypeError("Blob content must be serialized as a ReadableStream.");
1349
1573
  let promise = streamToBlobPromise(content, contentType);
1350
1574
  this.promises.push({
@@ -1385,7 +1609,7 @@ var Evaluator = class Evaluator {
1385
1609
  if (value.length == 3) return addStub(hook.get(path));
1386
1610
  let args = value[3];
1387
1611
  if (!(args instanceof Array)) break;
1388
- args = new Evaluator(this.importer).evaluate([args]);
1612
+ args = new Evaluator(this.importer).evaluateWithDepth([args], depth);
1389
1613
  return addStub(hook.call(path, args));
1390
1614
  }
1391
1615
  case "remap": {
@@ -1451,9 +1675,9 @@ var Evaluator = class Evaluator {
1451
1675
  } else if (value instanceof Object) {
1452
1676
  let result = value;
1453
1677
  for (let key in result) if (key in Object.prototype || key === "toJSON") {
1454
- this.evaluateImpl(result[key], result, key);
1678
+ this.evaluateImpl(result[key], result, key, depth + 1);
1455
1679
  delete result[key];
1456
- } else result[key] = this.evaluateImpl(result[key], result, key);
1680
+ } else result[key] = this.evaluateImpl(result[key], result, key, depth + 1);
1457
1681
  return result;
1458
1682
  } else return value;
1459
1683
  }
@@ -1602,24 +1826,28 @@ var RpcImportHook = class RpcImportHook extends StubHook {
1602
1826
  if (this.entry) return this.entry;
1603
1827
  else throw new Error("This RpcImportHook was already disposed.");
1604
1828
  }
1829
+ getEntryTakingOwnership(disposeOwned) {
1830
+ try {
1831
+ return this.getEntry();
1832
+ } catch (err) {
1833
+ disposeOwned();
1834
+ throw err;
1835
+ }
1836
+ }
1605
1837
  call(path, args) {
1606
- let entry = this.getEntry();
1838
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1607
1839
  if (entry.resolution) return entry.resolution.call(path, args);
1608
1840
  else return entry.session.sendCall(entry.importId, path, args);
1609
1841
  }
1610
1842
  stream(path, args) {
1611
- let entry = this.getEntry();
1843
+ let entry = this.getEntryTakingOwnership(() => args.dispose());
1612
1844
  if (entry.resolution) return entry.resolution.stream(path, args);
1613
1845
  else return entry.session.sendStream(entry.importId, path, args);
1614
1846
  }
1615
1847
  map(path, captures, instructions) {
1616
- let entry;
1617
- try {
1618
- entry = this.getEntry();
1619
- } catch (err) {
1848
+ let entry = this.getEntryTakingOwnership(() => {
1620
1849
  for (let cap of captures) cap.dispose();
1621
- throw err;
1622
- }
1850
+ });
1623
1851
  if (entry.resolution) return entry.resolution.map(path, captures, instructions);
1624
1852
  else return entry.session.sendMap(entry.importId, path, captures, instructions);
1625
1853
  }
@@ -1676,6 +1904,7 @@ var RpcSessionImpl = class {
1676
1904
  pullCount = 0;
1677
1905
  onBrokenCallbacks = [];
1678
1906
  encodingLevel;
1907
+ limits;
1679
1908
  constructor(transport, mainHook, options) {
1680
1909
  this.transport = transport;
1681
1910
  this.options = options;
@@ -1688,6 +1917,10 @@ var RpcSessionImpl = class {
1688
1917
  }
1689
1918
  }
1690
1919
  this.encodingLevel = level;
1920
+ this.limits = {
1921
+ ...DEFAULT_LIMITS,
1922
+ ...options.limits
1923
+ };
1691
1924
  this.exports.push({
1692
1925
  hook: mainHook,
1693
1926
  refcount: 1
@@ -1830,6 +2063,9 @@ var RpcSessionImpl = class {
1830
2063
  entry.pipeReadable = void 0;
1831
2064
  return readable;
1832
2065
  }
2066
+ getLimits() {
2067
+ return this.limits;
2068
+ }
1833
2069
  createPipe(readable, readableHook) {
1834
2070
  if (this.abortReason) throw this.abortReason;
1835
2071
  this.send(["pipe"]);
@@ -1872,14 +2108,23 @@ var RpcSessionImpl = class {
1872
2108
  }
1873
2109
  }
1874
2110
  sendCall(id, path, args) {
1875
- if (this.abortReason) throw this.abortReason;
2111
+ if (this.abortReason) {
2112
+ args?.dispose();
2113
+ throw this.abortReason;
2114
+ }
1876
2115
  let value = [
1877
2116
  "pipeline",
1878
2117
  id,
1879
2118
  path
1880
2119
  ];
1881
2120
  if (args) {
1882
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2121
+ let devalue;
2122
+ try {
2123
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2124
+ } catch (err) {
2125
+ args.dispose();
2126
+ throw err;
2127
+ }
1883
2128
  value.push(devalue[0]);
1884
2129
  }
1885
2130
  this.send(["push", value]);
@@ -1888,13 +2133,22 @@ var RpcSessionImpl = class {
1888
2133
  return new RpcImportHook(true, entry);
1889
2134
  }
1890
2135
  sendStream(id, path, args) {
1891
- if (this.abortReason) throw this.abortReason;
2136
+ if (this.abortReason) {
2137
+ args.dispose();
2138
+ throw this.abortReason;
2139
+ }
1892
2140
  let value = [
1893
2141
  "pipeline",
1894
2142
  id,
1895
2143
  path
1896
2144
  ];
1897
- let devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2145
+ let devalue;
2146
+ try {
2147
+ devalue = Devaluator.devaluate(args.value, void 0, this, args, this.encodingLevel);
2148
+ } catch (err) {
2149
+ args.dispose();
2150
+ throw err;
2151
+ }
1898
2152
  value.push(devalue[0]);
1899
2153
  let msg = ["stream", value];
1900
2154
  let size = this.send(msg);
@@ -1989,6 +2243,7 @@ var RpcSessionImpl = class {
1989
2243
  } finally {
1990
2244
  if (this.cancelReadLoop === readCanceled.reject) this.cancelReadLoop = void 0;
1991
2245
  }
2246
+ 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.`);
1992
2247
  if (this.abortReason) break;
1993
2248
  let msg = this.encodingLevel === "string" ? JSON.parse(raw) : raw;
1994
2249
  if (msg instanceof Array) switch (msg[0]) {
@@ -2063,7 +2318,7 @@ var RpcSessionImpl = class {
2063
2318
  case "abort": {
2064
2319
  let payload = new Evaluator(this, this.encodingLevel).evaluate(msg[1]);
2065
2320
  payload.dispose();
2066
- this.abort(payload, false);
2321
+ this.abort(payload.value, false);
2067
2322
  break;
2068
2323
  }
2069
2324
  }
@@ -2114,6 +2369,8 @@ var RpcSession$1 = class {
2114
2369
 
2115
2370
  //#endregion
2116
2371
  //#region src/websocket.ts
2372
+ /** Close-frame reason max UTF-8 bytes: 125 payload - 2-byte status (RFC 6455 section 5.5). */
2373
+ const MAX_CLOSE_REASON_BYTES = 123;
2117
2374
  function newWebSocketRpcSession$1(webSocket, localMain, options) {
2118
2375
  if (typeof webSocket === "string") webSocket = new WebSocket(webSocket);
2119
2376
  return new RpcSession$1(new WebSocketTransport(webSocket), localMain, options).getRemoteMain();
@@ -2189,6 +2446,8 @@ var WebSocketTransport = class {
2189
2446
  let message;
2190
2447
  if (reason instanceof Error) message = reason.message;
2191
2448
  else message = `${reason}`;
2449
+ let reasonBytes = new TextEncoder().encode(message);
2450
+ if (reasonBytes.length > 123) message = new TextDecoder().decode(reasonBytes.subarray(0, 123), { stream: true });
2192
2451
  this.#webSocket.close(3e3, message);
2193
2452
  if (!this.#error) this.#error = reason;
2194
2453
  }
@@ -2206,6 +2465,7 @@ var WebSocketTransport = class {
2206
2465
 
2207
2466
  //#endregion
2208
2467
  //#region src/batch.ts
2468
+ const yieldToMacrotask = typeof setImmediate === "function" ? () => new Promise((resolve) => setImmediate(resolve)) : () => new Promise((resolve) => setTimeout(resolve, 0));
2209
2469
  var BatchClientTransport = class {
2210
2470
  constructor(sendBatch) {
2211
2471
  this.#promise = this.#scheduleBatch(sendBatch);
@@ -2227,7 +2487,7 @@ var BatchClientTransport = class {
2227
2487
  this.#aborted = reason;
2228
2488
  }
2229
2489
  async #scheduleBatch(sendBatch) {
2230
- await new Promise((resolve) => setTimeout(resolve, 0));
2490
+ await yieldToMacrotask();
2231
2491
  if (this.#aborted !== void 0) throw this.#aborted;
2232
2492
  let batch = this.#batchToSend;
2233
2493
  this.#batchToSend = null;
@@ -2305,7 +2565,11 @@ async function newHttpBatchRpcResponse(request, localMain, options) {
2305
2565
  * @param options Optional RPC session options. You can also pass headers to set on the response.
2306
2566
  */
2307
2567
  async function nodeHttpBatchRpcResponse(request, response, localMain, options) {
2308
- if (request.method !== "POST") response.writeHead(405, "This endpoint only accepts POST requests.");
2568
+ if (request.method !== "POST") {
2569
+ response.writeHead(405, "This endpoint only accepts POST requests.", options?.headers);
2570
+ response.end();
2571
+ return;
2572
+ }
2309
2573
  let body = await new Promise((resolve, reject) => {
2310
2574
  let chunks = [];
2311
2575
  request.on("data", (chunk) => {
@@ -2515,9 +2779,11 @@ var MapVariableHook = class extends StubHook {
2515
2779
  else throwMapperBuilderUseError();
2516
2780
  }
2517
2781
  call(path, args) {
2782
+ args.dispose();
2518
2783
  throwMapperBuilderUseError();
2519
2784
  }
2520
2785
  map(path, captures, instructions) {
2786
+ for (let cap of captures) cap.dispose();
2521
2787
  throwMapperBuilderUseError();
2522
2788
  }
2523
2789
  pull() {
@@ -2570,6 +2836,9 @@ var MapApplicator = class {
2570
2836
  getPipeReadable(exportId) {
2571
2837
  throw new Error("A mapper function cannot use pipe readables.");
2572
2838
  }
2839
+ getLimits() {
2840
+ return DEFAULT_LIMITS;
2841
+ }
2573
2842
  };
2574
2843
  function applyMapToElement(input, parent, owner, captures, instructions) {
2575
2844
  let mapper = new MapApplicator(captures, new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)));
@@ -2625,14 +2894,11 @@ var WritableStreamStubHook = class WritableStreamStubHook extends StubHook {
2625
2894
  let state = this.getState();
2626
2895
  if (path.length !== 1 || typeof path[0] !== "string") throw new Error("WritableStream stub only supports direct method calls");
2627
2896
  const method = path[0];
2628
- if (method !== "write" && method !== "close" && method !== "abort") {
2629
- args.dispose();
2630
- throw new Error(`Unknown WritableStream method: ${method}`);
2631
- }
2897
+ if (method !== "write" && method !== "close" && method !== "abort") throw new Error(`Unknown WritableStream method: ${method}`);
2632
2898
  if (method === "close" || method === "abort") state.closed = true;
2633
- let func = state.writer[method];
2634
- return new PromiseStubHook(args.deliverCall(func, state.writer).then((payload) => new PayloadStubHook(payload)));
2899
+ return new PromiseStubHook((method === "write" ? args.deliverStreamWrite(state.writer) : args.deliverCall(state.writer[method], state.writer)).then((payload) => new PayloadStubHook(payload)));
2635
2900
  } catch (err) {
2901
+ args.dispose();
2636
2902
  return new ErrorStubHook(err);
2637
2903
  }
2638
2904
  }
@@ -2908,12 +3174,12 @@ let newMessagePortRpcSession = newMessagePortRpcSession$1;
2908
3174
  * credentials as parameters and returns the authorized API), then cross-origin requests should
2909
3175
  * be safe.
2910
3176
  */
2911
- async function newWorkersRpcResponse(request, localMain) {
3177
+ async function newWorkersRpcResponse(request, localMain, options) {
2912
3178
  if (request.method === "POST") {
2913
- let response = await newHttpBatchRpcResponse(request, localMain);
3179
+ let response = await newHttpBatchRpcResponse(request, localMain, options);
2914
3180
  response.headers.set("Access-Control-Allow-Origin", "*");
2915
3181
  return response;
2916
- } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain);
3182
+ } else if (request.headers.get("Upgrade")?.toLowerCase() === "websocket") return newWorkersWebSocketRpcResponse(request, localMain, options);
2917
3183
  else return new Response("This endpoint only accepts POST or WebSocket requests.", { status: 400 });
2918
3184
  }
2919
3185
 
@@ -3034,5 +3300,5 @@ var BunWebSocketTransport = class {
3034
3300
  let newBunWebSocketRpcSession = newBunWebSocketRpcSession$1;
3035
3301
 
3036
3302
  //#endregion
3037
- export { BunWebSocketTransport, RpcPromise, RpcSession, RpcStub, RpcTarget, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
3303
+ export { BunWebSocketTransport, DEFAULT_LIMITS, DEFAULT_MAX_DEPTH, RpcPromise, RpcSession, RpcStub, RpcTarget, WebSocketTransport, deserialize, newBunWebSocketRpcHandler, newBunWebSocketRpcSession, newHttpBatchRpcResponse, newHttpBatchRpcSession, newMessagePortRpcSession, newWebSocketRpcSession, newWorkersRpcResponse, newWorkersWebSocketRpcResponse, nodeHttpBatchRpcResponse, serialize };
3038
3304
  //# sourceMappingURL=index-bun.js.map