@depup/miniflare 4.20260317.0-depup.0

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.
Files changed (91) hide show
  1. package/README.md +31 -0
  2. package/bootstrap.js +11 -0
  3. package/changes.json +10 -0
  4. package/dist/local-explorer-ui/assets/Breadcrumbs-7hjI0sYt.js +1 -0
  5. package/dist/local-explorer-ui/assets/TableSelect-_bi6l6Iv.js +25 -0
  6. package/dist/local-explorer-ui/assets/_className-gSkjniQn.js +1 -0
  7. package/dist/local-explorer-ui/assets/_databaseId-DWcfgBis.js +1 -0
  8. package/dist/local-explorer-ui/assets/_namespaceId-8ViM8VDL.js +1 -0
  9. package/dist/local-explorer-ui/assets/_objectId-X6x-JUph.js +1 -0
  10. package/dist/local-explorer-ui/assets/dropdown-DFeFcKfn-BCd_NRZS.js +1 -0
  11. package/dist/local-explorer-ui/assets/index-BFNDwiew.js +42 -0
  12. package/dist/local-explorer-ui/assets/index-CLSFsgi0.js +1 -0
  13. package/dist/local-explorer-ui/assets/index-KG4JeHCX.js +1 -0
  14. package/dist/local-explorer-ui/assets/index-mgoUmSld.css +1 -0
  15. package/dist/local-explorer-ui/assets/table-BUmvaBj8-v-EIZgOz.js +1 -0
  16. package/dist/local-explorer-ui/favicon.svg +3 -0
  17. package/dist/local-explorer-ui/index.html +14 -0
  18. package/dist/src/index.d.ts +8703 -0
  19. package/dist/src/index.js +83666 -0
  20. package/dist/src/index.js.map +6 -0
  21. package/dist/src/shared/dev-registry.worker.js +69801 -0
  22. package/dist/src/shared/dev-registry.worker.js.map +6 -0
  23. package/dist/src/workers/analytics-engine/analytics-engine.worker.js +15 -0
  24. package/dist/src/workers/analytics-engine/analytics-engine.worker.js.map +6 -0
  25. package/dist/src/workers/assets/assets-kv.worker.js +28 -0
  26. package/dist/src/workers/assets/assets-kv.worker.js.map +6 -0
  27. package/dist/src/workers/assets/assets.worker.js +9014 -0
  28. package/dist/src/workers/assets/assets.worker.js.map +6 -0
  29. package/dist/src/workers/assets/router.worker.js +9625 -0
  30. package/dist/src/workers/assets/router.worker.js.map +6 -0
  31. package/dist/src/workers/assets/rpc-proxy.worker.js +29 -0
  32. package/dist/src/workers/assets/rpc-proxy.worker.js.map +6 -0
  33. package/dist/src/workers/browser-rendering/binding.worker.js +129 -0
  34. package/dist/src/workers/browser-rendering/binding.worker.js.map +6 -0
  35. package/dist/src/workers/cache/cache-entry-noop.worker.js +19 -0
  36. package/dist/src/workers/cache/cache-entry-noop.worker.js.map +6 -0
  37. package/dist/src/workers/cache/cache-entry.worker.js +28 -0
  38. package/dist/src/workers/cache/cache-entry.worker.js.map +6 -0
  39. package/dist/src/workers/cache/cache.worker.js +653 -0
  40. package/dist/src/workers/cache/cache.worker.js.map +6 -0
  41. package/dist/src/workers/core/do-wrapper.worker.js +43 -0
  42. package/dist/src/workers/core/do-wrapper.worker.js.map +6 -0
  43. package/dist/src/workers/core/entry.worker.js +4633 -0
  44. package/dist/src/workers/core/entry.worker.js.map +6 -0
  45. package/dist/src/workers/core/strip-cf-connecting-ip.worker.js +11 -0
  46. package/dist/src/workers/core/strip-cf-connecting-ip.worker.js.map +6 -0
  47. package/dist/src/workers/d1/database.worker.js +219 -0
  48. package/dist/src/workers/d1/database.worker.js.map +6 -0
  49. package/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js +2271 -0
  50. package/dist/src/workers/dispatch-namespace/dispatch-namespace-proxy.worker.js.map +6 -0
  51. package/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js +12 -0
  52. package/dist/src/workers/dispatch-namespace/dispatch-namespace.worker.js.map +6 -0
  53. package/dist/src/workers/email/email.worker.js +23 -0
  54. package/dist/src/workers/email/email.worker.js.map +6 -0
  55. package/dist/src/workers/email/send_email.worker.js +3294 -0
  56. package/dist/src/workers/email/send_email.worker.js.map +6 -0
  57. package/dist/src/workers/hello-world/binding.worker.js +19 -0
  58. package/dist/src/workers/hello-world/binding.worker.js.map +6 -0
  59. package/dist/src/workers/hello-world/object.worker.js +14 -0
  60. package/dist/src/workers/hello-world/object.worker.js.map +6 -0
  61. package/dist/src/workers/images/images.worker.js +155 -0
  62. package/dist/src/workers/images/images.worker.js.map +6 -0
  63. package/dist/src/workers/kv/namespace.worker.js +322 -0
  64. package/dist/src/workers/kv/namespace.worker.js.map +6 -0
  65. package/dist/src/workers/kv/sites.worker.js +146 -0
  66. package/dist/src/workers/kv/sites.worker.js.map +6 -0
  67. package/dist/src/workers/local-explorer/explorer.worker.js +5245 -0
  68. package/dist/src/workers/local-explorer/explorer.worker.js.map +6 -0
  69. package/dist/src/workers/pipelines/pipeline.worker.js +10 -0
  70. package/dist/src/workers/pipelines/pipeline.worker.js.map +6 -0
  71. package/dist/src/workers/queues/broker.worker.js +289 -0
  72. package/dist/src/workers/queues/broker.worker.js.map +6 -0
  73. package/dist/src/workers/r2/bucket.worker.js +1134 -0
  74. package/dist/src/workers/r2/bucket.worker.js.map +6 -0
  75. package/dist/src/workers/ratelimit/ratelimit.worker.js +54 -0
  76. package/dist/src/workers/ratelimit/ratelimit.worker.js.map +6 -0
  77. package/dist/src/workers/secrets-store/secret.worker.js +65 -0
  78. package/dist/src/workers/secrets-store/secret.worker.js.map +6 -0
  79. package/dist/src/workers/shared/index.worker.js +693 -0
  80. package/dist/src/workers/shared/index.worker.js.map +6 -0
  81. package/dist/src/workers/shared/object-entry.worker.js +21 -0
  82. package/dist/src/workers/shared/object-entry.worker.js.map +6 -0
  83. package/dist/src/workers/shared/remote-proxy-client.worker.js +2271 -0
  84. package/dist/src/workers/shared/remote-proxy-client.worker.js.map +6 -0
  85. package/dist/src/workers/shared/zod.worker.js +2954 -0
  86. package/dist/src/workers/shared/zod.worker.js.map +6 -0
  87. package/dist/src/workers/workflows/binding.worker.js +2422 -0
  88. package/dist/src/workers/workflows/binding.worker.js.map +6 -0
  89. package/dist/src/workers/workflows/wrapped-binding.worker.js +71 -0
  90. package/dist/src/workers/workflows/wrapped-binding.worker.js.map +6 -0
  91. package/package.json +139 -0
@@ -0,0 +1,2271 @@
1
+ // src/workers/shared/remote-proxy-client.worker.ts
2
+ import { WorkerEntrypoint } from "cloudflare:workers";
3
+
4
+ // ../../node_modules/.pnpm/capnweb@0.5.0/node_modules/capnweb/dist/index-workers.js
5
+ import * as cfw from "cloudflare:workers";
6
+ var WORKERS_MODULE_SYMBOL = /* @__PURE__ */ Symbol("workers-module");
7
+ globalThis[WORKERS_MODULE_SYMBOL] = cfw;
8
+ Symbol.dispose || (Symbol.dispose = /* @__PURE__ */ Symbol.for("dispose"));
9
+ Symbol.asyncDispose || (Symbol.asyncDispose = /* @__PURE__ */ Symbol.for("asyncDispose"));
10
+ Promise.withResolvers || (Promise.withResolvers = function() {
11
+ let resolve, reject;
12
+ return { promise: new Promise((res, rej) => {
13
+ resolve = res, reject = rej;
14
+ }), resolve, reject };
15
+ });
16
+ var workersModule = globalThis[WORKERS_MODULE_SYMBOL], RpcTarget = workersModule ? workersModule.RpcTarget : class {
17
+ }, AsyncFunction = (async function() {
18
+ }).constructor;
19
+ function typeForRpc(value) {
20
+ switch (typeof value) {
21
+ case "boolean":
22
+ case "number":
23
+ case "string":
24
+ return "primitive";
25
+ case "undefined":
26
+ return "undefined";
27
+ case "object":
28
+ case "function":
29
+ break;
30
+ case "bigint":
31
+ return "bigint";
32
+ default:
33
+ return "unsupported";
34
+ }
35
+ if (value === null)
36
+ return "primitive";
37
+ let prototype = Object.getPrototypeOf(value);
38
+ switch (prototype) {
39
+ case Object.prototype:
40
+ return "object";
41
+ case Function.prototype:
42
+ case AsyncFunction.prototype:
43
+ return "function";
44
+ case Array.prototype:
45
+ return "array";
46
+ case Date.prototype:
47
+ return "date";
48
+ case Uint8Array.prototype:
49
+ return "bytes";
50
+ case WritableStream.prototype:
51
+ return "writable";
52
+ case ReadableStream.prototype:
53
+ return "readable";
54
+ case Headers.prototype:
55
+ return "headers";
56
+ case Request.prototype:
57
+ return "request";
58
+ case Response.prototype:
59
+ return "response";
60
+ // TODO: All other structured clone types.
61
+ case RpcStub.prototype:
62
+ return "stub";
63
+ case RpcPromise.prototype:
64
+ return "rpc-promise";
65
+ // TODO: Promise<T> or thenable
66
+ default:
67
+ if (workersModule) {
68
+ if (prototype == workersModule.RpcStub.prototype || value instanceof workersModule.ServiceStub)
69
+ return "rpc-target";
70
+ if (prototype == workersModule.RpcPromise.prototype || prototype == workersModule.RpcProperty.prototype)
71
+ return "rpc-thenable";
72
+ }
73
+ return value instanceof RpcTarget ? "rpc-target" : value instanceof Error ? "error" : "unsupported";
74
+ }
75
+ }
76
+ function mapNotLoaded() {
77
+ throw new Error("RPC map() implementation was not loaded.");
78
+ }
79
+ var mapImpl = { applyMap: mapNotLoaded, sendMap: mapNotLoaded };
80
+ function streamNotLoaded() {
81
+ throw new Error("Stream implementation was not loaded.");
82
+ }
83
+ var streamImpl = {
84
+ createWritableStreamHook: streamNotLoaded,
85
+ createWritableStreamFromHook: streamNotLoaded,
86
+ createReadableStreamHook: streamNotLoaded
87
+ }, StubHook = class {
88
+ // Like call(), but designed for streaming calls (e.g. WritableStream writes). Returns:
89
+ // - promise: A Promise<void> for the completion of the call.
90
+ // - size: If the call was remote, the byte size of the serialized message. For local calls,
91
+ // undefined is returned, indicating the caller should await the promise to serialize writes
92
+ // (no overlapping).
93
+ stream(path, args) {
94
+ let pulled = this.call(path, args).pull(), promise;
95
+ return pulled instanceof Promise ? promise = pulled.then((p) => {
96
+ p.dispose();
97
+ }) : (pulled.dispose(), promise = Promise.resolve()), { promise };
98
+ }
99
+ }, ErrorStubHook = class extends StubHook {
100
+ constructor(error) {
101
+ super(), this.error = error;
102
+ }
103
+ call(path, args) {
104
+ return this;
105
+ }
106
+ map(path, captures, instructions) {
107
+ return this;
108
+ }
109
+ get(path) {
110
+ return this;
111
+ }
112
+ dup() {
113
+ return this;
114
+ }
115
+ pull() {
116
+ return Promise.reject(this.error);
117
+ }
118
+ ignoreUnhandledRejections() {
119
+ }
120
+ dispose() {
121
+ }
122
+ onBroken(callback) {
123
+ try {
124
+ callback(this.error);
125
+ } catch (err) {
126
+ Promise.resolve(err);
127
+ }
128
+ }
129
+ }, DISPOSED_HOOK = new ErrorStubHook(
130
+ new Error("Attempted to use RPC stub after it has been disposed.")
131
+ ), doCall = (hook, path, params) => hook.call(path, params);
132
+ function withCallInterceptor(interceptor, callback) {
133
+ let oldValue = doCall;
134
+ doCall = interceptor;
135
+ try {
136
+ return callback();
137
+ } finally {
138
+ doCall = oldValue;
139
+ }
140
+ }
141
+ var RAW_STUB = /* @__PURE__ */ Symbol("realStub"), PROXY_HANDLERS = {
142
+ apply(target, thisArg, argumentsList) {
143
+ let stub = target.raw;
144
+ return new RpcPromise(doCall(
145
+ stub.hook,
146
+ stub.pathIfPromise || [],
147
+ RpcPayload.fromAppParams(argumentsList)
148
+ ), []);
149
+ },
150
+ get(target, prop, receiver) {
151
+ let stub = target.raw;
152
+ return prop === RAW_STUB ? stub : prop in RpcPromise.prototype ? stub[prop] : typeof prop == "string" ? new RpcPromise(
153
+ stub.hook,
154
+ stub.pathIfPromise ? [...stub.pathIfPromise, prop] : [prop]
155
+ ) : prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0) ? () => {
156
+ stub.hook.dispose(), stub.hook = DISPOSED_HOOK;
157
+ } : void 0;
158
+ },
159
+ has(target, prop) {
160
+ let stub = target.raw;
161
+ return prop === RAW_STUB ? !0 : prop in RpcPromise.prototype ? prop in stub : typeof prop == "string" ? !0 : prop === Symbol.dispose && (!stub.pathIfPromise || stub.pathIfPromise.length == 0);
162
+ },
163
+ construct(target, args) {
164
+ throw new Error("An RPC stub cannot be used as a constructor.");
165
+ },
166
+ defineProperty(target, property, attributes) {
167
+ throw new Error("Can't define properties on RPC stubs.");
168
+ },
169
+ deleteProperty(target, p) {
170
+ throw new Error("Can't delete properties on RPC stubs.");
171
+ },
172
+ getOwnPropertyDescriptor(target, p) {
173
+ },
174
+ getPrototypeOf(target) {
175
+ return Object.getPrototypeOf(target.raw);
176
+ },
177
+ isExtensible(target) {
178
+ return !1;
179
+ },
180
+ ownKeys(target) {
181
+ return [];
182
+ },
183
+ preventExtensions(target) {
184
+ return !0;
185
+ },
186
+ set(target, p, newValue, receiver) {
187
+ throw new Error("Can't assign properties on RPC stubs.");
188
+ },
189
+ setPrototypeOf(target, v) {
190
+ throw new Error("Can't override prototype of RPC stubs.");
191
+ }
192
+ }, RpcStub = class _RpcStub extends RpcTarget {
193
+ // Although `hook` and `path` are declared `public` here, they are effectively hidden by the
194
+ // proxy.
195
+ constructor(hook, pathIfPromise) {
196
+ if (super(), !(hook instanceof StubHook)) {
197
+ let value = hook;
198
+ if (value instanceof RpcTarget || value instanceof Function ? hook = TargetStubHook.create(value, void 0) : hook = new PayloadStubHook(RpcPayload.fromAppReturn(value)), pathIfPromise)
199
+ throw new TypeError("RpcStub constructor expected one argument, received two.");
200
+ }
201
+ this.hook = hook, this.pathIfPromise = pathIfPromise;
202
+ let func = () => {
203
+ };
204
+ return func.raw = this, new Proxy(func, PROXY_HANDLERS);
205
+ }
206
+ hook;
207
+ pathIfPromise;
208
+ dup() {
209
+ let target = this[RAW_STUB];
210
+ return target.pathIfPromise ? new _RpcStub(target.hook.get(target.pathIfPromise)) : new _RpcStub(target.hook.dup());
211
+ }
212
+ onRpcBroken(callback) {
213
+ this[RAW_STUB].hook.onBroken(callback);
214
+ }
215
+ map(func) {
216
+ let { hook, pathIfPromise } = this[RAW_STUB];
217
+ return mapImpl.sendMap(hook, pathIfPromise || [], func);
218
+ }
219
+ toString() {
220
+ return "[object RpcStub]";
221
+ }
222
+ }, RpcPromise = class extends RpcStub {
223
+ // TODO: Support passing target value or promise to constructor.
224
+ constructor(hook, pathIfPromise) {
225
+ super(hook, pathIfPromise);
226
+ }
227
+ then(onfulfilled, onrejected) {
228
+ return pullPromise(this).then(...arguments);
229
+ }
230
+ catch(onrejected) {
231
+ return pullPromise(this).catch(...arguments);
232
+ }
233
+ finally(onfinally) {
234
+ return pullPromise(this).finally(...arguments);
235
+ }
236
+ toString() {
237
+ return "[object RpcPromise]";
238
+ }
239
+ };
240
+ function unwrapStubTakingOwnership(stub) {
241
+ let { hook, pathIfPromise } = stub[RAW_STUB];
242
+ return pathIfPromise && pathIfPromise.length > 0 ? hook.get(pathIfPromise) : hook;
243
+ }
244
+ function unwrapStubAndDup(stub) {
245
+ let { hook, pathIfPromise } = stub[RAW_STUB];
246
+ return pathIfPromise ? hook.get(pathIfPromise) : hook.dup();
247
+ }
248
+ function unwrapStubNoProperties(stub) {
249
+ let { hook, pathIfPromise } = stub[RAW_STUB];
250
+ if (!(pathIfPromise && pathIfPromise.length > 0))
251
+ return hook;
252
+ }
253
+ function unwrapStubOrParent(stub) {
254
+ return stub[RAW_STUB].hook;
255
+ }
256
+ function unwrapStubAndPath(stub) {
257
+ return stub[RAW_STUB];
258
+ }
259
+ async function pullPromise(promise) {
260
+ let { hook, pathIfPromise } = promise[RAW_STUB];
261
+ return pathIfPromise.length > 0 && (hook = hook.get(pathIfPromise)), (await hook.pull()).deliverResolve();
262
+ }
263
+ var RpcPayload = class _RpcPayload {
264
+ // Private constructor; use factory functions above to construct.
265
+ constructor(value, source, hooks, promises) {
266
+ this.value = value, this.source = source, this.hooks = hooks, this.promises = promises;
267
+ }
268
+ // Create a payload from a value passed as params to an RPC from the app.
269
+ //
270
+ // The payload does NOT take ownership of any stubs in `value`, and but promises not to modify
271
+ // `value`. If the payload is delivered locally, `value` will be deep-copied first, so as not
272
+ // to have the sender and recipient end up sharing the same mutable object. `value` will not be
273
+ // touched again after the call returns synchronously (returns a promise) -- by that point,
274
+ // the value has either been copied or serialized to the wire.
275
+ static fromAppParams(value) {
276
+ return new _RpcPayload(value, "params");
277
+ }
278
+ // Create a payload from a value return from an RPC implementation by the app.
279
+ //
280
+ // Unlike fromAppParams(), in this case the payload takes ownership of all stubs in `value`, and
281
+ // may hold onto `value` for an arbitrarily long time (e.g. to serve pipelined requests). It
282
+ // will still avoid modifying `value` and will make a deep copy if it is delivered locally.
283
+ static fromAppReturn(value) {
284
+ return new _RpcPayload(value, "return");
285
+ }
286
+ // Combine an array of payloads into a single payload whose value is an array. Ownership of all
287
+ // stubs is transferred from the inputs to the outputs, hence if the output is disposed, the
288
+ // inputs should not be. (In case of exception, nothing is disposed, though.)
289
+ static fromArray(array) {
290
+ let hooks = [], promises = [], resultArray = [];
291
+ for (let payload of array) {
292
+ payload.ensureDeepCopied();
293
+ for (let hook of payload.hooks)
294
+ hooks.push(hook);
295
+ for (let promise of payload.promises)
296
+ promise.parent === payload && (promise = {
297
+ parent: resultArray,
298
+ property: resultArray.length,
299
+ promise: promise.promise
300
+ }), promises.push(promise);
301
+ resultArray.push(payload.value);
302
+ }
303
+ return new _RpcPayload(resultArray, "owned", hooks, promises);
304
+ }
305
+ // Create a payload from a value parsed off the wire using Evaluator.evaluate().
306
+ //
307
+ // A payload is constructed with a null value and the given hooks and promises arrays. The value
308
+ // is expected to be filled in by the evaluator, and the hooks and promises arrays are expected
309
+ // to be extended with stubs found during parsing. (This weird usage model is necessary so that
310
+ // if the root value turns out to be a promise, its `parent` in `promises` can be the payload
311
+ // object itself.)
312
+ //
313
+ // When done, the payload takes ownership of the final value and all the stubs within. It may
314
+ // modify the value in preparation for delivery, and may deliver the value directly to the app
315
+ // without copying.
316
+ static forEvaluate(hooks, promises) {
317
+ return new _RpcPayload(null, "owned", hooks, promises);
318
+ }
319
+ // Deep-copy the given value, including dup()ing all stubs.
320
+ //
321
+ // If `value` is a function, it should be bound to `oldParent` as its `this`.
322
+ //
323
+ // If deep-copying from a branch of some other RpcPayload, it must be provided, to make sure
324
+ // RpcTargets found within don't get duplicate stubs.
325
+ static deepCopyFrom(value, oldParent, owner) {
326
+ let result = new _RpcPayload(null, "owned", [], []);
327
+ return result.value = result.deepCopy(
328
+ value,
329
+ oldParent,
330
+ "value",
331
+ result,
332
+ /*dupStubs=*/
333
+ !0,
334
+ owner
335
+ ), result;
336
+ }
337
+ // For `source === "return"` payloads only, this tracks any StubHooks created around RpcTargets
338
+ // or WritableStreams found in the payload at the time that it is serialized (or deep-copied) for
339
+ // return, so that we can make sure they are not disposed before the pipeline ends.
340
+ //
341
+ // This is initialized on first use.
342
+ rpcTargets;
343
+ // Get the StubHook representing the given RpcTarget found inside this payload.
344
+ getHookForRpcTarget(target, parent, dupStubs = !0) {
345
+ if (this.source === "params") {
346
+ if (dupStubs) {
347
+ let dupable = target;
348
+ typeof dupable.dup == "function" && (target = dupable.dup());
349
+ }
350
+ return TargetStubHook.create(target, parent);
351
+ } else if (this.source === "return") {
352
+ let hook = this.rpcTargets?.get(target);
353
+ return hook ? dupStubs ? hook.dup() : (this.rpcTargets?.delete(target), hook) : (hook = TargetStubHook.create(target, parent), dupStubs ? (this.rpcTargets || (this.rpcTargets = /* @__PURE__ */ new Map()), this.rpcTargets.set(target, hook), hook.dup()) : hook);
354
+ } else
355
+ throw new Error("owned payload shouldn't contain raw RpcTargets");
356
+ }
357
+ // Get the StubHook representing the given WritableStream found inside this payload.
358
+ getHookForWritableStream(stream, parent, dupStubs = !0) {
359
+ if (this.source === "params")
360
+ return streamImpl.createWritableStreamHook(stream);
361
+ if (this.source === "return") {
362
+ let hook = this.rpcTargets?.get(stream);
363
+ return hook ? dupStubs ? hook.dup() : (this.rpcTargets?.delete(stream), hook) : (hook = streamImpl.createWritableStreamHook(stream), dupStubs ? (this.rpcTargets || (this.rpcTargets = /* @__PURE__ */ new Map()), this.rpcTargets.set(stream, hook), hook.dup()) : hook);
364
+ } else
365
+ throw new Error("owned payload shouldn't contain raw WritableStreams");
366
+ }
367
+ // Get the StubHook representing the given ReadableStream found inside this payload.
368
+ getHookForReadableStream(stream, parent, dupStubs = !0) {
369
+ if (this.source === "params")
370
+ return streamImpl.createReadableStreamHook(stream);
371
+ if (this.source === "return") {
372
+ let hook = this.rpcTargets?.get(stream);
373
+ return hook ? dupStubs ? hook.dup() : (this.rpcTargets?.delete(stream), hook) : (hook = streamImpl.createReadableStreamHook(stream), dupStubs ? (this.rpcTargets || (this.rpcTargets = /* @__PURE__ */ new Map()), this.rpcTargets.set(stream, hook), hook.dup()) : hook);
374
+ } else
375
+ throw new Error("owned payload shouldn't contain raw ReadableStreams");
376
+ }
377
+ deepCopy(value, oldParent, property, parent, dupStubs, owner) {
378
+ switch (typeForRpc(value)) {
379
+ case "unsupported":
380
+ return value;
381
+ case "primitive":
382
+ case "bigint":
383
+ case "date":
384
+ case "bytes":
385
+ case "error":
386
+ case "undefined":
387
+ return value;
388
+ case "array": {
389
+ let array = value, len = array.length, result = new Array(len);
390
+ for (let i = 0; i < len; i++)
391
+ result[i] = this.deepCopy(array[i], array, i, result, dupStubs, owner);
392
+ return result;
393
+ }
394
+ case "object": {
395
+ let result = {}, object = value;
396
+ for (let i in object)
397
+ result[i] = this.deepCopy(object[i], object, i, result, dupStubs, owner);
398
+ return result;
399
+ }
400
+ case "stub":
401
+ case "rpc-promise": {
402
+ let stub = value, hook;
403
+ if (dupStubs ? hook = unwrapStubAndDup(stub) : hook = unwrapStubTakingOwnership(stub), stub instanceof RpcPromise) {
404
+ let promise = new RpcPromise(hook, []);
405
+ return this.promises.push({ parent, property, promise }), promise;
406
+ } else
407
+ return this.hooks.push(hook), new RpcStub(hook);
408
+ }
409
+ case "function":
410
+ case "rpc-target": {
411
+ let target = value, hook;
412
+ return owner ? hook = owner.getHookForRpcTarget(target, oldParent, dupStubs) : hook = TargetStubHook.create(target, oldParent), this.hooks.push(hook), new RpcStub(hook);
413
+ }
414
+ case "rpc-thenable": {
415
+ let target = value, promise;
416
+ return owner ? promise = new RpcPromise(owner.getHookForRpcTarget(target, oldParent, dupStubs), []) : promise = new RpcPromise(TargetStubHook.create(target, oldParent), []), this.promises.push({ parent, property, promise }), promise;
417
+ }
418
+ case "writable": {
419
+ let stream = value, hook;
420
+ return owner ? hook = owner.getHookForWritableStream(stream, oldParent, dupStubs) : hook = streamImpl.createWritableStreamHook(stream), this.hooks.push(hook), stream;
421
+ }
422
+ case "readable": {
423
+ let stream = value, hook;
424
+ return owner ? hook = owner.getHookForReadableStream(stream, oldParent, dupStubs) : hook = streamImpl.createReadableStreamHook(stream), this.hooks.push(hook), stream;
425
+ }
426
+ case "headers":
427
+ return new Headers(value);
428
+ case "request": {
429
+ let req = value;
430
+ return req.body && this.deepCopy(req.body, req, "body", req, dupStubs, owner), new Request(req);
431
+ }
432
+ case "response": {
433
+ let resp = value;
434
+ return resp.body && this.deepCopy(resp.body, resp, "body", resp, dupStubs, owner), new Response(resp.body, resp);
435
+ }
436
+ default:
437
+ throw new Error("unreachable");
438
+ }
439
+ }
440
+ // Ensures that if the value originally came from an unowned source, we have replaced it with a
441
+ // deep copy.
442
+ ensureDeepCopied() {
443
+ if (this.source !== "owned") {
444
+ let dupStubs = this.source === "params";
445
+ this.hooks = [], this.promises = [];
446
+ try {
447
+ this.value = this.deepCopy(this.value, void 0, "value", this, dupStubs, this);
448
+ } catch (err) {
449
+ throw this.hooks = void 0, this.promises = void 0, err;
450
+ }
451
+ if (this.source = "owned", this.rpcTargets && this.rpcTargets.size > 0)
452
+ throw new Error("Not all rpcTargets were accounted for in deep-copy?");
453
+ this.rpcTargets = void 0;
454
+ }
455
+ }
456
+ // Resolve all promises in this payload and then assign the final value into `parent[property]`.
457
+ deliverTo(parent, property, promises) {
458
+ if (this.ensureDeepCopied(), this.value instanceof RpcPromise)
459
+ _RpcPayload.deliverRpcPromiseTo(this.value, parent, property, promises);
460
+ else {
461
+ parent[property] = this.value;
462
+ for (let record of this.promises)
463
+ _RpcPayload.deliverRpcPromiseTo(record.promise, record.parent, record.property, promises);
464
+ }
465
+ }
466
+ static deliverRpcPromiseTo(promise, parent, property, promises) {
467
+ let hook = unwrapStubNoProperties(promise);
468
+ if (!hook)
469
+ throw new Error("property promises should have been resolved earlier");
470
+ let inner = hook.pull();
471
+ inner instanceof _RpcPayload ? inner.deliverTo(parent, property, promises) : promises.push(inner.then((payload) => {
472
+ let subPromises = [];
473
+ if (payload.deliverTo(parent, property, subPromises), subPromises.length > 0)
474
+ return Promise.all(subPromises);
475
+ }));
476
+ }
477
+ // Call the given function with the payload as an argument. The call is made synchronously if
478
+ // possible, in order to maintain e-order. However, if any RpcPromises exist in the payload,
479
+ // they are awaited and substituted before calling the function. The result of the call is
480
+ // wrapped into another payload.
481
+ //
482
+ // The payload is automatically disposed after the call completes. The caller should not call
483
+ // dispose().
484
+ async deliverCall(func, thisArg) {
485
+ try {
486
+ let promises = [];
487
+ this.deliverTo(this, "value", promises), promises.length > 0 && await Promise.all(promises);
488
+ let result = Function.prototype.apply.call(func, thisArg, this.value);
489
+ return result instanceof RpcPromise ? _RpcPayload.fromAppReturn(result) : _RpcPayload.fromAppReturn(await result);
490
+ } finally {
491
+ this.dispose();
492
+ }
493
+ }
494
+ // Produce a promise for this payload for return to the application. Any RpcPromises in the
495
+ // payload are awaited and substituted with their results first.
496
+ //
497
+ // The returned object will have a disposer which disposes the payload. The caller should not
498
+ // separately dispose it.
499
+ async deliverResolve() {
500
+ try {
501
+ let promises = [];
502
+ this.deliverTo(this, "value", promises), promises.length > 0 && await Promise.all(promises);
503
+ let result = this.value;
504
+ return result instanceof Object && (Symbol.dispose in result || Object.defineProperty(result, Symbol.dispose, {
505
+ // NOTE: Using `this.dispose.bind(this)` here causes Playwright's build of
506
+ // Chromium 140.0.7339.16 to fail when the object is assigned to a `using` variable,
507
+ // with the error:
508
+ // TypeError: Symbol(Symbol.dispose) is not a function
509
+ // I cannot reproduce this problem in Chrome 140.0.7339.127 nor in Node or workerd,
510
+ // so maybe it was a short-lived V8 bug or something. To be safe, though, we use
511
+ // `() => this.dispose()`, which seems to always work.
512
+ value: () => this.dispose(),
513
+ writable: !0,
514
+ enumerable: !1,
515
+ configurable: !0
516
+ })), result;
517
+ } catch (err) {
518
+ throw this.dispose(), err;
519
+ }
520
+ }
521
+ dispose() {
522
+ if (this.source === "owned")
523
+ this.hooks.forEach((hook) => hook.dispose()), this.promises.forEach((promise) => promise.promise[Symbol.dispose]());
524
+ else if (this.source === "return" && (this.disposeImpl(this.value, void 0), this.rpcTargets && this.rpcTargets.size > 0))
525
+ throw new Error("Not all rpcTargets were accounted for in disposeImpl()?");
526
+ this.source = "owned", this.hooks = [], this.promises = [];
527
+ }
528
+ // Recursive dispose, called only when `source` is "return".
529
+ disposeImpl(value, parent) {
530
+ switch (typeForRpc(value)) {
531
+ case "unsupported":
532
+ case "primitive":
533
+ case "bigint":
534
+ case "bytes":
535
+ case "date":
536
+ case "error":
537
+ case "undefined":
538
+ return;
539
+ case "array": {
540
+ let array = value, len = array.length;
541
+ for (let i = 0; i < len; i++)
542
+ this.disposeImpl(array[i], array);
543
+ return;
544
+ }
545
+ case "object": {
546
+ let object = value;
547
+ for (let i in object)
548
+ this.disposeImpl(object[i], object);
549
+ return;
550
+ }
551
+ case "stub":
552
+ case "rpc-promise": {
553
+ let hook = unwrapStubNoProperties(value);
554
+ hook && hook.dispose();
555
+ return;
556
+ }
557
+ case "function":
558
+ case "rpc-target": {
559
+ let target = value, hook = this.rpcTargets?.get(target);
560
+ hook ? (hook.dispose(), this.rpcTargets.delete(target)) : disposeRpcTarget(target);
561
+ return;
562
+ }
563
+ case "rpc-thenable":
564
+ return;
565
+ case "headers":
566
+ return;
567
+ case "request": {
568
+ let req = value;
569
+ req.body && this.disposeImpl(req.body, req);
570
+ return;
571
+ }
572
+ case "response": {
573
+ let resp = value;
574
+ resp.body && this.disposeImpl(resp.body, resp);
575
+ return;
576
+ }
577
+ case "writable": {
578
+ let stream = value, hook = this.rpcTargets?.get(stream);
579
+ hook ? this.rpcTargets.delete(stream) : hook = streamImpl.createWritableStreamHook(stream), hook.dispose();
580
+ return;
581
+ }
582
+ case "readable": {
583
+ let stream = value, hook = this.rpcTargets?.get(stream);
584
+ hook ? this.rpcTargets.delete(stream) : hook = streamImpl.createReadableStreamHook(stream), hook.dispose();
585
+ return;
586
+ }
587
+ default:
588
+ return;
589
+ }
590
+ }
591
+ // Ignore unhandled rejections in all promises in this payload -- that is, all promises that
592
+ // *would* be awaited if this payload were to be delivered. See the similarly-named method of
593
+ // StubHook for explanation.
594
+ ignoreUnhandledRejections() {
595
+ this.hooks ? (this.hooks.forEach((hook) => {
596
+ hook.ignoreUnhandledRejections();
597
+ }), this.promises.forEach(
598
+ (promise) => unwrapStubOrParent(promise.promise).ignoreUnhandledRejections()
599
+ )) : this.ignoreUnhandledRejectionsImpl(this.value);
600
+ }
601
+ ignoreUnhandledRejectionsImpl(value) {
602
+ switch (typeForRpc(value)) {
603
+ case "unsupported":
604
+ case "primitive":
605
+ case "bigint":
606
+ case "bytes":
607
+ case "date":
608
+ case "error":
609
+ case "undefined":
610
+ case "function":
611
+ case "rpc-target":
612
+ case "writable":
613
+ case "readable":
614
+ case "headers":
615
+ case "request":
616
+ case "response":
617
+ return;
618
+ case "array": {
619
+ let array = value, len = array.length;
620
+ for (let i = 0; i < len; i++)
621
+ this.ignoreUnhandledRejectionsImpl(array[i]);
622
+ return;
623
+ }
624
+ case "object": {
625
+ let object = value;
626
+ for (let i in object)
627
+ this.ignoreUnhandledRejectionsImpl(object[i]);
628
+ return;
629
+ }
630
+ case "stub":
631
+ case "rpc-promise":
632
+ unwrapStubOrParent(value).ignoreUnhandledRejections();
633
+ return;
634
+ case "rpc-thenable":
635
+ value.then((_) => {
636
+ }, (_) => {
637
+ });
638
+ return;
639
+ default:
640
+ return;
641
+ }
642
+ }
643
+ };
644
+ function followPath(value, parent, path, owner) {
645
+ for (let i = 0; i < path.length; i++) {
646
+ parent = value;
647
+ let part = path[i];
648
+ if (part in Object.prototype) {
649
+ value = void 0;
650
+ continue;
651
+ }
652
+ switch (typeForRpc(value)) {
653
+ case "object":
654
+ case "function":
655
+ Object.hasOwn(value, part) ? value = value[part] : value = void 0;
656
+ break;
657
+ case "array":
658
+ Number.isInteger(part) && part >= 0 ? value = value[part] : value = void 0;
659
+ break;
660
+ case "rpc-target":
661
+ case "rpc-thenable": {
662
+ if (Object.hasOwn(value, part))
663
+ throw new TypeError(
664
+ `Attempted to access property '${part}', which is an instance property of the RpcTarget. To avoid leaking private internals, instance properties cannot be accessed over RPC. If you want to make this property available over RPC, define it as a method or getter on the class, instead of an instance property.`
665
+ );
666
+ value = value[part], owner = null;
667
+ break;
668
+ }
669
+ case "stub":
670
+ case "rpc-promise": {
671
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
672
+ return { hook, remainingPath: pathIfPromise ? pathIfPromise.concat(path.slice(i)) : path.slice(i) };
673
+ }
674
+ case "writable":
675
+ value = void 0;
676
+ break;
677
+ case "readable":
678
+ value = void 0;
679
+ break;
680
+ case "primitive":
681
+ case "bigint":
682
+ case "bytes":
683
+ case "date":
684
+ case "error":
685
+ case "headers":
686
+ case "request":
687
+ case "response":
688
+ value = void 0;
689
+ break;
690
+ case "undefined":
691
+ value = value[part];
692
+ break;
693
+ case "unsupported": {
694
+ if (i === 0)
695
+ throw new TypeError("RPC stub points at a non-serializable type.");
696
+ {
697
+ let prefix = path.slice(0, i).join("."), remainder = path.slice(0, i).join(".");
698
+ throw new TypeError(
699
+ `'${prefix}' is not a serializable type, so property ${remainder} cannot be accessed.`
700
+ );
701
+ }
702
+ }
703
+ default:
704
+ throw new TypeError("unreachable");
705
+ }
706
+ }
707
+ if (value instanceof RpcPromise) {
708
+ let { hook, pathIfPromise } = unwrapStubAndPath(value);
709
+ return { hook, remainingPath: pathIfPromise || [] };
710
+ }
711
+ return {
712
+ value,
713
+ parent,
714
+ owner
715
+ };
716
+ }
717
+ var ValueStubHook = class extends StubHook {
718
+ call(path, args) {
719
+ try {
720
+ let { value, owner } = this.getValue(), followResult = followPath(value, void 0, path, owner);
721
+ if (followResult.hook)
722
+ return followResult.hook.call(followResult.remainingPath, args);
723
+ if (typeof followResult.value != "function")
724
+ throw new TypeError(`'${path.join(".")}' is not a function.`);
725
+ let promise = args.deliverCall(followResult.value, followResult.parent);
726
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
727
+ } catch (err) {
728
+ return new ErrorStubHook(err);
729
+ }
730
+ }
731
+ map(path, captures, instructions) {
732
+ try {
733
+ let followResult;
734
+ try {
735
+ let { value, owner } = this.getValue();
736
+ followResult = followPath(value, void 0, path, owner);
737
+ } catch (err) {
738
+ for (let cap of captures)
739
+ cap.dispose();
740
+ throw err;
741
+ }
742
+ return followResult.hook ? followResult.hook.map(followResult.remainingPath, captures, instructions) : mapImpl.applyMap(
743
+ followResult.value,
744
+ followResult.parent,
745
+ followResult.owner,
746
+ captures,
747
+ instructions
748
+ );
749
+ } catch (err) {
750
+ return new ErrorStubHook(err);
751
+ }
752
+ }
753
+ get(path) {
754
+ try {
755
+ let { value, owner } = this.getValue();
756
+ if (path.length === 0 && owner === null)
757
+ throw new Error("Can't dup an RpcTarget stub as a promise.");
758
+ let followResult = followPath(value, void 0, path, owner);
759
+ return followResult.hook ? followResult.hook.get(followResult.remainingPath) : new PayloadStubHook(RpcPayload.deepCopyFrom(
760
+ followResult.value,
761
+ followResult.parent,
762
+ followResult.owner
763
+ ));
764
+ } catch (err) {
765
+ return new ErrorStubHook(err);
766
+ }
767
+ }
768
+ }, PayloadStubHook = class _PayloadStubHook extends ValueStubHook {
769
+ constructor(payload) {
770
+ super(), this.payload = payload;
771
+ }
772
+ payload;
773
+ // cleared when disposed
774
+ getPayload() {
775
+ if (this.payload)
776
+ return this.payload;
777
+ throw new Error("Attempted to use an RPC StubHook after it was disposed.");
778
+ }
779
+ getValue() {
780
+ let payload = this.getPayload();
781
+ return { value: payload.value, owner: payload };
782
+ }
783
+ dup() {
784
+ let thisPayload = this.getPayload();
785
+ return new _PayloadStubHook(RpcPayload.deepCopyFrom(
786
+ thisPayload.value,
787
+ void 0,
788
+ thisPayload
789
+ ));
790
+ }
791
+ pull() {
792
+ return this.getPayload();
793
+ }
794
+ ignoreUnhandledRejections() {
795
+ this.payload && this.payload.ignoreUnhandledRejections();
796
+ }
797
+ dispose() {
798
+ this.payload && (this.payload.dispose(), this.payload = void 0);
799
+ }
800
+ onBroken(callback) {
801
+ this.payload && this.payload.value instanceof RpcStub && this.payload.value.onRpcBroken(callback);
802
+ }
803
+ };
804
+ function disposeRpcTarget(target) {
805
+ if (Symbol.dispose in target)
806
+ try {
807
+ target[Symbol.dispose]();
808
+ } catch (err) {
809
+ Promise.reject(err);
810
+ }
811
+ }
812
+ var TargetStubHook = class _TargetStubHook extends ValueStubHook {
813
+ // Constructs a TargetStubHook that is not duplicated from an existing hook.
814
+ //
815
+ // If `value` is a function, `parent` is bound as its "this".
816
+ static create(value, parent) {
817
+ return typeof value != "function" && (parent = void 0), new _TargetStubHook(value, parent);
818
+ }
819
+ constructor(target, parent, dupFrom) {
820
+ super(), this.target = target, this.parent = parent, dupFrom ? dupFrom.refcount && (this.refcount = dupFrom.refcount, ++this.refcount.count) : Symbol.dispose in target && (this.refcount = { count: 1 });
821
+ }
822
+ target;
823
+ // cleared when disposed
824
+ parent;
825
+ // `this` parameter when calling `target`
826
+ refcount;
827
+ // undefined if not needed (because target has no disposer)
828
+ getTarget() {
829
+ if (this.target)
830
+ return this.target;
831
+ throw new Error("Attempted to use an RPC StubHook after it was disposed.");
832
+ }
833
+ getValue() {
834
+ return { value: this.getTarget(), owner: null };
835
+ }
836
+ dup() {
837
+ return new _TargetStubHook(this.getTarget(), this.parent, this);
838
+ }
839
+ pull() {
840
+ let target = this.getTarget();
841
+ return "then" in target ? Promise.resolve(target).then((resolution) => RpcPayload.fromAppReturn(resolution)) : Promise.reject(new Error("Tried to resolve a non-promise stub."));
842
+ }
843
+ ignoreUnhandledRejections() {
844
+ }
845
+ dispose() {
846
+ this.target && (this.refcount && --this.refcount.count == 0 && disposeRpcTarget(this.target), this.target = void 0);
847
+ }
848
+ onBroken(callback) {
849
+ }
850
+ }, PromiseStubHook = class _PromiseStubHook extends StubHook {
851
+ promise;
852
+ resolution;
853
+ constructor(promise) {
854
+ super(), this.promise = promise.then((res) => (this.resolution = res, res));
855
+ }
856
+ call(path, args) {
857
+ return args.ensureDeepCopied(), new _PromiseStubHook(this.promise.then((hook) => hook.call(path, args)));
858
+ }
859
+ stream(path, args) {
860
+ return args.ensureDeepCopied(), { promise: this.promise.then((hook) => hook.stream(path, args).promise) };
861
+ }
862
+ map(path, captures, instructions) {
863
+ return new _PromiseStubHook(this.promise.then(
864
+ (hook) => hook.map(path, captures, instructions),
865
+ (err) => {
866
+ for (let cap of captures)
867
+ cap.dispose();
868
+ throw err;
869
+ }
870
+ ));
871
+ }
872
+ get(path) {
873
+ return new _PromiseStubHook(this.promise.then((hook) => hook.get(path)));
874
+ }
875
+ dup() {
876
+ return this.resolution ? this.resolution.dup() : new _PromiseStubHook(this.promise.then((hook) => hook.dup()));
877
+ }
878
+ pull() {
879
+ return this.resolution ? this.resolution.pull() : this.promise.then((hook) => hook.pull());
880
+ }
881
+ ignoreUnhandledRejections() {
882
+ this.resolution ? this.resolution.ignoreUnhandledRejections() : this.promise.then((res) => {
883
+ res.ignoreUnhandledRejections();
884
+ }, (err) => {
885
+ });
886
+ }
887
+ dispose() {
888
+ this.resolution ? this.resolution.dispose() : this.promise.then((hook) => {
889
+ hook.dispose();
890
+ }, (err) => {
891
+ });
892
+ }
893
+ onBroken(callback) {
894
+ this.resolution ? this.resolution.onBroken(callback) : this.promise.then((hook) => {
895
+ hook.onBroken(callback);
896
+ }, callback);
897
+ }
898
+ }, NullExporter = class {
899
+ exportStub(stub) {
900
+ throw new Error("Cannot serialize RPC stubs without an RPC session.");
901
+ }
902
+ exportPromise(stub) {
903
+ throw new Error("Cannot serialize RPC stubs without an RPC session.");
904
+ }
905
+ getImport(hook) {
906
+ }
907
+ unexport(ids) {
908
+ }
909
+ createPipe(readable) {
910
+ throw new Error("Cannot create pipes without an RPC session.");
911
+ }
912
+ onSendError(error) {
913
+ }
914
+ }, NULL_EXPORTER = new NullExporter(), ERROR_TYPES = {
915
+ Error,
916
+ EvalError,
917
+ RangeError,
918
+ ReferenceError,
919
+ SyntaxError,
920
+ TypeError,
921
+ URIError,
922
+ AggregateError
923
+ // TODO: DOMError? Others?
924
+ }, Devaluator = class _Devaluator {
925
+ constructor(exporter, source) {
926
+ this.exporter = exporter, this.source = source;
927
+ }
928
+ // Devaluate the given value.
929
+ // * value: The value to devaluate.
930
+ // * parent: The value's parent object, which would be used as `this` if the value were called
931
+ // as a function.
932
+ // * exporter: Callbacks to the RPC session for exporting capabilities found in this message.
933
+ // * source: The RpcPayload which contains the value, and therefore owns stubs within.
934
+ //
935
+ // Returns: The devaluated value, ready to be JSON-serialized.
936
+ static devaluate(value, parent, exporter = NULL_EXPORTER, source) {
937
+ let devaluator = new _Devaluator(exporter, source);
938
+ try {
939
+ return devaluator.devaluateImpl(value, parent, 0);
940
+ } catch (err) {
941
+ if (devaluator.exports)
942
+ try {
943
+ exporter.unexport(devaluator.exports);
944
+ } catch {
945
+ }
946
+ throw err;
947
+ }
948
+ }
949
+ exports;
950
+ devaluateImpl(value, parent, depth) {
951
+ if (depth >= 64)
952
+ throw new Error(
953
+ "Serialization exceeded maximum allowed depth. (Does the message contain cycles?)"
954
+ );
955
+ switch (typeForRpc(value)) {
956
+ case "unsupported": {
957
+ let msg;
958
+ try {
959
+ msg = `Cannot serialize value: ${value}`;
960
+ } catch {
961
+ msg = "Cannot serialize value: (couldn't stringify value)";
962
+ }
963
+ throw new TypeError(msg);
964
+ }
965
+ case "primitive":
966
+ return typeof value == "number" && !isFinite(value) ? value === 1 / 0 ? ["inf"] : value === -1 / 0 ? ["-inf"] : ["nan"] : value;
967
+ case "object": {
968
+ let object = value, result = {};
969
+ for (let key in object)
970
+ result[key] = this.devaluateImpl(object[key], object, depth + 1);
971
+ return result;
972
+ }
973
+ case "array": {
974
+ let array = value, len = array.length, result = new Array(len);
975
+ for (let i = 0; i < len; i++)
976
+ result[i] = this.devaluateImpl(array[i], array, depth + 1);
977
+ return [result];
978
+ }
979
+ case "bigint":
980
+ return ["bigint", value.toString()];
981
+ case "date":
982
+ return ["date", value.getTime()];
983
+ case "bytes": {
984
+ let bytes = value;
985
+ return bytes.toBase64 ? ["bytes", bytes.toBase64({ omitPadding: !0 })] : [
986
+ "bytes",
987
+ btoa(String.fromCharCode.apply(null, bytes).replace(/=*$/, ""))
988
+ ];
989
+ }
990
+ case "headers":
991
+ return ["headers", [...value]];
992
+ case "request": {
993
+ let req = value, init = {};
994
+ req.method !== "GET" && (init.method = req.method);
995
+ let headers = [...req.headers];
996
+ if (headers.length > 0 && (init.headers = headers), req.body)
997
+ init.body = this.devaluateImpl(req.body, req, depth + 1), init.duplex = req.duplex || "half";
998
+ else if (req.body === void 0 && !["GET", "HEAD", "OPTIONS", "TRACE", "DELETE"].includes(req.method)) {
999
+ let bodyPromise = req.arrayBuffer(), readable = new ReadableStream({
1000
+ async start(controller) {
1001
+ try {
1002
+ controller.enqueue(new Uint8Array(await bodyPromise)), controller.close();
1003
+ } catch (err) {
1004
+ controller.error(err);
1005
+ }
1006
+ }
1007
+ }), hook = streamImpl.createReadableStreamHook(readable), importId = this.exporter.createPipe(readable, hook);
1008
+ init.body = ["readable", importId], init.duplex = req.duplex || "half";
1009
+ }
1010
+ req.cache && req.cache !== "default" && (init.cache = req.cache), req.redirect !== "follow" && (init.redirect = req.redirect), req.integrity && (init.integrity = req.integrity), req.mode && req.mode !== "cors" && (init.mode = req.mode), req.credentials && req.credentials !== "same-origin" && (init.credentials = req.credentials), req.referrer && req.referrer !== "about:client" && (init.referrer = req.referrer), req.referrerPolicy && (init.referrerPolicy = req.referrerPolicy), req.keepalive && (init.keepalive = req.keepalive);
1011
+ let cfReq = req;
1012
+ return cfReq.cf && (init.cf = cfReq.cf), cfReq.encodeResponseBody && cfReq.encodeResponseBody !== "automatic" && (init.encodeResponseBody = cfReq.encodeResponseBody), ["request", req.url, init];
1013
+ }
1014
+ case "response": {
1015
+ let resp = value, body = this.devaluateImpl(resp.body, resp, depth + 1), init = {};
1016
+ resp.status !== 200 && (init.status = resp.status), resp.statusText && (init.statusText = resp.statusText);
1017
+ let headers = [...resp.headers];
1018
+ headers.length > 0 && (init.headers = headers);
1019
+ let cfResp = resp;
1020
+ if (cfResp.cf && (init.cf = cfResp.cf), cfResp.encodeBody && cfResp.encodeBody !== "automatic" && (init.encodeBody = cfResp.encodeBody), cfResp.webSocket)
1021
+ throw new TypeError("Can't serialize a Response containing a webSocket.");
1022
+ return ["response", body, init];
1023
+ }
1024
+ case "error": {
1025
+ let e = value, rewritten = this.exporter.onSendError(e);
1026
+ rewritten && (e = rewritten);
1027
+ let result = ["error", e.name, e.message];
1028
+ return rewritten && rewritten.stack && result.push(rewritten.stack), result;
1029
+ }
1030
+ case "undefined":
1031
+ return ["undefined"];
1032
+ case "stub":
1033
+ case "rpc-promise": {
1034
+ if (!this.source)
1035
+ throw new Error("Can't serialize RPC stubs in this context.");
1036
+ let { hook, pathIfPromise } = unwrapStubAndPath(value), importId = this.exporter.getImport(hook);
1037
+ return importId !== void 0 ? pathIfPromise ? pathIfPromise.length > 0 ? ["pipeline", importId, pathIfPromise] : ["pipeline", importId] : ["import", importId] : (pathIfPromise ? hook = hook.get(pathIfPromise) : hook = hook.dup(), this.devaluateHook(pathIfPromise ? "promise" : "export", hook));
1038
+ }
1039
+ case "function":
1040
+ case "rpc-target": {
1041
+ if (!this.source)
1042
+ throw new Error("Can't serialize RPC stubs in this context.");
1043
+ let hook = this.source.getHookForRpcTarget(value, parent);
1044
+ return this.devaluateHook("export", hook);
1045
+ }
1046
+ case "rpc-thenable": {
1047
+ if (!this.source)
1048
+ throw new Error("Can't serialize RPC stubs in this context.");
1049
+ let hook = this.source.getHookForRpcTarget(value, parent);
1050
+ return this.devaluateHook("promise", hook);
1051
+ }
1052
+ case "writable": {
1053
+ if (!this.source)
1054
+ throw new Error("Can't serialize WritableStream in this context.");
1055
+ let hook = this.source.getHookForWritableStream(value, parent);
1056
+ return this.devaluateHook("writable", hook);
1057
+ }
1058
+ case "readable": {
1059
+ if (!this.source)
1060
+ throw new Error("Can't serialize ReadableStream in this context.");
1061
+ let ws = value, hook = this.source.getHookForReadableStream(ws, parent);
1062
+ return ["readable", this.exporter.createPipe(ws, hook)];
1063
+ }
1064
+ default:
1065
+ throw new Error("unreachable");
1066
+ }
1067
+ }
1068
+ devaluateHook(type, hook) {
1069
+ this.exports || (this.exports = []);
1070
+ let exportId = type === "promise" ? this.exporter.exportPromise(hook) : this.exporter.exportStub(hook);
1071
+ return this.exports.push(exportId), [type, exportId];
1072
+ }
1073
+ };
1074
+ var NullImporter = class {
1075
+ importStub(idx) {
1076
+ throw new Error("Cannot deserialize RPC stubs without an RPC session.");
1077
+ }
1078
+ importPromise(idx) {
1079
+ throw new Error("Cannot deserialize RPC stubs without an RPC session.");
1080
+ }
1081
+ getExport(idx) {
1082
+ }
1083
+ getPipeReadable(exportId) {
1084
+ throw new Error("Cannot retrieve pipe readable without an RPC session.");
1085
+ }
1086
+ }, NULL_IMPORTER = new NullImporter();
1087
+ function fixBrokenRequestBody(request, body) {
1088
+ let promise = new Response(body).arrayBuffer().then((arrayBuffer) => {
1089
+ let bytes = new Uint8Array(arrayBuffer), result = new Request(request, { body: bytes });
1090
+ return new PayloadStubHook(RpcPayload.fromAppReturn(result));
1091
+ });
1092
+ return new RpcPromise(new PromiseStubHook(promise), []);
1093
+ }
1094
+ var Evaluator = class _Evaluator {
1095
+ constructor(importer) {
1096
+ this.importer = importer;
1097
+ }
1098
+ hooks = [];
1099
+ promises = [];
1100
+ evaluate(value) {
1101
+ let payload = RpcPayload.forEvaluate(this.hooks, this.promises);
1102
+ try {
1103
+ return payload.value = this.evaluateImpl(value, payload, "value"), payload;
1104
+ } catch (err) {
1105
+ throw payload.dispose(), err;
1106
+ }
1107
+ }
1108
+ // Evaluate the value without destroying it.
1109
+ evaluateCopy(value) {
1110
+ return this.evaluate(structuredClone(value));
1111
+ }
1112
+ evaluateImpl(value, parent, property) {
1113
+ if (value instanceof Array) {
1114
+ if (value.length == 1 && value[0] instanceof Array) {
1115
+ let result = value[0];
1116
+ for (let i = 0; i < result.length; i++)
1117
+ result[i] = this.evaluateImpl(result[i], result, i);
1118
+ return result;
1119
+ } else switch (value[0]) {
1120
+ case "bigint":
1121
+ if (typeof value[1] == "string")
1122
+ return BigInt(value[1]);
1123
+ break;
1124
+ case "date":
1125
+ if (typeof value[1] == "number")
1126
+ return new Date(value[1]);
1127
+ break;
1128
+ case "bytes": {
1129
+ let b64 = Uint8Array;
1130
+ if (typeof value[1] == "string") {
1131
+ if (b64.fromBase64)
1132
+ return b64.fromBase64(value[1]);
1133
+ {
1134
+ let bs = atob(value[1]), len = bs.length, bytes = new Uint8Array(len);
1135
+ for (let i = 0; i < len; i++)
1136
+ bytes[i] = bs.charCodeAt(i);
1137
+ return bytes;
1138
+ }
1139
+ }
1140
+ break;
1141
+ }
1142
+ case "error":
1143
+ if (value.length >= 3 && typeof value[1] == "string" && typeof value[2] == "string") {
1144
+ let cls = ERROR_TYPES[value[1]] || Error, result = new cls(value[2]);
1145
+ return typeof value[3] == "string" && (result.stack = value[3]), result;
1146
+ }
1147
+ break;
1148
+ case "undefined":
1149
+ if (value.length === 1)
1150
+ return;
1151
+ break;
1152
+ case "inf":
1153
+ return 1 / 0;
1154
+ case "-inf":
1155
+ return -1 / 0;
1156
+ case "nan":
1157
+ return NaN;
1158
+ case "headers":
1159
+ if (value.length === 2 && value[1] instanceof Array)
1160
+ return new Headers(value[1]);
1161
+ break;
1162
+ case "request": {
1163
+ if (value.length !== 3 || typeof value[1] != "string") break;
1164
+ let url = value[1], init = value[2];
1165
+ if (typeof init != "object" || init === null) break;
1166
+ if (init.body && (init.body = this.evaluateImpl(init.body, init, "body"), !(init.body === null || typeof init.body == "string" || init.body instanceof Uint8Array || init.body instanceof ReadableStream)))
1167
+ throw new TypeError("Request body must be of type ReadableStream.");
1168
+ if (init.signal && (init.signal = this.evaluateImpl(init.signal, init, "signal"), !(init.signal instanceof AbortSignal)))
1169
+ throw new TypeError("Request siganl must be of type AbortSignal.");
1170
+ if (init.headers && !(init.headers instanceof Array))
1171
+ throw new TypeError("Request headers must be serialized as an array of pairs.");
1172
+ let result = new Request(url, init);
1173
+ if (init.body instanceof ReadableStream && result.body === void 0) {
1174
+ let promise = fixBrokenRequestBody(result, init.body);
1175
+ return this.promises.push({ promise, parent, property }), promise;
1176
+ } else
1177
+ return result;
1178
+ }
1179
+ case "response": {
1180
+ if (value.length !== 3) break;
1181
+ let body = this.evaluateImpl(value[1], parent, property);
1182
+ if (!(body === null || typeof body == "string" || body instanceof Uint8Array || body instanceof ReadableStream)) throw new TypeError("Response body must be of type ReadableStream.");
1183
+ let init = value[2];
1184
+ if (typeof init != "object" || init === null) break;
1185
+ if (init.webSocket)
1186
+ throw new TypeError("Can't deserialize a Response containing a webSocket.");
1187
+ if (init.headers && !(init.headers instanceof Array))
1188
+ throw new TypeError("Request headers must be serialized as an array of pairs.");
1189
+ return new Response(body, init);
1190
+ }
1191
+ case "import":
1192
+ case "pipeline": {
1193
+ if (value.length < 2 || value.length > 4 || typeof value[1] != "number")
1194
+ break;
1195
+ let hook = this.importer.getExport(value[1]);
1196
+ if (!hook)
1197
+ throw new Error(`no such entry on exports table: ${value[1]}`);
1198
+ let isPromise = value[0] == "pipeline", addStub = (hook2) => {
1199
+ if (isPromise) {
1200
+ let promise = new RpcPromise(hook2, []);
1201
+ return this.promises.push({ promise, parent, property }), promise;
1202
+ } else
1203
+ return this.hooks.push(hook2), new RpcPromise(hook2, []);
1204
+ };
1205
+ if (value.length == 2)
1206
+ return addStub(isPromise ? hook.get([]) : hook.dup());
1207
+ let path = value[2];
1208
+ if (!(path instanceof Array) || !path.every(
1209
+ (part) => typeof part == "string" || typeof part == "number"
1210
+ ))
1211
+ break;
1212
+ if (value.length == 3)
1213
+ return addStub(hook.get(path));
1214
+ let args = value[3];
1215
+ if (!(args instanceof Array))
1216
+ break;
1217
+ return args = new _Evaluator(this.importer).evaluate([args]), addStub(hook.call(path, args));
1218
+ }
1219
+ case "remap": {
1220
+ if (value.length !== 5 || typeof value[1] != "number" || !(value[2] instanceof Array) || !(value[3] instanceof Array) || !(value[4] instanceof Array))
1221
+ break;
1222
+ let hook = this.importer.getExport(value[1]);
1223
+ if (!hook)
1224
+ throw new Error(`no such entry on exports table: ${value[1]}`);
1225
+ let path = value[2];
1226
+ if (!path.every(
1227
+ (part) => typeof part == "string" || typeof part == "number"
1228
+ ))
1229
+ break;
1230
+ let captures = value[3].map((cap) => {
1231
+ if (!(cap instanceof Array) || cap.length !== 2 || cap[0] !== "import" && cap[0] !== "export" || typeof cap[1] != "number")
1232
+ throw new TypeError(`unknown map capture: ${JSON.stringify(cap)}`);
1233
+ if (cap[0] === "export")
1234
+ return this.importer.importStub(cap[1]);
1235
+ {
1236
+ let exp = this.importer.getExport(cap[1]);
1237
+ if (!exp)
1238
+ throw new Error(`no such entry on exports table: ${cap[1]}`);
1239
+ return exp.dup();
1240
+ }
1241
+ }), instructions = value[4], resultHook = hook.map(path, captures, instructions), promise = new RpcPromise(resultHook, []);
1242
+ return this.promises.push({ promise, parent, property }), promise;
1243
+ }
1244
+ case "export":
1245
+ case "promise":
1246
+ if (typeof value[1] == "number")
1247
+ if (value[0] == "promise") {
1248
+ let hook = this.importer.importPromise(value[1]), promise = new RpcPromise(hook, []);
1249
+ return this.promises.push({ parent, property, promise }), promise;
1250
+ } else {
1251
+ let hook = this.importer.importStub(value[1]);
1252
+ return this.hooks.push(hook), new RpcStub(hook);
1253
+ }
1254
+ break;
1255
+ case "writable":
1256
+ if (typeof value[1] == "number") {
1257
+ let hook = this.importer.importStub(value[1]), stream = streamImpl.createWritableStreamFromHook(hook);
1258
+ return this.hooks.push(hook), stream;
1259
+ }
1260
+ break;
1261
+ case "readable":
1262
+ if (typeof value[1] == "number") {
1263
+ let stream = this.importer.getPipeReadable(value[1]), hook = streamImpl.createReadableStreamHook(stream);
1264
+ return this.hooks.push(hook), stream;
1265
+ }
1266
+ break;
1267
+ }
1268
+ throw new TypeError(`unknown special value: ${JSON.stringify(value)}`);
1269
+ } else if (value instanceof Object) {
1270
+ let result = value;
1271
+ for (let key in result)
1272
+ key in Object.prototype || key === "toJSON" ? (this.evaluateImpl(result[key], result, key), delete result[key]) : result[key] = this.evaluateImpl(result[key], result, key);
1273
+ return result;
1274
+ } else
1275
+ return value;
1276
+ }
1277
+ };
1278
+ var ImportTableEntry = class {
1279
+ constructor(session, importId, pulling) {
1280
+ this.session = session, this.importId = importId, pulling && (this.activePull = Promise.withResolvers());
1281
+ }
1282
+ localRefcount = 0;
1283
+ remoteRefcount = 1;
1284
+ activePull;
1285
+ resolution;
1286
+ // List of integer indexes into session.onBrokenCallbacks which are callbacks registered on
1287
+ // this import. Initialized on first use (so `undefined` is the same as an empty list).
1288
+ onBrokenRegistrations;
1289
+ resolve(resolution) {
1290
+ if (this.localRefcount == 0) {
1291
+ resolution.dispose();
1292
+ return;
1293
+ }
1294
+ if (this.resolution = resolution, this.sendRelease(), this.onBrokenRegistrations) {
1295
+ for (let i of this.onBrokenRegistrations) {
1296
+ let callback = this.session.onBrokenCallbacks[i], endIndex = this.session.onBrokenCallbacks.length;
1297
+ resolution.onBroken(callback), this.session.onBrokenCallbacks[endIndex] === callback ? delete this.session.onBrokenCallbacks[endIndex] : delete this.session.onBrokenCallbacks[i];
1298
+ }
1299
+ this.onBrokenRegistrations = void 0;
1300
+ }
1301
+ this.activePull && (this.activePull.resolve(), this.activePull = void 0);
1302
+ }
1303
+ async awaitResolution() {
1304
+ return this.activePull || (this.session.sendPull(this.importId), this.activePull = Promise.withResolvers()), await this.activePull.promise, this.resolution.pull();
1305
+ }
1306
+ dispose() {
1307
+ this.resolution ? this.resolution.dispose() : (this.abort(new Error("RPC was canceled because the RpcPromise was disposed.")), this.sendRelease());
1308
+ }
1309
+ abort(error) {
1310
+ this.resolution || (this.resolution = new ErrorStubHook(error), this.activePull && (this.activePull.reject(error), this.activePull = void 0), this.onBrokenRegistrations = void 0);
1311
+ }
1312
+ onBroken(callback) {
1313
+ if (this.resolution)
1314
+ this.resolution.onBroken(callback);
1315
+ else {
1316
+ let index = this.session.onBrokenCallbacks.length;
1317
+ this.session.onBrokenCallbacks.push(callback), this.onBrokenRegistrations || (this.onBrokenRegistrations = []), this.onBrokenRegistrations.push(index);
1318
+ }
1319
+ }
1320
+ sendRelease() {
1321
+ this.remoteRefcount > 0 && (this.session.sendRelease(this.importId, this.remoteRefcount), this.remoteRefcount = 0);
1322
+ }
1323
+ }, RpcImportHook = class _RpcImportHook extends StubHook {
1324
+ // undefined when we're disposed
1325
+ // `pulling` is true if we already expect that this import is going to be resolved later, and
1326
+ // null if this import is not allowed to be pulled (i.e. it's a stub not a promise).
1327
+ constructor(isPromise, entry) {
1328
+ super(), this.isPromise = isPromise, ++entry.localRefcount, this.entry = entry;
1329
+ }
1330
+ entry;
1331
+ collectPath(path) {
1332
+ return this;
1333
+ }
1334
+ getEntry() {
1335
+ if (this.entry)
1336
+ return this.entry;
1337
+ throw new Error("This RpcImportHook was already disposed.");
1338
+ }
1339
+ // -------------------------------------------------------------------------------------
1340
+ // implements StubHook
1341
+ call(path, args) {
1342
+ let entry = this.getEntry();
1343
+ return entry.resolution ? entry.resolution.call(path, args) : entry.session.sendCall(entry.importId, path, args);
1344
+ }
1345
+ stream(path, args) {
1346
+ let entry = this.getEntry();
1347
+ return entry.resolution ? entry.resolution.stream(path, args) : entry.session.sendStream(entry.importId, path, args);
1348
+ }
1349
+ map(path, captures, instructions) {
1350
+ let entry;
1351
+ try {
1352
+ entry = this.getEntry();
1353
+ } catch (err) {
1354
+ for (let cap of captures)
1355
+ cap.dispose();
1356
+ throw err;
1357
+ }
1358
+ return entry.resolution ? entry.resolution.map(path, captures, instructions) : entry.session.sendMap(entry.importId, path, captures, instructions);
1359
+ }
1360
+ get(path) {
1361
+ let entry = this.getEntry();
1362
+ return entry.resolution ? entry.resolution.get(path) : entry.session.sendCall(entry.importId, path);
1363
+ }
1364
+ dup() {
1365
+ return new _RpcImportHook(!1, this.getEntry());
1366
+ }
1367
+ pull() {
1368
+ let entry = this.getEntry();
1369
+ if (!this.isPromise)
1370
+ throw new Error("Can't pull this hook because it's not a promise hook.");
1371
+ return entry.resolution ? entry.resolution.pull() : entry.awaitResolution();
1372
+ }
1373
+ ignoreUnhandledRejections() {
1374
+ }
1375
+ dispose() {
1376
+ let entry = this.entry;
1377
+ this.entry = void 0, entry && --entry.localRefcount === 0 && entry.dispose();
1378
+ }
1379
+ onBroken(callback) {
1380
+ this.entry && this.entry.onBroken(callback);
1381
+ }
1382
+ }, RpcMainHook = class extends RpcImportHook {
1383
+ session;
1384
+ constructor(entry) {
1385
+ super(!1, entry), this.session = entry.session;
1386
+ }
1387
+ dispose() {
1388
+ if (this.session) {
1389
+ let session = this.session;
1390
+ this.session = void 0, session.shutdown();
1391
+ }
1392
+ }
1393
+ }, RpcSessionImpl = class {
1394
+ constructor(transport, mainHook, options) {
1395
+ this.transport = transport, this.options = options, this.exports.push({ hook: mainHook, refcount: 1 }), this.imports.push(new ImportTableEntry(this, 0, !1));
1396
+ let rejectFunc, abortPromise = new Promise((resolve, reject) => {
1397
+ rejectFunc = reject;
1398
+ });
1399
+ this.cancelReadLoop = rejectFunc, this.readLoop(abortPromise).catch((err) => this.abort(err));
1400
+ }
1401
+ exports = [];
1402
+ reverseExports = /* @__PURE__ */ new Map();
1403
+ imports = [];
1404
+ abortReason;
1405
+ cancelReadLoop;
1406
+ // We assign positive numbers to imports we initiate, and negative numbers to exports we
1407
+ // initiate. So the next import ID is just `imports.length`, but the next export ID needs
1408
+ // to be tracked explicitly.
1409
+ nextExportId = -1;
1410
+ // If set, call this when all incoming calls are complete.
1411
+ onBatchDone;
1412
+ // How many promises is our peer expecting us to resolve?
1413
+ pullCount = 0;
1414
+ // Sparse array of onBrokenCallback registrations. Items are strictly appended to the end but
1415
+ // may be deleted from the middle (hence leaving the array sparse).
1416
+ onBrokenCallbacks = [];
1417
+ // Should only be called once immediately after construction.
1418
+ getMainImport() {
1419
+ return new RpcMainHook(this.imports[0]);
1420
+ }
1421
+ shutdown() {
1422
+ this.abort(new Error("RPC session was shut down by disposing the main stub"), !1);
1423
+ }
1424
+ exportStub(hook) {
1425
+ if (this.abortReason) throw this.abortReason;
1426
+ let existingExportId = this.reverseExports.get(hook);
1427
+ if (existingExportId !== void 0)
1428
+ return ++this.exports[existingExportId].refcount, existingExportId;
1429
+ {
1430
+ let exportId = this.nextExportId--;
1431
+ return this.exports[exportId] = { hook, refcount: 1 }, this.reverseExports.set(hook, exportId), exportId;
1432
+ }
1433
+ }
1434
+ exportPromise(hook) {
1435
+ if (this.abortReason) throw this.abortReason;
1436
+ let exportId = this.nextExportId--;
1437
+ return this.exports[exportId] = { hook, refcount: 1 }, this.reverseExports.set(hook, exportId), this.ensureResolvingExport(exportId), exportId;
1438
+ }
1439
+ unexport(ids) {
1440
+ for (let id of ids)
1441
+ this.releaseExport(id, 1);
1442
+ }
1443
+ releaseExport(exportId, refcount) {
1444
+ let entry = this.exports[exportId];
1445
+ if (!entry)
1446
+ throw new Error(`no such export ID: ${exportId}`);
1447
+ if (entry.refcount < refcount)
1448
+ throw new Error(`refcount would go negative: ${entry.refcount} < ${refcount}`);
1449
+ entry.refcount -= refcount, entry.refcount === 0 && (delete this.exports[exportId], this.reverseExports.delete(entry.hook), entry.hook.dispose());
1450
+ }
1451
+ onSendError(error) {
1452
+ if (this.options.onSendError)
1453
+ return this.options.onSendError(error);
1454
+ }
1455
+ ensureResolvingExport(exportId) {
1456
+ let exp = this.exports[exportId];
1457
+ if (!exp)
1458
+ throw new Error(`no such export ID: ${exportId}`);
1459
+ if (!exp.pull) {
1460
+ let resolve = async () => {
1461
+ let hook = exp.hook;
1462
+ for (; ; ) {
1463
+ let payload = await hook.pull();
1464
+ if (payload.value instanceof RpcStub) {
1465
+ let { hook: inner, pathIfPromise } = unwrapStubAndPath(payload.value);
1466
+ if (pathIfPromise && pathIfPromise.length == 0 && this.getImport(hook) === void 0) {
1467
+ hook = inner;
1468
+ continue;
1469
+ }
1470
+ }
1471
+ return payload;
1472
+ }
1473
+ }, autoRelease = exp.autoRelease;
1474
+ ++this.pullCount, exp.pull = resolve().then(
1475
+ (payload) => {
1476
+ let value = Devaluator.devaluate(payload.value, void 0, this, payload);
1477
+ this.send(["resolve", exportId, value]), autoRelease && this.releaseExport(exportId, 1);
1478
+ },
1479
+ (error) => {
1480
+ this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]), autoRelease && this.releaseExport(exportId, 1);
1481
+ }
1482
+ ).catch(
1483
+ (error) => {
1484
+ try {
1485
+ this.send(["reject", exportId, Devaluator.devaluate(error, void 0, this)]), autoRelease && this.releaseExport(exportId, 1);
1486
+ } catch (error2) {
1487
+ this.abort(error2);
1488
+ }
1489
+ }
1490
+ ).finally(() => {
1491
+ --this.pullCount === 0 && this.onBatchDone && this.onBatchDone.resolve();
1492
+ });
1493
+ }
1494
+ }
1495
+ getImport(hook) {
1496
+ if (hook instanceof RpcImportHook && hook.entry && hook.entry.session === this)
1497
+ return hook.entry.importId;
1498
+ }
1499
+ importStub(idx) {
1500
+ if (this.abortReason) throw this.abortReason;
1501
+ let entry = this.imports[idx];
1502
+ return entry || (entry = new ImportTableEntry(this, idx, !1), this.imports[idx] = entry), new RpcImportHook(
1503
+ /*isPromise=*/
1504
+ !1,
1505
+ entry
1506
+ );
1507
+ }
1508
+ importPromise(idx) {
1509
+ if (this.abortReason) throw this.abortReason;
1510
+ if (this.imports[idx])
1511
+ return new ErrorStubHook(new Error(
1512
+ "Bug in RPC system: The peer sent a promise reusing an existing export ID."
1513
+ ));
1514
+ let entry = new ImportTableEntry(this, idx, !0);
1515
+ return this.imports[idx] = entry, new RpcImportHook(
1516
+ /*isPromise=*/
1517
+ !0,
1518
+ entry
1519
+ );
1520
+ }
1521
+ getExport(idx) {
1522
+ return this.exports[idx]?.hook;
1523
+ }
1524
+ getPipeReadable(exportId) {
1525
+ let entry = this.exports[exportId];
1526
+ if (!entry || !entry.pipeReadable)
1527
+ throw new Error(`Export ${exportId} is not a pipe or its readable end was already consumed.`);
1528
+ let readable = entry.pipeReadable;
1529
+ return entry.pipeReadable = void 0, readable;
1530
+ }
1531
+ createPipe(readable, readableHook) {
1532
+ if (this.abortReason) throw this.abortReason;
1533
+ this.send(["pipe"]);
1534
+ let importId = this.imports.length, entry = new ImportTableEntry(this, importId, !1);
1535
+ this.imports.push(entry);
1536
+ let hook = new RpcImportHook(
1537
+ /*isPromise=*/
1538
+ !1,
1539
+ entry
1540
+ ), writable = streamImpl.createWritableStreamFromHook(hook);
1541
+ return readable.pipeTo(writable).catch(() => {
1542
+ }).finally(() => readableHook.dispose()), importId;
1543
+ }
1544
+ // Serializes and sends a message. Returns the byte length of the serialized message.
1545
+ send(msg) {
1546
+ if (this.abortReason !== void 0)
1547
+ return 0;
1548
+ let msgText;
1549
+ try {
1550
+ msgText = JSON.stringify(msg);
1551
+ } catch (err) {
1552
+ try {
1553
+ this.abort(err);
1554
+ } catch {
1555
+ }
1556
+ throw err;
1557
+ }
1558
+ return this.transport.send(msgText).catch((err) => this.abort(err, !1)), msgText.length;
1559
+ }
1560
+ sendCall(id, path, args) {
1561
+ if (this.abortReason) throw this.abortReason;
1562
+ let value = ["pipeline", id, path];
1563
+ if (args) {
1564
+ let devalue = Devaluator.devaluate(args.value, void 0, this, args);
1565
+ value.push(devalue[0]);
1566
+ }
1567
+ this.send(["push", value]);
1568
+ let entry = new ImportTableEntry(this, this.imports.length, !1);
1569
+ return this.imports.push(entry), new RpcImportHook(
1570
+ /*isPromise=*/
1571
+ !0,
1572
+ entry
1573
+ );
1574
+ }
1575
+ sendStream(id, path, args) {
1576
+ if (this.abortReason) throw this.abortReason;
1577
+ let value = ["pipeline", id, path], devalue = Devaluator.devaluate(args.value, void 0, this, args);
1578
+ value.push(devalue[0]);
1579
+ let size = this.send(["stream", value]), importId = this.imports.length, entry = new ImportTableEntry(
1580
+ this,
1581
+ importId,
1582
+ /*pulling=*/
1583
+ !0
1584
+ );
1585
+ return entry.remoteRefcount = 0, entry.localRefcount = 1, this.imports.push(entry), { promise: entry.awaitResolution().then(
1586
+ (p) => {
1587
+ p.dispose(), delete this.imports[importId];
1588
+ },
1589
+ (err) => {
1590
+ throw delete this.imports[importId], err;
1591
+ }
1592
+ ), size };
1593
+ }
1594
+ sendMap(id, path, captures, instructions) {
1595
+ if (this.abortReason) {
1596
+ for (let cap of captures)
1597
+ cap.dispose();
1598
+ throw this.abortReason;
1599
+ }
1600
+ let devaluedCaptures = captures.map((hook) => {
1601
+ let importId = this.getImport(hook);
1602
+ return importId !== void 0 ? ["import", importId] : ["export", this.exportStub(hook)];
1603
+ }), value = ["remap", id, path, devaluedCaptures, instructions];
1604
+ this.send(["push", value]);
1605
+ let entry = new ImportTableEntry(this, this.imports.length, !1);
1606
+ return this.imports.push(entry), new RpcImportHook(
1607
+ /*isPromise=*/
1608
+ !0,
1609
+ entry
1610
+ );
1611
+ }
1612
+ sendPull(id) {
1613
+ if (this.abortReason) throw this.abortReason;
1614
+ this.send(["pull", id]);
1615
+ }
1616
+ sendRelease(id, remoteRefcount) {
1617
+ this.abortReason || (this.send(["release", id, remoteRefcount]), delete this.imports[id]);
1618
+ }
1619
+ abort(error, trySendAbortMessage = !0) {
1620
+ if (this.abortReason === void 0) {
1621
+ if (this.cancelReadLoop(error), trySendAbortMessage)
1622
+ try {
1623
+ this.transport.send(JSON.stringify(["abort", Devaluator.devaluate(error, void 0, this)])).catch((err) => {
1624
+ });
1625
+ } catch {
1626
+ }
1627
+ if (error === void 0 && (error = "undefined"), this.abortReason = error, this.onBatchDone && this.onBatchDone.reject(error), this.transport.abort)
1628
+ try {
1629
+ this.transport.abort(error);
1630
+ } catch (err) {
1631
+ Promise.resolve(err);
1632
+ }
1633
+ for (let i in this.onBrokenCallbacks)
1634
+ try {
1635
+ this.onBrokenCallbacks[i](error);
1636
+ } catch (err) {
1637
+ Promise.resolve(err);
1638
+ }
1639
+ for (let i in this.imports)
1640
+ this.imports[i].abort(error);
1641
+ for (let i in this.exports)
1642
+ this.exports[i].hook.dispose();
1643
+ }
1644
+ }
1645
+ async readLoop(abortPromise) {
1646
+ for (; !this.abortReason; ) {
1647
+ let msg = JSON.parse(await Promise.race([this.transport.receive(), abortPromise]));
1648
+ if (this.abortReason) break;
1649
+ if (msg instanceof Array)
1650
+ switch (msg[0]) {
1651
+ case "push":
1652
+ if (msg.length > 1) {
1653
+ let payload = new Evaluator(this).evaluate(msg[1]), hook = new PayloadStubHook(payload);
1654
+ hook.ignoreUnhandledRejections(), this.exports.push({ hook, refcount: 1 });
1655
+ continue;
1656
+ }
1657
+ break;
1658
+ case "stream": {
1659
+ if (msg.length > 1) {
1660
+ let payload = new Evaluator(this).evaluate(msg[1]), hook = new PayloadStubHook(payload);
1661
+ hook.ignoreUnhandledRejections();
1662
+ let exportId = this.exports.length;
1663
+ this.exports.push({ hook, refcount: 1, autoRelease: !0 }), this.ensureResolvingExport(exportId);
1664
+ continue;
1665
+ }
1666
+ break;
1667
+ }
1668
+ case "pipe": {
1669
+ let { readable, writable } = new TransformStream(), hook = streamImpl.createWritableStreamHook(writable);
1670
+ this.exports.push({ hook, refcount: 1, pipeReadable: readable });
1671
+ continue;
1672
+ }
1673
+ case "pull": {
1674
+ let exportId = msg[1];
1675
+ if (typeof exportId == "number") {
1676
+ this.ensureResolvingExport(exportId);
1677
+ continue;
1678
+ }
1679
+ break;
1680
+ }
1681
+ case "resolve":
1682
+ // ["resolve", ExportId, Expression]
1683
+ case "reject": {
1684
+ let importId = msg[1];
1685
+ if (typeof importId == "number" && msg.length > 2) {
1686
+ let imp = this.imports[importId];
1687
+ if (imp)
1688
+ if (msg[0] == "resolve")
1689
+ imp.resolve(new PayloadStubHook(new Evaluator(this).evaluate(msg[2])));
1690
+ else {
1691
+ let payload = new Evaluator(this).evaluate(msg[2]);
1692
+ payload.dispose(), imp.resolve(new ErrorStubHook(payload.value));
1693
+ }
1694
+ else
1695
+ msg[0] == "resolve" && new Evaluator(this).evaluate(msg[2]).dispose();
1696
+ continue;
1697
+ }
1698
+ break;
1699
+ }
1700
+ case "release": {
1701
+ let exportId = msg[1], refcount = msg[2];
1702
+ if (typeof exportId == "number" && typeof refcount == "number") {
1703
+ this.releaseExport(exportId, refcount);
1704
+ continue;
1705
+ }
1706
+ break;
1707
+ }
1708
+ case "abort": {
1709
+ let payload = new Evaluator(this).evaluate(msg[1]);
1710
+ payload.dispose(), this.abort(payload, !1);
1711
+ break;
1712
+ }
1713
+ }
1714
+ throw new Error(`bad RPC message: ${JSON.stringify(msg)}`);
1715
+ }
1716
+ }
1717
+ async drain() {
1718
+ if (this.abortReason)
1719
+ throw this.abortReason;
1720
+ if (this.pullCount > 0) {
1721
+ let { promise, resolve, reject } = Promise.withResolvers();
1722
+ this.onBatchDone = { resolve, reject }, await promise;
1723
+ }
1724
+ }
1725
+ getStats() {
1726
+ let result = { imports: 0, exports: 0 };
1727
+ for (let i in this.imports)
1728
+ ++result.imports;
1729
+ for (let i in this.exports)
1730
+ ++result.exports;
1731
+ return result;
1732
+ }
1733
+ }, RpcSession = class {
1734
+ #session;
1735
+ #mainStub;
1736
+ constructor(transport, localMain, options = {}) {
1737
+ let mainHook;
1738
+ localMain ? mainHook = new PayloadStubHook(RpcPayload.fromAppReturn(localMain)) : mainHook = new ErrorStubHook(new Error("This connection has no main object.")), this.#session = new RpcSessionImpl(transport, mainHook, options), this.#mainStub = new RpcStub(this.#session.getMainImport());
1739
+ }
1740
+ getRemoteMain() {
1741
+ return this.#mainStub;
1742
+ }
1743
+ getStats() {
1744
+ return this.#session.getStats();
1745
+ }
1746
+ drain() {
1747
+ return this.#session.drain();
1748
+ }
1749
+ };
1750
+ function newWebSocketRpcSession(webSocket, localMain, options) {
1751
+ typeof webSocket == "string" && (webSocket = new WebSocket(webSocket));
1752
+ let transport = new WebSocketTransport(webSocket);
1753
+ return new RpcSession(transport, localMain, options).getRemoteMain();
1754
+ }
1755
+ var WebSocketTransport = class {
1756
+ constructor(webSocket) {
1757
+ this.#webSocket = webSocket, webSocket.readyState === WebSocket.CONNECTING && (this.#sendQueue = [], webSocket.addEventListener("open", (event) => {
1758
+ try {
1759
+ for (let message of this.#sendQueue)
1760
+ webSocket.send(message);
1761
+ } catch (err) {
1762
+ this.#receivedError(err);
1763
+ }
1764
+ this.#sendQueue = void 0;
1765
+ })), webSocket.addEventListener("message", (event) => {
1766
+ this.#error || (typeof event.data == "string" ? this.#receiveResolver ? (this.#receiveResolver(event.data), this.#receiveResolver = void 0, this.#receiveRejecter = void 0) : this.#receiveQueue.push(event.data) : this.#receivedError(new TypeError("Received non-string message from WebSocket.")));
1767
+ }), webSocket.addEventListener("close", (event) => {
1768
+ this.#receivedError(new Error(`Peer closed WebSocket: ${event.code} ${event.reason}`));
1769
+ }), webSocket.addEventListener("error", (event) => {
1770
+ this.#receivedError(new Error("WebSocket connection failed."));
1771
+ });
1772
+ }
1773
+ #webSocket;
1774
+ #sendQueue;
1775
+ // only if not opened yet
1776
+ #receiveResolver;
1777
+ #receiveRejecter;
1778
+ #receiveQueue = [];
1779
+ #error;
1780
+ async send(message) {
1781
+ this.#sendQueue === void 0 ? this.#webSocket.send(message) : this.#sendQueue.push(message);
1782
+ }
1783
+ async receive() {
1784
+ if (this.#receiveQueue.length > 0)
1785
+ return this.#receiveQueue.shift();
1786
+ if (this.#error)
1787
+ throw this.#error;
1788
+ return new Promise((resolve, reject) => {
1789
+ this.#receiveResolver = resolve, this.#receiveRejecter = reject;
1790
+ });
1791
+ }
1792
+ abort(reason) {
1793
+ let message;
1794
+ reason instanceof Error ? message = reason.message : message = `${reason}`, this.#webSocket.close(3e3, message), this.#error || (this.#error = reason);
1795
+ }
1796
+ #receivedError(reason) {
1797
+ this.#error || (this.#error = reason, this.#receiveRejecter && (this.#receiveRejecter(reason), this.#receiveResolver = void 0, this.#receiveRejecter = void 0));
1798
+ }
1799
+ };
1800
+ var currentMapBuilder, MapBuilder = class {
1801
+ context;
1802
+ captureMap = /* @__PURE__ */ new Map();
1803
+ instructions = [];
1804
+ constructor(subject, path) {
1805
+ currentMapBuilder ? this.context = {
1806
+ parent: currentMapBuilder,
1807
+ captures: [],
1808
+ subject: currentMapBuilder.capture(subject),
1809
+ path
1810
+ } : this.context = {
1811
+ parent: void 0,
1812
+ captures: [],
1813
+ subject,
1814
+ path
1815
+ }, currentMapBuilder = this;
1816
+ }
1817
+ unregister() {
1818
+ currentMapBuilder = this.context.parent;
1819
+ }
1820
+ makeInput() {
1821
+ return new MapVariableHook(this, 0);
1822
+ }
1823
+ makeOutput(result) {
1824
+ let devalued;
1825
+ try {
1826
+ devalued = Devaluator.devaluate(result.value, void 0, this, result);
1827
+ } finally {
1828
+ result.dispose();
1829
+ }
1830
+ return this.instructions.push(devalued), this.context.parent ? (this.context.parent.instructions.push(
1831
+ [
1832
+ "remap",
1833
+ this.context.subject,
1834
+ this.context.path,
1835
+ this.context.captures.map((cap) => ["import", cap]),
1836
+ this.instructions
1837
+ ]
1838
+ ), new MapVariableHook(this.context.parent, this.context.parent.instructions.length)) : this.context.subject.map(this.context.path, this.context.captures, this.instructions);
1839
+ }
1840
+ pushCall(hook, path, params) {
1841
+ let devalued = Devaluator.devaluate(params.value, void 0, this, params);
1842
+ devalued = devalued[0];
1843
+ let subject = this.capture(hook.dup());
1844
+ return this.instructions.push(["pipeline", subject, path, devalued]), new MapVariableHook(this, this.instructions.length);
1845
+ }
1846
+ pushGet(hook, path) {
1847
+ let subject = this.capture(hook.dup());
1848
+ return this.instructions.push(["pipeline", subject, path]), new MapVariableHook(this, this.instructions.length);
1849
+ }
1850
+ capture(hook) {
1851
+ if (hook instanceof MapVariableHook && hook.mapper === this)
1852
+ return hook.idx;
1853
+ let result = this.captureMap.get(hook);
1854
+ if (result === void 0) {
1855
+ if (this.context.parent) {
1856
+ let parentIdx = this.context.parent.capture(hook);
1857
+ this.context.captures.push(parentIdx);
1858
+ } else
1859
+ this.context.captures.push(hook);
1860
+ result = -this.context.captures.length, this.captureMap.set(hook, result);
1861
+ }
1862
+ return result;
1863
+ }
1864
+ // ---------------------------------------------------------------------------
1865
+ // implements Exporter
1866
+ exportStub(hook) {
1867
+ throw new Error(
1868
+ "Can't construct an RpcTarget or RPC callback inside a mapper function. Try creating a new RpcStub outside the callback first, then using it inside the callback."
1869
+ );
1870
+ }
1871
+ exportPromise(hook) {
1872
+ return this.exportStub(hook);
1873
+ }
1874
+ getImport(hook) {
1875
+ return this.capture(hook);
1876
+ }
1877
+ unexport(ids) {
1878
+ }
1879
+ createPipe(readable) {
1880
+ throw new Error("Cannot send ReadableStream inside a mapper function.");
1881
+ }
1882
+ onSendError(error) {
1883
+ }
1884
+ };
1885
+ mapImpl.sendMap = (hook, path, func) => {
1886
+ let builder = new MapBuilder(hook, path), result;
1887
+ try {
1888
+ result = RpcPayload.fromAppReturn(withCallInterceptor(builder.pushCall.bind(builder), () => func(new RpcPromise(builder.makeInput(), []))));
1889
+ } finally {
1890
+ builder.unregister();
1891
+ }
1892
+ if (result instanceof Promise)
1893
+ throw result.catch((err) => {
1894
+ }), new Error("RPC map() callbacks cannot be async.");
1895
+ return new RpcPromise(builder.makeOutput(result), []);
1896
+ };
1897
+ function throwMapperBuilderUseError() {
1898
+ throw new Error(
1899
+ "Attempted to use an abstract placeholder from a mapper function. Please make sure your map function has no side effects."
1900
+ );
1901
+ }
1902
+ var MapVariableHook = class extends StubHook {
1903
+ constructor(mapper, idx) {
1904
+ super(), this.mapper = mapper, this.idx = idx;
1905
+ }
1906
+ // We don't have anything we actually need to dispose, so dup() can just return the same hook.
1907
+ dup() {
1908
+ return this;
1909
+ }
1910
+ dispose() {
1911
+ }
1912
+ get(path) {
1913
+ if (path.length == 0)
1914
+ return this;
1915
+ if (currentMapBuilder)
1916
+ return currentMapBuilder.pushGet(this, path);
1917
+ throwMapperBuilderUseError();
1918
+ }
1919
+ // Other methods should never be called.
1920
+ call(path, args) {
1921
+ throwMapperBuilderUseError();
1922
+ }
1923
+ map(path, captures, instructions) {
1924
+ throwMapperBuilderUseError();
1925
+ }
1926
+ pull() {
1927
+ throwMapperBuilderUseError();
1928
+ }
1929
+ ignoreUnhandledRejections() {
1930
+ }
1931
+ onBroken(callback) {
1932
+ throwMapperBuilderUseError();
1933
+ }
1934
+ }, MapApplicator = class {
1935
+ constructor(captures, input) {
1936
+ this.captures = captures, this.variables = [input];
1937
+ }
1938
+ variables;
1939
+ dispose() {
1940
+ for (let variable of this.variables)
1941
+ variable.dispose();
1942
+ }
1943
+ apply(instructions) {
1944
+ try {
1945
+ if (instructions.length < 1)
1946
+ throw new Error("Invalid empty mapper function.");
1947
+ for (let instruction of instructions.slice(0, -1)) {
1948
+ let payload = new Evaluator(this).evaluateCopy(instruction);
1949
+ if (payload.value instanceof RpcStub) {
1950
+ let hook = unwrapStubNoProperties(payload.value);
1951
+ if (hook) {
1952
+ this.variables.push(hook);
1953
+ continue;
1954
+ }
1955
+ }
1956
+ this.variables.push(new PayloadStubHook(payload));
1957
+ }
1958
+ return new Evaluator(this).evaluateCopy(instructions[instructions.length - 1]);
1959
+ } finally {
1960
+ for (let variable of this.variables)
1961
+ variable.dispose();
1962
+ }
1963
+ }
1964
+ importStub(idx) {
1965
+ throw new Error("A mapper function cannot refer to exports.");
1966
+ }
1967
+ importPromise(idx) {
1968
+ return this.importStub(idx);
1969
+ }
1970
+ getExport(idx) {
1971
+ return idx < 0 ? this.captures[-idx - 1] : this.variables[idx];
1972
+ }
1973
+ getPipeReadable(exportId) {
1974
+ throw new Error("A mapper function cannot use pipe readables.");
1975
+ }
1976
+ };
1977
+ function applyMapToElement(input, parent, owner, captures, instructions) {
1978
+ let inputHook = new PayloadStubHook(RpcPayload.deepCopyFrom(input, parent, owner)), mapper = new MapApplicator(captures, inputHook);
1979
+ try {
1980
+ return mapper.apply(instructions);
1981
+ } finally {
1982
+ mapper.dispose();
1983
+ }
1984
+ }
1985
+ mapImpl.applyMap = (input, parent, owner, captures, instructions) => {
1986
+ try {
1987
+ let result;
1988
+ if (input instanceof RpcPromise)
1989
+ throw new Error("applyMap() can't be called on RpcPromise");
1990
+ if (input instanceof Array) {
1991
+ let payloads = [];
1992
+ try {
1993
+ for (let elem of input)
1994
+ payloads.push(applyMapToElement(elem, input, owner, captures, instructions));
1995
+ } catch (err) {
1996
+ for (let payload of payloads)
1997
+ payload.dispose();
1998
+ throw err;
1999
+ }
2000
+ result = RpcPayload.fromArray(payloads);
2001
+ } else input == null ? result = RpcPayload.fromAppReturn(input) : result = applyMapToElement(input, parent, owner, captures, instructions);
2002
+ return new PayloadStubHook(result);
2003
+ } finally {
2004
+ for (let cap of captures)
2005
+ cap.dispose();
2006
+ }
2007
+ };
2008
+ var WritableStreamStubHook = class _WritableStreamStubHook extends StubHook {
2009
+ state;
2010
+ // undefined when disposed
2011
+ // Creates a new WritableStreamStubHook that is not duplicated from an existing hook.
2012
+ static create(stream) {
2013
+ let writer = stream.getWriter();
2014
+ return new _WritableStreamStubHook({ refcount: 1, writer, closed: !1 });
2015
+ }
2016
+ constructor(state, dupFrom) {
2017
+ super(), this.state = state, dupFrom && ++state.refcount;
2018
+ }
2019
+ getState() {
2020
+ if (this.state)
2021
+ return this.state;
2022
+ throw new Error("Attempted to use a WritableStreamStubHook after it was disposed.");
2023
+ }
2024
+ call(path, args) {
2025
+ try {
2026
+ let state = this.getState();
2027
+ if (path.length !== 1 || typeof path[0] != "string")
2028
+ throw new Error("WritableStream stub only supports direct method calls");
2029
+ let method = path[0];
2030
+ if (method !== "write" && method !== "close" && method !== "abort")
2031
+ throw args.dispose(), new Error(`Unknown WritableStream method: ${method}`);
2032
+ (method === "close" || method === "abort") && (state.closed = !0);
2033
+ let func = state.writer[method], promise = args.deliverCall(func, state.writer);
2034
+ return new PromiseStubHook(promise.then((payload) => new PayloadStubHook(payload)));
2035
+ } catch (err) {
2036
+ return new ErrorStubHook(err);
2037
+ }
2038
+ }
2039
+ map(path, captures, instructions) {
2040
+ for (let cap of captures)
2041
+ cap.dispose();
2042
+ return new ErrorStubHook(new Error("Cannot use map() on a WritableStream"));
2043
+ }
2044
+ get(path) {
2045
+ return new ErrorStubHook(new Error("Cannot access properties on a WritableStream stub"));
2046
+ }
2047
+ dup() {
2048
+ let state = this.getState();
2049
+ return new _WritableStreamStubHook(state, this);
2050
+ }
2051
+ pull() {
2052
+ return Promise.reject(new Error("Cannot pull a WritableStream stub"));
2053
+ }
2054
+ ignoreUnhandledRejections() {
2055
+ }
2056
+ dispose() {
2057
+ let state = this.state;
2058
+ this.state = void 0, state && --state.refcount === 0 && (state.closed || state.writer.abort(new Error("WritableStream RPC stub was disposed without calling close()")).catch(() => {
2059
+ }), state.writer.releaseLock());
2060
+ }
2061
+ onBroken(callback) {
2062
+ }
2063
+ }, INITIAL_WINDOW = 256 * 1024, MAX_WINDOW = 1024 * 1024 * 1024, MIN_WINDOW = 64 * 1024, STARTUP_GROWTH_FACTOR = 2, STEADY_GROWTH_FACTOR = 1.25, DECAY_FACTOR = 0.9, STARTUP_EXIT_ROUNDS = 3, FlowController = class {
2064
+ constructor(now) {
2065
+ this.now = now;
2066
+ }
2067
+ // The current window size in bytes. The sender blocks when bytesInFlight >= window.
2068
+ window = INITIAL_WINDOW;
2069
+ // Total bytes currently in flight (sent but not yet acked).
2070
+ bytesInFlight = 0;
2071
+ // Whether we're still in the startup phase.
2072
+ inStartupPhase = !0;
2073
+ // ----- BDP estimation state (private) -----
2074
+ // Total bytes acked so far.
2075
+ delivered = 0;
2076
+ // Time of most recent ack.
2077
+ deliveredTime = 0;
2078
+ // Time when the very first ack was received.
2079
+ firstAckTime = 0;
2080
+ firstAckDelivered = 0;
2081
+ // Global minimum RTT observed (milliseconds).
2082
+ minRtt = 1 / 0;
2083
+ // For startup exit: count of consecutive RTT rounds where the window didn't meaningfully grow.
2084
+ roundsWithoutIncrease = 0;
2085
+ // Window size at the start of the current round, for startup exit detection.
2086
+ lastRoundWindow = 0;
2087
+ // Time when the current round started.
2088
+ roundStartTime = 0;
2089
+ // Called when a write of `size` bytes is about to be sent. Returns a token that must be
2090
+ // passed to onAck() when the ack arrives, and whether the sender should block (window full).
2091
+ onSend(size) {
2092
+ this.bytesInFlight += size;
2093
+ let token = {
2094
+ sentTime: this.now(),
2095
+ size,
2096
+ deliveredAtSend: this.delivered,
2097
+ deliveredTimeAtSend: this.deliveredTime,
2098
+ windowAtSend: this.window,
2099
+ windowFullAtSend: this.bytesInFlight >= this.window
2100
+ };
2101
+ return { token, shouldBlock: token.windowFullAtSend };
2102
+ }
2103
+ // Called when a previously-sent write fails. Restores bytesInFlight without updating
2104
+ // any BDP estimates.
2105
+ onError(token) {
2106
+ this.bytesInFlight -= token.size;
2107
+ }
2108
+ // Called when an ack is received for a previously-sent write. Updates BDP estimates and
2109
+ // the window. Returns whether a blocked sender should now unblock.
2110
+ onAck(token) {
2111
+ let ackTime = this.now();
2112
+ this.delivered += token.size, this.deliveredTime = ackTime, this.bytesInFlight -= token.size;
2113
+ let rtt = ackTime - token.sentTime;
2114
+ if (this.minRtt = Math.min(this.minRtt, rtt), this.firstAckTime === 0)
2115
+ this.firstAckTime = ackTime, this.firstAckDelivered = this.delivered;
2116
+ else {
2117
+ let baseTime, baseDelivered;
2118
+ token.deliveredTimeAtSend === 0 ? (baseTime = this.firstAckTime, baseDelivered = this.firstAckDelivered) : (baseTime = token.deliveredTimeAtSend, baseDelivered = token.deliveredAtSend);
2119
+ let interval = ackTime - baseTime, bandwidth = (this.delivered - baseDelivered) / interval, growthFactor = this.inStartupPhase ? STARTUP_GROWTH_FACTOR : STEADY_GROWTH_FACTOR, newWindow = bandwidth * this.minRtt * growthFactor;
2120
+ newWindow = Math.min(newWindow, token.windowAtSend * growthFactor), token.windowFullAtSend ? newWindow = Math.max(newWindow, token.windowAtSend * DECAY_FACTOR) : newWindow = Math.max(newWindow, this.window), this.window = Math.max(Math.min(newWindow, MAX_WINDOW), MIN_WINDOW), this.inStartupPhase && token.sentTime >= this.roundStartTime && (this.window > this.lastRoundWindow * STEADY_GROWTH_FACTOR ? this.roundsWithoutIncrease = 0 : ++this.roundsWithoutIncrease >= STARTUP_EXIT_ROUNDS && (this.inStartupPhase = !1), this.roundStartTime = ackTime, this.lastRoundWindow = this.window);
2121
+ }
2122
+ return this.bytesInFlight < this.window;
2123
+ }
2124
+ };
2125
+ function createWritableStreamFromHook(hook) {
2126
+ let pendingError, hookDisposed = !1, fc = new FlowController(() => performance.now()), windowResolve, windowReject, disposeHook = () => {
2127
+ hookDisposed || (hookDisposed = !0, hook.dispose());
2128
+ };
2129
+ return new WritableStream({
2130
+ write(chunk, controller) {
2131
+ if (pendingError !== void 0)
2132
+ throw pendingError;
2133
+ let payload = RpcPayload.fromAppParams([chunk]), { promise, size } = hook.stream(["write"], payload);
2134
+ if (size === void 0)
2135
+ return promise.catch((err) => {
2136
+ throw pendingError === void 0 && (pendingError = err), err;
2137
+ });
2138
+ {
2139
+ let { token, shouldBlock } = fc.onSend(size);
2140
+ if (promise.then(() => {
2141
+ fc.onAck(token) && windowResolve && (windowResolve(), windowResolve = void 0, windowReject = void 0);
2142
+ }, (err) => {
2143
+ fc.onError(token), pendingError === void 0 && (pendingError = err, controller.error(err), disposeHook()), windowReject && (windowReject(err), windowResolve = void 0, windowReject = void 0);
2144
+ }), shouldBlock)
2145
+ return new Promise((resolve, reject) => {
2146
+ windowResolve = resolve, windowReject = reject;
2147
+ });
2148
+ }
2149
+ },
2150
+ async close() {
2151
+ if (pendingError !== void 0)
2152
+ throw disposeHook(), pendingError;
2153
+ let { promise } = hook.stream(["close"], RpcPayload.fromAppParams([]));
2154
+ try {
2155
+ await promise;
2156
+ } catch (err) {
2157
+ throw pendingError ?? err;
2158
+ } finally {
2159
+ disposeHook();
2160
+ }
2161
+ },
2162
+ abort(reason) {
2163
+ if (pendingError !== void 0)
2164
+ return;
2165
+ pendingError = reason ?? new Error("WritableStream was aborted"), windowReject && (windowReject(pendingError), windowResolve = void 0, windowReject = void 0);
2166
+ let { promise } = hook.stream(["abort"], RpcPayload.fromAppParams([reason]));
2167
+ promise.then(() => disposeHook(), () => disposeHook());
2168
+ }
2169
+ });
2170
+ }
2171
+ var ReadableStreamStubHook = class _ReadableStreamStubHook extends StubHook {
2172
+ state;
2173
+ // undefined when disposed
2174
+ // Creates a new ReadableStreamStubHook.
2175
+ static create(stream) {
2176
+ return new _ReadableStreamStubHook({ refcount: 1, stream, canceled: !1 });
2177
+ }
2178
+ constructor(state, dupFrom) {
2179
+ super(), this.state = state, dupFrom && ++state.refcount;
2180
+ }
2181
+ call(path, args) {
2182
+ return args.dispose(), new ErrorStubHook(new Error("Cannot call methods on a ReadableStream stub"));
2183
+ }
2184
+ map(path, captures, instructions) {
2185
+ for (let cap of captures)
2186
+ cap.dispose();
2187
+ return new ErrorStubHook(new Error("Cannot use map() on a ReadableStream"));
2188
+ }
2189
+ get(path) {
2190
+ return new ErrorStubHook(new Error("Cannot access properties on a ReadableStream stub"));
2191
+ }
2192
+ dup() {
2193
+ let state = this.state;
2194
+ if (!state)
2195
+ throw new Error("Attempted to dup a ReadableStreamStubHook after it was disposed.");
2196
+ return new _ReadableStreamStubHook(state, this);
2197
+ }
2198
+ pull() {
2199
+ return Promise.reject(new Error("Cannot pull a ReadableStream stub"));
2200
+ }
2201
+ ignoreUnhandledRejections() {
2202
+ }
2203
+ dispose() {
2204
+ let state = this.state;
2205
+ this.state = void 0, state && --state.refcount === 0 && (state.canceled || (state.canceled = !0, state.stream.locked || state.stream.cancel(
2206
+ new Error("ReadableStream RPC stub was disposed without being consumed")
2207
+ ).catch(() => {
2208
+ })));
2209
+ }
2210
+ onBroken(callback) {
2211
+ }
2212
+ };
2213
+ streamImpl.createWritableStreamHook = WritableStreamStubHook.create;
2214
+ streamImpl.createWritableStreamFromHook = createWritableStreamFromHook;
2215
+ streamImpl.createReadableStreamHook = ReadableStreamStubHook.create;
2216
+ var newWebSocketRpcSession2 = newWebSocketRpcSession;
2217
+
2218
+ // src/workers/shared/remote-bindings-utils.ts
2219
+ function throwRemoteRequired(bindingName) {
2220
+ throw new Error(`Binding ${bindingName} needs to be run remotely`);
2221
+ }
2222
+ function makeFetch(remoteProxyConnectionString, bindingName, extraHeaders) {
2223
+ return (input, init) => {
2224
+ remoteProxyConnectionString || throwRemoteRequired(bindingName);
2225
+ let request = new Request(input, init), proxiedHeaders = new Headers(extraHeaders);
2226
+ for (let [name, value] of request.headers)
2227
+ name === "upgrade" ? proxiedHeaders.set(name, value) : proxiedHeaders.set(`MF-Header-${name}`, value);
2228
+ proxiedHeaders.set("MF-URL", request.url), proxiedHeaders.set("MF-Binding", bindingName);
2229
+ let req = new Request(request, {
2230
+ headers: proxiedHeaders
2231
+ });
2232
+ return fetch(remoteProxyConnectionString, req);
2233
+ };
2234
+ }
2235
+ function makeRemoteProxyStub(remoteProxyConnectionString, bindingName, metadata) {
2236
+ let url = new URL(remoteProxyConnectionString);
2237
+ if (url.protocol = url.protocol === "https:" ? "wss:" : "ws:", url.searchParams.set("MF-Binding", bindingName), metadata)
2238
+ for (let [key, value] of Object.entries(metadata))
2239
+ value !== void 0 && url.searchParams.set(key, value);
2240
+ let stub = newWebSocketRpcSession2(url.href), headers = metadata ? new Headers(
2241
+ Object.entries(metadata).filter(
2242
+ (entry) => entry[1] !== void 0
2243
+ )
2244
+ ) : void 0;
2245
+ return new Proxy(stub, {
2246
+ get(_, p) {
2247
+ return p === "fetch" ? makeFetch(remoteProxyConnectionString, bindingName, headers) : Reflect.get(stub, p);
2248
+ }
2249
+ });
2250
+ }
2251
+
2252
+ // src/workers/shared/remote-proxy-client.worker.ts
2253
+ var Client = class extends WorkerEntrypoint {
2254
+ fetch(request) {
2255
+ return makeFetch(
2256
+ this.env.remoteProxyConnectionString,
2257
+ this.env.binding
2258
+ )(request);
2259
+ }
2260
+ constructor(ctx, env) {
2261
+ super(ctx, env);
2262
+ let stub = env.remoteProxyConnectionString ? makeRemoteProxyStub(env.remoteProxyConnectionString, env.binding) : void 0;
2263
+ return new Proxy(this, {
2264
+ get: (target, prop) => Reflect.has(target, prop) ? Reflect.get(target, prop) : (stub || throwRemoteRequired(env.binding), Reflect.get(stub, prop))
2265
+ });
2266
+ }
2267
+ };
2268
+ export {
2269
+ Client as default
2270
+ };
2271
+ //# sourceMappingURL=remote-proxy-client.worker.js.map