osra 0.2.10 → 0.2.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/build/index.d.ts +25 -6
- package/build/index.js +67 -66
- package/build/index.js.map +1 -1
- package/package.json +1 -1
package/build/index.d.ts
CHANGED
|
@@ -18,6 +18,10 @@ declare namespace arrayBuffer {
|
|
|
18
18
|
}
|
|
19
19
|
}
|
|
20
20
|
|
|
21
|
+
export declare type AsCapable<T> = DeepReplaceAsync<T, never, never>;
|
|
22
|
+
|
|
23
|
+
declare const BadValueType: unique symbol;
|
|
24
|
+
|
|
21
25
|
export declare type BidirectionalConnectionMessage = {
|
|
22
26
|
type: 'init';
|
|
23
27
|
remoteUuid: Uuid;
|
|
@@ -157,13 +161,14 @@ export declare type Capable<TModules extends readonly RevivableModule[] = Defaul
|
|
|
157
161
|
[key: string]: Capable;
|
|
158
162
|
} | Array<Capable> | Map<Capable, Capable> | Set<Capable>;
|
|
159
163
|
|
|
160
|
-
declare const CapableError: unique symbol;
|
|
161
|
-
|
|
162
164
|
declare type CapableFunction<T> = T extends (...args: infer P) => infer R ? P extends Capable[] ? R extends Capable ? T : never : never : never;
|
|
163
165
|
|
|
164
|
-
declare type CapablePromise<T> = T extends Capable ?
|
|
165
|
-
[
|
|
166
|
-
|
|
166
|
+
declare type CapablePromise<T> = T extends Promise<infer U> ? U extends Capable ? T : {
|
|
167
|
+
[ErrorMessage]: 'Value type must extend a Promise that resolves to a Capable';
|
|
168
|
+
[BadValueType]: U;
|
|
169
|
+
} : {
|
|
170
|
+
[ErrorMessage]: 'Value type must extend a Promise that resolves to a Capable';
|
|
171
|
+
[BadValueType]: T;
|
|
167
172
|
};
|
|
168
173
|
|
|
169
174
|
export declare type ConnectionMessage = BidirectionalConnectionMessage | UnidirectionalConnectionMessage;
|
|
@@ -204,6 +209,18 @@ declare namespace date {
|
|
|
204
209
|
}
|
|
205
210
|
}
|
|
206
211
|
|
|
212
|
+
export declare type DeepReplace<T, From, To> = T extends From ? DeepReplace<To, From, To> : T extends (...args: infer A) => infer R ? (...args: {
|
|
213
|
+
[K in keyof A]: DeepReplace<A[K], From, To>;
|
|
214
|
+
}) => DeepReplace<R, From, To> : T extends Array<infer U> ? Array<DeepReplace<U, From, To>> : T extends object ? {
|
|
215
|
+
[K in keyof T]: DeepReplace<T[K], From, To>;
|
|
216
|
+
} : T;
|
|
217
|
+
|
|
218
|
+
export declare type DeepReplaceAsync<T, From, To> = T extends From ? DeepReplaceAsync<To, From, To> : T extends (...args: infer A) => infer R ? (...args: {
|
|
219
|
+
[K in keyof A]: DeepReplaceAsync<A[K], From, To>;
|
|
220
|
+
}) => Promise<Awaited<DeepReplaceAsync<R, From, To>>> : T extends Array<infer U> ? Array<DeepReplaceAsync<U, From, To>> : T extends object ? {
|
|
221
|
+
[K in keyof T]: DeepReplaceAsync<T[K], From, To>;
|
|
222
|
+
} : T;
|
|
223
|
+
|
|
207
224
|
declare type DeepReplaceWithBox<T, M> = [
|
|
208
225
|
FindMatchingBox<T, M>
|
|
209
226
|
] extends [never] ? (T extends Array<infer U> ? Array<DeepReplaceWithBox<U, M>> : T extends object ? {
|
|
@@ -239,6 +256,8 @@ declare namespace error {
|
|
|
239
256
|
}
|
|
240
257
|
}
|
|
241
258
|
|
|
259
|
+
declare const ErrorMessage: unique symbol;
|
|
260
|
+
|
|
242
261
|
/**
|
|
243
262
|
* Protocol mode:
|
|
244
263
|
* - Bidirectional mode
|
|
@@ -260,7 +279,7 @@ export declare const expose: <T extends Capable>(value: Capable, { transport: _t
|
|
|
260
279
|
logger?: {};
|
|
261
280
|
}) => Promise<T>;
|
|
262
281
|
|
|
263
|
-
declare type ExtractCapable<T> = T extends Capable ?
|
|
282
|
+
declare type ExtractCapable<T> = T extends Promise<infer U> ? U extends Capable ? U : never : never;
|
|
264
283
|
|
|
265
284
|
declare type ExtractStructurableTransferable<T> = T extends StructurableTransferable ? T : never;
|
|
266
285
|
|
package/build/index.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
const C = "__OSRA_KEY__", le = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", m = {
|
|
2
2
|
[M]: "revivable",
|
|
3
3
|
type: ""
|
|
4
|
-
},
|
|
4
|
+
}, v = (e, t) => e && typeof e == "object" && M in e && e[M] === "revivable", pe = () => {
|
|
5
5
|
const e = /* @__PURE__ */ new Map(), t = {
|
|
6
6
|
getUniqueUuid: () => {
|
|
7
7
|
let r = globalThis.crypto.randomUUID();
|
|
@@ -33,14 +33,14 @@ const C = "__OSRA_KEY__", le = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", m = {
|
|
|
33
33
|
}
|
|
34
34
|
};
|
|
35
35
|
return t;
|
|
36
|
-
},
|
|
36
|
+
}, K = (e, t) => ue(e) && e[C] === t, ge = ({ listener: e, transport: t, remoteName: r, key: n = C, unregisterSignal: a }) => {
|
|
37
37
|
const s = (o) => {
|
|
38
38
|
if (typeof o == "function")
|
|
39
39
|
o(e);
|
|
40
40
|
else if (O(o) || R(o) || $(o)) {
|
|
41
41
|
const i = (c, y) => {
|
|
42
42
|
const l = (p, d) => {
|
|
43
|
-
|
|
43
|
+
K(p, n) && (r && p.name !== r || e(p, { port: y, sender: d }));
|
|
44
44
|
};
|
|
45
45
|
c.addListener(l), a && a.addEventListener(
|
|
46
46
|
"abort",
|
|
@@ -58,7 +58,7 @@ const C = "__OSRA_KEY__", le = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", m = {
|
|
|
58
58
|
} else $(o) ? i(o) : i(o.onMessage);
|
|
59
59
|
} else {
|
|
60
60
|
const i = (c) => {
|
|
61
|
-
|
|
61
|
+
K(c.data, n) && (r && c.data.name !== r || e(c.data, { receiveTransport: o, source: c.source }));
|
|
62
62
|
};
|
|
63
63
|
o.addEventListener("message", i), a && a.addEventListener(
|
|
64
64
|
"abort",
|
|
@@ -74,7 +74,7 @@ const C = "__OSRA_KEY__", le = "__OSRA_DEFAULT_KEY__", M = "__OSRA_BOX__", m = {
|
|
|
74
74
|
J(e) ? a(e.emit) : a(e);
|
|
75
75
|
};
|
|
76
76
|
new Int8Array(), new Uint8Array(), new Uint8ClampedArray(), new Int16Array(), new Uint16Array(), new Int32Array(), new Uint32Array(), new Float16Array(), new Float32Array(), new Float64Array(), new BigInt64Array(), new BigUint64Array();
|
|
77
|
-
const k = (e) => e instanceof WebSocket,
|
|
77
|
+
const k = (e) => e instanceof WebSocket, x = (e) => globalThis.ServiceWorkerContainer && e instanceof ServiceWorkerContainer, Y = (e) => globalThis.Worker && e instanceof Worker, G = (e) => globalThis.DedicatedWorkerGlobalScope && e instanceof DedicatedWorkerGlobalScope, D = (e) => globalThis.SharedWorker && e instanceof SharedWorker, H = (e) => e instanceof MessagePort, ue = (e) => !!(e && typeof e == "object" && e[C]), me = (e) => !!(globalThis.SharedArrayBuffer && e instanceof globalThis.SharedArrayBuffer), Ae = (e) => globalThis.ArrayBuffer && e instanceof globalThis.ArrayBuffer || globalThis.MessagePort && e instanceof globalThis.MessagePort || globalThis.ReadableStream && e instanceof globalThis.ReadableStream || globalThis.WritableStream && e instanceof globalThis.WritableStream || globalThis.TransformStream && e instanceof globalThis.TransformStream ? !0 : !!(globalThis.ImageBitmap && e instanceof globalThis.ImageBitmap), O = (e, t = !1) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && "name" in e && "disconnect" in e && "postMessage" in e && (!t || "sender" in e && "onMessage" in e && "onDisconnect" in e)), R = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && e.addListener && e.hasListener && e.removeListener), $ = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && e.addListener && e.hasListener && e.removeListener), z = (e) => {
|
|
78
78
|
if (!e || typeof e != "object") return !1;
|
|
79
79
|
try {
|
|
80
80
|
return e.window === e;
|
|
@@ -86,10 +86,10 @@ const k = (e) => e instanceof WebSocket, Y = (e) => globalThis.ServiceWorkerCont
|
|
|
86
86
|
return !1;
|
|
87
87
|
}
|
|
88
88
|
}
|
|
89
|
-
}, X = (e) => k(e) || O(e), Q = (e) => k(e) || O(e) || R(e) || $(e), S = (e) => "isJson" in e && e.isJson === !0 || X(e) || Q(e), _ = (e) => z(e) || X(e) ||
|
|
89
|
+
}, X = (e) => k(e) || O(e), Q = (e) => k(e) || O(e) || R(e) || $(e), S = (e) => "isJson" in e && e.isJson === !0 || X(e) || Q(e), _ = (e) => z(e) || X(e) || x(e) || Y(e) || G(e) || D(e) || H(e) || Z(e), W = (e) => z(e) || Q(e) || x(e) || Y(e) || G(e) || D(e) || H(e) || N(e), Z = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && "emit" in e && (_(e.emit) || typeof e.emit == "function")), N = (e) => !!(e && typeof e == "object" && !(globalThis.Window && e instanceof globalThis.Window) && "receive" in e && (W(e.receive) || typeof e.receive == "function")), J = (e) => Z(e) || N(e), w = (e) => {
|
|
90
90
|
const t = [], r = (n) => me(n) ? void 0 : Ae(n) ? t.push(n) : Array.isArray(n) ? n.map(r) : n && typeof n == "object" ? Object.values(n).map(r) : void 0;
|
|
91
91
|
return r(e), t;
|
|
92
|
-
},
|
|
92
|
+
}, E = (e, t = !1) => {
|
|
93
93
|
const { port1: r, port2: n } = new MessageChannel(), a = new Promise(
|
|
94
94
|
(s) => r.addEventListener(
|
|
95
95
|
"message",
|
|
@@ -99,20 +99,20 @@ const k = (e) => e instanceof WebSocket, Y = (e) => globalThis.ServiceWorkerCont
|
|
|
99
99
|
return r.start(), n.postMessage(e, t ? w(e) : []), a;
|
|
100
100
|
}, he = async () => {
|
|
101
101
|
const { port1: e } = new MessageChannel();
|
|
102
|
-
return await
|
|
102
|
+
return await E(e, !0) instanceof MessagePort;
|
|
103
103
|
}, we = async () => {
|
|
104
104
|
const e = new ArrayBuffer(1);
|
|
105
|
-
return await
|
|
105
|
+
return await E(e) instanceof ArrayBuffer;
|
|
106
106
|
}, Ue = async () => {
|
|
107
107
|
const e = new ArrayBuffer(1);
|
|
108
|
-
return await
|
|
108
|
+
return await E(e, !0) instanceof ArrayBuffer;
|
|
109
109
|
}, Te = async () => {
|
|
110
110
|
const e = new ReadableStream({
|
|
111
111
|
start(r) {
|
|
112
112
|
r.enqueue(new Uint8Array(1)), r.close();
|
|
113
113
|
}
|
|
114
114
|
});
|
|
115
|
-
return await
|
|
115
|
+
return await E(e, !0) instanceof ReadableStream;
|
|
116
116
|
}, Me = async () => {
|
|
117
117
|
const [
|
|
118
118
|
e,
|
|
@@ -146,11 +146,11 @@ const k = (e) => e instanceof WebSocket, Y = (e) => globalThis.ServiceWorkerCont
|
|
|
146
146
|
...m,
|
|
147
147
|
type: te,
|
|
148
148
|
ISOString: e.toISOString()
|
|
149
|
-
}),
|
|
149
|
+
}), Ee = (e, t) => new Date(e.ISOString), Ie = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
150
150
|
__proto__: null,
|
|
151
151
|
box: Se,
|
|
152
152
|
isType: Oe,
|
|
153
|
-
revive:
|
|
153
|
+
revive: Ee,
|
|
154
154
|
type: te
|
|
155
155
|
}, Symbol.toStringTag, { value: "Module" })), re = "headers", Le = (e) => e instanceof Headers, je = (e, t) => ({
|
|
156
156
|
...m,
|
|
@@ -204,7 +204,7 @@ const oe = (e) => {
|
|
|
204
204
|
}), qe = (e, t) => {
|
|
205
205
|
const r = ae(e.typedArrayType), n = "arrayBuffer" in e ? e.arrayBuffer : Uint8Array.fromBase64(e.base64Buffer).buffer;
|
|
206
206
|
return new r(n);
|
|
207
|
-
},
|
|
207
|
+
}, Ke = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
208
208
|
__proto__: null,
|
|
209
209
|
box: Ve,
|
|
210
210
|
isType: Je,
|
|
@@ -218,7 +218,7 @@ const oe = (e) => {
|
|
|
218
218
|
remoteUuid: e.remoteUuid,
|
|
219
219
|
portId: e.portId
|
|
220
220
|
}), e.cleanup();
|
|
221
|
-
}), F = "messagePort",
|
|
221
|
+
}), F = "messagePort", ve = (e) => e instanceof MessagePort, ie = (e) => e !== null && typeof e == "object" && M in e && e[M] === "revivable", I = (e, t) => {
|
|
222
222
|
if (S(t.transport)) {
|
|
223
223
|
let n = function({ data: y }) {
|
|
224
224
|
t.sendMessage({
|
|
@@ -302,13 +302,14 @@ const oe = (e) => {
|
|
|
302
302
|
}, a), s.addEventListener("message", r), s.start(), t.eventTarget.addEventListener("message", y), i.addEventListener("message", l), i.start(), a;
|
|
303
303
|
}
|
|
304
304
|
return e.port;
|
|
305
|
-
},
|
|
305
|
+
}, xe = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
306
306
|
__proto__: null,
|
|
307
|
-
box:
|
|
308
|
-
isType:
|
|
307
|
+
box: I,
|
|
308
|
+
isType: ve,
|
|
309
309
|
revive: L,
|
|
310
310
|
type: F
|
|
311
|
-
}, Symbol.toStringTag, { value: "Module" })), ce = "promise",
|
|
311
|
+
}, Symbol.toStringTag, { value: "Module" })), ce = "promise", Ye = (e) => e instanceof Promise, Ge = (e) => e instanceof Promise, He = (e, t) => {
|
|
312
|
+
if (!Ye(e)) throw new TypeError("Expected Promise");
|
|
312
313
|
const r = e, { port1: n, port2: a } = new MessageChannel();
|
|
313
314
|
t.messagePorts.add(a);
|
|
314
315
|
const s = (o) => {
|
|
@@ -318,9 +319,9 @@ const oe = (e) => {
|
|
|
318
319
|
return r.then((o) => s({ type: "resolve", data: o })).catch((o) => s({ type: "reject", error: o?.stack ?? String(o) })), {
|
|
319
320
|
...m,
|
|
320
321
|
type: ce,
|
|
321
|
-
port:
|
|
322
|
+
port: I(a, t)
|
|
322
323
|
};
|
|
323
|
-
},
|
|
324
|
+
}, Xe = (e, t) => {
|
|
324
325
|
const r = L(e.port, t);
|
|
325
326
|
return t.messagePorts.add(r), new Promise((n, a) => {
|
|
326
327
|
r.addEventListener("message", (s) => {
|
|
@@ -328,13 +329,13 @@ const oe = (e) => {
|
|
|
328
329
|
i.type === "resolve" ? n(i.data) : a(i.error), t.messagePorts.delete(r), r.close();
|
|
329
330
|
}, { once: !0 }), r.start();
|
|
330
331
|
});
|
|
331
|
-
},
|
|
332
|
+
}, Qe = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
332
333
|
__proto__: null,
|
|
333
|
-
box:
|
|
334
|
-
isType:
|
|
335
|
-
revive:
|
|
334
|
+
box: He,
|
|
335
|
+
isType: Ge,
|
|
336
|
+
revive: Xe,
|
|
336
337
|
type: ce
|
|
337
|
-
}, Symbol.toStringTag, { value: "Module" })), ye = "function",
|
|
338
|
+
}, Symbol.toStringTag, { value: "Module" })), ye = "function", Ze = new FinalizationRegistry((e) => {
|
|
338
339
|
try {
|
|
339
340
|
e.port.postMessage({ __osra_close__: !0 });
|
|
340
341
|
} catch {
|
|
@@ -343,7 +344,7 @@ const oe = (e) => {
|
|
|
343
344
|
e.port.close();
|
|
344
345
|
} catch {
|
|
345
346
|
}
|
|
346
|
-
}),
|
|
347
|
+
}), Ne = (e) => typeof e == "function", et = (e, t) => {
|
|
347
348
|
const { port1: r, port2: n } = new MessageChannel();
|
|
348
349
|
t.messagePorts.add(n);
|
|
349
350
|
const a = () => {
|
|
@@ -360,9 +361,9 @@ const oe = (e) => {
|
|
|
360
361
|
...m,
|
|
361
362
|
type: ye,
|
|
362
363
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
363
|
-
port:
|
|
364
|
+
port: I(n, t)
|
|
364
365
|
};
|
|
365
|
-
},
|
|
366
|
+
}, tt = (e, t) => {
|
|
366
367
|
const r = L(e.port, t), n = (...a) => new Promise((s, o) => {
|
|
367
368
|
const { port1: i, port2: c } = new MessageChannel();
|
|
368
369
|
t.messagePorts.add(c);
|
|
@@ -373,14 +374,14 @@ const oe = (e) => {
|
|
|
373
374
|
});
|
|
374
375
|
}, { once: !0 }), i.start();
|
|
375
376
|
});
|
|
376
|
-
return
|
|
377
|
-
},
|
|
377
|
+
return Ze.register(n, { port: r }, n), n;
|
|
378
|
+
}, rt = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
378
379
|
__proto__: null,
|
|
379
|
-
box:
|
|
380
|
-
isType:
|
|
381
|
-
revive:
|
|
380
|
+
box: et,
|
|
381
|
+
isType: Ne,
|
|
382
|
+
revive: tt,
|
|
382
383
|
type: ye
|
|
383
|
-
}, Symbol.toStringTag, { value: "Module" })), de = "readableStream",
|
|
384
|
+
}, Symbol.toStringTag, { value: "Module" })), de = "readableStream", nt = (e) => e instanceof ReadableStream, st = (e, t) => {
|
|
384
385
|
const { port1: r, port2: n } = new MessageChannel();
|
|
385
386
|
t.messagePorts.add(n);
|
|
386
387
|
const a = e.getReader();
|
|
@@ -394,9 +395,9 @@ const oe = (e) => {
|
|
|
394
395
|
}), r.start(), {
|
|
395
396
|
...m,
|
|
396
397
|
type: de,
|
|
397
|
-
port:
|
|
398
|
+
port: I(n, t)
|
|
398
399
|
};
|
|
399
|
-
},
|
|
400
|
+
}, ot = (e, t) => {
|
|
400
401
|
const r = L(e.port, t);
|
|
401
402
|
return t.messagePorts.add(r), r.start(), new ReadableStream({
|
|
402
403
|
start(n) {
|
|
@@ -414,26 +415,26 @@ const oe = (e) => {
|
|
|
414
415
|
r.postMessage(b({ type: "cancel" }, t)), r.close();
|
|
415
416
|
}
|
|
416
417
|
});
|
|
417
|
-
},
|
|
418
|
+
}, at = /* @__PURE__ */ Object.freeze(/* @__PURE__ */ Object.defineProperty({
|
|
418
419
|
__proto__: null,
|
|
419
|
-
box:
|
|
420
|
-
isType:
|
|
421
|
-
revive:
|
|
420
|
+
box: st,
|
|
421
|
+
isType: nt,
|
|
422
|
+
revive: ot,
|
|
422
423
|
type: de
|
|
423
|
-
}, Symbol.toStringTag, { value: "Module" })),
|
|
424
|
+
}, Symbol.toStringTag, { value: "Module" })), it = [
|
|
424
425
|
Ce,
|
|
425
|
-
|
|
426
|
+
Ie,
|
|
426
427
|
$e,
|
|
427
428
|
De,
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
],
|
|
429
|
+
Ke,
|
|
430
|
+
Qe,
|
|
431
|
+
rt,
|
|
432
|
+
xe,
|
|
433
|
+
at
|
|
434
|
+
], ft = (e, t) => {
|
|
434
435
|
const r = t.revivableModules.find((n) => n.isType(e));
|
|
435
436
|
return r?.isType(e) ? r.box(e, t) : e;
|
|
436
|
-
},
|
|
437
|
+
}, lt = (e, t) => {
|
|
437
438
|
const r = t.revivableModules.find((n) => n.isType(e));
|
|
438
439
|
return r?.isType(e) ? r.box(e, t) : e;
|
|
439
440
|
}, b = (e, t) => {
|
|
@@ -444,11 +445,11 @@ const oe = (e) => {
|
|
|
444
445
|
b(a, t)
|
|
445
446
|
])
|
|
446
447
|
) : e;
|
|
447
|
-
},
|
|
448
|
-
const r =
|
|
448
|
+
}, pt = (e, t) => {
|
|
449
|
+
const r = v(e) ? e.type : void 0, n = t.revivableModules.find((a) => a.type === r);
|
|
449
450
|
return n ? n.revive(e, t) : e;
|
|
450
451
|
}, A = (e, t) => {
|
|
451
|
-
if (
|
|
452
|
+
if (v(e)) {
|
|
452
453
|
const r = t.revivableModules.find((n) => n.type === e.type);
|
|
453
454
|
if (r)
|
|
454
455
|
return r.revive(e, t);
|
|
@@ -459,7 +460,7 @@ const oe = (e) => {
|
|
|
459
460
|
A(n, t)
|
|
460
461
|
])
|
|
461
462
|
) : e;
|
|
462
|
-
},
|
|
463
|
+
}, ct = ({ transport: e, value: t, uuid: r, remoteUuid: n, platformCapabilities: a, eventTarget: s, send: o, close: i }) => {
|
|
463
464
|
const c = {
|
|
464
465
|
platformCapabilities: a,
|
|
465
466
|
transport: e,
|
|
@@ -468,7 +469,7 @@ const oe = (e) => {
|
|
|
468
469
|
messageChannels: pe(),
|
|
469
470
|
sendMessage: o,
|
|
470
471
|
eventTarget: s,
|
|
471
|
-
revivableModules:
|
|
472
|
+
revivableModules: it
|
|
472
473
|
};
|
|
473
474
|
let y;
|
|
474
475
|
const l = new Promise((p, d) => {
|
|
@@ -489,7 +490,7 @@ const oe = (e) => {
|
|
|
489
490
|
},
|
|
490
491
|
remoteValue: l.then((p) => A(p.data, c))
|
|
491
492
|
};
|
|
492
|
-
},
|
|
493
|
+
}, yt = ({ value: e, uuid: t, platformCapabilities: r, send: n, close: a }) => ({
|
|
493
494
|
close: () => {
|
|
494
495
|
},
|
|
495
496
|
remoteValueProxy: new Proxy(
|
|
@@ -502,12 +503,12 @@ const oe = (e) => {
|
|
|
502
503
|
}
|
|
503
504
|
)
|
|
504
505
|
});
|
|
505
|
-
var
|
|
506
|
+
var dt = class extends EventTarget {
|
|
506
507
|
dispatchTypedEvent(e, t) {
|
|
507
508
|
return super.dispatchEvent(t);
|
|
508
509
|
}
|
|
509
510
|
};
|
|
510
|
-
const
|
|
511
|
+
const gt = async (e, {
|
|
511
512
|
transport: t,
|
|
512
513
|
name: r,
|
|
513
514
|
remoteName: n,
|
|
@@ -559,10 +560,10 @@ const pt = async (e, {
|
|
|
559
560
|
if (f.remoteUuid !== u || d.has(f.uuid))
|
|
560
561
|
return;
|
|
561
562
|
U(l, { type: "announce", remoteUuid: f.uuid });
|
|
562
|
-
const g = new
|
|
563
|
+
const g = new dt(), q = {
|
|
563
564
|
type: "bidirectional",
|
|
564
565
|
eventTarget: g,
|
|
565
|
-
connection:
|
|
566
|
+
connection: ct({
|
|
566
567
|
transport: l,
|
|
567
568
|
value: e,
|
|
568
569
|
uuid: u,
|
|
@@ -608,7 +609,7 @@ const pt = async (e, {
|
|
|
608
609
|
key: a,
|
|
609
610
|
unregisterSignal: o
|
|
610
611
|
}), _(l) && U(l, { type: "announce" }), _(l) && !W(l)) {
|
|
611
|
-
const { remoteValueProxy: f } =
|
|
612
|
+
const { remoteValueProxy: f } = yt({
|
|
612
613
|
value: e,
|
|
613
614
|
uuid: u,
|
|
614
615
|
platformCapabilities: p,
|
|
@@ -624,12 +625,12 @@ export {
|
|
|
624
625
|
M as OSRA_BOX,
|
|
625
626
|
le as OSRA_DEFAULT_KEY,
|
|
626
627
|
C as OSRA_KEY,
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
628
|
+
lt as box,
|
|
629
|
+
it as defaultRevivableModules,
|
|
630
|
+
gt as expose,
|
|
631
|
+
ft as findModuleForValue,
|
|
631
632
|
b as recursiveBox,
|
|
632
633
|
A as recursiveRevive,
|
|
633
|
-
|
|
634
|
+
pt as revive
|
|
634
635
|
};
|
|
635
636
|
//# sourceMappingURL=index.js.map
|
package/build/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sources":["../src/types.ts","../src/revivables/utils.ts","../src/utils/allocator.ts","../src/utils/platform.ts","../src/utils/type-guards.ts","../src/utils/transferable.ts","../src/utils/capabilities.ts","../src/revivables/array-buffer.ts","../src/revivables/date.ts","../src/revivables/headers.ts","../src/revivables/error.ts","../src/revivables/typed-array.ts","../src/revivables/message-port.ts","../src/revivables/promise.ts","../src/revivables/function.ts","../src/revivables/readable-stream.ts","../src/revivables/index.ts","../src/utils/connection.ts","../node_modules/typescript-event-target/dist/index.mjs","../src/index.ts"],"sourcesContent":["import { TypedEventTarget } from 'typescript-event-target'\r\nimport type { TypedArray, WebExtOnConnect, WebExtOnMessage, WebExtPort, WebExtRuntime, WebExtSender } from './utils/type-guards'\r\nimport { DefaultRevivableModule, DefaultRevivableModules, RevivableModule } from './revivables'\r\nimport { InferRevivables } from './revivables/utils'\r\n\r\nexport const OSRA_KEY = '__OSRA_KEY__' as const\r\nexport const OSRA_DEFAULT_KEY = '__OSRA_DEFAULT_KEY__' as const\r\nexport const OSRA_BOX = '__OSRA_BOX__' as const\r\n\r\nexport type Uuid = `${string}-${string}-${string}-${string}-${string}`\r\n\r\nexport type Jsonable =\r\n | boolean\r\n | null\r\n | number\r\n | string\r\n | { [key: string]: Jsonable }\r\n | Array<Jsonable>\r\n\r\nexport type Structurable =\r\n | Jsonable\r\n /** not really structureable but here for convenience */\r\n | void\r\n | undefined\r\n | BigInt\r\n | Date\r\n | RegExp\r\n | Blob\r\n | File\r\n | FileList\r\n | ArrayBuffer\r\n | ArrayBufferView\r\n | ImageBitmap\r\n | ImageData\r\n | { [key: string]: Structurable }\r\n | Array<Structurable>\r\n | Map<Structurable, Structurable>\r\n | Set<Structurable>\r\n \r\nexport type StructurableTransferable =\r\n | Structurable\r\n | Transferable\r\n | { [key: string]: StructurableTransferable }\r\n | Array<StructurableTransferable>\r\n | Map<StructurableTransferable, StructurableTransferable>\r\n | Set<StructurableTransferable>\r\n\r\nexport type Capable<TModules extends readonly RevivableModule[] = DefaultRevivableModules> =\r\n | StructurableTransferable\r\n | InferRevivables<TModules>\r\n | { [key: string]: Capable }\r\n | Array<Capable>\r\n | Map<Capable, Capable>\r\n | Set<Capable>\r\n\r\nexport type MessageBase = {\r\n [OSRA_KEY]: string\r\n /** UUID of the client that sent the message */\r\n uuid: Uuid\r\n name?: string\r\n}\r\n\r\nexport type ProtocolMessage =\r\n | {\r\n type: 'announce'\r\n /** Only set when acknowledging a remote announcement */\r\n remoteUuid?: Uuid\r\n }\r\n | {\r\n /** uuid already taken, try announcing with another one */\r\n type: 'reject-uuid-taken'\r\n remoteUuid: Uuid\r\n }\r\n | {\r\n type: 'close'\r\n remoteUuid: Uuid\r\n }\r\n\r\nexport type BidirectionalConnectionMessage =\r\n | {\r\n type: 'init'\r\n remoteUuid: Uuid\r\n data: Capable\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n /** uuid of the messagePort that the message was sent through */\r\n portId: Uuid\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message-port-close'\r\n remoteUuid: Uuid\r\n /** uuid of the messagePort that closed */\r\n portId: string\r\n }\r\n\r\nexport type UnidirectionalConnectionMessage = {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n portId: Uuid\r\n}\r\n\r\nexport type ConnectionMessage =\r\n | BidirectionalConnectionMessage\r\n | UnidirectionalConnectionMessage\r\n\r\nexport type MessageVariant =\r\n | ProtocolMessage\r\n | ConnectionMessage\r\n\r\nexport type Message =\r\n | MessageBase\r\n & MessageVariant\r\n\r\nexport type MessageContext = {\r\n port?: MessagePort | WebExtPort // WebExtension\r\n sender?: WebExtSender // WebExtension\r\n receiveTransport?: ReceivePlatformTransport\r\n source?: MessageEventSource | null // Window, Worker, WebSocket, ect...\r\n}\r\n\r\nexport type MessageEventMap = {\r\n message: CustomEvent<Message>\r\n}\r\nexport type MessageEventTarget = TypedEventTarget<MessageEventMap>\r\n\r\nexport type CustomTransport =\r\n { isJson?: boolean }\r\n & (\r\n | {\r\n receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void)\r\n emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void)\r\n }\r\n | { receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void) }\r\n | { emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void) }\r\n )\r\n\r\nexport type CustomEmitTransport = Extract<CustomTransport, { emit: any }>\r\nexport type CustomReceiveTransport = Extract<CustomTransport, { receive: any }>\r\n\r\nexport type EmitJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n\r\nexport type ReceiveJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n | WebExtOnConnect\r\n | WebExtOnMessage\r\n\r\nexport type JsonPlatformTransport =\r\n | { isJson: true }\r\n | EmitJsonPlatformTransport\r\n | ReceiveJsonPlatformTransport\r\n\r\nexport type EmitPlatformTransport =\r\n | EmitJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type ReceivePlatformTransport =\r\n | ReceiveJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type PlatformTransport =\r\n | EmitPlatformTransport\r\n | ReceivePlatformTransport\r\n\r\nexport type EmitTransport = EmitPlatformTransport & Extract<CustomTransport, { emit: any }>\r\nexport type ReceiveTransport = ReceivePlatformTransport & Extract<CustomTransport, { receive: any }>\r\n\r\nexport type Transport =\r\n | PlatformTransport\r\n | CustomTransport\r\n","import type { DefaultRevivableModules, RevivableModule } from '.'\r\nimport type { ConnectionMessage, MessageEventTarget, Transport, Uuid } from '../types'\r\nimport type { MessageChannelAllocator, PlatformCapabilities } from '../utils'\r\n\r\nimport { OSRA_BOX } from '../types'\r\n\r\nexport declare const UnderlyingType: unique symbol\r\nexport type UnderlyingType = typeof UnderlyingType\r\n\r\nexport const BoxBase = {\r\n [OSRA_BOX]: 'revivable',\r\n type: '' as string\r\n} as const\r\n\r\nexport type BoxBase<T extends string = string> =\r\n & typeof BoxBase\r\n & { type: T }\r\n\r\nexport type RevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n}\r\n\r\nexport type ExtractModule<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractType<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractBoxInput<T> = T extends { box: (value: infer S) => value is any } ? S : never\r\nexport type ExtractReviveInput<T> = T extends { revive: (value: infer S) => value is any } ? S : never\r\nexport type ExtractBox<T> = T extends { box: (...args: any[]) => infer B } ? B : never\r\nexport type InferRevivables<TModules extends readonly unknown[]> =\r\n ExtractType<TModules[number]>\r\nexport type InferRevivableBox<TModules extends readonly unknown[]> =\r\n ExtractBox<TModules[number]>\r\n\r\nexport const isRevivableBox = <T extends RevivableContext>(value: any, _context: T): value is InferRevivableBox<T['revivableModules']> =>\r\n value\r\n && typeof value === 'object'\r\n && OSRA_BOX in value\r\n && value[OSRA_BOX] === 'revivable'\r\n","import type { StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessageChannel, StrictMessagePort } from './message-channel'\r\n\r\nexport const makeAllocator = <T>() => {\r\n const channels = new Map<string, T>()\r\n\r\n const alloc = (value: T): string => {\r\n let uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n channels.set(uuid, value)\r\n return uuid\r\n }\r\n\r\n const has = (uuid: string) => channels.has(uuid)\r\n const get = (uuid: string) => channels.get(uuid)\r\n\r\n const free = (uuid: string) => {\r\n channels.delete(uuid)\r\n }\r\n\r\n const set = (uuid: string, value: T) => {\r\n channels.set(uuid, value)\r\n }\r\n\r\n return {\r\n alloc,\r\n has,\r\n get,\r\n free,\r\n set\r\n }\r\n}\r\n\r\nexport type Allocator<T> = ReturnType<typeof makeAllocator<T>>\r\n\r\ntype AllocatedMessageChannel<\r\n T extends StructurableTransferable = StructurableTransferable,\r\n T2 extends StructurableTransferable = StructurableTransferable\r\n> = {\r\n uuid: Uuid\r\n /** Local port */\r\n port1: StrictMessagePort<T>\r\n /** Remote port that gets transferred, might be undefined if a remote context created the channel */\r\n port2?: StrictMessagePort<T2>\r\n}\r\n\r\nexport const makeMessageChannelAllocator = () => {\r\n const channels = new Map<string, AllocatedMessageChannel>()\r\n\r\n const result = {\r\n getUniqueUuid: () => {\r\n let uuid: Uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n return uuid\r\n },\r\n set: (uuid: Uuid, messagePorts: { port1: StrictMessagePort, port2?: StrictMessagePort }) => {\r\n channels.set(uuid, { uuid, ...messagePorts })\r\n },\r\n alloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n if (messagePorts) {\r\n const allocatedMessageChannel = { uuid, ...messagePorts } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n }\r\n const messageChannel = new MessageChannel() as StrictMessageChannel\r\n const allocatedMessageChannel = {\r\n uuid,\r\n port1: messageChannel.port1,\r\n port2: messageChannel.port2\r\n } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n },\r\n has: (uuid: string) => channels.has(uuid),\r\n get: (uuid: string) => channels.get(uuid),\r\n free: (uuid: string) => channels.delete(uuid),\r\n getOrAlloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n const existingChannel = result.get(uuid)\r\n if (existingChannel) return existingChannel!\r\n return result.alloc(uuid, messagePorts)\r\n }\r\n }\r\n return result\r\n}\r\n\r\nexport type MessageChannelAllocator = ReturnType<typeof makeMessageChannelAllocator>\r\n","import type {\r\n CustomTransport, EmitTransport,\r\n Message, MessageContext,\r\n ReceiveTransport\r\n} from '../types'\r\nimport type { WebExtOnMessage, WebExtPort, WebExtSender } from './type-guards'\r\n\r\nimport { OSRA_KEY } from '../types'\r\nimport {\r\n isOsraMessage, isCustomTransport,\r\n isWebExtensionOnConnect, isWebExtensionOnMessage,\r\n isWebExtensionPort, isWebSocket, isWindow, isSharedWorker\r\n} from './type-guards'\r\n\r\nexport const getWebExtensionGlobal = () => globalThis.browser ?? globalThis.chrome\r\nexport const getWebExtensionRuntime = () => getWebExtensionGlobal().runtime\r\n\r\nexport const checkOsraMessageKey = (message: any, key: string): message is Message =>\r\n isOsraMessage(message)\r\n && message[OSRA_KEY] === key\r\n\r\nexport const registerOsraMessageListener = (\r\n { listener, transport, remoteName, key = OSRA_KEY, unregisterSignal }:\r\n {\r\n listener: (message: Message, messageContext: MessageContext) => Promise<void>\r\n transport: ReceiveTransport\r\n remoteName?: string\r\n key?: string\r\n unregisterSignal?: AbortSignal\r\n }\r\n) => {\r\n const registerListenerOnReceiveTransport = (receiveTransport: Extract<CustomTransport, { receive: any }>['receive']) => {\r\n // Custom function handler\r\n if (typeof receiveTransport === 'function') {\r\n receiveTransport(listener)\r\n // WebExtension handler\r\n } else if (\r\n isWebExtensionPort(receiveTransport)\r\n || isWebExtensionOnConnect(receiveTransport)\r\n || isWebExtensionOnMessage(receiveTransport)\r\n ) {\r\n const listenOnWebExtOnMessage = (onMessage: WebExtOnMessage, port?: WebExtPort) => {\r\n const _listener = (message: object, sender?: WebExtSender) => {\r\n if (!checkOsraMessageKey(message, key)) return\r\n if (remoteName && message.name !== remoteName) return\r\n listener(message, { port, sender })\r\n }\r\n onMessage.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n onMessage.removeListener(_listener)\r\n )\r\n }\r\n }\r\n\r\n // WebExtOnConnect\r\n if (isWebExtensionOnConnect(receiveTransport)) {\r\n const _listener = (port: WebExtPort) => {\r\n listenOnWebExtOnMessage(port.onMessage as WebExtOnMessage, port)\r\n }\r\n receiveTransport.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeListener(_listener)\r\n )\r\n }\r\n // WebExtOnMessage\r\n } else if (isWebExtensionOnMessage(receiveTransport)) {\r\n listenOnWebExtOnMessage(receiveTransport)\r\n } else { // WebExtPort\r\n listenOnWebExtOnMessage(receiveTransport.onMessage as WebExtOnMessage)\r\n }\r\n } else { // Window, Worker, WebSocket, ect...\r\n const messageListener = (event: MessageEvent<Message>) => {\r\n if (!checkOsraMessageKey(event.data, key)) return\r\n if (remoteName && event.data.name !== remoteName) return\r\n listener(event.data, { receiveTransport, source: event.source })\r\n }\r\n receiveTransport.addEventListener('message', messageListener as EventListener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeEventListener('message', messageListener as EventListener)\r\n )\r\n }\r\n }\r\n }\r\n if (isCustomTransport(transport)) {\r\n registerListenerOnReceiveTransport(transport.receive)\r\n } else {\r\n registerListenerOnReceiveTransport(transport)\r\n }\r\n}\r\n\r\nexport const sendOsraMessage = (\r\n transport: EmitTransport,\r\n message: Message,\r\n origin = '*',\r\n transferables: Transferable[] = []\r\n) => {\r\n const sendToEmitTransport = (emitTransport: Extract<EmitTransport, { emit: any }>['emit']) => {\r\n if (typeof emitTransport === 'function') {\r\n emitTransport(message, transferables)\r\n } else if (isWebExtensionPort(emitTransport)) {\r\n emitTransport.postMessage(message)\r\n } else if (isWindow(emitTransport)) {\r\n emitTransport.postMessage(message, origin, transferables)\r\n } else if (isWebSocket(emitTransport)) {\r\n emitTransport.send(JSON.stringify(message))\r\n } else if (isSharedWorker(emitTransport)) {\r\n emitTransport.port.postMessage(message, transferables)\r\n } else { // MessagePort | ServiceWorker | Worker\r\n emitTransport.postMessage(message, transferables)\r\n }\r\n }\r\n\r\n if (isCustomTransport(transport)) {\r\n sendToEmitTransport(transport.emit)\r\n } else {\r\n sendToEmitTransport(transport)\r\n }\r\n}\r\n","import type { Runtime } from 'webextension-polyfill'\r\nimport type {\r\n CustomEmitTransport, CustomReceiveTransport,\r\n CustomTransport, EmitJsonPlatformTransport,\r\n EmitTransport, JsonPlatformTransport,\r\n Message, ReceiveJsonPlatformTransport,\r\n ReceiveTransport, Transport\r\n} from '../types'\r\n\r\nimport { OSRA_BOX, OSRA_KEY } from '../types'\r\nimport { getWebExtensionRuntime } from './platform'\r\n\r\nexport type TransferBox<T extends Transferable = Transferable> = {\r\n [OSRA_BOX]: 'transferable'\r\n value: T\r\n}\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypeArrayType = ReturnType<typeof typedArrayToType>\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypeArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isTypedArray = (value: any): value is TypedArray => typedArrayConstructors.some(typedArray => value instanceof typedArray)\r\nexport const isWebSocket = (value: any) => value instanceof WebSocket\r\nexport const isServiceWorkerContainer = (value: any): value is ServiceWorkerContainer => globalThis.ServiceWorkerContainer && value instanceof ServiceWorkerContainer\r\nexport const isWorker = (value: any): value is Worker => globalThis.Worker && value instanceof Worker\r\n// @ts-expect-error\r\nexport const isDedicatedWorker = (value: any): value is DedicatedWorkerGlobalScope => globalThis.DedicatedWorkerGlobalScope && value instanceof DedicatedWorkerGlobalScope\r\nexport const isSharedWorker = (value: any): value is SharedWorker => globalThis.SharedWorker && value instanceof SharedWorker\r\nexport const isMessagePort = (value: any) => value instanceof MessagePort\r\nexport const isPromise = (value: any) => value instanceof Promise\r\nexport const isFunction = (value: any): value is Function => typeof value === 'function'\r\nexport const isArrayBuffer = (value: any) => value instanceof ArrayBuffer\r\nexport const isReadableStream = (value: any) => value instanceof ReadableStream\r\nexport const isDate = (value: any) => value instanceof Date\r\nexport const isError = (value: any) => value instanceof Error\r\n\r\nexport const isAlwaysBox = (value: any): value is Function | Promise<any> | Date | Error =>\r\n isFunction(value)\r\n || isPromise(value)\r\n || isTypedArray(value)\r\n || isDate(value)\r\n || isError(value)\r\n\r\nexport const isOsraMessage = (value: any): value is Message =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Message)[OSRA_KEY]\r\n )\r\n\r\nexport const isClonable = (value: any) =>\r\n globalThis.SharedArrayBuffer && value instanceof globalThis.SharedArrayBuffer ? true\r\n : false\r\n\r\nexport const isTransferable = (value: any): value is Transferable =>\r\n globalThis.ArrayBuffer && value instanceof globalThis.ArrayBuffer ? true\r\n : globalThis.MessagePort && value instanceof globalThis.MessagePort ? true\r\n : globalThis.ReadableStream && value instanceof globalThis.ReadableStream ? true\r\n : globalThis.WritableStream && value instanceof globalThis.WritableStream ? true\r\n : globalThis.TransformStream && value instanceof globalThis.TransformStream ? true\r\n : globalThis.ImageBitmap && value instanceof globalThis.ImageBitmap ? true\r\n : false\r\n\r\nexport const isTransferBox = (value: any): value is TransferBox<any> =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as TransferBox<Transferable>)[OSRA_BOX] === 'transferable'\r\n )\r\n\r\nexport type WebExtRuntime = typeof browser.runtime\r\nexport const isWebExtensionRuntime = (value: any): value is WebExtRuntime => {\r\n const runtime = getWebExtensionRuntime()\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && isWebExtensionOnConnect(runtime.onConnect)\r\n && runtime.id\r\n )\r\n}\r\n\r\nexport type WebExtPort = ReturnType<WebExtRuntime['connect']> | Runtime.Port\r\nexport const isWebExtensionPort = (value: any, connectPort: boolean = false): value is WebExtPort => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && ('name' in (value as WebExtPort))\r\n && ('disconnect' in (value as WebExtPort))\r\n && ('postMessage' in (value as WebExtPort))\r\n && (\r\n connectPort\r\n // these properties are only present on WebExtPort that were created through runtime.connect()\r\n ? (\r\n ('sender' in (value as WebExtPort))\r\n && ('onMessage' in (value as WebExtPort))\r\n && ('onDisconnect' in (value as WebExtPort))\r\n )\r\n : true\r\n )\r\n )\r\n}\r\n\r\nexport type WebExtSender = NonNullable<WebExtPort['sender']>\r\n\r\nexport type WebExtOnConnect = WebExtRuntime['onConnect']\r\nexport const isWebExtensionOnConnect = (value: any): value is WebExtOnConnect =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnConnect).addListener\r\n && (value as WebExtOnConnect).hasListener\r\n && (value as WebExtOnConnect).removeListener\r\n )\r\n\r\nexport type WebExtOnMessage = WebExtRuntime['onMessage']\r\nexport const isWebExtensionOnMessage = (value: any): value is WebExtOnMessage =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnMessage).addListener\r\n && (value as WebExtOnMessage).hasListener\r\n && (value as WebExtOnMessage).removeListener\r\n )\r\n\r\nexport const isWindow = (value: unknown): value is Window => {\r\n if (!value || typeof value !== 'object') return false\r\n\r\n try {\r\n return (value as Window).window === value\r\n } catch {\r\n try {\r\n const w = value as Window\r\n return typeof w.closed === 'boolean' && typeof w.close === 'function'\r\n } catch {\r\n return false\r\n }\r\n }\r\n }\r\n\r\nexport type IsEmitJsonOnlyTransport<T extends Transport> = T extends EmitJsonPlatformTransport ? true : false\r\nexport const isEmitJsonOnlyTransport = (value: any): value is EmitJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n\r\nexport type IsReceiveJsonOnlyTransport<T extends Transport> = T extends ReceiveJsonPlatformTransport ? true : false\r\nexport const isReceiveJsonOnlyTransport = (value: any): value is ReceiveJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n || isWebExtensionOnConnect(value)\r\n || isWebExtensionOnMessage(value)\r\n\r\nexport type IsJsonOnlyTransport<T extends Transport> = T extends JsonPlatformTransport ? true : false\r\nexport const isJsonOnlyTransport = (value: Transport): value is Extract<Transport, JsonPlatformTransport> =>\r\n ('isJson' in value && value.isJson === true)\r\n || isEmitJsonOnlyTransport(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n\r\nexport type IsEmitTransport<T extends Transport> = T extends EmitTransport ? true : false\r\nexport const isEmitTransport = (value: any): value is EmitTransport =>\r\n isWindow(value)\r\n || isEmitJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomEmitTransport(value)\r\n\r\nexport function assertEmitTransport (transport: Transport): asserts transport is EmitTransport {\r\n if (!isEmitTransport(transport)) throw new Error('Transport is not emitable')\r\n}\r\n\r\n\r\nexport type IsReceiveTransport<T extends Transport> = T extends ReceiveTransport ? true : false\r\nexport const isReceiveTransport = (value: any): value is ReceiveTransport =>\r\n isWindow(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport function assertReceiveTransport (transport: Transport): asserts transport is ReceiveTransport {\r\n if (!isReceiveTransport(transport)) throw new Error('Transport is not receiveable')\r\n}\r\n\r\nexport const isCustomEmitTransport = (value: any): value is CustomEmitTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'emit' in value\r\n && (\r\n isEmitTransport(value.emit)\r\n || typeof value.emit === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport const isCustomReceiveTransport = (value: any): value is CustomReceiveTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'receive' in value\r\n && (\r\n isReceiveTransport(value.receive)\r\n || typeof value.receive === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport type IsCustomTransport<T extends Transport> = T extends CustomTransport ? true : false\r\nexport const isCustomTransport = (value: any): value is CustomTransport =>\r\n isCustomEmitTransport(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport const isTransport = (value: any): value is Transport =>\r\n isEmitTransport(value)\r\n || isReceiveTransport(value)\r\n || isCustomTransport(value)\r\n || isJsonOnlyTransport(value)\r\n","import type { Capable } from '../types'\r\nimport type { TransferBox } from './type-guards'\r\n\r\nimport { OSRA_BOX } from '../types'\r\nimport { deepReplace } from './replace'\r\nimport { isClonable, isTransferable, isTransferBox } from './type-guards'\r\n\r\nexport const getTransferableObjects = (value: any): Transferable[] => {\r\n const transferables: Transferable[] = []\r\n const recurse = (value: any): any =>\r\n isClonable(value) ? undefined\r\n : isTransferable(value) ? transferables.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferables\r\n}\r\n\r\nexport const getTransferBoxes = (value: any): TransferBox<Transferable>[] => {\r\n const transferBoxes: TransferBox<any>[] = []\r\n const recurse = (value: any): any =>\r\n isTransferBox(value) ? transferBoxes.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferBoxes\r\n}\r\n\r\n/** This box tells the protocol that the value should be copied instead of transfered */\r\nexport const transfer = <T extends Transferable>(value: T) => ({\r\n [OSRA_BOX]: 'transferable',\r\n value\r\n}) as TransferBox<T>\r\n\r\nexport const recursiveTransfer = <T extends Capable>(value: T) =>\r\n deepReplace(\r\n value,\r\n isTransferable,\r\n (value) => transfer(value)\r\n )\r\n","import { getTransferableObjects } from './transferable'\r\n\r\nexport type PlatformCapabilities = {\r\n jsonOnly: boolean\r\n messagePort: boolean\r\n arrayBuffer: boolean\r\n transferable: boolean\r\n transferableStream: boolean\r\n}\r\n\r\nconst probePlatformCapabilityUtil = <T>(value: T, transfer = false): Promise<T> => {\r\n const { port1, port2 } = new MessageChannel()\r\n const result = new Promise<T>(resolve =>\r\n port1.addEventListener('message', message =>\r\n resolve(message.data)\r\n )\r\n )\r\n port1.start()\r\n port2.postMessage(value, transfer ? getTransferableObjects(value) : [])\r\n return result\r\n}\r\n\r\nconst probeMessagePortTransfer = async () => {\r\n const { port1 } = new MessageChannel()\r\n const port = await probePlatformCapabilityUtil(port1, true)\r\n return port instanceof MessagePort\r\n}\r\n\r\nconst probeArrayBufferClone = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeArrayBufferTransfer = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer, true)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeTransferableStream = async () => {\r\n const stream = new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(new Uint8Array(1))\r\n controller.close()\r\n }\r\n })\r\n const transferableStream = await probePlatformCapabilityUtil(stream, true)\r\n return transferableStream instanceof ReadableStream\r\n}\r\n\r\nexport const probePlatformCapabilities = async (): Promise<PlatformCapabilities> => {\r\n const [\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n ] = await Promise.all([\r\n probeMessagePortTransfer().catch(() => false),\r\n probeArrayBufferClone().catch(() => false),\r\n probeArrayBufferTransfer().catch(() => false),\r\n probeTransferableStream().catch(() => false)\r\n ])\r\n return {\r\n jsonOnly:\r\n !messagePort\r\n && !arrayBuffer\r\n && !transferable\r\n && !transferableStream,\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n }\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'arrayBuffer' as const\r\n\r\nexport const isType = (value: unknown): value is ArrayBuffer =>\r\n value instanceof ArrayBuffer\r\n\r\nexport const box = <T extends ArrayBuffer, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ...(\r\n isJsonOnlyTransport(_context.transport)\r\n ? { base64Buffer: new Uint8Array(value).toBase64() }\r\n : { arrayBuffer: value }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n )\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) =>\r\n 'arrayBuffer' in value ? value.arrayBuffer\r\n : (\r\n Uint8Array\r\n .fromBase64(value.base64Buffer)\r\n .buffer\r\n )\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new ArrayBuffer(10), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ArrayBuffer = revived\r\n // @ts-expect-error - not an ArrayBuffer\r\n const notArrayBuffer: string = revived\r\n // @ts-expect-error - cannot box non-ArrayBuffer\r\n box('not an array buffer', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'date' as const\r\n\r\nexport const isType = (value: unknown): value is Date =>\r\n value instanceof Date\r\n\r\nexport const box = <T extends Date, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ISOString: value.toISOString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Date => {\r\n return new Date(value.ISOString)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Date(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Date = revived\r\n // @ts-expect-error - not a Date\r\n const notDate: string = revived\r\n // @ts-expect-error - cannot box non-Date\r\n box('not a date', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'headers' as const\r\n\r\nexport const isType = (value: unknown): value is Headers =>\r\n value instanceof Headers\r\n\r\nexport const box = <T extends Headers, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n entries: [...value.entries()]\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Headers => {\r\n return new Headers(value.entries)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Headers(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Headers = revived\r\n // @ts-expect-error - not a Headers\r\n const notHeaders: string = revived\r\n // @ts-expect-error - cannot box non-Headers\r\n box('not a header', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'error' as const\r\n\r\nexport const isType = (value: unknown): value is Error =>\r\n value instanceof Error\r\n\r\nexport const box = <T extends Error, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n message: value.message,\r\n stack: value.stack || value.toString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => new Error(value.message, { cause: value.stack })\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Error('test'), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Error = revived\r\n // @ts-expect-error - not an Error\r\n const notError: string = revived\r\n // @ts-expect-error - cannot box non-Error\r\n box('not an error', {} as RevivableContext)\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'typedArray' as const\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\n\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypedArrayType = ReturnType<typeof typedArrayToType>\r\n\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypedArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isType = (value: unknown): value is TypedArray =>\r\n typedArrayConstructors.some(constructor => value instanceof constructor)\r\n\r\nexport const box = <T extends TypedArray, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n typedArrayType: typedArrayToType(value),\r\n ...(\r\n isJsonOnlyTransport(context.transport)\r\n ? { base64Buffer: new Uint8Array(value.buffer).toBase64() }\r\n : { arrayBuffer: value.buffer }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n ) & { [UnderlyingType]: T }\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const TypedArrayConstructor = typedArrayTypeToTypedArrayConstructor(value.typedArrayType as TypedArrayType)\r\n const arrayBuffer =\r\n 'arrayBuffer' in value\r\n ? value.arrayBuffer\r\n : Uint8Array.fromBase64(value.base64Buffer).buffer\r\n return new TypedArrayConstructor(arrayBuffer)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const uint8Boxed = box(new Uint8Array(10), {} as RevivableContext)\r\n const uint8Revived = revive(uint8Boxed, {} as RevivableContext)\r\n const expectedUint8: Uint8Array = uint8Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongType: Int32Array = uint8Revived\r\n\r\n const float32Boxed = box(new Float32Array(10), {} as RevivableContext)\r\n const float32Revived = revive(float32Boxed, {} as RevivableContext)\r\n const expectedFloat32: Float32Array = float32Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongFloat: Uint8Array = float32Revived\r\n\r\n // @ts-expect-error - cannot box non-TypedArray\r\n box('not a typed array', {} as RevivableContext)\r\n}\r\n","import type { Capable, ConnectionMessage, Message, StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { RevivableContext, BoxBase as BoxBaseType, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { OSRA_BOX } from '../types'\r\nimport { getTransferableObjects, isJsonOnlyTransport } from '../utils'\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up MessagePorts when they are garbage collected.\r\n * This is used in JSON-only mode where MessagePorts can't be transferred directly.\r\n */\r\ntype PortCleanupInfo = {\r\n sendMessage: (message: ConnectionMessage) => void\r\n remoteUuid: Uuid\r\n portId: string\r\n cleanup: () => void\r\n}\r\n\r\nconst messagePortRegistry = new FinalizationRegistry<PortCleanupInfo>((info) => {\r\n // Send close message to remote side\r\n info.sendMessage({\r\n type: 'message-port-close',\r\n remoteUuid: info.remoteUuid,\r\n portId: info.portId\r\n })\r\n // Perform local cleanup\r\n info.cleanup()\r\n})\r\n\r\nexport const type = 'messagePort' as const\r\n\r\nexport type BoxedMessagePort<T extends StructurableTransferable = StructurableTransferable> =\r\n & BoxBaseType<typeof type>\r\n & ({ portId: string } | { port: StrictMessagePort<T> })\r\n & { [UnderlyingType]: StrictMessagePort<T> }\r\n\r\ndeclare const StructurableTransferableError: unique symbol\r\ntype StructurableTransferablePort<T> = T extends StructurableTransferable\r\n ? StrictMessagePort<T>\r\n : { [StructurableTransferableError]: 'Message type must extend StructurableTransferable'; __badType__: T }\r\n\r\ntype ExtractStructurableTransferable<T> = T extends StructurableTransferable ? T : never\r\n\r\nexport const isType = (value: unknown): value is MessagePort =>\r\n value instanceof MessagePort\r\n\r\nconst isAlreadyBoxed = (value: unknown): boolean =>\r\n value !== null &&\r\n typeof value === 'object' &&\r\n OSRA_BOX in value &&\r\n (value as Record<string, unknown>)[OSRA_BOX] === 'revivable'\r\n\r\nexport const box = <T, T2 extends RevivableContext = RevivableContext>(\r\n value: StructurableTransferablePort<T>,\r\n context: T2\r\n) => {\r\n if (isJsonOnlyTransport(context.transport)) {\r\n const messagePort = value as StrictMessagePort<ExtractStructurableTransferable<T>>\r\n // Only generate a unique UUID, don't store the port in the allocator.\r\n // Storing the port would create a strong reference that prevents GC and FinalizationRegistry cleanup.\r\n const portId = context.messageChannels.getUniqueUuid()\r\n\r\n // Use WeakRef to allow messagePort to be garbage collected.\r\n // The eventTargetListener would otherwise hold a strong reference preventing GC.\r\n const messagePortRef = new WeakRef(messagePort)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n // Define listener before registering with FinalizationRegistry so we can remove it in cleanup\r\n const eventTargetListener = ({ detail: message }: CustomEvent<Message>) => {\r\n if (message.type === 'message-port-close') {\r\n if (message.portId !== portId) return\r\n context.messageChannels.free(portId)\r\n const port = messagePortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n port.close()\r\n }\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n const port = messagePortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, remove this listener\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n port.postMessage(message.data as ExtractStructurableTransferable<T>, getTransferableObjects(message.data))\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before registering so it can be removed in cleanup\r\n function messagePortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: (isAlreadyBoxed(data) ? data : recursiveBox(data as Capable, context)) as Capable,\r\n portId\r\n })\r\n }\r\n\r\n // Register the messagePort for automatic cleanup when garbage collected\r\n // Use messagePort itself as the unregister token\r\n messagePortRegistry.register(messagePortRef.deref()!, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: () => {\r\n context.messageChannels.free(portId)\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n messagePortRef.deref()?.removeEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.close()\r\n }\r\n }, messagePortRef.deref())\r\n\r\n messagePortRef.deref()?.addEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.start()\r\n\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n \r\n const result = {\r\n ...BoxBase,\r\n type,\r\n portId\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n }\r\n const result = {\r\n ...BoxBase,\r\n type,\r\n port: value\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n}\r\n\r\nexport const revive = <T extends StructurableTransferable, T2 extends RevivableContext>(\r\n value: BoxedMessagePort<T>,\r\n context: T2\r\n): StrictMessagePort<T> => {\r\n if ('portId' in value) {\r\n const { portId } = value\r\n const { port1: userPort, port2: internalPort } = new MessageChannel()\r\n\r\n const existingChannel = context.messageChannels.get(value.portId)\r\n const { port1 } =\r\n existingChannel\r\n ? existingChannel\r\n : context.messageChannels.alloc(value.portId as Uuid)\r\n\r\n const userPortRef = new WeakRef(userPort)\r\n\r\n // Define all listeners before registering so they can be removed in cleanup\r\n const eventTargetListener = ({ detail: message }: CustomEvent<Message>) => {\r\n if (message.type !== 'message-port-close' || message.portId !== portId) return\r\n const port = userPortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n }\r\n performCleanup()\r\n }\r\n\r\n const port1Listener = ({ data: message }: MessageEvent) => {\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n\r\n const port = userPortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, cleanup\r\n performCleanup()\r\n return\r\n }\r\n\r\n // if the returned messagePort has been registered as internal message port, then we proxy the data without reviving it\r\n if (context.messagePorts.has(port)) {\r\n internalPort.postMessage(message.data)\r\n } else {\r\n // In this case, userPort is actually passed by the user of osra and we should revive all the message data\r\n const revivedData = recursiveRevive(message.data, context)\r\n internalPort.postMessage(revivedData, getTransferableObjects(revivedData))\r\n }\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before performCleanup so it can be removed in cleanup\r\n function internalPortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: isAlreadyBoxed(data) ? data : recursiveBox(data, context),\r\n portId: portId as Uuid\r\n })\r\n }\r\n\r\n const performCleanup = () => {\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n port1.removeEventListener('message', port1Listener)\r\n internalPort.removeEventListener('message', internalPortListener)\r\n internalPort.close()\r\n // Close the allocator's MessageChannel ports before freeing\r\n // The allocator creates a MessageChannel with port1 and port2 - both must be closed\r\n const allocatedChannel = context.messageChannels.get(portId)\r\n if (allocatedChannel) {\r\n allocatedChannel.port1.close()\r\n if (allocatedChannel.port2) {\r\n allocatedChannel.port2.close()\r\n }\r\n }\r\n context.messageChannels.free(portId)\r\n }\r\n\r\n // Register the userPort for automatic cleanup when garbage collected\r\n // Use userPort itself as the unregister token\r\n messagePortRegistry.register(userPort, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: performCleanup\r\n }, userPort)\r\n\r\n internalPort.addEventListener('message', internalPortListener)\r\n internalPort.start()\r\n\r\n // Listen for close messages from the remote side through the main event target\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n port1.addEventListener('message', port1Listener)\r\n port1.start()\r\n\r\n return userPort as StrictMessagePort<T>\r\n }\r\n return value.port\r\n}\r\n\r\nconst typeCheck = () => {\r\n const port = new MessageChannel().port1 as StrictMessagePort<{ foo: string }>\r\n const boxed = box(port, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: StrictMessagePort<{ foo: string }> = revived\r\n // @ts-expect-error - wrong message type\r\n const wrongType: StrictMessagePort<{ bar: number }> = revived\r\n // @ts-expect-error - non-StructurableTransferable message type\r\n box(new MessageChannel().port1 as StrictMessagePort<Promise<string>>, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'promise' as const\r\n\r\nexport type Context =\r\n | { type: 'resolve', data: Capable }\r\n | { type: 'reject', error: string }\r\n\r\ndeclare const CapableError: unique symbol\r\ntype CapablePromise<T> = T extends Capable\r\n ? Promise<T>\r\n : { [CapableError]: 'Message type must extend Capable'; __badType__: T }\r\n\r\ntype ExtractCapable<T> = T extends Capable ? T : never\r\n\r\nexport type BoxedPromise<T extends Capable = Capable> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: ReturnType<typeof boxMessagePort>\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is Promise<any> =>\r\n value instanceof Promise\r\n\r\nexport const box = <T, T2 extends RevivableContext>(\r\n value: CapablePromise<T>,\r\n context: T2\r\n): BoxedPromise<ExtractCapable<T>> => {\r\n const promise = value as Promise<ExtractCapable<T>>\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const sendResult = (result: Context) => {\r\n const boxedResult = recursiveBox(result, context)\r\n localPort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n localPort.close()\r\n // Clean up the remote port from the set (it was transferred earlier)\r\n context.messagePorts.delete(remotePort)\r\n }\r\n\r\n promise\r\n .then((data: ExtractCapable<T>) => sendResult({ type: 'resolve', data }))\r\n .catch((error: unknown) => sendResult({ type: 'reject', error: (error as Error)?.stack ?? String(error) }))\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as unknown as StrictMessagePort<string>, context)\r\n } as unknown as BoxedPromise<ExtractCapable<T>>\r\n}\r\n\r\nexport const revive = <T extends BoxedPromise, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort<string>, context)\r\n context.messagePorts.add(port as MessagePort)\r\n return new Promise<T[UnderlyingType]>((resolve, reject) => {\r\n port.addEventListener('message', (event) => {\r\n const data = (event as unknown as MessageEvent<Context>).data\r\n const result = recursiveRevive(data, context) as Context\r\n if (result.type === 'resolve') {\r\n resolve(result.data as T[UnderlyingType])\r\n } else {\r\n reject(result.error)\r\n }\r\n context.messagePorts.delete(port as MessagePort)\r\n port.close()\r\n }, { once: true })\r\n port.start()\r\n })\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(Promise.resolve(1 as const), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Promise<1> = revived\r\n // @ts-expect-error\r\n const notExpected: Promise<string> = revived\r\n // @ts-expect-error\r\n box(1 as const, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { UnderlyingType, RevivableContext, BoxBase as BoxBaseType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'function' as const\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up function ports when the revived function is garbage collected.\r\n */\r\ntype FunctionCleanupInfo = {\r\n port: MessagePort\r\n}\r\n\r\nconst functionRegistry = new FinalizationRegistry<FunctionCleanupInfo>((info) => {\r\n // Send a close signal through the port before closing it\r\n try {\r\n info.port.postMessage({ __osra_close__: true })\r\n } catch { /* Port may already be closed */ }\r\n try {\r\n info.port.close()\r\n } catch { /* Port may already be closed */ }\r\n})\r\n\r\nexport type CallContext = [\r\n /** MessagePort or portId that will be used to send the result of the function call */\r\n MessagePort | string,\r\n /** Arguments that will be passed to the function call */\r\n Capable[]\r\n]\r\n\r\nexport type BoxedFunction<T extends (...args: any[]) => any = (...args: any[]) => any> =\r\n & BoxBaseType<typeof type>\r\n & { port: BoxedMessagePort }\r\n & { [UnderlyingType]: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> }\r\n\r\ntype CapableFunction<T> = T extends (...args: infer P) => infer R\r\n ? P extends Capable[]\r\n ? R extends Capable ? T : never\r\n : never\r\n : never\r\n\r\nexport const isType = (value: unknown): value is (...args: any[]) => any =>\r\n typeof value === 'function'\r\n\r\nexport const box = <T extends (...args: any[]) => any, T2 extends RevivableContext>(\r\n value: T & CapableFunction<T>,\r\n context: T2\r\n): BoxedFunction<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const cleanup = () => {\r\n context.messagePorts.delete(remotePort)\r\n localPort.close()\r\n }\r\n\r\n localPort.addEventListener('message', ({ data }: MessageEvent<CallContext | { __osra_close__: true }>) => {\r\n // Check for close signal\r\n if (data && typeof data === 'object' && '__osra_close__' in data) {\r\n cleanup()\r\n return\r\n }\r\n const [returnValuePort, args] = recursiveRevive(data as CallContext, context) as [MessagePort, Capable[]]\r\n const result = (async () => value(...args))()\r\n const boxedResult = recursiveBox(result, context)\r\n returnValuePort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n port: boxMessagePort(remotePort as any, context)\r\n } as BoxedFunction<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedFunction, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context)\r\n\r\n const func = (...args: Capable[]) =>\r\n new Promise((resolve, reject) => {\r\n const { port1: returnValueLocalPort, port2: returnValueRemotePort } = new MessageChannel()\r\n context.messagePorts.add(returnValueRemotePort)\r\n const callContext = recursiveBox([returnValueRemotePort, args] as const, context)\r\n ;(port as MessagePort).postMessage(callContext, getTransferableObjects(callContext))\r\n // Remove the remote port from the set after transfer (it's neutered now)\r\n context.messagePorts.delete(returnValueRemotePort)\r\n\r\n returnValueLocalPort.addEventListener('message', ({ data }: MessageEvent<Capable>) => {\r\n const result = recursiveRevive(data, context) as Promise<Capable>\r\n result\r\n .then(resolve)\r\n .catch(reject)\r\n .finally(() => {\r\n returnValueLocalPort.close()\r\n })\r\n }, { once: true })\r\n returnValueLocalPort.start()\r\n })\r\n\r\n // Register the function for automatic cleanup when garbage collected\r\n functionRegistry.register(func, { port: port as MessagePort }, func)\r\n\r\n return func\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box((a: number, b: string) => a + b.length, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: (a: number, b: string) => Promise<number> = revived\r\n // @ts-expect-error - wrong return type\r\n const wrongReturn: (a: number, b: string) => Promise<string> = revived\r\n // @ts-expect-error - wrong parameter types\r\n const wrongParams: (a: string, b: number) => Promise<number> = revived\r\n // @ts-expect-error - non-Capable parameter type (Set is not directly Capable as parameter)\r\n box((a: WeakMap<object, string>) => a, {} as RevivableContext)\r\n // @ts-expect-error - non-Capable return type\r\n box(() => new WeakMap(), {} as RevivableContext)\r\n}\r\n","import type { Capable, StructurableTransferable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessageChannel, StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'readableStream' as const\r\n\r\nexport type PullContext = {\r\n type: 'pull' | 'cancel'\r\n}\r\n\r\nexport type BoxedReadableStream<T extends ReadableStream = ReadableStream> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: BoxedMessagePort\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is ReadableStream =>\r\n value instanceof ReadableStream\r\n\r\nexport const box = <T extends ReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): BoxedReadableStream<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel() as StrictMessageChannel<StructurableTransferable, StructurableTransferable>\r\n context.messagePorts.add(remotePort as MessagePort)\r\n\r\n const reader = value.getReader()\r\n\r\n ;(localPort as MessagePort).addEventListener('message', async ({ data }) => {\r\n const { type } = recursiveRevive(data, context) as PullContext\r\n if (type === 'pull') {\r\n const pullResult = reader.read()\r\n const boxedResult = recursiveBox(pullResult, context)\r\n ;(localPort as MessagePort).postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n } else {\r\n reader.cancel()\r\n localPort.close()\r\n }\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as MessagePort as StrictMessagePort<Record<string, StructurableTransferable>>, context)\r\n } as BoxedReadableStream<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context) as MessagePort\r\n context.messagePorts.add(port as MessagePort)\r\n port.start()\r\n\r\n return new ReadableStream({\r\n start(_controller) {},\r\n pull(controller) {\r\n return new Promise((resolve, reject) => {\r\n port.addEventListener('message', async ({ data }) => {\r\n const result = recursiveRevive(data, context) as Promise<ReadableStreamReadResult<any>>\r\n result\r\n .then(result => {\r\n if (result.done) controller.close()\r\n else controller.enqueue(result.value)\r\n resolve()\r\n })\r\n .catch(reject)\r\n }, { once: true })\r\n port.postMessage(recursiveBox({ type: 'pull' }, context))\r\n })\r\n },\r\n cancel() {\r\n port.postMessage(recursiveBox({ type: 'cancel' }, context))\r\n port.close()\r\n }\r\n }) as T[UnderlyingType]\r\n}\r\n\r\nconst typeCheck = () => {\r\n const stream = new ReadableStream<number>()\r\n const boxed = box(stream, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ReadableStream<number> = revived\r\n // @ts-expect-error - wrong stream type\r\n const wrongType: ReadableStream<string> = revived\r\n // @ts-expect-error - not a ReadableStream\r\n box('not a stream', {} as RevivableContext)\r\n}\r\n","import type { BoxBase, RevivableContext } from './utils'\r\nexport type { UnderlyingType } from './utils'\r\nimport type { DeepReplaceWithBox, DeepReplaceWithRevive, ReplaceWithBox, ReplaceWithRevive } from '../utils/replace'\r\n\r\nimport { Capable } from '../types'\r\nimport { isRevivableBox } from './utils'\r\nimport * as arrayBuffer from './array-buffer'\r\nimport * as date from './date'\r\nimport * as headers from './headers'\r\nimport * as error from './error'\r\nimport * as typedArray from './typed-array'\r\nimport * as promise from './promise'\r\nimport * as func from './function'\r\nimport * as messagePort from './message-port'\r\nimport * as readableStream from './readable-stream'\r\n\r\nexport type RevivableModule<T extends string = string, T2 = any, T3 extends BoxBase<T> = any> = {\r\n readonly type: T\r\n readonly isType: (value: unknown) => value is T2\r\n readonly box: ((value: T2, context: RevivableContext) => T3) | ((...args: any[]) => any)\r\n readonly revive: (value: T3, context: RevivableContext) => T2\r\n}\r\n\r\nexport const defaultRevivableModules = [\r\n arrayBuffer,\r\n date,\r\n headers,\r\n error,\r\n typedArray,\r\n promise,\r\n func,\r\n messagePort,\r\n readableStream\r\n] as const\r\n\r\nexport type DefaultRevivableModules = typeof defaultRevivableModules\r\n\r\nexport type DefaultRevivableModule = DefaultRevivableModules[number]\r\n\r\nexport const findModuleForValue = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const box = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveBox = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithBox<T, T2['revivableModules'][number]>\r\n\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveBox(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveBox(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithRevive<T, T2['revivableModules'][number]>\r\n const boxType =\r\n isRevivableBox(value, context)\r\n ? value.type\r\n : undefined\r\n const handledByModule = context.revivableModules.find(module => module.type === boxType)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveRevive = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithRevive<T, T2['revivableModules'][number]>\r\n\r\n // First check if the value is a revivable box and revive it\r\n if (isRevivableBox(value, context)) {\r\n const handledByModule = context.revivableModules.find(module => module.type === value.type)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n }\r\n\r\n // Then recurse into arrays and plain objects\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveRevive(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveRevive(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n","import type {\r\n Capable, ConnectionMessage,\r\n Message,\r\n MessageEventTarget,\r\n Transport,\r\n Uuid\r\n} from '../types'\r\nimport type { MessageChannelAllocator } from './allocator'\r\nimport type { PlatformCapabilities } from './capabilities'\r\nimport type { StrictMessagePort } from './message-channel'\r\n\r\nimport { makeMessageChannelAllocator } from './allocator'\r\nimport { DefaultRevivableModules, defaultRevivableModules, recursiveBox, recursiveRevive, RevivableModule } from '../revivables'\r\n\r\nexport type BidirectionalConnectionContext = {\r\n type: 'bidirectional'\r\n eventTarget: MessageEventTarget\r\n connection: BidirectionalConnection\r\n}\r\nexport type UnidirectionalEmittingConnectionContext = {\r\n type: 'unidirectional-emitting'\r\n connection: UnidirectionalEmittingConnection\r\n}\r\nexport type UnidirectionalReceivingConnectionContext = {\r\n type: 'unidirectional-receiving'\r\n eventTarget: MessageEventTarget\r\n connection: UnidirectionalReceivingConnection\r\n}\r\n\r\nexport type ConnectionContext =\r\n | BidirectionalConnectionContext\r\n | UnidirectionalEmittingConnectionContext\r\n | UnidirectionalReceivingConnectionContext\r\n\r\nexport type ConnectionRevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n}\r\n\r\nexport type BidirectionalConnection<T extends Capable = Capable> = {\r\n revivableContext: ConnectionRevivableContext\r\n close: () => void\r\n remoteValue: Promise<T>\r\n}\r\n\r\nexport const startBidirectionalConnection = <T extends Capable>(\r\n { transport, value, uuid, remoteUuid, platformCapabilities, eventTarget, send, close }:\r\n {\r\n transport: Transport\r\n value: Capable\r\n uuid: Uuid\r\n remoteUuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: MessageEventTarget\r\n send: (message: ConnectionMessage) => void\r\n close: () => void\r\n }\r\n) => {\r\n const revivableContext = {\r\n platformCapabilities,\r\n transport,\r\n remoteUuid,\r\n messagePorts: new Set(),\r\n messageChannels: makeMessageChannelAllocator(),\r\n sendMessage: send,\r\n eventTarget,\r\n revivableModules: defaultRevivableModules\r\n } satisfies ConnectionRevivableContext\r\n let initResolve: ((message: ConnectionMessage & { type: 'init' }) => void)\r\n const initMessage = new Promise<ConnectionMessage & { type: 'init' }>((resolve, reject) => {\r\n initResolve = resolve\r\n })\r\n\r\n eventTarget.addEventListener('message', ({ detail }) => {\r\n if (detail.type === 'init') {\r\n initResolve(detail)\r\n return\r\n } else if (detail.type === 'message') {\r\n const messageChannel = revivableContext.messageChannels.getOrAlloc(detail.portId)\r\n ;(messageChannel.port2 as MessagePort)?.postMessage(detail)\r\n }\r\n })\r\n\r\n send({\r\n type: 'init',\r\n remoteUuid,\r\n data: recursiveBox(value, revivableContext) as Capable\r\n })\r\n\r\n return {\r\n revivableContext,\r\n close: () => {\r\n },\r\n remoteValue:\r\n initMessage\r\n .then(initMessage => recursiveRevive(initMessage.data, revivableContext)) as Promise<T>\r\n } satisfies BidirectionalConnection<T>\r\n}\r\n\r\nexport type UnidirectionalEmittingConnection<T extends Capable = Capable> = {\r\n close: () => void\r\n remoteValueProxy: T\r\n}\r\n\r\nexport const startUnidirectionalEmittingConnection = <T extends Capable>(\r\n { value, uuid, platformCapabilities, send, close }:\r\n {\r\n value: Capable\r\n uuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n send: (message: Message) => void\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n },\r\n remoteValueProxy: new Proxy(\r\n new Function(),\r\n {\r\n apply: (target, thisArg, args) => {\r\n },\r\n get: (target, prop) => {\r\n }\r\n }\r\n ) as T\r\n }\r\n}\r\n\r\nexport type UnidirectionalReceivingConnection = {\r\n close: () => void\r\n}\r\n\r\nexport const startUnidirectionalReceivingConnection = (\r\n { uuid, remoteUuid, platformCapabilities, close }:\r\n {\r\n uuid: Uuid\r\n remoteUuid?: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: StrictMessagePort<Message>\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n }\r\n }\r\n}\r\n","var e=class extends EventTarget{dispatchTypedEvent(s,t){return super.dispatchEvent(t)}};export{e as TypedEventTarget};\n","import type {\r\n EmitTransport, Message,\r\n MessageContext, MessageVariant,\r\n Capable, Transport,\r\n MessageEventTarget,\r\n MessageEventMap\r\n} from './types'\r\nexport type { UnderlyingType } from './revivables/utils'\r\nimport type {\r\n PlatformCapabilities, ConnectionContext,\r\n BidirectionalConnectionContext\r\n} from './utils'\r\n\r\nimport { OSRA_DEFAULT_KEY, OSRA_KEY } from './types'\r\nexport { BoxBase } from './revivables/utils'\r\nimport {\r\n probePlatformCapabilities,\r\n registerOsraMessageListener,\r\n sendOsraMessage,\r\n startBidirectionalConnection,\r\n isReceiveTransport,\r\n isEmitTransport,\r\n startUnidirectionalEmittingConnection,\r\n getTransferableObjects,\r\n isJsonOnlyTransport,\r\n isCustomTransport\r\n} from './utils'\r\nimport { TypedEventTarget } from 'typescript-event-target'\r\n\r\nexport * from './types'\r\nexport * from './revivables'\r\n\r\n/**\r\n * Protocol mode:\r\n * - Bidirectional mode\r\n * - Unidirectional mode\r\n *\r\n * Transport modes:\r\n * - Capable mode\r\n * - Jsonable mode\r\n */\r\nexport const expose = async <T extends Capable>(\r\n value: Capable,\r\n {\r\n transport: _transport,\r\n name,\r\n remoteName,\r\n key = OSRA_DEFAULT_KEY,\r\n origin = '*',\r\n unregisterSignal,\r\n platformCapabilities: _platformCapabilities,\r\n transferAll,\r\n logger\r\n }: {\r\n transport: Transport\r\n name?: string\r\n remoteName?: string\r\n key?: string\r\n origin?: string\r\n unregisterSignal?: AbortSignal\r\n platformCapabilities?: PlatformCapabilities\r\n transferAll?: boolean\r\n logger?: {}\r\n }\r\n): Promise<T> => {\r\n const transport = {\r\n isJson:\r\n 'isJson' in _transport && _transport.isJson !== undefined\r\n ? _transport.isJson\r\n : isJsonOnlyTransport(_transport),\r\n ...(\r\n isCustomTransport(_transport)\r\n ? _transport\r\n : {\r\n emit: _transport,\r\n receive: _transport\r\n }\r\n )\r\n } satisfies Transport\r\n const platformCapabilities = _platformCapabilities ?? await probePlatformCapabilities()\r\n const connectionContexts = new Map<string, ConnectionContext>()\r\n\r\n let resolveRemoteValue: (connection: T) => void\r\n const remoteValuePromise = new Promise<T>((resolve) => {\r\n resolveRemoteValue = resolve\r\n })\r\n\r\n let uuid = globalThis.crypto.randomUUID()\r\n \r\n \r\n let aborted = false\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () => {\r\n aborted = true\r\n })\r\n }\r\n\r\n const sendMessage = (transport: EmitTransport, message: MessageVariant) => {\r\n if (aborted) return\r\n const transferables = getTransferableObjects(message)\r\n sendOsraMessage(\r\n transport,\r\n {\r\n [OSRA_KEY]: key,\r\n name,\r\n uuid,\r\n ...message\r\n },\r\n origin,\r\n transferables\r\n )\r\n }\r\n\r\n const listener = async (message: Message, messageContext: MessageContext) => {\r\n // means that our own message looped back on the channel\r\n if (message.uuid === uuid) return\r\n // Unidirectional receiving mode\r\n if (!isEmitTransport(transport)) {\r\n // Handle non bidirectional based messages here\r\n throw new Error('Unidirectional receiving mode not implemented')\r\n }\r\n // Bidirectional mode\r\n if (message.type === 'announce') {\r\n if (!message.remoteUuid) {\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n return\r\n }\r\n if (message.remoteUuid !== uuid) return\r\n // todo: re-add uuid collision handling\r\n if (connectionContexts.has(message.uuid)) {\r\n return\r\n }\r\n // Send announce back so the other side can also create a connection\r\n // (in case they missed our initial announce due to timing)\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n const eventTarget = new TypedEventTarget<MessageEventMap>()\r\n const connectionContext = {\r\n type: 'bidirectional',\r\n eventTarget,\r\n connection:\r\n startBidirectionalConnection({\r\n transport,\r\n value,\r\n uuid,\r\n remoteUuid: message.uuid,\r\n platformCapabilities,\r\n eventTarget,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => void connectionContexts.delete(message.uuid)\r\n })\r\n } satisfies BidirectionalConnectionContext\r\n connectionContexts.set(message.uuid, connectionContext)\r\n connectionContext.connection.remoteValue.then((remoteValue) =>\r\n resolveRemoteValue(remoteValue as T)\r\n )\r\n } else if (message.type === 'reject-uuid-taken') {\r\n if (message.remoteUuid !== uuid) return\r\n uuid = globalThis.crypto.randomUUID()\r\n sendMessage(transport, { type: 'announce' })\r\n } else if (message.type === 'close') {\r\n if (message.remoteUuid !== uuid) return\r\n const connectionContext = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connectionContext) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n connectionContext.connection.close()\r\n connectionContexts.delete(message.uuid)\r\n } else { // \"init\" | \"message\" | \"message-port-close\"\r\n if (message.remoteUuid !== uuid) return\r\n const connection = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connection) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n if (connection.type !== 'unidirectional-emitting') {\r\n connection.eventTarget.dispatchTypedEvent(\r\n 'message',\r\n new CustomEvent('message', { detail: message })\r\n )\r\n }\r\n }\r\n }\r\n\r\n if (isReceiveTransport(transport)) {\r\n registerOsraMessageListener({\r\n listener,\r\n transport,\r\n remoteName,\r\n key,\r\n unregisterSignal\r\n })\r\n }\r\n\r\n if (isEmitTransport(transport)) {\r\n sendMessage(transport, { type: 'announce' })\r\n }\r\n\r\n // Unidirectional emitting mode\r\n if (isEmitTransport(transport) && !isReceiveTransport(transport)) {\r\n const { remoteValueProxy } = startUnidirectionalEmittingConnection<T>({\r\n value,\r\n uuid,\r\n platformCapabilities,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => connectionContexts.delete(uuid)\r\n })\r\n return remoteValueProxy\r\n }\r\n\r\n return remoteValuePromise\r\n}\r\n"],"names":["OSRA_KEY","OSRA_DEFAULT_KEY","OSRA_BOX","BoxBase","isRevivableBox","value","_context","makeMessageChannelAllocator","channels","result","uuid","messagePorts","allocatedMessageChannel","messageChannel","existingChannel","checkOsraMessageKey","message","key","isOsraMessage","registerOsraMessageListener","listener","transport","remoteName","unregisterSignal","registerListenerOnReceiveTransport","receiveTransport","isWebExtensionPort","isWebExtensionOnConnect","isWebExtensionOnMessage","listenOnWebExtOnMessage","onMessage","port","_listener","sender","messageListener","event","isCustomTransport","sendOsraMessage","origin","transferables","sendToEmitTransport","emitTransport","isWindow","isWebSocket","isSharedWorker","isServiceWorkerContainer","isWorker","isDedicatedWorker","isMessagePort","isClonable","isTransferable","connectPort","w","isEmitJsonOnlyTransport","isReceiveJsonOnlyTransport","isJsonOnlyTransport","isEmitTransport","isCustomEmitTransport","isReceiveTransport","isCustomReceiveTransport","getTransferableObjects","recurse","probePlatformCapabilityUtil","transfer","port1","port2","resolve","probeMessagePortTransfer","probeArrayBufferClone","buffer","probeArrayBufferTransfer","probeTransferableStream","stream","controller","probePlatformCapabilities","messagePort","arrayBuffer","transferable","transferableStream","type","isType","box","revive","typedArrayConstructors","typedArrayToType","typedArrayTypeToTypedArrayConstructor","typedArray","constructor","context","TypedArrayConstructor","messagePortRegistry","info","isAlreadyBoxed","messagePortListener","data","recursiveBox","portId","messagePortRef","eventTargetListener","internalPortListener","userPort","internalPort","userPortRef","performCleanup","port1Listener","revivedData","recursiveRevive","allocatedChannel","promise","localPort","remotePort","sendResult","boxedResult","error","boxMessagePort","reviveMessagePort","reject","functionRegistry","cleanup","returnValuePort","args","func","returnValueLocalPort","returnValueRemotePort","callContext","reader","pullResult","_controller","defaultRevivableModules","date","headers","readableStream","findModuleForValue","handledByModule","module","boxType","startBidirectionalConnection","remoteUuid","platformCapabilities","eventTarget","send","close","revivableContext","initResolve","initMessage","detail","startUnidirectionalEmittingConnection","target","thisArg","prop","e","s","expose","_transport","name","_platformCapabilities","transferAll","logger","connectionContexts","resolveRemoteValue","remoteValuePromise","aborted","sendMessage","messageContext","TypedEventTarget","connectionContext","remoteValue","connection","remoteValueProxy"],"mappings":"AAKO,MAAMA,IAAW,gBACXC,KAAmB,wBACnBC,IAAW,gBCEXC,IAAU;AAAA,EACrB,CAACD,CAAQ,GAAG;AAAA,EACZ,MAAM;AACR,GA2BaE,IAAiB,CAA6BC,GAAYC,MACrED,KACG,OAAOA,KAAU,YACjBH,KAAYG,KACZA,EAAMH,CAAQ,MAAM,aCKZK,KAA8B,MAAM;AAC/C,QAAMC,wBAAe,IAAA,GAEfC,IAAS;AAAA,IACb,eAAe,MAAM;AACnB,UAAIC,IAAa,WAAW,OAAO,WAAA;AACnC,aAAOF,EAAS,IAAIE,CAAI;AACtB,QAAAA,IAAO,WAAW,OAAO,WAAA;AAE3B,aAAOA;AAAA,IACT;AAAA,IACA,KAAK,CAACA,GAAYC,MAA0E;AAC1F,MAAAH,EAAS,IAAIE,GAAM,EAAE,MAAAA,GAAM,GAAGC,GAAc;AAAA,IAC9C;AAAA,IACA,OAAO,CACLD,IAAyBD,EAAO,cAAA,GAChCE,MACG;AACH,UAAIA,GAAc;AAChB,cAAMC,IAA0B,EAAE,MAAAF,GAAM,GAAGC,EAAA;AAC3C,eAAAH,EAAS,IAAIE,GAAME,CAAuB,GACnCA;AAAAA,MACT;AACA,YAAMC,IAAiB,IAAI,eAAA,GACrBD,IAA0B;AAAA,QAC9B,MAAAF;AAAA,QACA,OAAOG,EAAe;AAAA,QACtB,OAAOA,EAAe;AAAA,MAAA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AyC;AAAA,MACpE,OAAA7I;AAAA,MACA,MAAAK;AAAA,MACA,sBAAAgI;AAAA,MACA,MAAM,CAAC1H,MAA4BkJ,EAAY7I,GAAWL,CAAO;AAAA,MACjE,OAAO,MAAM8I,EAAmB,OAAOpJ,CAAI;AAAA,IAAA,CAC5C;AACD,WAAO8J;AAAA,EACT;AAEA,SAAOR;AACT;","x_google_ignoreList":[18]}
|
|
1
|
+
{"version":3,"file":"index.js","sources":["../src/types.ts","../src/revivables/utils.ts","../src/utils/allocator.ts","../src/utils/platform.ts","../src/utils/type-guards.ts","../src/utils/transferable.ts","../src/utils/capabilities.ts","../src/revivables/array-buffer.ts","../src/revivables/date.ts","../src/revivables/headers.ts","../src/revivables/error.ts","../src/revivables/typed-array.ts","../src/revivables/message-port.ts","../src/revivables/promise.ts","../src/revivables/function.ts","../src/revivables/readable-stream.ts","../src/revivables/index.ts","../src/utils/connection.ts","../node_modules/typescript-event-target/dist/index.mjs","../src/index.ts"],"sourcesContent":["import { TypedEventTarget } from 'typescript-event-target'\r\nimport type { TypedArray, WebExtOnConnect, WebExtOnMessage, WebExtPort, WebExtRuntime, WebExtSender } from './utils/type-guards'\r\nimport { DefaultRevivableModule, DefaultRevivableModules, RevivableModule } from './revivables'\r\nimport { InferRevivables } from './revivables/utils'\r\n\r\nexport const OSRA_KEY = '__OSRA_KEY__' as const\r\nexport const OSRA_DEFAULT_KEY = '__OSRA_DEFAULT_KEY__' as const\r\nexport const OSRA_BOX = '__OSRA_BOX__' as const\r\n\r\nexport type Uuid = `${string}-${string}-${string}-${string}-${string}`\r\n\r\nexport type Jsonable =\r\n | boolean\r\n | null\r\n | number\r\n | string\r\n | { [key: string]: Jsonable }\r\n | Array<Jsonable>\r\n\r\nexport type Structurable =\r\n | Jsonable\r\n /** not really structureable but here for convenience */\r\n | void\r\n | undefined\r\n | BigInt\r\n | Date\r\n | RegExp\r\n | Blob\r\n | File\r\n | FileList\r\n | ArrayBuffer\r\n | ArrayBufferView\r\n | ImageBitmap\r\n | ImageData\r\n | { [key: string]: Structurable }\r\n | Array<Structurable>\r\n | Map<Structurable, Structurable>\r\n | Set<Structurable>\r\n \r\nexport type StructurableTransferable =\r\n | Structurable\r\n | Transferable\r\n | { [key: string]: StructurableTransferable }\r\n | Array<StructurableTransferable>\r\n | Map<StructurableTransferable, StructurableTransferable>\r\n | Set<StructurableTransferable>\r\n\r\nexport type Capable<TModules extends readonly RevivableModule[] = DefaultRevivableModules> =\r\n | StructurableTransferable\r\n | InferRevivables<TModules>\r\n | { [key: string]: Capable }\r\n | Array<Capable>\r\n | Map<Capable, Capable>\r\n | Set<Capable>\r\n\r\nexport type MessageBase = {\r\n [OSRA_KEY]: string\r\n /** UUID of the client that sent the message */\r\n uuid: Uuid\r\n name?: string\r\n}\r\n\r\nexport type ProtocolMessage =\r\n | {\r\n type: 'announce'\r\n /** Only set when acknowledging a remote announcement */\r\n remoteUuid?: Uuid\r\n }\r\n | {\r\n /** uuid already taken, try announcing with another one */\r\n type: 'reject-uuid-taken'\r\n remoteUuid: Uuid\r\n }\r\n | {\r\n type: 'close'\r\n remoteUuid: Uuid\r\n }\r\n\r\nexport type BidirectionalConnectionMessage =\r\n | {\r\n type: 'init'\r\n remoteUuid: Uuid\r\n data: Capable\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n /** uuid of the messagePort that the message was sent through */\r\n portId: Uuid\r\n }\r\n /** message not needed if transferring MessagePort is supported */\r\n | {\r\n type: 'message-port-close'\r\n remoteUuid: Uuid\r\n /** uuid of the messagePort that closed */\r\n portId: string\r\n }\r\n\r\nexport type UnidirectionalConnectionMessage = {\r\n type: 'message'\r\n remoteUuid: Uuid\r\n data: Capable\r\n portId: Uuid\r\n}\r\n\r\nexport type ConnectionMessage =\r\n | BidirectionalConnectionMessage\r\n | UnidirectionalConnectionMessage\r\n\r\nexport type MessageVariant =\r\n | ProtocolMessage\r\n | ConnectionMessage\r\n\r\nexport type Message =\r\n | MessageBase\r\n & MessageVariant\r\n\r\nexport type MessageContext = {\r\n port?: MessagePort | WebExtPort // WebExtension\r\n sender?: WebExtSender // WebExtension\r\n receiveTransport?: ReceivePlatformTransport\r\n source?: MessageEventSource | null // Window, Worker, WebSocket, ect...\r\n}\r\n\r\nexport type MessageEventMap = {\r\n message: CustomEvent<Message>\r\n}\r\nexport type MessageEventTarget = TypedEventTarget<MessageEventMap>\r\n\r\nexport type CustomTransport =\r\n { isJson?: boolean }\r\n & (\r\n | {\r\n receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void)\r\n emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void)\r\n }\r\n | { receive: ReceivePlatformTransport | ((listener: (event: Message, messageContext: MessageContext) => void) => void) }\r\n | { emit: EmitPlatformTransport | ((message: Message, transferables?: Transferable[]) => void) }\r\n )\r\n\r\nexport type CustomEmitTransport = Extract<CustomTransport, { emit: any }>\r\nexport type CustomReceiveTransport = Extract<CustomTransport, { receive: any }>\r\n\r\nexport type EmitJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n\r\nexport type ReceiveJsonPlatformTransport =\r\n | WebSocket\r\n | WebExtPort\r\n | WebExtOnConnect\r\n | WebExtOnMessage\r\n\r\nexport type JsonPlatformTransport =\r\n | { isJson: true }\r\n | EmitJsonPlatformTransport\r\n | ReceiveJsonPlatformTransport\r\n\r\nexport type EmitPlatformTransport =\r\n | EmitJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type ReceivePlatformTransport =\r\n | ReceiveJsonPlatformTransport\r\n | Window\r\n | ServiceWorker\r\n | Worker\r\n | SharedWorker\r\n | MessagePort\r\n\r\nexport type PlatformTransport =\r\n | EmitPlatformTransport\r\n | ReceivePlatformTransport\r\n\r\nexport type EmitTransport = EmitPlatformTransport & Extract<CustomTransport, { emit: any }>\r\nexport type ReceiveTransport = ReceivePlatformTransport & Extract<CustomTransport, { receive: any }>\r\n\r\nexport type Transport =\r\n | PlatformTransport\r\n | CustomTransport\r\n","import type { DefaultRevivableModules, RevivableModule } from '.'\r\nimport type { ConnectionMessage, MessageEventTarget, Transport, Uuid } from '../types'\r\nimport type { MessageChannelAllocator, PlatformCapabilities } from '../utils'\r\n\r\nimport { OSRA_BOX } from '../types'\r\n\r\nexport declare const UnderlyingType: unique symbol\r\nexport type UnderlyingType = typeof UnderlyingType\r\n\r\nexport const BoxBase = {\r\n [OSRA_BOX]: 'revivable',\r\n type: '' as string\r\n} as const\r\n\r\nexport type BoxBase<T extends string = string> =\r\n & typeof BoxBase\r\n & { type: T }\r\n\r\nexport type RevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n}\r\n\r\nexport type ExtractModule<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractType<T> = T extends { isType: (value: unknown) => value is infer S } ? S : never\r\nexport type ExtractBoxInput<T> = T extends { box: (value: infer S) => value is any } ? S : never\r\nexport type ExtractReviveInput<T> = T extends { revive: (value: infer S) => value is any } ? S : never\r\nexport type ExtractBox<T> = T extends { box: (...args: any[]) => infer B } ? B : never\r\nexport type InferRevivables<TModules extends readonly unknown[]> =\r\n ExtractType<TModules[number]>\r\nexport type InferRevivableBox<TModules extends readonly unknown[]> =\r\n ExtractBox<TModules[number]>\r\n\r\nexport const isRevivableBox = <T extends RevivableContext>(value: any, _context: T): value is InferRevivableBox<T['revivableModules']> =>\r\n value\r\n && typeof value === 'object'\r\n && OSRA_BOX in value\r\n && value[OSRA_BOX] === 'revivable'\r\n","import type { StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessageChannel, StrictMessagePort } from './message-channel'\r\n\r\nexport const makeAllocator = <T>() => {\r\n const channels = new Map<string, T>()\r\n\r\n const alloc = (value: T): string => {\r\n let uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n channels.set(uuid, value)\r\n return uuid\r\n }\r\n\r\n const has = (uuid: string) => channels.has(uuid)\r\n const get = (uuid: string) => channels.get(uuid)\r\n\r\n const free = (uuid: string) => {\r\n channels.delete(uuid)\r\n }\r\n\r\n const set = (uuid: string, value: T) => {\r\n channels.set(uuid, value)\r\n }\r\n\r\n return {\r\n alloc,\r\n has,\r\n get,\r\n free,\r\n set\r\n }\r\n}\r\n\r\nexport type Allocator<T> = ReturnType<typeof makeAllocator<T>>\r\n\r\ntype AllocatedMessageChannel<\r\n T extends StructurableTransferable = StructurableTransferable,\r\n T2 extends StructurableTransferable = StructurableTransferable\r\n> = {\r\n uuid: Uuid\r\n /** Local port */\r\n port1: StrictMessagePort<T>\r\n /** Remote port that gets transferred, might be undefined if a remote context created the channel */\r\n port2?: StrictMessagePort<T2>\r\n}\r\n\r\nexport const makeMessageChannelAllocator = () => {\r\n const channels = new Map<string, AllocatedMessageChannel>()\r\n\r\n const result = {\r\n getUniqueUuid: () => {\r\n let uuid: Uuid = globalThis.crypto.randomUUID()\r\n while (channels.has(uuid)) {\r\n uuid = globalThis.crypto.randomUUID()\r\n }\r\n return uuid\r\n },\r\n set: (uuid: Uuid, messagePorts: { port1: StrictMessagePort, port2?: StrictMessagePort }) => {\r\n channels.set(uuid, { uuid, ...messagePorts })\r\n },\r\n alloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n if (messagePorts) {\r\n const allocatedMessageChannel = { uuid, ...messagePorts } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n }\r\n const messageChannel = new MessageChannel() as StrictMessageChannel\r\n const allocatedMessageChannel = {\r\n uuid,\r\n port1: messageChannel.port1,\r\n port2: messageChannel.port2\r\n } satisfies AllocatedMessageChannel\r\n channels.set(uuid, allocatedMessageChannel)\r\n return allocatedMessageChannel\r\n },\r\n has: (uuid: string) => channels.has(uuid),\r\n get: (uuid: string) => channels.get(uuid),\r\n free: (uuid: string) => channels.delete(uuid),\r\n getOrAlloc: (\r\n uuid: Uuid | undefined = result.getUniqueUuid(),\r\n messagePorts?: { port1: StrictMessagePort, port2?: StrictMessagePort }\r\n ) => {\r\n const existingChannel = result.get(uuid)\r\n if (existingChannel) return existingChannel!\r\n return result.alloc(uuid, messagePorts)\r\n }\r\n }\r\n return result\r\n}\r\n\r\nexport type MessageChannelAllocator = ReturnType<typeof makeMessageChannelAllocator>\r\n","import type {\r\n CustomTransport, EmitTransport,\r\n Message, MessageContext,\r\n ReceiveTransport\r\n} from '../types'\r\nimport type { WebExtOnMessage, WebExtPort, WebExtSender } from './type-guards'\r\n\r\nimport { OSRA_KEY } from '../types'\r\nimport {\r\n isOsraMessage, isCustomTransport,\r\n isWebExtensionOnConnect, isWebExtensionOnMessage,\r\n isWebExtensionPort, isWebSocket, isWindow, isSharedWorker\r\n} from './type-guards'\r\n\r\nexport const getWebExtensionGlobal = () => globalThis.browser ?? globalThis.chrome\r\nexport const getWebExtensionRuntime = () => getWebExtensionGlobal().runtime\r\n\r\nexport const checkOsraMessageKey = (message: any, key: string): message is Message =>\r\n isOsraMessage(message)\r\n && message[OSRA_KEY] === key\r\n\r\nexport const registerOsraMessageListener = (\r\n { listener, transport, remoteName, key = OSRA_KEY, unregisterSignal }:\r\n {\r\n listener: (message: Message, messageContext: MessageContext) => Promise<void>\r\n transport: ReceiveTransport\r\n remoteName?: string\r\n key?: string\r\n unregisterSignal?: AbortSignal\r\n }\r\n) => {\r\n const registerListenerOnReceiveTransport = (receiveTransport: Extract<CustomTransport, { receive: any }>['receive']) => {\r\n // Custom function handler\r\n if (typeof receiveTransport === 'function') {\r\n receiveTransport(listener)\r\n // WebExtension handler\r\n } else if (\r\n isWebExtensionPort(receiveTransport)\r\n || isWebExtensionOnConnect(receiveTransport)\r\n || isWebExtensionOnMessage(receiveTransport)\r\n ) {\r\n const listenOnWebExtOnMessage = (onMessage: WebExtOnMessage, port?: WebExtPort) => {\r\n const _listener = (message: object, sender?: WebExtSender) => {\r\n if (!checkOsraMessageKey(message, key)) return\r\n if (remoteName && message.name !== remoteName) return\r\n listener(message, { port, sender })\r\n }\r\n onMessage.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n onMessage.removeListener(_listener)\r\n )\r\n }\r\n }\r\n\r\n // WebExtOnConnect\r\n if (isWebExtensionOnConnect(receiveTransport)) {\r\n const _listener = (port: WebExtPort) => {\r\n listenOnWebExtOnMessage(port.onMessage as WebExtOnMessage, port)\r\n }\r\n receiveTransport.addListener(_listener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeListener(_listener)\r\n )\r\n }\r\n // WebExtOnMessage\r\n } else if (isWebExtensionOnMessage(receiveTransport)) {\r\n listenOnWebExtOnMessage(receiveTransport)\r\n } else { // WebExtPort\r\n listenOnWebExtOnMessage(receiveTransport.onMessage as WebExtOnMessage)\r\n }\r\n } else { // Window, Worker, WebSocket, ect...\r\n const messageListener = (event: MessageEvent<Message>) => {\r\n if (!checkOsraMessageKey(event.data, key)) return\r\n if (remoteName && event.data.name !== remoteName) return\r\n listener(event.data, { receiveTransport, source: event.source })\r\n }\r\n receiveTransport.addEventListener('message', messageListener as EventListener)\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () =>\r\n receiveTransport.removeEventListener('message', messageListener as EventListener)\r\n )\r\n }\r\n }\r\n }\r\n if (isCustomTransport(transport)) {\r\n registerListenerOnReceiveTransport(transport.receive)\r\n } else {\r\n registerListenerOnReceiveTransport(transport)\r\n }\r\n}\r\n\r\nexport const sendOsraMessage = (\r\n transport: EmitTransport,\r\n message: Message,\r\n origin = '*',\r\n transferables: Transferable[] = []\r\n) => {\r\n const sendToEmitTransport = (emitTransport: Extract<EmitTransport, { emit: any }>['emit']) => {\r\n if (typeof emitTransport === 'function') {\r\n emitTransport(message, transferables)\r\n } else if (isWebExtensionPort(emitTransport)) {\r\n emitTransport.postMessage(message)\r\n } else if (isWindow(emitTransport)) {\r\n emitTransport.postMessage(message, origin, transferables)\r\n } else if (isWebSocket(emitTransport)) {\r\n emitTransport.send(JSON.stringify(message))\r\n } else if (isSharedWorker(emitTransport)) {\r\n emitTransport.port.postMessage(message, transferables)\r\n } else { // MessagePort | ServiceWorker | Worker\r\n emitTransport.postMessage(message, transferables)\r\n }\r\n }\r\n\r\n if (isCustomTransport(transport)) {\r\n sendToEmitTransport(transport.emit)\r\n } else {\r\n sendToEmitTransport(transport)\r\n }\r\n}\r\n","import type { Runtime } from 'webextension-polyfill'\r\nimport type {\r\n CustomEmitTransport, CustomReceiveTransport,\r\n CustomTransport, EmitJsonPlatformTransport,\r\n EmitTransport, JsonPlatformTransport,\r\n Message, ReceiveJsonPlatformTransport,\r\n ReceiveTransport, Transport\r\n} from '../types'\r\n\r\nimport { OSRA_BOX, OSRA_KEY } from '../types'\r\nimport { getWebExtensionRuntime } from './platform'\r\n\r\nexport type TransferBox<T extends Transferable = Transferable> = {\r\n [OSRA_BOX]: 'transferable'\r\n value: T\r\n}\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypeArrayType = ReturnType<typeof typedArrayToType>\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypeArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isTypedArray = (value: any): value is TypedArray => typedArrayConstructors.some(typedArray => value instanceof typedArray)\r\nexport const isWebSocket = (value: any) => value instanceof WebSocket\r\nexport const isServiceWorkerContainer = (value: any): value is ServiceWorkerContainer => globalThis.ServiceWorkerContainer && value instanceof ServiceWorkerContainer\r\nexport const isWorker = (value: any): value is Worker => globalThis.Worker && value instanceof Worker\r\n// @ts-expect-error\r\nexport const isDedicatedWorker = (value: any): value is DedicatedWorkerGlobalScope => globalThis.DedicatedWorkerGlobalScope && value instanceof DedicatedWorkerGlobalScope\r\nexport const isSharedWorker = (value: any): value is SharedWorker => globalThis.SharedWorker && value instanceof SharedWorker\r\nexport const isMessagePort = (value: any) => value instanceof MessagePort\r\nexport const isPromise = (value: any) => value instanceof Promise\r\nexport const isFunction = (value: any): value is Function => typeof value === 'function'\r\nexport const isArrayBuffer = (value: any) => value instanceof ArrayBuffer\r\nexport const isReadableStream = (value: any) => value instanceof ReadableStream\r\nexport const isDate = (value: any) => value instanceof Date\r\nexport const isError = (value: any) => value instanceof Error\r\n\r\nexport const isAlwaysBox = (value: any): value is Function | Promise<any> | Date | Error =>\r\n isFunction(value)\r\n || isPromise(value)\r\n || isTypedArray(value)\r\n || isDate(value)\r\n || isError(value)\r\n\r\nexport const isOsraMessage = (value: any): value is Message =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as Message)[OSRA_KEY]\r\n )\r\n\r\nexport const isClonable = (value: any) =>\r\n globalThis.SharedArrayBuffer && value instanceof globalThis.SharedArrayBuffer ? true\r\n : false\r\n\r\nexport const isTransferable = (value: any): value is Transferable =>\r\n globalThis.ArrayBuffer && value instanceof globalThis.ArrayBuffer ? true\r\n : globalThis.MessagePort && value instanceof globalThis.MessagePort ? true\r\n : globalThis.ReadableStream && value instanceof globalThis.ReadableStream ? true\r\n : globalThis.WritableStream && value instanceof globalThis.WritableStream ? true\r\n : globalThis.TransformStream && value instanceof globalThis.TransformStream ? true\r\n : globalThis.ImageBitmap && value instanceof globalThis.ImageBitmap ? true\r\n : false\r\n\r\nexport const isTransferBox = (value: any): value is TransferBox<any> =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n && (value as TransferBox<Transferable>)[OSRA_BOX] === 'transferable'\r\n )\r\n\r\nexport type WebExtRuntime = typeof browser.runtime\r\nexport const isWebExtensionRuntime = (value: any): value is WebExtRuntime => {\r\n const runtime = getWebExtensionRuntime()\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && isWebExtensionOnConnect(runtime.onConnect)\r\n && runtime.id\r\n )\r\n}\r\n\r\nexport type WebExtPort = ReturnType<WebExtRuntime['connect']> | Runtime.Port\r\nexport const isWebExtensionPort = (value: any, connectPort: boolean = false): value is WebExtPort => {\r\n return Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && ('name' in (value as WebExtPort))\r\n && ('disconnect' in (value as WebExtPort))\r\n && ('postMessage' in (value as WebExtPort))\r\n && (\r\n connectPort\r\n // these properties are only present on WebExtPort that were created through runtime.connect()\r\n ? (\r\n ('sender' in (value as WebExtPort))\r\n && ('onMessage' in (value as WebExtPort))\r\n && ('onDisconnect' in (value as WebExtPort))\r\n )\r\n : true\r\n )\r\n )\r\n}\r\n\r\nexport type WebExtSender = NonNullable<WebExtPort['sender']>\r\n\r\nexport type WebExtOnConnect = WebExtRuntime['onConnect']\r\nexport const isWebExtensionOnConnect = (value: any): value is WebExtOnConnect =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnConnect).addListener\r\n && (value as WebExtOnConnect).hasListener\r\n && (value as WebExtOnConnect).removeListener\r\n )\r\n\r\nexport type WebExtOnMessage = WebExtRuntime['onMessage']\r\nexport const isWebExtensionOnMessage = (value: any): value is WebExtOnMessage =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (value as WebExtOnMessage).addListener\r\n && (value as WebExtOnMessage).hasListener\r\n && (value as WebExtOnMessage).removeListener\r\n )\r\n\r\nexport const isWindow = (value: unknown): value is Window => {\r\n if (!value || typeof value !== 'object') return false\r\n\r\n try {\r\n return (value as Window).window === value\r\n } catch {\r\n try {\r\n const w = value as Window\r\n return typeof w.closed === 'boolean' && typeof w.close === 'function'\r\n } catch {\r\n return false\r\n }\r\n }\r\n }\r\n\r\nexport type IsEmitJsonOnlyTransport<T extends Transport> = T extends EmitJsonPlatformTransport ? true : false\r\nexport const isEmitJsonOnlyTransport = (value: any): value is EmitJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n\r\nexport type IsReceiveJsonOnlyTransport<T extends Transport> = T extends ReceiveJsonPlatformTransport ? true : false\r\nexport const isReceiveJsonOnlyTransport = (value: any): value is ReceiveJsonPlatformTransport =>\r\n isWebSocket(value)\r\n || isWebExtensionPort(value)\r\n || isWebExtensionOnConnect(value)\r\n || isWebExtensionOnMessage(value)\r\n\r\nexport type IsJsonOnlyTransport<T extends Transport> = T extends JsonPlatformTransport ? true : false\r\nexport const isJsonOnlyTransport = (value: Transport): value is Extract<Transport, JsonPlatformTransport> =>\r\n ('isJson' in value && value.isJson === true)\r\n || isEmitJsonOnlyTransport(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n\r\nexport type IsEmitTransport<T extends Transport> = T extends EmitTransport ? true : false\r\nexport const isEmitTransport = (value: any): value is EmitTransport =>\r\n isWindow(value)\r\n || isEmitJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomEmitTransport(value)\r\n\r\nexport function assertEmitTransport (transport: Transport): asserts transport is EmitTransport {\r\n if (!isEmitTransport(transport)) throw new Error('Transport is not emitable')\r\n}\r\n\r\n\r\nexport type IsReceiveTransport<T extends Transport> = T extends ReceiveTransport ? true : false\r\nexport const isReceiveTransport = (value: any): value is ReceiveTransport =>\r\n isWindow(value)\r\n || isReceiveJsonOnlyTransport(value)\r\n || isServiceWorkerContainer(value)\r\n || isWorker(value)\r\n || isDedicatedWorker(value)\r\n || isSharedWorker(value)\r\n || isMessagePort(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport function assertReceiveTransport (transport: Transport): asserts transport is ReceiveTransport {\r\n if (!isReceiveTransport(transport)) throw new Error('Transport is not receiveable')\r\n}\r\n\r\nexport const isCustomEmitTransport = (value: any): value is CustomEmitTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'emit' in value\r\n && (\r\n isEmitTransport(value.emit)\r\n || typeof value.emit === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport const isCustomReceiveTransport = (value: any): value is CustomReceiveTransport =>\r\n Boolean(\r\n value\r\n && typeof value === 'object'\r\n /**\r\n * This is needed to prevent throwing an error when the value is a cross origin iframe window object.\r\n * e.g SecurityError: Blocked a frame with origin \"http://localhost:8080\" from accessing a cross-origin frame.\r\n */\r\n && !(globalThis.Window && value instanceof globalThis.Window)\r\n && (\r\n 'receive' in value\r\n && (\r\n isReceiveTransport(value.receive)\r\n || typeof value.receive === 'function'\r\n )\r\n )\r\n )\r\n\r\nexport type IsCustomTransport<T extends Transport> = T extends CustomTransport ? true : false\r\nexport const isCustomTransport = (value: any): value is CustomTransport =>\r\n isCustomEmitTransport(value)\r\n || isCustomReceiveTransport(value)\r\n\r\nexport const isTransport = (value: any): value is Transport =>\r\n isEmitTransport(value)\r\n || isReceiveTransport(value)\r\n || isCustomTransport(value)\r\n || isJsonOnlyTransport(value)\r\n","import type { Capable } from '../types'\r\nimport type { TransferBox } from './type-guards'\r\n\r\nimport { OSRA_BOX } from '../types'\r\nimport { deepReplace } from './replace'\r\nimport { isClonable, isTransferable, isTransferBox } from './type-guards'\r\n\r\nexport const getTransferableObjects = (value: any): Transferable[] => {\r\n const transferables: Transferable[] = []\r\n const recurse = (value: any): any =>\r\n isClonable(value) ? undefined\r\n : isTransferable(value) ? transferables.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferables\r\n}\r\n\r\nexport const getTransferBoxes = (value: any): TransferBox<Transferable>[] => {\r\n const transferBoxes: TransferBox<any>[] = []\r\n const recurse = (value: any): any =>\r\n isTransferBox(value) ? transferBoxes.push(value)\r\n : Array.isArray(value) ? value.map(recurse)\r\n : value && typeof value === 'object' ? Object.values(value).map(recurse)\r\n : undefined\r\n\r\n recurse(value)\r\n return transferBoxes\r\n}\r\n\r\n/** This box tells the protocol that the value should be copied instead of transfered */\r\nexport const transfer = <T extends Transferable>(value: T) => ({\r\n [OSRA_BOX]: 'transferable',\r\n value\r\n}) as TransferBox<T>\r\n\r\nexport const recursiveTransfer = <T extends Capable>(value: T) =>\r\n deepReplace(\r\n value,\r\n isTransferable,\r\n (value) => transfer(value)\r\n )\r\n","import { getTransferableObjects } from './transferable'\r\n\r\nexport type PlatformCapabilities = {\r\n jsonOnly: boolean\r\n messagePort: boolean\r\n arrayBuffer: boolean\r\n transferable: boolean\r\n transferableStream: boolean\r\n}\r\n\r\nconst probePlatformCapabilityUtil = <T>(value: T, transfer = false): Promise<T> => {\r\n const { port1, port2 } = new MessageChannel()\r\n const result = new Promise<T>(resolve =>\r\n port1.addEventListener('message', message =>\r\n resolve(message.data)\r\n )\r\n )\r\n port1.start()\r\n port2.postMessage(value, transfer ? getTransferableObjects(value) : [])\r\n return result\r\n}\r\n\r\nconst probeMessagePortTransfer = async () => {\r\n const { port1 } = new MessageChannel()\r\n const port = await probePlatformCapabilityUtil(port1, true)\r\n return port instanceof MessagePort\r\n}\r\n\r\nconst probeArrayBufferClone = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeArrayBufferTransfer = async () => {\r\n const buffer = new ArrayBuffer(1)\r\n const arrayBuffer = await probePlatformCapabilityUtil(buffer, true)\r\n return arrayBuffer instanceof ArrayBuffer\r\n}\r\n\r\nconst probeTransferableStream = async () => {\r\n const stream = new ReadableStream({\r\n start(controller) {\r\n controller.enqueue(new Uint8Array(1))\r\n controller.close()\r\n }\r\n })\r\n const transferableStream = await probePlatformCapabilityUtil(stream, true)\r\n return transferableStream instanceof ReadableStream\r\n}\r\n\r\nexport const probePlatformCapabilities = async (): Promise<PlatformCapabilities> => {\r\n const [\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n ] = await Promise.all([\r\n probeMessagePortTransfer().catch(() => false),\r\n probeArrayBufferClone().catch(() => false),\r\n probeArrayBufferTransfer().catch(() => false),\r\n probeTransferableStream().catch(() => false)\r\n ])\r\n return {\r\n jsonOnly:\r\n !messagePort\r\n && !arrayBuffer\r\n && !transferable\r\n && !transferableStream,\r\n messagePort,\r\n arrayBuffer,\r\n transferable,\r\n transferableStream,\r\n }\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'arrayBuffer' as const\r\n\r\nexport const isType = (value: unknown): value is ArrayBuffer =>\r\n value instanceof ArrayBuffer\r\n\r\nexport const box = <T extends ArrayBuffer, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ...(\r\n isJsonOnlyTransport(_context.transport)\r\n ? { base64Buffer: new Uint8Array(value).toBase64() }\r\n : { arrayBuffer: value }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n )\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) =>\r\n 'arrayBuffer' in value ? value.arrayBuffer\r\n : (\r\n Uint8Array\r\n .fromBase64(value.base64Buffer)\r\n .buffer\r\n )\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new ArrayBuffer(10), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ArrayBuffer = revived\r\n // @ts-expect-error - not an ArrayBuffer\r\n const notArrayBuffer: string = revived\r\n // @ts-expect-error - cannot box non-ArrayBuffer\r\n box('not an array buffer', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'date' as const\r\n\r\nexport const isType = (value: unknown): value is Date =>\r\n value instanceof Date\r\n\r\nexport const box = <T extends Date, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n ISOString: value.toISOString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Date => {\r\n return new Date(value.ISOString)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Date(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Date = revived\r\n // @ts-expect-error - not a Date\r\n const notDate: string = revived\r\n // @ts-expect-error - cannot box non-Date\r\n box('not a date', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'headers' as const\r\n\r\nexport const isType = (value: unknown): value is Headers =>\r\n value instanceof Headers\r\n\r\nexport const box = <T extends Headers, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n entries: [...value.entries()]\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n): Headers => {\r\n return new Headers(value.entries)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Headers(), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Headers = revived\r\n // @ts-expect-error - not a Headers\r\n const notHeaders: string = revived\r\n // @ts-expect-error - cannot box non-Headers\r\n box('not a header', {} as RevivableContext)\r\n}\r\n","import type { RevivableContext } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\n\r\nexport const type = 'error' as const\r\n\r\nexport const isType = (value: unknown): value is Error =>\r\n value instanceof Error\r\n\r\nexport const box = <T extends Error, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n message: value.message,\r\n stack: value.stack || value.toString()\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n _context: T2\r\n) => new Error(value.message, { cause: value.stack })\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(new Error('test'), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Error = revived\r\n // @ts-expect-error - not an Error\r\n const notError: string = revived\r\n // @ts-expect-error - cannot box non-Error\r\n box('not an error', {} as RevivableContext)\r\n}\r\n","import type { IsJsonOnlyTransport } from '../utils'\r\nimport type { RevivableContext, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { isJsonOnlyTransport } from '../utils'\r\n\r\nexport const type = 'typedArray' as const\r\n\r\nconst typedArrayConstructors = [\r\n Int8Array,\r\n Uint8Array,\r\n Uint8ClampedArray,\r\n Int16Array,\r\n Uint16Array,\r\n Int32Array,\r\n Uint32Array,\r\n Float16Array,\r\n Float32Array,\r\n Float64Array,\r\n BigInt64Array,\r\n BigUint64Array\r\n]\r\nexport type TypedArrayConstructor = typeof typedArrayConstructors[number]\r\n\r\nconst typedArrays = [\r\n new Int8Array(),\r\n new Uint8Array(),\r\n new Uint8ClampedArray(),\r\n new Int16Array(),\r\n new Uint16Array(),\r\n new Int32Array(),\r\n new Uint32Array(),\r\n new Float16Array(),\r\n new Float32Array(),\r\n new Float64Array(),\r\n new BigInt64Array(),\r\n new BigUint64Array()\r\n]\r\nexport type TypedArray = typeof typedArrays[number]\r\n\r\nexport const typedArrayToType = <T extends TypedArray>(value: T) => {\r\n const type =\r\n value instanceof Int8Array ? 'Int8Array' :\r\n value instanceof Uint8Array ? 'Uint8Array' :\r\n value instanceof Uint8ClampedArray ? 'Uint8ClampedArray' :\r\n value instanceof Int16Array ? 'Int16Array' :\r\n value instanceof Uint16Array ? 'Uint16Array' :\r\n value instanceof Int32Array ? 'Int32Array' :\r\n value instanceof Uint32Array ? 'Uint32Array' :\r\n value instanceof Float16Array ? 'Float16Array' :\r\n value instanceof Float32Array ? 'Float32Array' :\r\n value instanceof Float64Array ? 'Float64Array' :\r\n value instanceof BigInt64Array ? 'BigInt64Array' :\r\n value instanceof BigUint64Array ? 'BigUint64Array' :\r\n undefined\r\n if (type === undefined) throw new Error('Unknown typed array type')\r\n return type\r\n}\r\nexport type TypedArrayType = ReturnType<typeof typedArrayToType>\r\n\r\nexport const typedArrayTypeToTypedArrayConstructor = (value: TypedArrayType): TypedArrayConstructor => {\r\n const typedArray =\r\n value === 'Int8Array' ? Int8Array :\r\n value === 'Uint8Array' ? Uint8Array :\r\n value === 'Uint8ClampedArray' ? Uint8ClampedArray :\r\n value === 'Int16Array' ? Int16Array :\r\n value === 'Uint16Array' ? Uint16Array :\r\n value === 'Int32Array' ? Int32Array :\r\n value === 'Uint32Array' ? Uint32Array :\r\n value === 'Float16Array' ? Float16Array :\r\n value === 'Float32Array' ? Float32Array :\r\n value === 'Float64Array' ? Float64Array :\r\n value === 'BigInt64Array' ? BigInt64Array :\r\n value === 'BigUint64Array' ? BigUint64Array :\r\n undefined\r\n if (typedArray === undefined) throw new Error('Unknown typed array type')\r\n return typedArray\r\n}\r\n\r\nexport const isType = (value: unknown): value is TypedArray =>\r\n typedArrayConstructors.some(constructor => value instanceof constructor)\r\n\r\nexport const box = <T extends TypedArray, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => ({\r\n ...BoxBase,\r\n type,\r\n typedArrayType: typedArrayToType(value),\r\n ...(\r\n isJsonOnlyTransport(context.transport)\r\n ? { base64Buffer: new Uint8Array(value.buffer).toBase64() }\r\n : { arrayBuffer: value.buffer }\r\n ) as (\r\n IsJsonOnlyTransport<T2['transport']> extends true ? { base64Buffer: string }\r\n : IsJsonOnlyTransport<T2['transport']> extends false ? { arrayBuffer: ArrayBuffer }\r\n : { base64Buffer: string } | { arrayBuffer: ArrayBuffer }\r\n ) & { [UnderlyingType]: T }\r\n})\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const TypedArrayConstructor = typedArrayTypeToTypedArrayConstructor(value.typedArrayType as TypedArrayType)\r\n const arrayBuffer =\r\n 'arrayBuffer' in value\r\n ? value.arrayBuffer\r\n : Uint8Array.fromBase64(value.base64Buffer).buffer\r\n return new TypedArrayConstructor(arrayBuffer)\r\n}\r\n\r\nconst typeCheck = () => {\r\n const uint8Boxed = box(new Uint8Array(10), {} as RevivableContext)\r\n const uint8Revived = revive(uint8Boxed, {} as RevivableContext)\r\n const expectedUint8: Uint8Array = uint8Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongType: Int32Array = uint8Revived\r\n\r\n const float32Boxed = box(new Float32Array(10), {} as RevivableContext)\r\n const float32Revived = revive(float32Boxed, {} as RevivableContext)\r\n const expectedFloat32: Float32Array = float32Revived\r\n // @ts-expect-error - wrong typed array type\r\n const wrongFloat: Uint8Array = float32Revived\r\n\r\n // @ts-expect-error - cannot box non-TypedArray\r\n box('not a typed array', {} as RevivableContext)\r\n}\r\n","import type { Capable, ConnectionMessage, Message, StructurableTransferable, Uuid } from '../types'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { RevivableContext, BoxBase as BoxBaseType, UnderlyingType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { OSRA_BOX } from '../types'\r\nimport { getTransferableObjects, isJsonOnlyTransport } from '../utils'\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up MessagePorts when they are garbage collected.\r\n * This is used in JSON-only mode where MessagePorts can't be transferred directly.\r\n */\r\ntype PortCleanupInfo = {\r\n sendMessage: (message: ConnectionMessage) => void\r\n remoteUuid: Uuid\r\n portId: string\r\n cleanup: () => void\r\n}\r\n\r\nconst messagePortRegistry = new FinalizationRegistry<PortCleanupInfo>((info) => {\r\n // Send close message to remote side\r\n info.sendMessage({\r\n type: 'message-port-close',\r\n remoteUuid: info.remoteUuid,\r\n portId: info.portId\r\n })\r\n // Perform local cleanup\r\n info.cleanup()\r\n})\r\n\r\nexport const type = 'messagePort' as const\r\n\r\nexport type BoxedMessagePort<T extends StructurableTransferable = StructurableTransferable> =\r\n & BoxBaseType<typeof type>\r\n & ({ portId: string } | { port: StrictMessagePort<T> })\r\n & { [UnderlyingType]: StrictMessagePort<T> }\r\n\r\ndeclare const StructurableTransferableError: unique symbol\r\ntype StructurableTransferablePort<T> = T extends StructurableTransferable\r\n ? StrictMessagePort<T>\r\n : { [StructurableTransferableError]: 'Message type must extend StructurableTransferable'; __badType__: T }\r\n\r\ntype ExtractStructurableTransferable<T> = T extends StructurableTransferable ? T : never\r\n\r\nexport const isType = (value: unknown): value is MessagePort =>\r\n value instanceof MessagePort\r\n\r\nconst isAlreadyBoxed = (value: unknown): boolean =>\r\n value !== null &&\r\n typeof value === 'object' &&\r\n OSRA_BOX in value &&\r\n (value as Record<string, unknown>)[OSRA_BOX] === 'revivable'\r\n\r\nexport const box = <T, T2 extends RevivableContext = RevivableContext>(\r\n value: StructurableTransferablePort<T>,\r\n context: T2\r\n) => {\r\n if (isJsonOnlyTransport(context.transport)) {\r\n const messagePort = value as StrictMessagePort<ExtractStructurableTransferable<T>>\r\n // Only generate a unique UUID, don't store the port in the allocator.\r\n // Storing the port would create a strong reference that prevents GC and FinalizationRegistry cleanup.\r\n const portId = context.messageChannels.getUniqueUuid()\r\n\r\n // Use WeakRef to allow messagePort to be garbage collected.\r\n // The eventTargetListener would otherwise hold a strong reference preventing GC.\r\n const messagePortRef = new WeakRef(messagePort)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n // Define listener before registering with FinalizationRegistry so we can remove it in cleanup\r\n const eventTargetListener = ({ detail: message }: CustomEvent<Message>) => {\r\n if (message.type === 'message-port-close') {\r\n if (message.portId !== portId) return\r\n context.messageChannels.free(portId)\r\n const port = messagePortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n port.close()\r\n }\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n const port = messagePortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, remove this listener\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n return\r\n }\r\n port.postMessage(message.data as ExtractStructurableTransferable<T>, getTransferableObjects(message.data))\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before registering so it can be removed in cleanup\r\n function messagePortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: (isAlreadyBoxed(data) ? data : recursiveBox(data as Capable, context)) as Capable,\r\n portId\r\n })\r\n }\r\n\r\n // Register the messagePort for automatic cleanup when garbage collected\r\n // Use messagePort itself as the unregister token\r\n messagePortRegistry.register(messagePortRef.deref()!, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: () => {\r\n context.messageChannels.free(portId)\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n messagePortRef.deref()?.removeEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.close()\r\n }\r\n }, messagePortRef.deref())\r\n\r\n messagePortRef.deref()?.addEventListener('message', messagePortListener)\r\n messagePortRef.deref()?.start()\r\n\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n \r\n const result = {\r\n ...BoxBase,\r\n type,\r\n portId\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n }\r\n const result = {\r\n ...BoxBase,\r\n type,\r\n port: value\r\n }\r\n return result as typeof result & { [UnderlyingType]: StrictMessagePort<ExtractStructurableTransferable<T>> }\r\n}\r\n\r\nexport const revive = <T extends StructurableTransferable, T2 extends RevivableContext>(\r\n value: BoxedMessagePort<T>,\r\n context: T2\r\n): StrictMessagePort<T> => {\r\n if ('portId' in value) {\r\n const { portId } = value\r\n const { port1: userPort, port2: internalPort } = new MessageChannel()\r\n\r\n const existingChannel = context.messageChannels.get(value.portId)\r\n const { port1 } =\r\n existingChannel\r\n ? existingChannel\r\n : context.messageChannels.alloc(value.portId as Uuid)\r\n\r\n const userPortRef = new WeakRef(userPort)\r\n\r\n // Define all listeners before registering so they can be removed in cleanup\r\n const eventTargetListener = ({ detail: message }: CustomEvent<Message>) => {\r\n if (message.type !== 'message-port-close' || message.portId !== portId) return\r\n const port = userPortRef.deref()\r\n if (port) {\r\n // Unregister from FinalizationRegistry to prevent double-close\r\n messagePortRegistry.unregister(port)\r\n }\r\n performCleanup()\r\n }\r\n\r\n const port1Listener = ({ data: message }: MessageEvent) => {\r\n if (message.type !== 'message' || message.portId !== portId) return\r\n\r\n const port = userPortRef.deref()\r\n if (!port) {\r\n // Port was garbage collected, cleanup\r\n performCleanup()\r\n return\r\n }\r\n\r\n // if the returned messagePort has been registered as internal message port, then we proxy the data without reviving it\r\n if (context.messagePorts.has(port)) {\r\n internalPort.postMessage(message.data)\r\n } else {\r\n // In this case, userPort is actually passed by the user of osra and we should revive all the message data\r\n const revivedData = recursiveRevive(message.data, context)\r\n internalPort.postMessage(revivedData, getTransferableObjects(revivedData))\r\n }\r\n }\r\n\r\n // Since we are in a boxed MessagePort, we want to send a message to the other side through the EmitTransport\r\n // Define this listener before performCleanup so it can be removed in cleanup\r\n function internalPortListener({ data }: MessageEvent) {\r\n context.sendMessage({\r\n type: 'message',\r\n remoteUuid: context.remoteUuid,\r\n data: isAlreadyBoxed(data) ? data : recursiveBox(data, context),\r\n portId: portId as Uuid\r\n })\r\n }\r\n\r\n const performCleanup = () => {\r\n context.eventTarget.removeEventListener('message', eventTargetListener)\r\n port1.removeEventListener('message', port1Listener)\r\n internalPort.removeEventListener('message', internalPortListener)\r\n internalPort.close()\r\n // Close the allocator's MessageChannel ports before freeing\r\n // The allocator creates a MessageChannel with port1 and port2 - both must be closed\r\n const allocatedChannel = context.messageChannels.get(portId)\r\n if (allocatedChannel) {\r\n allocatedChannel.port1.close()\r\n if (allocatedChannel.port2) {\r\n allocatedChannel.port2.close()\r\n }\r\n }\r\n context.messageChannels.free(portId)\r\n }\r\n\r\n // Register the userPort for automatic cleanup when garbage collected\r\n // Use userPort itself as the unregister token\r\n messagePortRegistry.register(userPort, {\r\n sendMessage: context.sendMessage,\r\n remoteUuid: context.remoteUuid,\r\n portId,\r\n cleanup: performCleanup\r\n }, userPort)\r\n\r\n internalPort.addEventListener('message', internalPortListener)\r\n internalPort.start()\r\n\r\n // Listen for close messages from the remote side through the main event target\r\n context.eventTarget.addEventListener('message', eventTargetListener)\r\n\r\n // The ReceiveTransport received a message from the other side so we call it on our own side's MessagePort after reviving it\r\n port1.addEventListener('message', port1Listener)\r\n port1.start()\r\n\r\n return userPort as StrictMessagePort<T>\r\n }\r\n return value.port\r\n}\r\n\r\nconst typeCheck = () => {\r\n const port = new MessageChannel().port1 as StrictMessagePort<{ foo: string }>\r\n const boxed = box(port, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: StrictMessagePort<{ foo: string }> = revived\r\n // @ts-expect-error - wrong message type\r\n const wrongType: StrictMessagePort<{ bar: number }> = revived\r\n // @ts-expect-error - non-StructurableTransferable message type\r\n box(new MessageChannel().port1 as StrictMessagePort<Promise<string>>, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'promise' as const\r\n\r\nexport type Context =\r\n | { type: 'resolve', data: Capable }\r\n | { type: 'reject', error: string }\r\n\r\ndeclare const ErrorMessage: unique symbol\r\ndeclare const BadValueType: unique symbol\r\ntype CapablePromise<T> = T extends Promise<infer U>\r\n ? U extends Capable\r\n ? T\r\n : { [ErrorMessage]: 'Value type must extend a Promise that resolves to a Capable'; [BadValueType]: U }\r\n : { [ErrorMessage]: 'Value type must extend a Promise that resolves to a Capable'; [BadValueType]: T }\r\n\r\ntype ExtractCapable<T> = T extends Promise<infer U>\r\n ? U extends Capable ? U : never\r\n : never\r\n\r\nconst isCapablePromise = <T, U extends Capable = ExtractCapable<T>>(value: T): value is T & Promise<U> =>\r\n value instanceof Promise\r\n\r\nexport type BoxedPromise<T extends Capable = Capable> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: ReturnType<typeof boxMessagePort>\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is Promise<any> =>\r\n value instanceof Promise\r\n\r\nexport const box = <T, T2 extends RevivableContext>(\r\n value: CapablePromise<T>,\r\n context: T2\r\n): BoxedPromise<ExtractCapable<T>> => {\r\n if (!isCapablePromise(value)) throw new TypeError('Expected Promise')\r\n const promise = value\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const sendResult = (result: Context) => {\r\n const boxedResult = recursiveBox(result, context)\r\n localPort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n localPort.close()\r\n // Clean up the remote port from the set (it was transferred earlier)\r\n context.messagePorts.delete(remotePort)\r\n }\r\n\r\n promise\r\n .then((data: ExtractCapable<T>) => sendResult({ type: 'resolve', data }))\r\n .catch((error: unknown) => sendResult({ type: 'reject', error: (error as Error)?.stack ?? String(error) }))\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as unknown as StrictMessagePort<string>, context)\r\n } as unknown as BoxedPromise<ExtractCapable<T>>\r\n}\r\n\r\nexport const revive = <T extends BoxedPromise, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n) => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort<string>, context)\r\n context.messagePorts.add(port as MessagePort)\r\n return new Promise<T[UnderlyingType]>((resolve, reject) => {\r\n port.addEventListener('message', (event) => {\r\n const data = (event as unknown as MessageEvent<Context>).data\r\n const result = recursiveRevive(data, context) as Context\r\n if (result.type === 'resolve') {\r\n resolve(result.data as T[UnderlyingType])\r\n } else {\r\n reject(result.error)\r\n }\r\n context.messagePorts.delete(port as MessagePort)\r\n port.close()\r\n }, { once: true })\r\n port.start()\r\n })\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box(Promise.resolve(1 as const), {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: Promise<1> = revived\r\n // @ts-expect-error\r\n const notExpected: Promise<string> = revived\r\n // @ts-expect-error\r\n box(1 as const, {} as RevivableContext)\r\n}\r\n","import type { Capable } from '../types'\r\nimport type { UnderlyingType, RevivableContext, BoxBase as BoxBaseType } from './utils'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'function' as const\r\n\r\n/**\r\n * FinalizationRegistry for automatically cleaning up function ports when the revived function is garbage collected.\r\n */\r\ntype FunctionCleanupInfo = {\r\n port: MessagePort\r\n}\r\n\r\nconst functionRegistry = new FinalizationRegistry<FunctionCleanupInfo>((info) => {\r\n // Send a close signal through the port before closing it\r\n try {\r\n info.port.postMessage({ __osra_close__: true })\r\n } catch { /* Port may already be closed */ }\r\n try {\r\n info.port.close()\r\n } catch { /* Port may already be closed */ }\r\n})\r\n\r\nexport type CallContext = [\r\n /** MessagePort or portId that will be used to send the result of the function call */\r\n MessagePort | string,\r\n /** Arguments that will be passed to the function call */\r\n Capable[]\r\n]\r\n\r\nexport type BoxedFunction<T extends (...args: any[]) => any = (...args: any[]) => any> =\r\n & BoxBaseType<typeof type>\r\n & { port: BoxedMessagePort }\r\n & { [UnderlyingType]: (...args: Parameters<T>) => Promise<Awaited<ReturnType<T>>> }\r\n\r\ntype CapableFunction<T> = T extends (...args: infer P) => infer R\r\n ? P extends Capable[]\r\n ? R extends Capable ? T : never\r\n : never\r\n : never\r\n\r\nexport const isType = (value: unknown): value is (...args: any[]) => any =>\r\n typeof value === 'function'\r\n\r\nexport const box = <T extends (...args: any[]) => any, T2 extends RevivableContext>(\r\n value: T & CapableFunction<T>,\r\n context: T2\r\n): BoxedFunction<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel()\r\n context.messagePorts.add(remotePort)\r\n\r\n const cleanup = () => {\r\n context.messagePorts.delete(remotePort)\r\n localPort.close()\r\n }\r\n\r\n localPort.addEventListener('message', ({ data }: MessageEvent<CallContext | { __osra_close__: true }>) => {\r\n // Check for close signal\r\n if (data && typeof data === 'object' && '__osra_close__' in data) {\r\n cleanup()\r\n return\r\n }\r\n const [returnValuePort, args] = recursiveRevive(data as CallContext, context) as [MessagePort, Capable[]]\r\n const result = (async () => value(...args))()\r\n const boxedResult = recursiveBox(result, context)\r\n returnValuePort.postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\r\n port: boxMessagePort(remotePort as any, context)\r\n } as BoxedFunction<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedFunction, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context)\r\n\r\n const func = (...args: Capable[]) =>\r\n new Promise((resolve, reject) => {\r\n const { port1: returnValueLocalPort, port2: returnValueRemotePort } = new MessageChannel()\r\n context.messagePorts.add(returnValueRemotePort)\r\n const callContext = recursiveBox([returnValueRemotePort, args] as const, context)\r\n ;(port as MessagePort).postMessage(callContext, getTransferableObjects(callContext))\r\n // Remove the remote port from the set after transfer (it's neutered now)\r\n context.messagePorts.delete(returnValueRemotePort)\r\n\r\n returnValueLocalPort.addEventListener('message', ({ data }: MessageEvent<Capable>) => {\r\n const result = recursiveRevive(data, context) as Promise<Capable>\r\n result\r\n .then(resolve)\r\n .catch(reject)\r\n .finally(() => {\r\n returnValueLocalPort.close()\r\n })\r\n }, { once: true })\r\n returnValueLocalPort.start()\r\n })\r\n\r\n // Register the function for automatic cleanup when garbage collected\r\n functionRegistry.register(func, { port: port as MessagePort }, func)\r\n\r\n return func\r\n}\r\n\r\nconst typeCheck = () => {\r\n const boxed = box((a: number, b: string) => a + b.length, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: (a: number, b: string) => Promise<number> = revived\r\n // @ts-expect-error - wrong return type\r\n const wrongReturn: (a: number, b: string) => Promise<string> = revived\r\n // @ts-expect-error - wrong parameter types\r\n const wrongParams: (a: string, b: number) => Promise<number> = revived\r\n // @ts-expect-error - non-Capable parameter type (Set is not directly Capable as parameter)\r\n box((a: WeakMap<object, string>) => a, {} as RevivableContext)\r\n // @ts-expect-error - non-Capable return type\r\n box(() => new WeakMap(), {} as RevivableContext)\r\n}\r\n","import type { Capable, StructurableTransferable } from '../types'\r\nimport type { RevivableContext } from './utils'\r\nimport type { StrictMessageChannel, StrictMessagePort } from '../utils/message-channel'\r\nimport type { UnderlyingType } from '.'\r\n\r\nimport { BoxBase } from './utils'\r\nimport { recursiveBox, recursiveRevive } from '.'\r\nimport { getTransferableObjects } from '../utils'\r\nimport { box as boxMessagePort, revive as reviveMessagePort, BoxedMessagePort } from './message-port'\r\n\r\nexport const type = 'readableStream' as const\r\n\r\nexport type PullContext = {\r\n type: 'pull' | 'cancel'\r\n}\r\n\r\nexport type BoxedReadableStream<T extends ReadableStream = ReadableStream> = {\r\n __OSRA_BOX__: 'revivable'\r\n type: typeof type\r\n port: BoxedMessagePort\r\n [UnderlyingType]: T\r\n}\r\n\r\nexport const isType = (value: unknown): value is ReadableStream =>\r\n value instanceof ReadableStream\r\n\r\nexport const box = <T extends ReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): BoxedReadableStream<T> => {\r\n const { port1: localPort, port2: remotePort } = new MessageChannel() as StrictMessageChannel<StructurableTransferable, StructurableTransferable>\r\n context.messagePorts.add(remotePort as MessagePort)\r\n\r\n const reader = value.getReader()\r\n\r\n ;(localPort as MessagePort).addEventListener('message', async ({ data }) => {\r\n const { type } = recursiveRevive(data, context) as PullContext\r\n if (type === 'pull') {\r\n const pullResult = reader.read()\r\n const boxedResult = recursiveBox(pullResult, context)\r\n ;(localPort as MessagePort).postMessage(boxedResult, getTransferableObjects(boxedResult))\r\n } else {\r\n reader.cancel()\r\n localPort.close()\r\n }\r\n })\r\n localPort.start()\r\n\r\n return {\r\n ...BoxBase,\r\n type,\r\n port: boxMessagePort(remotePort as MessagePort as StrictMessagePort<Record<string, StructurableTransferable>>, context)\r\n } as BoxedReadableStream<T>\r\n}\r\n\r\nexport const revive = <T extends BoxedReadableStream, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): T[UnderlyingType] => {\r\n const port = reviveMessagePort(value.port as unknown as BoxedMessagePort, context) as MessagePort\r\n context.messagePorts.add(port as MessagePort)\r\n port.start()\r\n\r\n return new ReadableStream({\r\n start(_controller) {},\r\n pull(controller) {\r\n return new Promise((resolve, reject) => {\r\n port.addEventListener('message', async ({ data }) => {\r\n const result = recursiveRevive(data, context) as Promise<ReadableStreamReadResult<any>>\r\n result\r\n .then(result => {\r\n if (result.done) controller.close()\r\n else controller.enqueue(result.value)\r\n resolve()\r\n })\r\n .catch(reject)\r\n }, { once: true })\r\n port.postMessage(recursiveBox({ type: 'pull' }, context))\r\n })\r\n },\r\n cancel() {\r\n port.postMessage(recursiveBox({ type: 'cancel' }, context))\r\n port.close()\r\n }\r\n }) as T[UnderlyingType]\r\n}\r\n\r\nconst typeCheck = () => {\r\n const stream = new ReadableStream<number>()\r\n const boxed = box(stream, {} as RevivableContext)\r\n const revived = revive(boxed, {} as RevivableContext)\r\n const expected: ReadableStream<number> = revived\r\n // @ts-expect-error - wrong stream type\r\n const wrongType: ReadableStream<string> = revived\r\n // @ts-expect-error - not a ReadableStream\r\n box('not a stream', {} as RevivableContext)\r\n}\r\n","import type { BoxBase, RevivableContext } from './utils'\r\nexport type { UnderlyingType } from './utils'\r\nimport type { DeepReplaceWithBox, DeepReplaceWithRevive, ReplaceWithBox, ReplaceWithRevive } from '../utils/replace'\r\n\r\nimport { Capable } from '../types'\r\nimport { isRevivableBox } from './utils'\r\nimport * as arrayBuffer from './array-buffer'\r\nimport * as date from './date'\r\nimport * as headers from './headers'\r\nimport * as error from './error'\r\nimport * as typedArray from './typed-array'\r\nimport * as promise from './promise'\r\nimport * as func from './function'\r\nimport * as messagePort from './message-port'\r\nimport * as readableStream from './readable-stream'\r\n\r\nexport type RevivableModule<T extends string = string, T2 = any, T3 extends BoxBase<T> = any> = {\r\n readonly type: T\r\n readonly isType: (value: unknown) => value is T2\r\n readonly box: ((value: T2, context: RevivableContext) => T3) | ((...args: any[]) => any)\r\n readonly revive: (value: T3, context: RevivableContext) => T2\r\n}\r\n\r\nexport const defaultRevivableModules = [\r\n arrayBuffer,\r\n date,\r\n headers,\r\n error,\r\n typedArray,\r\n promise,\r\n func,\r\n messagePort,\r\n readableStream\r\n] as const\r\n\r\nexport type DefaultRevivableModules = typeof defaultRevivableModules\r\n\r\nexport type DefaultRevivableModule = DefaultRevivableModules[number]\r\n\r\nexport const findModuleForValue = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const box = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithBox<T, T2['revivableModules'][number]>\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveBox = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithBox<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithBox<T, T2['revivableModules'][number]>\r\n\r\n const handledByModule = context.revivableModules.find(module => module.isType(value))\r\n if (handledByModule?.isType(value)) {\r\n return (handledByModule.box as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveBox(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveBox(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n\r\nexport const revive = <T extends ReturnType<typeof box>, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): ReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = ReplaceWithRevive<T, T2['revivableModules'][number]>\r\n const boxType =\r\n isRevivableBox(value, context)\r\n ? value.type\r\n : undefined\r\n const handledByModule = context.revivableModules.find(module => module.type === boxType)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n return value as ReturnCastType\r\n}\r\n\r\nexport const recursiveRevive = <T extends Capable, T2 extends RevivableContext>(\r\n value: T,\r\n context: T2\r\n): DeepReplaceWithRevive<T, T2['revivableModules'][number]> => {\r\n type ReturnCastType = DeepReplaceWithRevive<T, T2['revivableModules'][number]>\r\n\r\n // First check if the value is a revivable box and revive it\r\n if (isRevivableBox(value, context)) {\r\n const handledByModule = context.revivableModules.find(module => module.type === value.type)\r\n if (handledByModule) {\r\n return (handledByModule.revive as (v: unknown, c: RevivableContext) => unknown)(value, context) as ReturnCastType\r\n }\r\n }\r\n\r\n // Then recurse into arrays and plain objects\r\n return (\r\n Array.isArray(value) ? value.map(value => recursiveRevive(value, context)) as ReturnCastType\r\n : value && typeof value === 'object' && Object.getPrototypeOf(value) === Object.prototype ? (\r\n Object.fromEntries(\r\n Object\r\n .entries(value)\r\n .map(([key, value]: [string, Capable]) => [\r\n key,\r\n recursiveRevive(value, context)\r\n ])\r\n )\r\n ) as ReturnCastType\r\n : value as ReturnCastType\r\n )\r\n}\r\n","import type {\r\n Capable, ConnectionMessage,\r\n Message,\r\n MessageEventTarget,\r\n Transport,\r\n Uuid\r\n} from '../types'\r\nimport type { MessageChannelAllocator } from './allocator'\r\nimport type { PlatformCapabilities } from './capabilities'\r\nimport type { StrictMessagePort } from './message-channel'\r\n\r\nimport { makeMessageChannelAllocator } from './allocator'\r\nimport { DefaultRevivableModules, defaultRevivableModules, recursiveBox, recursiveRevive, RevivableModule } from '../revivables'\r\n\r\nexport type BidirectionalConnectionContext = {\r\n type: 'bidirectional'\r\n eventTarget: MessageEventTarget\r\n connection: BidirectionalConnection\r\n}\r\nexport type UnidirectionalEmittingConnectionContext = {\r\n type: 'unidirectional-emitting'\r\n connection: UnidirectionalEmittingConnection\r\n}\r\nexport type UnidirectionalReceivingConnectionContext = {\r\n type: 'unidirectional-receiving'\r\n eventTarget: MessageEventTarget\r\n connection: UnidirectionalReceivingConnection\r\n}\r\n\r\nexport type ConnectionContext =\r\n | BidirectionalConnectionContext\r\n | UnidirectionalEmittingConnectionContext\r\n | UnidirectionalReceivingConnectionContext\r\n\r\nexport type ConnectionRevivableContext<TModules extends readonly RevivableModule[] = DefaultRevivableModules> = {\r\n platformCapabilities: PlatformCapabilities\r\n transport: Transport\r\n remoteUuid: Uuid\r\n messagePorts: Set<MessagePort>\r\n messageChannels: MessageChannelAllocator\r\n sendMessage: (message: ConnectionMessage) => void\r\n revivableModules: TModules\r\n eventTarget: MessageEventTarget\r\n}\r\n\r\nexport type BidirectionalConnection<T extends Capable = Capable> = {\r\n revivableContext: ConnectionRevivableContext\r\n close: () => void\r\n remoteValue: Promise<T>\r\n}\r\n\r\nexport const startBidirectionalConnection = <T extends Capable>(\r\n { transport, value, uuid, remoteUuid, platformCapabilities, eventTarget, send, close }:\r\n {\r\n transport: Transport\r\n value: Capable\r\n uuid: Uuid\r\n remoteUuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: MessageEventTarget\r\n send: (message: ConnectionMessage) => void\r\n close: () => void\r\n }\r\n) => {\r\n const revivableContext = {\r\n platformCapabilities,\r\n transport,\r\n remoteUuid,\r\n messagePorts: new Set(),\r\n messageChannels: makeMessageChannelAllocator(),\r\n sendMessage: send,\r\n eventTarget,\r\n revivableModules: defaultRevivableModules\r\n } satisfies ConnectionRevivableContext\r\n let initResolve: ((message: ConnectionMessage & { type: 'init' }) => void)\r\n const initMessage = new Promise<ConnectionMessage & { type: 'init' }>((resolve, reject) => {\r\n initResolve = resolve\r\n })\r\n\r\n eventTarget.addEventListener('message', ({ detail }) => {\r\n if (detail.type === 'init') {\r\n initResolve(detail)\r\n return\r\n } else if (detail.type === 'message') {\r\n const messageChannel = revivableContext.messageChannels.getOrAlloc(detail.portId)\r\n ;(messageChannel.port2 as MessagePort)?.postMessage(detail)\r\n }\r\n })\r\n\r\n send({\r\n type: 'init',\r\n remoteUuid,\r\n data: recursiveBox(value, revivableContext) as Capable\r\n })\r\n\r\n return {\r\n revivableContext,\r\n close: () => {\r\n },\r\n remoteValue:\r\n initMessage\r\n .then(initMessage => recursiveRevive(initMessage.data, revivableContext)) as Promise<T>\r\n } satisfies BidirectionalConnection<T>\r\n}\r\n\r\nexport type UnidirectionalEmittingConnection<T extends Capable = Capable> = {\r\n close: () => void\r\n remoteValueProxy: T\r\n}\r\n\r\nexport const startUnidirectionalEmittingConnection = <T extends Capable>(\r\n { value, uuid, platformCapabilities, send, close }:\r\n {\r\n value: Capable\r\n uuid: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n send: (message: Message) => void\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n },\r\n remoteValueProxy: new Proxy(\r\n new Function(),\r\n {\r\n apply: (target, thisArg, args) => {\r\n },\r\n get: (target, prop) => {\r\n }\r\n }\r\n ) as T\r\n }\r\n}\r\n\r\nexport type UnidirectionalReceivingConnection = {\r\n close: () => void\r\n}\r\n\r\nexport const startUnidirectionalReceivingConnection = (\r\n { uuid, remoteUuid, platformCapabilities, close }:\r\n {\r\n uuid: Uuid\r\n remoteUuid?: Uuid\r\n platformCapabilities: PlatformCapabilities\r\n eventTarget: StrictMessagePort<Message>\r\n close: () => void\r\n }\r\n) => {\r\n\r\n return {\r\n close: () => {\r\n }\r\n }\r\n}\r\n","var e=class extends EventTarget{dispatchTypedEvent(s,t){return super.dispatchEvent(t)}};export{e as TypedEventTarget};\n","import type {\r\n EmitTransport, Message,\r\n MessageContext, MessageVariant,\r\n Capable, Transport,\r\n MessageEventMap\r\n} from './types'\r\nexport type { UnderlyingType } from './revivables/utils'\r\nimport type {\r\n PlatformCapabilities, ConnectionContext,\r\n BidirectionalConnectionContext\r\n} from './utils'\r\n\r\nimport { OSRA_DEFAULT_KEY, OSRA_KEY } from './types'\r\nexport { BoxBase } from './revivables/utils'\r\nimport {\r\n probePlatformCapabilities,\r\n registerOsraMessageListener,\r\n sendOsraMessage,\r\n startBidirectionalConnection,\r\n isReceiveTransport,\r\n isEmitTransport,\r\n startUnidirectionalEmittingConnection,\r\n getTransferableObjects,\r\n isJsonOnlyTransport,\r\n isCustomTransport,\r\n DeepReplace,\r\n DeepReplaceAsync,\r\n AsCapable\r\n} from './utils'\r\nimport { TypedEventTarget } from 'typescript-event-target'\r\n\r\nexport * from './types'\r\nexport * from './revivables'\r\nexport type {\r\n DeepReplace,\r\n DeepReplaceAsync,\r\n AsCapable\r\n}\r\n\r\n/**\r\n * Protocol mode:\r\n * - Bidirectional mode\r\n * - Unidirectional mode\r\n *\r\n * Transport modes:\r\n * - Capable mode\r\n * - Jsonable mode\r\n */\r\nexport const expose = async <T extends Capable>(\r\n value: Capable,\r\n {\r\n transport: _transport,\r\n name,\r\n remoteName,\r\n key = OSRA_DEFAULT_KEY,\r\n origin = '*',\r\n unregisterSignal,\r\n platformCapabilities: _platformCapabilities,\r\n transferAll,\r\n logger\r\n }: {\r\n transport: Transport\r\n name?: string\r\n remoteName?: string\r\n key?: string\r\n origin?: string\r\n unregisterSignal?: AbortSignal\r\n platformCapabilities?: PlatformCapabilities\r\n transferAll?: boolean\r\n logger?: {}\r\n }\r\n): Promise<T> => {\r\n const transport = {\r\n isJson:\r\n 'isJson' in _transport && _transport.isJson !== undefined\r\n ? _transport.isJson\r\n : isJsonOnlyTransport(_transport),\r\n ...(\r\n isCustomTransport(_transport)\r\n ? _transport\r\n : {\r\n emit: _transport,\r\n receive: _transport\r\n }\r\n )\r\n } satisfies Transport\r\n const platformCapabilities = _platformCapabilities ?? await probePlatformCapabilities()\r\n const connectionContexts = new Map<string, ConnectionContext>()\r\n\r\n let resolveRemoteValue: (connection: T) => void\r\n const remoteValuePromise = new Promise<T>((resolve) => {\r\n resolveRemoteValue = resolve\r\n })\r\n\r\n let uuid = globalThis.crypto.randomUUID()\r\n \r\n \r\n let aborted = false\r\n if (unregisterSignal) {\r\n unregisterSignal.addEventListener('abort', () => {\r\n aborted = true\r\n })\r\n }\r\n\r\n const sendMessage = (transport: EmitTransport, message: MessageVariant) => {\r\n if (aborted) return\r\n const transferables = getTransferableObjects(message)\r\n sendOsraMessage(\r\n transport,\r\n {\r\n [OSRA_KEY]: key,\r\n name,\r\n uuid,\r\n ...message\r\n },\r\n origin,\r\n transferables\r\n )\r\n }\r\n\r\n const listener = async (message: Message, messageContext: MessageContext) => {\r\n // means that our own message looped back on the channel\r\n if (message.uuid === uuid) return\r\n // Unidirectional receiving mode\r\n if (!isEmitTransport(transport)) {\r\n // Handle non bidirectional based messages here\r\n throw new Error('Unidirectional receiving mode not implemented')\r\n }\r\n // Bidirectional mode\r\n if (message.type === 'announce') {\r\n if (!message.remoteUuid) {\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n return\r\n }\r\n if (message.remoteUuid !== uuid) return\r\n // todo: re-add uuid collision handling\r\n if (connectionContexts.has(message.uuid)) {\r\n return\r\n }\r\n // Send announce back so the other side can also create a connection\r\n // (in case they missed our initial announce due to timing)\r\n sendMessage(transport, { type: 'announce', remoteUuid: message.uuid })\r\n const eventTarget = new TypedEventTarget<MessageEventMap>()\r\n const connectionContext = {\r\n type: 'bidirectional',\r\n eventTarget,\r\n connection:\r\n startBidirectionalConnection({\r\n transport,\r\n value,\r\n uuid,\r\n remoteUuid: message.uuid,\r\n platformCapabilities,\r\n eventTarget,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => void connectionContexts.delete(message.uuid)\r\n })\r\n } satisfies BidirectionalConnectionContext\r\n connectionContexts.set(message.uuid, connectionContext)\r\n connectionContext.connection.remoteValue.then((remoteValue) =>\r\n resolveRemoteValue(remoteValue as T)\r\n )\r\n } else if (message.type === 'reject-uuid-taken') {\r\n if (message.remoteUuid !== uuid) return\r\n uuid = globalThis.crypto.randomUUID()\r\n sendMessage(transport, { type: 'announce' })\r\n } else if (message.type === 'close') {\r\n if (message.remoteUuid !== uuid) return\r\n const connectionContext = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connectionContext) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n connectionContext.connection.close()\r\n connectionContexts.delete(message.uuid)\r\n } else { // \"init\" | \"message\" | \"message-port-close\"\r\n if (message.remoteUuid !== uuid) return\r\n const connection = connectionContexts.get(message.uuid)\r\n // We just drop the message if the remote uuid hasn't announced itself\r\n if (!connection) {\r\n console.warn(`Connection not found for remoteUuid: ${message.uuid}`)\r\n return\r\n }\r\n if (connection.type !== 'unidirectional-emitting') {\r\n connection.eventTarget.dispatchTypedEvent(\r\n 'message',\r\n new CustomEvent('message', { detail: message })\r\n )\r\n }\r\n }\r\n }\r\n\r\n if (isReceiveTransport(transport)) {\r\n registerOsraMessageListener({\r\n listener,\r\n transport,\r\n remoteName,\r\n key,\r\n unregisterSignal\r\n })\r\n }\r\n\r\n if (isEmitTransport(transport)) {\r\n sendMessage(transport, { type: 'announce' })\r\n }\r\n\r\n // Unidirectional emitting mode\r\n if (isEmitTransport(transport) && !isReceiveTransport(transport)) {\r\n const { remoteValueProxy } = startUnidirectionalEmittingConnection<T>({\r\n value,\r\n uuid,\r\n platformCapabilities,\r\n send: (message: MessageVariant) => sendMessage(transport, message),\r\n close: () => connectionContexts.delete(uuid)\r\n })\r\n return remoteValueProxy\r\n }\r\n\r\n return remoteValuePromise\r\n}\r\n"],"names":["OSRA_KEY","OSRA_DEFAULT_KEY","OSRA_BOX","BoxBase","isRevivableBox","value","_context","makeMessageChannelAllocator","channels","result","uuid","messagePorts","allocatedMessageChannel","messageChannel","existingChannel","checkOsraMessageKey","message","key","isOsraMessage","registerOsraMessageListener","listener","transport","remoteName","unregisterSignal","registerListenerOnReceiveTransport","receiveTransport","isWebExtensionPort","isWebExtensionOnConnect","isWebExtensionOnMessage","listenOnWebExtOnMessage","onMessage","port","_listener","sender","messageListener","event","isCustomTransport","sendOsraMessage","origin","transferables","sendToEmitTransport","emitTransport","isWindow","isWebSocket","isSharedWorker","isServiceWorkerContainer","isWorker","isDedicatedWorker","isMessagePort","isClonable","isTransferable","connectPort","w","isEmitJsonOnlyTransport","isReceiveJsonOnlyTransport","isJsonOnlyTransport","isEmitTransport","isCustomEmitTransport","isReceiveTransport","isCustomReceiveTransport","getTransferableObjects","recurse","probePlatformCapabilityUtil","transfer","port1","port2","resolve","probeMessagePortTransfer","probeArrayBufferClone","buffer","probeArrayBufferTransfer","probeTransferableStream","stream","controller","probePlatformCapabilities","messagePort","arrayBuffer","transferable","transferableStream","type","isType","box","revive","typedArrayConstructors","typedArrayToType","typedArrayTypeToTypedArrayConstructor","typedArray","constructor","context","TypedArrayConstructor","messagePortRegistry","info","isAlreadyBoxed","messagePortListener","data","recursiveBox","portId","messagePortRef","eventTargetListener","internalPortListener","userPort","internalPort","userPortRef","performCleanup","port1Listener","revivedData","recursiveRevive","allocatedChannel","isCapablePromise","promise","localPort","remotePort","sendResult","boxedResult","error","boxMessagePort","reviveMessagePort","reject","functionRegistry","cleanup","returnValuePort","args","func","returnValueLocalPort","returnValueRemotePort","callContext","reader","pullResult","_controller","defaultRevivableModules","date","headers","readableStream","findModuleForValue","handledByModule","module","boxType","startBidirectionalConnection","remoteUuid","platformCapabilities","eventTarget","send","close","revivableContext","initResolve","initMessage","detail","startUnidirectionalEmittingConnection","target","thisArg","prop","e","s","expose","_transport","name","_platformCapabilities","transferAll","logger","connectionContexts","resolveRemoteValue","remoteValuePromise","aborted","sendMessage","messageContext","TypedEventTarget","connectionContext","remoteValue","connection","remoteValueProxy"],"mappings":"AAKO,MAAMA,IAAW,gBACXC,KAAmB,wBACnBC,IAAW,gBCEXC,IAAU;AAAA,EACrB,CAACD,CAAQ,GAAG;AAAA,EACZ,MAAM;AACR,GA2BaE,IAAiB,CAA6BC,GAAYC,MACrED,KACG,OAAOA,KAAU,YACjBH,KAAYG,KACZA,EAAMH,CAAQ,MAAM,aCKZK,KAA8B,MAAM;AAC/C,QAAMC,wBAAe,IAAA,GAEfC,IAAS;AAAA,IACb,eAAe,MAAM;AACnB,UAAIC,IAAa,WAAW,OAAO,WAAA;AACnC,aAAOF,EAAS,IAAIE,CAAI;AACtB,QAAAA,IAAO,WAAW,OAAO,WAAA;AAE3B,aAAOA;AAAA,IACT;AAAA,IACA,KAAK,CAACA,GAAYC,MAA0E;AAC1F,MAAAH,EAAS,IAAIE,GAAM,EAAE,MAAAA,GAAM,GAAGC,GAAc;AAAA,IAC9C;AAAA,IACA,OAAO,CACLD,IAAyBD,EAAO,cAAA,GAChCE,MACG;AACH,UAAIA,GAAc;AAChB,cAAMC,IAA0B,EAAE,MAAAF,GAAM,GAA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