@fest-lib/lure 0.1.19 → 0.1.21

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.
@@ -1,2976 +0,0 @@
1
- (function() {
2
- var Z = Object.defineProperty, De = (e, t, n) => () => {
3
- if (n) throw n[0];
4
- try {
5
- return e && (t = e(e = 0)), t;
6
- } catch (s) {
7
- throw n = [s], s;
8
- }
9
- }, Ne = (e, t) => {
10
- let n = {};
11
- for (var s in e) Z(n, s, {
12
- get: e[s],
13
- enumerable: !0
14
- });
15
- return t || Z(n, Symbol.toStringTag, { value: "Module" }), n;
16
- };
17
- let h = (function(e) {
18
- return e.GET = "get", e.SET = "set", e.CALL = "call", e.APPLY = "apply", e.CONSTRUCT = "construct", e.DELETE = "delete", e.DELETE_PROPERTY = "deleteProperty", e.HAS = "has", e.OWN_KEYS = "ownKeys", e.GET_OWN_PROPERTY_DESCRIPTOR = "getOwnPropertyDescriptor", e.GET_PROPERTY_DESCRIPTOR = "getPropertyDescriptor", e.GET_PROTOTYPE_OF = "getPrototypeOf", e.SET_PROTOTYPE_OF = "setPrototypeOf", e.IS_EXTENSIBLE = "isExtensible", e.PREVENT_EXTENSIONS = "preventExtensions", e.TRANSFER = "transfer", e.IMPORT = "import", e.DISPOSE = "dispose", e;
19
- })({});
20
- const Le = {
21
- ws: "websocket",
22
- socket: "websocket",
23
- socketio: "socket-io",
24
- service: "service-worker",
25
- sw: "service-worker",
26
- "service-worker-client": "service-worker",
27
- "service-worker-host": "service-worker",
28
- "ring-buffer": "atomics"
29
- };
30
- function Be(e) {
31
- const t = String(e ?? "").trim().toLowerCase();
32
- return t ? Le[t] ?? t : "internal";
33
- }
34
- function qe(e) {
35
- return typeof e == "string" ? Be(e) : typeof Worker < "u" && e instanceof Worker ? "worker" : typeof SharedWorker < "u" && e instanceof SharedWorker ? "shared-worker" : typeof MessagePort < "u" && e instanceof MessagePort ? "message-port" : typeof BroadcastChannel < "u" && e instanceof BroadcastChannel ? "broadcast" : typeof WebSocket < "u" && e instanceof WebSocket ? "websocket" : typeof RTCDataChannel < "u" && e instanceof RTCDataChannel ? "rtc-data" : typeof chrome < "u" && e && typeof e == "object" && typeof e.postMessage == "function" && e.onMessage?.addListener ? "chrome-port" : "internal";
36
- }
37
- const ee = Symbol.for("@fix"), C = (e) => typeof e == "string" || typeof e == "number" || typeof e == "boolean" || typeof e == "bigint" || typeof e > "u" || e == null, Fe = (e, t) => C(e) ? t == "number" ? Number(e) || 0 : t == "string" ? String(e) || "" : t == "boolean" ? !!e : e : null, p = (e, t) => e?.[ee] ?? e ?? t ?? t, He = (e) => {
38
- if (typeof e == "function" || e == null) return e;
39
- const t = function() {};
40
- return t[ee] = e, t;
41
- }, Ge = (e) => crypto?.getRandomValues ? crypto?.getRandomValues?.(e) : (() => {
42
- const t = new Uint8Array(e.length);
43
- for (let n = 0; n < e.length; n++) t[n] = Math.floor(Math.random() * 256);
44
- return t;
45
- })(), d = () => crypto?.randomUUID ? crypto?.randomUUID?.() : "10000000-1000-4000-8000-100000000000".replace(/[018]/g, (e) => (+e ^ Ge?.(/* @__PURE__ */ new Uint8Array(1))?.[0] & 15 >> +e / 4).toString(16)), te = (e) => Array.isArray(e) ? e?.flatMap?.((t) => Array.isArray(t) ? te(t) : t) : e, $ = (e) => te(e)?.every?.(x), x = (e) => C(e) || typeof SharedArrayBuffer == "function" && e instanceof SharedArrayBuffer || Ue(e) || Array.isArray(e) && $(e), Ue = (e) => ArrayBuffer.isView(e) && !(e instanceof DataView), z = (e) => C(e) || typeof ArrayBuffer == "function" && e instanceof ArrayBuffer || typeof MessagePort == "function" && e instanceof MessagePort || typeof ReadableStream == "function" && e instanceof ReadableStream || typeof WritableStream == "function" && e instanceof WritableStream || typeof TransformStream == "function" && e instanceof TransformStream || typeof ImageBitmap == "function" && e instanceof ImageBitmap || typeof VideoFrame == "function" && e instanceof VideoFrame || typeof OffscreenCanvas == "function" && e instanceof OffscreenCanvas || typeof RTCDataChannel == "function" && e instanceof RTCDataChannel || typeof AudioData == "function" && e instanceof AudioData || typeof WebTransportReceiveStream == "function" && e instanceof WebTransportReceiveStream || typeof WebTransportSendStream == "function" && e instanceof WebTransportSendStream || typeof WebTransportReceiveStream == "function" && e instanceof WebTransportReceiveStream, ne = Symbol.for("object.boundCtx");
46
- globalThis[ne] ??= /* @__PURE__ */ new WeakMap();
47
- globalThis[ne];
48
- const k = (e, t, n) => {
49
- if (Array.isArray(e)) return e.every(x) ? e.map(t) : e.map((s, r) => k(s, t, [e, r]));
50
- if (e instanceof Map) {
51
- const s = Array.from(e.entries());
52
- return s.map(([r, i]) => i).every(x) ? new Map(s.map(([r, i]) => [r, t(i, r, e)])) : new Map(s.map(([r, i]) => [r, k(i, t, [e, r])]));
53
- }
54
- if (e instanceof Set) {
55
- const s = Array.from(e.entries()), r = s.map(([i, o]) => o);
56
- return s.every(x) ? new Set(r.map(t)) : new Set(r.map((i) => k(i, t, [e, i])));
57
- }
58
- if (typeof e == "object" && e?.constructor == Object && Object.prototype.toString.call(e) == "[object Object]") {
59
- const s = Array.from(Object.entries(e));
60
- return s.map(([r, i]) => i).every(x) ? Object.fromEntries(s.map(([r, i]) => [r, t(i, r, e)])) : Object.fromEntries(s.map(([r, i]) => [r, k(i, t, [e, r])]));
61
- }
62
- return t(e, n?.[1] ?? "", n?.[0] ?? null);
63
- }, S = /* @__PURE__ */ new WeakMap(), se = /* @__PURE__ */ new WeakMap(), g = (e, t) => e instanceof Promise || typeof e?.then == "function" ? S?.has?.(e) ? t(S?.get?.(e)) : Promise.try?.(async () => {
64
- const n = await e;
65
- return S?.set?.(e, n), n;
66
- })?.then?.(t) : t(e);
67
- var We = class {
68
- #e;
69
- #t;
70
- constructor(e, t) {
71
- this.#e = e, this.#t = t;
72
- }
73
- defineProperty(e, t, n) {
74
- return p(e) instanceof Promise ? Reflect.defineProperty(e, t, n) : g(p(e), (s) => Reflect.defineProperty(s, t, n));
75
- }
76
- deleteProperty(e, t) {
77
- return p(e) instanceof Promise ? Reflect.deleteProperty(e, t) : g(p(e), (n) => Reflect.deleteProperty(n, t));
78
- }
79
- getPrototypeOf(e) {
80
- return p(e) instanceof Promise ? Reflect.getPrototypeOf(e) : g(p(e), (t) => Reflect.getPrototypeOf(t));
81
- }
82
- setPrototypeOf(e, t) {
83
- return p(e) instanceof Promise ? Reflect.setPrototypeOf(e, t) : g(p(e), (n) => Reflect.setPrototypeOf(n, t));
84
- }
85
- isExtensible(e) {
86
- return p(e) instanceof Promise ? Reflect.isExtensible(e) : g(p(e), (t) => Reflect.isExtensible(t));
87
- }
88
- preventExtensions(e) {
89
- return p(e) instanceof Promise ? Reflect.ownKeys(e) : g(p(e), (t) => Reflect.preventExtensions(t));
90
- }
91
- ownKeys(e) {
92
- const t = p(e);
93
- return t instanceof Promise ? Object.keys(t) : g(t, (n) => (typeof n == "object" || typeof n == "function") && n != null ? Object.keys(n) : []) ?? [];
94
- }
95
- getOwnPropertyDescriptor(e, t) {
96
- return p(e) instanceof Promise ? Reflect.getOwnPropertyDescriptor(e, t) : g(p(e), (n) => Reflect.getOwnPropertyDescriptor(n, t));
97
- }
98
- construct(e, t, n) {
99
- return g(p(e), (s) => Reflect.construct(s, t, n));
100
- }
101
- has(e, t) {
102
- return p(e) instanceof Promise ? Reflect.has(e, t) : g(p(e), (n) => Reflect.has(n, t));
103
- }
104
- get(e, t, n) {
105
- if (e = p(e), t == "promise") return e;
106
- if (t == "resolve" && this.#e) return (...r) => {
107
- const i = this.#e?.(...r);
108
- return this.#e = null, i;
109
- };
110
- if (t == "reject" && this.#t) return (...r) => {
111
- const i = this.#t?.(...r);
112
- return this.#t = null, i;
113
- };
114
- if (t == "then" || t == "catch" || t == "finally") {
115
- if (e instanceof Promise) return e?.[t]?.bind?.(e);
116
- {
117
- const r = Promise.try(() => e);
118
- return r?.[t]?.bind?.(r);
119
- }
120
- }
121
- let s;
122
- return S?.has?.(e) && (s = S?.get?.(e))?.[t] != null ? s = S?.get?.(e)?.[t] : s = re(g(e, async (r) => {
123
- if (p(r) instanceof Promise) return Reflect.get(r, t, n);
124
- if (C(r)) return t == Symbol.toPrimitive || t == Symbol.toStringTag ? r : void 0;
125
- let i;
126
- try {
127
- i = Reflect.get(r, t, n);
128
- } catch {
129
- i = e?.[t];
130
- }
131
- return typeof i == "function" ? i?.bind?.(r) : i;
132
- })), t == Symbol.toStringTag ? C(s) ? String(s ?? "") || "" : s?.[Symbol.toStringTag]?.() || String(s ?? "") || "" : t == Symbol.toPrimitive ? (r) => {
133
- if (C(s)) return Fe(s, r);
134
- } : s;
135
- }
136
- set(e, t, n) {
137
- return g(p(e), (s) => Reflect.set(s, t, n));
138
- }
139
- apply(e, t, n) {
140
- if (this.#e) {
141
- const s = this.#e?.(...n);
142
- return this.#e = null, s;
143
- }
144
- return g(p(e, this.#e), (s) => {
145
- if (typeof s == "function") return p(s) instanceof Promise, Reflect.apply(s, t, n);
146
- });
147
- }
148
- };
149
- function re(e, t, n) {
150
- return e instanceof Promise || typeof e?.then == "function" ? S?.has?.(e) ? S?.get?.(e) : (se?.has?.(e) || e?.then?.((s) => S?.set?.(e, s)), se?.getOrInsertComputed?.(e, () => new Proxy(He(e), new We(t, n)))) : e;
151
- }
152
- var oe = class {
153
- _unsubscribe;
154
- _closed = !1;
155
- constructor(e) {
156
- this._unsubscribe = e;
157
- }
158
- get closed() {
159
- return this._closed;
160
- }
161
- unsubscribe() {
162
- this._closed || (this._closed = !0, this._unsubscribe());
163
- }
164
- }, $e = class {
165
- _producer;
166
- constructor(e) {
167
- this._producer = e;
168
- }
169
- subscribe(e, t) {
170
- const n = typeof e == "function" ? { next: e } : e ?? {}, s = new AbortController();
171
- t?.signal?.addEventListener("abort", () => s.abort());
172
- let r = !0, i;
173
- const o = () => {
174
- r = !1, s.abort(), i?.();
175
- }, a = {
176
- next: (c) => r && n.next?.(c),
177
- error: (c) => {
178
- r && (n.error?.(c), o());
179
- },
180
- complete: () => {
181
- r && (n.complete?.(), o());
182
- },
183
- signal: s.signal,
184
- get active() {
185
- return r && !s.signal.aborted;
186
- }
187
- };
188
- try {
189
- i = this._producer(a);
190
- } catch (c) {
191
- a.error(c);
192
- }
193
- return new oe(o);
194
- }
195
- pipe(...e) {
196
- return e.reduce((t, n) => n(t), this);
197
- }
198
- }, y = class {
199
- _subs = /* @__PURE__ */ new Set();
200
- _buffer = [];
201
- _maxBuffer;
202
- _replay;
203
- constructor(e = {}) {
204
- this._maxBuffer = e.bufferSize ?? 0, this._replay = e.replayOnSubscribe ?? !1;
205
- }
206
- next(e) {
207
- this._maxBuffer > 0 && (this._buffer.push(e), this._buffer.length > this._maxBuffer && this._buffer.shift());
208
- for (const t of this._subs) try {
209
- t.next?.(e);
210
- } catch (n) {
211
- t.error?.(n);
212
- }
213
- }
214
- error(e) {
215
- for (const t of this._subs) t.error?.(e);
216
- }
217
- complete() {
218
- for (const e of this._subs) e.complete?.();
219
- this._subs.clear();
220
- }
221
- subscribe(e) {
222
- const t = typeof e == "function" ? { next: e } : e;
223
- if (this._subs.add(t), this._replay) for (const n of this._buffer) try {
224
- t.next?.(n);
225
- } catch (s) {
226
- t.error?.(s);
227
- }
228
- return new oe(() => {
229
- this._subs.delete(t);
230
- });
231
- }
232
- getValue() {
233
- return this._buffer.at(-1);
234
- }
235
- getBuffer() {
236
- return [...this._buffer];
237
- }
238
- get subscriberCount() {
239
- return this._subs.size;
240
- }
241
- };
242
- const ze = (e) => (t) => new $e((n) => {
243
- const s = t.subscribe({
244
- next: (r) => e(r) && n.next(r),
245
- error: (r) => n.error(r),
246
- complete: () => n.complete()
247
- });
248
- return () => s.unsubscribe();
249
- });
250
- function ie() {
251
- if (typeof globalThis.Deno < "u") return "deno";
252
- if (typeof globalThis.process < "u" && globalThis.process?.versions?.node) return "node";
253
- const e = globalThis.ServiceWorkerGlobalScope, t = globalThis.SharedWorkerGlobalScope, n = globalThis.DedicatedWorkerGlobalScope;
254
- if (e && self instanceof e) return "service-worker";
255
- if (t && self instanceof t) return "shared-worker";
256
- if (n && self instanceof n) return "worker";
257
- if (typeof chrome < "u" && chrome.runtime?.id) {
258
- if (typeof chrome.runtime.getBackgroundPage == "function" || chrome.runtime.getManifest?.()?.background?.service_worker) return "chrome-background";
259
- if (typeof chrome.devtools < "u") return "chrome-devtools";
260
- if (typeof document < "u" && globalThis?.location?.protocol === "chrome-extension:" && (chrome.extension?.getViews?.({ type: "popup" }) ?? []).includes(globalThis)) return "chrome-popup";
261
- if (typeof document < "u" && globalThis?.location?.protocol !== "chrome-extension:") return "chrome-content";
262
- }
263
- return typeof globalThis < "u" && typeof document < "u" ? "window" : "unknown";
264
- }
265
- function ae(e) {
266
- if (typeof RTCDataChannel < "u" && e instanceof RTCDataChannel) return "rtc-data";
267
- const t = qe(e);
268
- return t && t !== "internal" ? t : e === self || e === globalThis || e === "self" ? "self" : "internal";
269
- }
270
- function Ye(e) {
271
- if (!e) return "unknown";
272
- if (e.contextType) return e.contextType;
273
- const t = e.sender ?? "";
274
- return t.includes("worker") ? "worker" : t.includes("sw") || t.includes("service") ? "service-worker" : t.includes("chrome") || t.includes("crx") ? "chrome-content" : t.includes("background") ? "chrome-background" : "unknown";
275
- }
276
- const Ke = {
277
- get: (e, t) => Reflect.get(e, t),
278
- set: (e, t, n) => Reflect.set(e, t, n),
279
- has: (e, t) => Reflect.has(e, t),
280
- apply: (e, t, n) => Reflect.apply(e, t, n),
281
- construct: (e, t) => Reflect.construct(e, t),
282
- deleteProperty: (e, t) => Reflect.deleteProperty(e, t),
283
- ownKeys: (e) => Reflect.ownKeys(e),
284
- getOwnPropertyDescriptor: (e, t) => Reflect.getOwnPropertyDescriptor(e, t),
285
- getPrototypeOf: (e) => Reflect.getPrototypeOf(e),
286
- setPrototypeOf: (e, t) => Reflect.setPrototypeOf(e, t),
287
- isExtensible: (e) => Reflect.isExtensible(e),
288
- preventExtensions: (e) => Reflect.preventExtensions(e)
289
- }, Ve = Symbol.for("uniform.proxy"), Xe = Symbol.for("uniform.proxy.internals");
290
- var je = class {
291
- _invoker;
292
- _config;
293
- _childCache = /* @__PURE__ */ new Map();
294
- constructor(e, t) {
295
- this._invoker = e, this._config = {
296
- channel: t.channel,
297
- basePath: t.basePath ?? [],
298
- invoker: e,
299
- cache: t.cache ?? !0,
300
- timeout: t.timeout ?? 3e4
301
- };
302
- }
303
- get(e, t, n) {
304
- const s = String(t);
305
- if (t === Ve) return !0;
306
- if (t === Xe) return this._config;
307
- if (t === at) return !0;
308
- if (t === D) return this._getDescriptor();
309
- if (t === "then" || t === "catch" || t === "finally" || typeof t == "symbol") return;
310
- if (t === "$path") return this._config.basePath;
311
- if (t === "$channel") return this._config.channel;
312
- if (t === "$descriptor") return this._getDescriptor();
313
- if (t === "$invoke") return this._invoker;
314
- const r = [...this._config.basePath, s];
315
- if (this._config.cache && this._childCache.has(s)) return this._childCache.get(s);
316
- const i = H(this._invoker, {
317
- ...this._config,
318
- basePath: r
319
- });
320
- return this._config.cache && this._childCache.set(s, i), i;
321
- }
322
- set(e, t, n, s) {
323
- return typeof t == "symbol" || this._invoker(h.SET, [...this._config.basePath, String(t)], [n]), !0;
324
- }
325
- apply(e, t, n) {
326
- return this._invoker(h.APPLY, this._config.basePath, [n]);
327
- }
328
- construct(e, t, n) {
329
- return this._invoker(h.CONSTRUCT, this._config.basePath, [t]);
330
- }
331
- has(e, t) {
332
- return typeof t == "symbol" ? !1 : this._invoker(h.HAS, this._config.basePath, [t]);
333
- }
334
- deleteProperty(e, t) {
335
- return typeof t == "symbol" ? !0 : this._invoker(h.DELETE_PROPERTY, [...this._config.basePath, String(t)], []);
336
- }
337
- ownKeys(e) {
338
- return [];
339
- }
340
- getOwnPropertyDescriptor(e, t) {
341
- return {
342
- configurable: !0,
343
- enumerable: !0,
344
- writable: !0
345
- };
346
- }
347
- getPrototypeOf(e) {
348
- return Function.prototype;
349
- }
350
- setPrototypeOf(e, t) {
351
- return this._invoker(h.SET_PROTOTYPE_OF, this._config.basePath, [t]);
352
- }
353
- isExtensible(e) {
354
- return !0;
355
- }
356
- preventExtensions(e) {
357
- return this._invoker(h.PREVENT_EXTENSIONS, this._config.basePath, []);
358
- }
359
- _getDescriptor() {
360
- return {
361
- path: this._config.basePath,
362
- channel: this._config.channel,
363
- primitive: !1
364
- };
365
- }
366
- };
367
- function H(e, t) {
368
- const n = function() {}, s = new je(e, t);
369
- return new Proxy(n, s);
370
- }
371
- function ce(e, t, n) {
372
- if (!e || typeof e != "object" || e.primitive) return e;
373
- const s = _e.get(e);
374
- if (s) return s;
375
- const r = H(t, {
376
- channel: n ?? e.channel ?? "unknown",
377
- basePath: e.path ?? []
378
- });
379
- return _e.set(e, r), V.set(r, e), r;
380
- }
381
- const Ze = ce;
382
- function et(e) {
383
- return [
384
- e.localChannel,
385
- e.remoteChannel,
386
- e.sender,
387
- e.transportType,
388
- e.direction
389
- ].join("::");
390
- }
391
- function tt(e, t = {}) {
392
- const n = t.includeClosed ?? !1, s = t.status ?? (n ? void 0 : "active");
393
- return [...e].filter((r) => !(s && r.status !== s || t.channel && r.localChannel !== t.channel && r.remoteChannel !== t.channel || t.localChannel && r.localChannel !== t.localChannel || t.remoteChannel && r.remoteChannel !== t.remoteChannel || t.sender && r.sender !== t.sender || t.transportType && r.transportType !== t.transportType || t.direction && r.direction !== t.direction)).sort((r, i) => i.updatedAt - r.updatedAt);
394
- }
395
- var le = class {
396
- _createId;
397
- _emitEvent;
398
- _connections = /* @__PURE__ */ new Map();
399
- constructor(e, t) {
400
- this._createId = e, this._emitEvent = t;
401
- }
402
- register(e) {
403
- const t = et(e), n = Date.now(), s = this._connections.get(t);
404
- if (s) return s.updatedAt = n, s.status = "active", s.metadata = {
405
- ...s.metadata,
406
- ...e.metadata
407
- }, s;
408
- const r = {
409
- id: this._createId(),
410
- localChannel: e.localChannel,
411
- remoteChannel: e.remoteChannel,
412
- sender: e.sender,
413
- transportType: e.transportType,
414
- direction: e.direction,
415
- status: "active",
416
- createdAt: n,
417
- updatedAt: n,
418
- metadata: e.metadata
419
- };
420
- return this._connections.set(t, r), this._emitEvent?.({
421
- type: "connected",
422
- connection: r,
423
- timestamp: n
424
- }), r;
425
- }
426
- markNotified(e, t) {
427
- const n = Date.now();
428
- e.lastNotifyAt = n, e.updatedAt = n, this._emitEvent?.({
429
- type: "notified",
430
- connection: e,
431
- timestamp: n,
432
- payload: t
433
- });
434
- }
435
- closeByChannel(e) {
436
- const t = Date.now();
437
- for (const n of this._connections.values()) n.localChannel !== e && n.remoteChannel !== e || n.status !== "closed" && (n.status = "closed", n.updatedAt = t, this._emitEvent?.({
438
- type: "disconnected",
439
- connection: n,
440
- timestamp: t
441
- }));
442
- }
443
- closeAll() {
444
- const e = Date.now();
445
- for (const t of this._connections.values()) t.status !== "closed" && (t.status = "closed", t.updatedAt = e, this._emitEvent?.({
446
- type: "disconnected",
447
- connection: t,
448
- timestamp: e
449
- }));
450
- }
451
- query(e = {}) {
452
- return tt(this._connections.values(), e);
453
- }
454
- values() {
455
- return [...this._connections.values()];
456
- }
457
- clear() {
458
- this._connections.clear();
459
- }
460
- }, ue = class {
461
- _name;
462
- _contextType;
463
- _config;
464
- _transports = /* @__PURE__ */ new Map();
465
- _defaultTransport = null;
466
- _connectionEvents = new y({ bufferSize: 200 });
467
- _connectionRegistry = new le(() => d(), (e) => this._connectionEvents.next(e));
468
- _pending = /* @__PURE__ */ new Map();
469
- _subscriptions = [];
470
- _inbound = new y({ bufferSize: 100 });
471
- _outbound = new y({ bufferSize: 100 });
472
- _invocations = new y({ bufferSize: 100 });
473
- _responses = new y({ bufferSize: 100 });
474
- _exposed = /* @__PURE__ */ new Map();
475
- _proxyCache = /* @__PURE__ */ new WeakMap();
476
- __getPrivate(e) {
477
- return this[e];
478
- }
479
- __setPrivate(e, t) {
480
- this[e] = t;
481
- }
482
- constructor(e) {
483
- const t = typeof e == "string" ? { name: e } : e;
484
- this._name = t.name, this._contextType = t.autoDetect !== !1 ? ie() : "unknown", this._config = {
485
- name: t.name,
486
- autoDetect: t.autoDetect ?? !0,
487
- timeout: t.timeout ?? 3e4,
488
- reflect: t.reflect ?? Ke,
489
- bufferSize: t.bufferSize ?? 100,
490
- autoListen: t.autoListen ?? !0
491
- }, this._config.autoListen && this._isWorkerContext() && this.listen(self);
492
- }
493
- connect(e, t = {}) {
494
- const n = ae(e), s = t.targetChannel ?? this._inferTargetChannel(e, n), r = this._createTransportBinding(e, n, s, t);
495
- this._transports.set(s, r), this._defaultTransport || (this._defaultTransport = r);
496
- const i = this._registerConnection({
497
- localChannel: this._name,
498
- remoteChannel: s,
499
- sender: this._name,
500
- transportType: n,
501
- direction: "outgoing",
502
- metadata: { phase: "connect" }
503
- });
504
- return this._emitConnectionSignal(r, "connect", {
505
- connectionId: i.id,
506
- from: this._name,
507
- to: s
508
- }), this;
509
- }
510
- listen(e, t = {}) {
511
- const n = ae(e), s = t.targetChannel ?? this._inferTargetChannel(e, n), r = (o) => this._handleIncoming(o), i = this._registerConnection({
512
- localChannel: this._name,
513
- remoteChannel: s,
514
- sender: s,
515
- transportType: n,
516
- direction: "incoming",
517
- metadata: { phase: "listen" }
518
- });
519
- switch (n) {
520
- case "worker":
521
- case "message-port":
522
- case "broadcast":
523
- t.autoStart !== !1 && e.start && e.start(), e.addEventListener?.("message", ((o) => r(o.data)));
524
- break;
525
- case "websocket":
526
- e.addEventListener?.("message", ((o) => {
527
- try {
528
- r(JSON.parse(o.data));
529
- } catch {}
530
- }));
531
- break;
532
- case "chrome-runtime":
533
- chrome.runtime.onMessage?.addListener?.((o, a, c) => (r(o), !0));
534
- break;
535
- case "chrome-tabs":
536
- chrome.runtime.onMessage?.addListener?.((o, a) => t.tabId != null && a?.tab?.id !== t.tabId ? !1 : (r(o), !0));
537
- break;
538
- case "chrome-port":
539
- e?.onMessage?.addListener?.((o) => {
540
- r(o);
541
- });
542
- break;
543
- case "chrome-external":
544
- chrome.runtime.onMessageExternal?.addListener?.((o) => (r(o), !0));
545
- break;
546
- case "self":
547
- addEventListener?.("message", ((o) => r(o.data)));
548
- break;
549
- default: t.onMessage && t.onMessage(r);
550
- }
551
- return this._sendSignalToTarget(e, n, {
552
- connectionId: i.id,
553
- from: this._name,
554
- to: s,
555
- tabId: t.tabId,
556
- externalId: t.externalId
557
- }, "notify"), this;
558
- }
559
- attach(e, t = {}) {
560
- return this.connect(e, t);
561
- }
562
- expose(e, t) {
563
- const n = [e];
564
- return U(n, t), this._exposed.set(e, {
565
- name: e,
566
- obj: t,
567
- path: n
568
- }), this;
569
- }
570
- exposeAll(e) {
571
- for (const [t, n] of Object.entries(e)) this.expose(t, n);
572
- return this;
573
- }
574
- async import(e, t) {
575
- return this.invoke(t ?? this._getDefaultTarget(), h.IMPORT, [], [e]);
576
- }
577
- invoke(e, t, n, s = []) {
578
- const r = d(), i = Promise.withResolvers();
579
- this._pending.set(r, i);
580
- const o = setTimeout(() => {
581
- this._pending.has(r) && (this._pending.delete(r), i.reject(/* @__PURE__ */ new Error(`Request timeout: ${t} on ${n.join(".")}`)));
582
- }, this._config.timeout), a = {
583
- id: r,
584
- channel: e,
585
- sender: this._name,
586
- type: "request",
587
- payload: {
588
- channel: e,
589
- sender: this._name,
590
- action: t,
591
- path: n,
592
- args: s
593
- },
594
- timestamp: Date.now()
595
- };
596
- return this._send(e, a), this._outbound.next(a), i.promise.finally(() => clearTimeout(o));
597
- }
598
- get(e, t, n) {
599
- return this.invoke(e, h.GET, t, [n]);
600
- }
601
- set(e, t, n, s) {
602
- return this.invoke(e, h.SET, t, [n, s]);
603
- }
604
- call(e, t, n = []) {
605
- return this.invoke(e, h.APPLY, t, [n]);
606
- }
607
- construct(e, t, n = []) {
608
- return this.invoke(e, h.CONSTRUCT, t, [n]);
609
- }
610
- proxy(e, t = []) {
611
- const n = e ?? this._getDefaultTarget();
612
- return this._createProxy(n, t);
613
- }
614
- remote(e, t) {
615
- return this.proxy(t, [e]);
616
- }
617
- wrapDescriptor(e, t) {
618
- return ce(e, (s, r, i) => {
619
- const o = t ?? e?.channel ?? this._getDefaultTarget();
620
- return this.invoke(o, s, r, i);
621
- }, t ?? e?.channel ?? this._getDefaultTarget());
622
- }
623
- subscribe(e) {
624
- return this._inbound.subscribe(e);
625
- }
626
- next(e) {
627
- this._send(e.channel, e), this._outbound.next(e);
628
- }
629
- emit(e, t, n) {
630
- const s = {
631
- id: d(),
632
- channel: e,
633
- sender: this._name,
634
- type: "event",
635
- payload: {
636
- type: t,
637
- data: n
638
- },
639
- timestamp: Date.now()
640
- };
641
- this.next(s);
642
- }
643
- notify(e, t = {}, n = "notify") {
644
- const s = this._transports.get(e);
645
- return s ? (this._emitConnectionSignal(s, n, {
646
- from: this._name,
647
- to: e,
648
- ...t
649
- }), !0) : !1;
650
- }
651
- get onMessage() {
652
- return this._inbound;
653
- }
654
- get onOutbound() {
655
- return this._outbound;
656
- }
657
- get onInvocation() {
658
- return this._invocations;
659
- }
660
- get onResponse() {
661
- return this._responses;
662
- }
663
- get onConnection() {
664
- return this._connectionEvents;
665
- }
666
- subscribeConnections(e) {
667
- return this._connectionEvents.subscribe(e);
668
- }
669
- queryConnections(e = {}) {
670
- return this._connectionRegistry.query(e);
671
- }
672
- notifyConnections(e = {}, t = {}) {
673
- let n = 0;
674
- const s = this.queryConnections({
675
- ...t,
676
- status: "active",
677
- includeClosed: !1
678
- });
679
- for (const r of s) {
680
- const i = this._transports.get(r.remoteChannel);
681
- i && (this._emitConnectionSignal(i, "notify", {
682
- connectionId: r.id,
683
- from: this._name,
684
- to: r.remoteChannel,
685
- ...e
686
- }), n++);
687
- }
688
- return n;
689
- }
690
- get name() {
691
- return this._name;
692
- }
693
- get contextType() {
694
- return this._contextType;
695
- }
696
- get config() {
697
- return this._config;
698
- }
699
- get connectedChannels() {
700
- return [...this._transports.keys()];
701
- }
702
- get exposedModules() {
703
- return [...this._exposed.keys()];
704
- }
705
- close() {
706
- this._subscriptions.forEach((e) => e.unsubscribe()), this._subscriptions = [], this._pending.clear(), this._markAllConnectionsClosed();
707
- for (const e of this._transports.values()) {
708
- try {
709
- e.cleanup?.();
710
- } catch {}
711
- if (e.transportType === "message-port" || e.transportType === "broadcast") try {
712
- e.target?.close?.();
713
- } catch {}
714
- }
715
- this._transports.clear(), this._defaultTransport = null, this._connectionRegistry.clear(), this._inbound.complete(), this._outbound.complete(), this._invocations.complete(), this._responses.complete(), this._connectionEvents.complete();
716
- }
717
- _handleIncoming(e) {
718
- if (!(!e || typeof e != "object")) switch (this._inbound.next(e), e.type) {
719
- case "request":
720
- e.channel === this._name && this._handleRequest(e);
721
- break;
722
- case "response":
723
- this._handleResponse(e);
724
- break;
725
- case "event": break;
726
- case "signal": this._handleSignal(e);
727
- }
728
- }
729
- _handleResponse(e) {
730
- const t = e.reqId ?? e.id, n = this._pending.get(t);
731
- if (n) {
732
- if (this._pending.delete(t), e.payload?.error) n.reject(new Error(e.payload.error));
733
- else {
734
- const s = e.payload?.result, r = e.payload?.descriptor;
735
- s != null ? n.resolve(s) : r ? n.resolve(this.wrapDescriptor(r, e.sender)) : n.resolve(void 0);
736
- }
737
- this._responses.next({
738
- id: t,
739
- channel: e.channel,
740
- sender: e.sender,
741
- result: e.payload?.result,
742
- descriptor: e.payload?.descriptor,
743
- timestamp: Date.now()
744
- });
745
- }
746
- }
747
- async _handleRequest(e) {
748
- const t = e.payload;
749
- if (!t) return;
750
- const { action: n, path: s, args: r, sender: i } = t, o = e.reqId ?? e.id;
751
- this._invocations.next({
752
- id: o,
753
- channel: this._name,
754
- sender: i,
755
- action: n,
756
- path: s,
757
- args: r ?? [],
758
- timestamp: Date.now(),
759
- contextType: Ye(e)
760
- });
761
- const { result: a, toTransfer: c, newPath: l } = await this._executeAction(n, s, r ?? [], i);
762
- await this._sendResponse(o, n, i, l, a, c);
763
- }
764
- async _executeAction(e, t, n, s) {
765
- const { result: r, toTransfer: i, path: o } = we(e, t, n, {
766
- channel: this._name,
767
- sender: s,
768
- reflect: this._config.reflect
769
- });
770
- return {
771
- result: await r,
772
- toTransfer: i,
773
- newPath: o
774
- };
775
- }
776
- async _sendResponse(e, t, n, s, r, i) {
777
- const { response: o, transfer: a } = await be(e, t, this._name, n, s, r, i), c = {
778
- id: e,
779
- ...o,
780
- timestamp: Date.now(),
781
- transferable: a
782
- };
783
- this._send(n, c, a);
784
- }
785
- _handleSignal(e) {
786
- const t = e?.payload ?? {}, n = t.from ?? e.sender ?? "unknown", s = e.transportType ?? this._transports.get(e.channel)?.transportType ?? "internal", r = this._registerConnection({
787
- localChannel: this._name,
788
- remoteChannel: n,
789
- sender: e.sender ?? n,
790
- transportType: s,
791
- direction: "incoming"
792
- });
793
- this._markConnectionNotified(r, t);
794
- }
795
- _registerConnection(e) {
796
- return this._connectionRegistry.register(e);
797
- }
798
- _markConnectionNotified(e, t) {
799
- this._connectionRegistry.markNotified(e, t);
800
- }
801
- _emitConnectionSignal(e, t, n = {}) {
802
- const s = {
803
- id: d(),
804
- type: "signal",
805
- channel: e.targetChannel,
806
- sender: this._name,
807
- transportType: e.transportType,
808
- payload: {
809
- type: t,
810
- from: this._name,
811
- to: e.targetChannel,
812
- ...n
813
- },
814
- timestamp: Date.now()
815
- };
816
- (e?.sender ?? e?.postMessage)?.call(e, s);
817
- const r = this._registerConnection({
818
- localChannel: this._name,
819
- remoteChannel: e.targetChannel,
820
- sender: this._name,
821
- transportType: e.transportType,
822
- direction: "outgoing"
823
- });
824
- this._markConnectionNotified(r, s.payload);
825
- }
826
- _sendSignalToTarget(e, t, n, s) {
827
- const r = {
828
- id: d(),
829
- type: "signal",
830
- channel: n.to ?? this._name,
831
- sender: this._name,
832
- transportType: t,
833
- payload: {
834
- type: s,
835
- ...n
836
- },
837
- timestamp: Date.now()
838
- };
839
- try {
840
- if (t === "websocket") {
841
- e?.send?.(JSON.stringify(r));
842
- return;
843
- }
844
- if (t === "chrome-runtime") {
845
- chrome.runtime?.sendMessage?.(r);
846
- return;
847
- }
848
- if (t === "chrome-tabs") {
849
- const i = n.tabId;
850
- i != null && chrome.tabs?.sendMessage?.(i, r);
851
- return;
852
- }
853
- if (t === "chrome-port") {
854
- e?.postMessage?.(r);
855
- return;
856
- }
857
- if (t === "chrome-external") {
858
- n.externalId && chrome.runtime?.sendMessage?.(n.externalId, r);
859
- return;
860
- }
861
- e?.postMessage?.(r, { transfer: [] });
862
- } catch {}
863
- }
864
- _markAllConnectionsClosed() {
865
- this._connectionRegistry.closeAll();
866
- }
867
- _createTransportBinding(e, t, n, s) {
868
- let r, i;
869
- switch (t) {
870
- case "worker":
871
- case "message-port":
872
- case "broadcast":
873
- s.autoStart !== !1 && e.start && e.start(), r = (o, a) => e.postMessage(o, { transfer: a });
874
- {
875
- const o = ((a) => this._handleIncoming(a.data));
876
- e.addEventListener?.("message", o), i = () => e.removeEventListener?.("message", o);
877
- }
878
- break;
879
- case "websocket":
880
- r = (o) => e.send(JSON.stringify(o));
881
- {
882
- const o = ((a) => {
883
- try {
884
- this._handleIncoming(JSON.parse(a.data));
885
- } catch {}
886
- });
887
- e.addEventListener?.("message", o), i = () => e.removeEventListener?.("message", o);
888
- }
889
- break;
890
- case "chrome-runtime":
891
- r = (o) => chrome.runtime.sendMessage(o);
892
- {
893
- const o = (a) => this._handleIncoming(a);
894
- chrome.runtime.onMessage?.addListener?.(o), i = () => chrome.runtime.onMessage?.removeListener?.(o);
895
- }
896
- break;
897
- case "chrome-tabs":
898
- r = (o) => {
899
- s.tabId != null && chrome.tabs?.sendMessage?.(s.tabId, o);
900
- };
901
- {
902
- const o = (a, c) => s.tabId != null && c?.tab?.id !== s.tabId ? !1 : (this._handleIncoming(a), !0);
903
- chrome.runtime.onMessage?.addListener?.(o), i = () => chrome.runtime.onMessage?.removeListener?.(o);
904
- }
905
- break;
906
- case "chrome-port":
907
- if (e?.postMessage && e?.onMessage?.addListener) {
908
- r = (a) => e.postMessage(a);
909
- const o = (a) => this._handleIncoming(a);
910
- e.onMessage.addListener(o), i = () => {
911
- try {
912
- e.onMessage.removeListener(o);
913
- } catch {}
914
- try {
915
- e.disconnect?.();
916
- } catch {}
917
- };
918
- } else {
919
- const o = s.portName ?? n, a = s.tabId != null && chrome.tabs?.connect ? chrome.tabs.connect(s.tabId, { name: o }) : chrome.runtime.connect({ name: o });
920
- r = (l) => a.postMessage(l);
921
- const c = (l) => this._handleIncoming(l);
922
- a.onMessage.addListener(c), i = () => {
923
- try {
924
- a.onMessage.removeListener(c);
925
- } catch {}
926
- try {
927
- a.disconnect();
928
- } catch {}
929
- };
930
- }
931
- break;
932
- case "chrome-external":
933
- r = (o) => {
934
- s.externalId && chrome.runtime.sendMessage(s.externalId, o);
935
- };
936
- {
937
- const o = (a) => (this._handleIncoming(a), !0);
938
- chrome.runtime.onMessageExternal?.addListener?.(o), i = () => chrome.runtime.onMessageExternal?.removeListener?.(o);
939
- }
940
- break;
941
- case "self":
942
- r = (o, a) => globalThis.postMessage?.(o, { transfer: a ?? [] });
943
- {
944
- const o = ((a) => this._handleIncoming(a.data));
945
- globalThis.addEventListener?.("message", o), i = () => globalThis.removeEventListener?.("message", o);
946
- }
947
- break;
948
- default: s.onMessage && (i = s.onMessage((o) => this._handleIncoming(o))), r = (o) => e?.postMessage?.(o);
949
- }
950
- return {
951
- target: e,
952
- targetChannel: n,
953
- transportType: t,
954
- sender: r,
955
- cleanup: i,
956
- postMessage: (o, a) => r?.(o, a),
957
- start: () => e?.start?.(),
958
- close: () => e?.close?.()
959
- };
960
- }
961
- _send(e, t, n) {
962
- const s = this._transports.get(e) ?? this._defaultTransport;
963
- (s?.sender ?? s?.postMessage)?.call(s, t, n);
964
- }
965
- _getDefaultTarget() {
966
- return this._defaultTransport ? this._defaultTransport.targetChannel : "worker";
967
- }
968
- _inferTargetChannel(e, t) {
969
- return t === "worker" ? "worker" : t === "broadcast" && e.name ? e.name : t === "self" ? "self" : `${t}-${d().slice(0, 8)}`;
970
- }
971
- _createProxy(e, t) {
972
- return H((s, r, i) => this.invoke(e, s, r, i), {
973
- channel: e,
974
- basePath: t,
975
- cache: !0,
976
- timeout: this._config.timeout
977
- });
978
- }
979
- _isWorkerContext() {
980
- return [
981
- "worker",
982
- "shared-worker",
983
- "service-worker"
984
- ].includes(this._contextType);
985
- }
986
- };
987
- function Y(e) {
988
- return new ue(e);
989
- }
990
- let G = null;
991
- function nt() {
992
- if (!G) {
993
- const e = ie();
994
- [
995
- "worker",
996
- "shared-worker",
997
- "service-worker"
998
- ].includes(e) ? G = Y({
999
- name: "worker",
1000
- autoListen: !0
1001
- }) : G = Y({
1002
- name: "host",
1003
- autoListen: !1
1004
- });
1005
- }
1006
- return G;
1007
- }
1008
- const m = {
1009
- rjb: "rejectBy",
1010
- rvb: "resolveBy",
1011
- rj: "reject",
1012
- rv: "resolve",
1013
- cr: "create",
1014
- cs: "createSync",
1015
- a: "array",
1016
- ta: "typedarray",
1017
- udf: "undefined"
1018
- };
1019
- [
1020
- typeof ArrayBuffer != m.udf ? ArrayBuffer : null,
1021
- typeof MessagePort != m.udf ? MessagePort : null,
1022
- typeof ReadableStream != m.udf ? ReadableStream : null,
1023
- typeof WritableStream != m.udf ? WritableStream : null,
1024
- typeof TransformStream != m.udf ? TransformStream : null,
1025
- typeof WebTransportReceiveStream != m.udf ? WebTransportReceiveStream : null,
1026
- typeof WebTransportSendStream != m.udf ? WebTransportSendStream : null,
1027
- typeof AudioData != m.udf ? AudioData : null,
1028
- typeof ImageBitmap != m.udf ? ImageBitmap : null,
1029
- typeof VideoFrame != m.udf ? VideoFrame : null,
1030
- typeof OffscreenCanvas != m.udf ? OffscreenCanvas : null,
1031
- typeof RTCDataChannel != m.udf ? RTCDataChannel : null
1032
- ].filter((e) => e != null);
1033
- function he() {
1034
- try {
1035
- const e = globalThis.location?.href;
1036
- if (typeof e == "string" && e.length > 0) return e;
1037
- } catch {}
1038
- try {
1039
- if (typeof document < "u" && typeof document.baseURI == "string" && document.baseURI.length > 0) return document.baseURI;
1040
- } catch {}
1041
- return "";
1042
- }
1043
- function de(e) {
1044
- const t = he();
1045
- if (!t.length) throw new TypeError("[uniform] No base URL for worker resolution (missing location / document.baseURI)");
1046
- const n = e.startsWith("/") ? e.replace(/^\//, "./") : e;
1047
- return new URL(n, t).href;
1048
- }
1049
- const w = {
1050
- name: "unknown",
1051
- instance: null
1052
- }, K = /* @__PURE__ */ new Map(), fe = (e) => [...Object.values(h)].includes(e);
1053
- var st = class {
1054
- channelName;
1055
- options;
1056
- _channel;
1057
- constructor(e, t = {}) {
1058
- this.channelName = e, this.options = t, this._channel = nt();
1059
- }
1060
- request(e, t, n, s = {}) {
1061
- return typeof e == "string" && (e = [e]), Array.isArray(t) && fe(e) && (s = n, n = t, t = e, e = []), this._channel.invoke(this.channelName, t, e, n);
1062
- }
1063
- doImportModule(e, t) {
1064
- return this._channel.import(e, this.channelName);
1065
- }
1066
- }, rt = class {
1067
- channel;
1068
- options;
1069
- _unified;
1070
- broadcasts = {};
1071
- constructor(e, t = {}) {
1072
- this.channel = e, this.options = t, this._unified = Y({
1073
- name: e,
1074
- autoListen: !1
1075
- }), w.name = e, w.instance = this;
1076
- }
1077
- createRemoteChannel(e, t = {}, n) {
1078
- return n && (this._unified.attach(n, { targetChannel: e }), this.broadcasts[e] = n), Promise.resolve(new st(e, t));
1079
- }
1080
- getChannel() {
1081
- return this.channel;
1082
- }
1083
- request(e, t, n, s = {}, r = "worker") {
1084
- return typeof e == "string" && (e = [e]), Array.isArray(t) && fe(e) && (r = s, s = n, n = t, t = e, e = []), this._unified.invoke(r, t, e, n);
1085
- }
1086
- resolveResponse(e, t) {
1087
- return Promise.resolve(t);
1088
- }
1089
- async handleAndResponse(e, t, n) {
1090
- const s = await ut(e, t, this.channel);
1091
- s && n?.(s.response, s.transfer);
1092
- }
1093
- close() {
1094
- this._unified.close();
1095
- }
1096
- };
1097
- const ot = (e = "$host$") => {
1098
- if (w?.instance && e === "$host$") return w.instance;
1099
- if (K.has(e)) return K.get(e) ?? null;
1100
- const t = new rt(e);
1101
- return e === "$host$" && (w.name = e, w.instance = t), K.set(e, t), t;
1102
- }, pe = /* @__PURE__ */ new WeakMap(), V = /* @__PURE__ */ new WeakMap(), _e = /* @__PURE__ */ new WeakMap(), it = (e, t = w?.name, n) => typeof e == "object" && e != null || typeof e == "function" && e != null ? V.has(e) ? V.get(e) : pe.has(e) ? pe.get(e) : $(e) || n?.includes?.(e) || t == w?.name ? e : {
1103
- $isDescriptor: !0,
1104
- path: T.get(e) ?? (() => {
1105
- const s = [d()];
1106
- return U(s, e), s;
1107
- })(),
1108
- owner: w?.name,
1109
- channel: t,
1110
- primitive: C(e),
1111
- writable: !0,
1112
- enumerable: !0,
1113
- configurable: !0,
1114
- argumentCount: e instanceof Function ? e.length : -1
1115
- } : x(e) ? e : null, at = Symbol.for("@requestHandler"), D = Symbol.for("@descriptor"), X = (e) => x(e) || e?.[D] ? e : e?.$isDescriptor ? Ze(e, async () => {}) : $(e) ? e : null, L = /* @__PURE__ */ new Map(), T = /* @__PURE__ */ new WeakMap(), ye = (e, t) => {
1116
- if (t != null && !Array.isArray(t) && (t = [t]), t == null || t?.length < 1) return e;
1117
- const n = e?.[D] ?? (e?.$isDescriptor ? e : null);
1118
- if (n && n?.owner == w?.name && (e = R(n?.path) ?? e), C(e)) return e;
1119
- for (const s of t) if (e = e?.[s], e == null) return e;
1120
- return e;
1121
- }, R = (e) => {
1122
- if (e != null && !Array.isArray(e) && (e = [e]), e == null || e?.length < 1) return null;
1123
- const t = L?.get?.(e?.[0]) ?? null;
1124
- return t != null ? ye(t, e?.slice?.(1)) : null;
1125
- }, U = (e, t) => {
1126
- const n = t?.[D] ?? (t?.$isDescriptor ? t : null);
1127
- if (n && n?.owner == w?.name && (t = R(n?.path) ?? t), e != null && !Array.isArray(e) && (e = [e]), e == null || e?.length < 1) return null;
1128
- const s = L?.get?.(e?.[0]) ?? null;
1129
- return e?.length > 1 ? ye(s, e?.slice?.(1, -1))[e?.[e?.length - 1]] = t : L?.set?.(e?.[0], t), (typeof t == "object" || typeof t == "function") && T?.set?.(t, e), t;
1130
- }, ge = (e) => (e != null && !Array.isArray(e) && (e = [e]), e == null || e?.length < 1 ? !1 : !(L?.get?.(e?.[0]) ?? null) && e?.length <= 1 ? (L?.delete?.(e?.[0]), !0) : !1), ct = (e) => {
1131
- const t = e?.[D] ?? (e?.$isDescriptor ? e : null);
1132
- t && t?.owner == w?.name && (e = R(t?.path) ?? e);
1133
- const n = T?.get?.(e) ?? t?.path;
1134
- return n == null || n?.length < 1 ? !1 : (ge(n), (typeof e == "object" || typeof e == "function") && T?.delete?.(e), !0);
1135
- }, lt = (e) => {
1136
- const t = e?.[D] ?? (e?.$isDescriptor ? e : null);
1137
- return (T?.get?.(e) ?? t?.path) == null;
1138
- }, E = (e) => (typeof e == "object" || typeof e == "function") && e != null, me = {
1139
- get: (e, t) => e?.[t],
1140
- set: (e, t, n) => (e[t] = n, !0),
1141
- has: (e, t) => t in e,
1142
- apply: (e, t, n) => e.apply(t, n),
1143
- construct: (e, t) => new e(...t),
1144
- deleteProperty: (e, t) => delete e[t],
1145
- ownKeys: (e) => Object.keys(e),
1146
- getOwnPropertyDescriptor: (e, t) => Object.getOwnPropertyDescriptor(e, t),
1147
- getPrototypeOf: (e) => Object.getPrototypeOf(e),
1148
- setPrototypeOf: (e, t) => Object.setPrototypeOf(e, t),
1149
- isExtensible: (e) => Object.isExtensible(e),
1150
- preventExtensions: (e) => Object.preventExtensions(e)
1151
- };
1152
- function we(e, t, n, s = {}) {
1153
- const { channel: r = "", sender: i = "", reflect: o = me } = s, a = s.target ?? R(t), c = [];
1154
- let l = null, _ = t;
1155
- switch (String(e).toLowerCase()) {
1156
- case "import":
1157
- case h.IMPORT:
1158
- l = import(n?.[0]);
1159
- break;
1160
- case "transfer":
1161
- case h.TRANSFER:
1162
- z(a) && r !== i && c.push(a), l = a;
1163
- break;
1164
- case "get":
1165
- case h.GET: {
1166
- const f = n?.[0], b = o.get?.(a, f) ?? a?.[f];
1167
- l = typeof b == "function" && a != null ? b.bind(a) : b, _ = [...t, String(f)];
1168
- break;
1169
- }
1170
- case "set":
1171
- case h.SET: {
1172
- const [f, b] = n, N = k(b, X);
1173
- s.target ? l = o.set?.(a, f, N) ?? (a[f] = N, !0) : l = o.set?.(a, f, N) ?? U([...t, String(f)], N);
1174
- break;
1175
- }
1176
- case "apply":
1177
- case "call":
1178
- case h.APPLY:
1179
- case h.CALL:
1180
- if (typeof a == "function") {
1181
- const f = s.context ?? (s.target ? void 0 : R(t.slice(0, -1))), b = k(n?.[0] ?? n ?? [], X);
1182
- l = o.apply?.(a, f, b) ?? a.apply(f, b), z(l) && t?.at(-1) === "transfer" && r !== i && c.push(l);
1183
- }
1184
- break;
1185
- case "construct":
1186
- case h.CONSTRUCT:
1187
- if (typeof a == "function") {
1188
- const f = k(n?.[0] ?? n ?? [], X);
1189
- l = o.construct?.(a, f) ?? new a(...f);
1190
- }
1191
- break;
1192
- case "delete":
1193
- case "deleteproperty":
1194
- case "dispose":
1195
- case h.DELETE:
1196
- case h.DELETE_PROPERTY:
1197
- case h.DISPOSE:
1198
- if (s.target) {
1199
- const f = t[t.length - 1];
1200
- l = o.deleteProperty?.(a, f) ?? delete a[f];
1201
- } else l = t?.length > 0 ? ge(t) : ct(a), l && (_ = T.get(a) ?? []);
1202
- break;
1203
- case "has":
1204
- case h.HAS:
1205
- l = o.has?.(a, n?.[0]) ?? (E(a) ? n?.[0] in a : !1);
1206
- break;
1207
- case "ownkeys":
1208
- case h.OWN_KEYS:
1209
- l = o.ownKeys?.(a) ?? (E(a) ? Object.keys(a) : []);
1210
- break;
1211
- case "getownpropertydescriptor":
1212
- case "getpropertydescriptor":
1213
- case h.GET_OWN_PROPERTY_DESCRIPTOR:
1214
- case h.GET_PROPERTY_DESCRIPTOR:
1215
- l = o.getOwnPropertyDescriptor?.(a, n?.[0] ?? t?.at(-1) ?? "") ?? (E(a) ? Object.getOwnPropertyDescriptor(a, n?.[0] ?? t?.at(-1) ?? "") : void 0);
1216
- break;
1217
- case "getprototypeof":
1218
- case h.GET_PROTOTYPE_OF:
1219
- l = o.getPrototypeOf?.(a) ?? (E(a) ? Object.getPrototypeOf(a) : null);
1220
- break;
1221
- case "setprototypeof":
1222
- case h.SET_PROTOTYPE_OF:
1223
- l = o.setPrototypeOf?.(a, n?.[0]) ?? (E(a) ? Object.setPrototypeOf(a, n?.[0]) : !1);
1224
- break;
1225
- case "isextensible":
1226
- case h.IS_EXTENSIBLE:
1227
- l = o.isExtensible?.(a) ?? (E(a) ? Object.isExtensible(a) : !0);
1228
- break;
1229
- case "preventextensions":
1230
- case h.PREVENT_EXTENSIONS: l = o.preventExtensions?.(a) ?? (E(a) ? Object.preventExtensions(a) : !1);
1231
- }
1232
- return {
1233
- result: l,
1234
- toTransfer: c,
1235
- path: _
1236
- };
1237
- }
1238
- async function be(e, t, n, s, r, i, o) {
1239
- const a = await i, c = z(a) && o.includes(a) || x(a);
1240
- let l = r;
1241
- !c && t !== "get" && t !== h.GET && (typeof a == "object" || typeof a == "function") && (lt(a) ? (l = [d()], U(l, a)) : l = T.get(a) ?? []);
1242
- const _ = R(l), f = t === "get" || t === h.GET ? l?.at(-1) : void 0, b = R(r), N = k(a, (Ot) => it(Ot, n, o)) ?? a;
1243
- return {
1244
- response: {
1245
- channel: s,
1246
- sender: n,
1247
- reqId: e,
1248
- action: t,
1249
- type: "response",
1250
- payload: {
1251
- result: c ? N : null,
1252
- type: typeof a,
1253
- channel: s,
1254
- sender: n,
1255
- descriptor: {
1256
- $isDescriptor: !0,
1257
- path: l,
1258
- owner: n,
1259
- channel: n,
1260
- primitive: C(a),
1261
- writable: !0,
1262
- enumerable: !0,
1263
- configurable: !0,
1264
- argumentCount: b instanceof Function ? b.length : -1,
1265
- ...E(_) && f != null ? Object.getOwnPropertyDescriptor(_, f) : {}
1266
- }
1267
- }
1268
- },
1269
- transfer: o
1270
- };
1271
- }
1272
- async function ut(e, t, n, s) {
1273
- const { channel: r, sender: i, path: o, action: a, args: c } = e;
1274
- if (r !== n) return null;
1275
- const { result: l, toTransfer: _, path: f } = we(a, o, c, {
1276
- channel: r,
1277
- sender: i,
1278
- ...s
1279
- });
1280
- return be(t, a, n, i, f, l, _);
1281
- }
1282
- var dt = class {
1283
- _name;
1284
- _transportType;
1285
- _id = d();
1286
- _state = "disconnected";
1287
- _inbound = new y({ bufferSize: 1e3 });
1288
- _outbound = new y({ bufferSize: 1e3 });
1289
- _stateChanges = new y();
1290
- _connectedPeers = /* @__PURE__ */ new Map();
1291
- _subs = [];
1292
- _stats = {
1293
- messagesSent: 0,
1294
- messagesReceived: 0,
1295
- bytesTransferred: 0,
1296
- latencyMs: 0,
1297
- uptime: 0,
1298
- reconnectCount: 0
1299
- };
1300
- _startTime = 0;
1301
- _pending = /* @__PURE__ */ new Map();
1302
- _buffer = [];
1303
- _opts;
1304
- constructor(e, t = "internal", n = {}) {
1305
- this._name = e, this._transportType = t, this._opts = {
1306
- timeout: 3e4,
1307
- autoReconnect: !0,
1308
- reconnectInterval: 1e3,
1309
- maxReconnectAttempts: 5,
1310
- bufferMessages: !0,
1311
- bufferSize: 1e3,
1312
- metadata: {},
1313
- ...n
1314
- }, this._setupSubscriptions();
1315
- }
1316
- subscribe(e, t) {
1317
- return (t ? ze((n) => n.sender === t)(this._inbound) : this._inbound).subscribe(typeof e == "function" ? { next: e } : e);
1318
- }
1319
- next(e) {
1320
- if (this._state !== "connected") {
1321
- this._opts.bufferMessages && this._buffer.length < this._opts.bufferSize && this._buffer.push(e);
1322
- return;
1323
- }
1324
- this._outbound.next(e), this._stats.messagesSent++;
1325
- }
1326
- async request(e, t, n = {}) {
1327
- const s = d(), r = Promise.withResolvers();
1328
- this._pending.set(s, r);
1329
- const i = setTimeout(() => {
1330
- this._pending.has(s) && (this._pending.delete(s), r.reject(/* @__PURE__ */ new Error("Request timeout")));
1331
- }, n.timeout ?? this._opts.timeout);
1332
- return this.next({
1333
- id: d(),
1334
- channel: e,
1335
- sender: this._name,
1336
- type: "request",
1337
- reqId: s,
1338
- payload: {
1339
- ...t,
1340
- action: n.action,
1341
- path: n.path
1342
- },
1343
- timestamp: Date.now()
1344
- }), r.promise.finally(() => clearTimeout(i));
1345
- }
1346
- respond(e, t) {
1347
- this.next({
1348
- id: d(),
1349
- channel: e.sender,
1350
- sender: this._name,
1351
- type: "response",
1352
- reqId: e.reqId,
1353
- payload: t,
1354
- timestamp: Date.now()
1355
- });
1356
- }
1357
- emit(e, t, n) {
1358
- this.next({
1359
- id: d(),
1360
- channel: e,
1361
- sender: this._name,
1362
- type: "event",
1363
- payload: {
1364
- type: t,
1365
- data: n
1366
- },
1367
- timestamp: Date.now()
1368
- });
1369
- }
1370
- subscribeOutbound(e) {
1371
- return this._outbound.subscribe(typeof e == "function" ? { next: e } : e);
1372
- }
1373
- pushInbound(e) {
1374
- if (this._stats.messagesReceived++, e.type === "response" && e.reqId) {
1375
- const t = this._pending.get(e.reqId);
1376
- if (t) {
1377
- this._pending.delete(e.reqId), t.resolve(e.payload);
1378
- return;
1379
- }
1380
- }
1381
- this._inbound.next(e);
1382
- }
1383
- async connect() {
1384
- this._state !== "connected" && (this._setState("connecting"), this._startTime = Date.now(), this._setState("connected"), this._flushBuffer());
1385
- }
1386
- disconnect() {
1387
- this._state === "disconnected" || this._state === "closed" || (this._setState("disconnected"), this._subs.forEach((e) => e.unsubscribe()), this._subs = []);
1388
- }
1389
- close() {
1390
- this.disconnect(), this._setState("closed"), this._inbound.complete(), this._outbound.complete(), this._stateChanges.complete();
1391
- }
1392
- markConnected() {
1393
- this._setState("connected"), this._flushBuffer();
1394
- }
1395
- markDisconnected() {
1396
- this._setState("disconnected");
1397
- }
1398
- _setState(e) {
1399
- this._state !== e && (this._state = e, this._stateChanges.next(e));
1400
- }
1401
- _flushBuffer() {
1402
- for (const e of this._buffer) this._outbound.next(e);
1403
- this._buffer = [];
1404
- }
1405
- _setupSubscriptions() {
1406
- this._subs.push(this._inbound.subscribe({ next: (e) => {
1407
- e.type === "signal" && e.payload?.type === "connect" && this._connectedPeers.set(e.sender, {
1408
- name: e.sender,
1409
- state: "connected",
1410
- isHost: !1
1411
- });
1412
- } }));
1413
- }
1414
- get id() {
1415
- return this._id;
1416
- }
1417
- get name() {
1418
- return this._name;
1419
- }
1420
- get state() {
1421
- return this._state;
1422
- }
1423
- get transportType() {
1424
- return this._transportType;
1425
- }
1426
- get stats() {
1427
- return {
1428
- ...this._stats,
1429
- uptime: this._startTime ? Date.now() - this._startTime : 0
1430
- };
1431
- }
1432
- get stateChanges() {
1433
- return this._stateChanges;
1434
- }
1435
- get connectedPeers() {
1436
- return [...this._connectedPeers.keys()];
1437
- }
1438
- get meta() {
1439
- return {
1440
- id: this._id,
1441
- name: this._name,
1442
- state: this._state,
1443
- isHost: !1,
1444
- connectedChannels: new Set(this._connectedPeers.keys())
1445
- };
1446
- }
1447
- }, ft = class F {
1448
- _connections = /* @__PURE__ */ new Map();
1449
- static _instance = null;
1450
- static getInstance() {
1451
- return F._instance || (F._instance = new F()), F._instance;
1452
- }
1453
- getOrCreate(t, n = "internal", s = {}) {
1454
- return this._connections.has(t) || this._connections.set(t, new dt(t, n, s)), this._connections.get(t);
1455
- }
1456
- get(t) {
1457
- return this._connections.get(t);
1458
- }
1459
- has(t) {
1460
- return this._connections.has(t);
1461
- }
1462
- delete(t) {
1463
- return this._connections.get(t)?.close(), this._connections.delete(t);
1464
- }
1465
- clear() {
1466
- this._connections.forEach((t) => t.close()), this._connections.clear();
1467
- }
1468
- get size() {
1469
- return this._connections.size;
1470
- }
1471
- get names() {
1472
- return [...this._connections.keys()];
1473
- }
1474
- };
1475
- const Ce = () => ft.getInstance(), pt = (e, t, n) => Ce().getOrCreate(e, t, n), _t = "uniform_channels", yt = 1, u = {
1476
- MESSAGES: "messages",
1477
- MAILBOX: "mailbox",
1478
- PENDING: "pending",
1479
- EXCHANGE: "exchange",
1480
- TRANSACTIONS: "transactions"
1481
- };
1482
- var gt = class {
1483
- _db = null;
1484
- _isOpen = !1;
1485
- _openPromise = null;
1486
- _channelName;
1487
- _messageUpdates = new y();
1488
- _exchangeUpdates = new y();
1489
- constructor(e) {
1490
- this._channelName = e;
1491
- }
1492
- async open() {
1493
- return this._db && this._isOpen ? this._db : this._openPromise ? this._openPromise : (this._openPromise = new Promise((e, t) => {
1494
- const n = indexedDB.open(_t, yt);
1495
- n.onerror = () => {
1496
- this._openPromise = null, t(/* @__PURE__ */ new Error("Failed to open IndexedDB"));
1497
- }, n.onsuccess = () => {
1498
- this._db = n.result, this._isOpen = !0, this._openPromise = null, e(this._db);
1499
- }, n.onupgradeneeded = (s) => {
1500
- const r = s.target.result;
1501
- this._createStores(r);
1502
- };
1503
- }), this._openPromise);
1504
- }
1505
- close() {
1506
- this._db && (this._db.close(), this._db = null, this._isOpen = !1);
1507
- }
1508
- _createStores(e) {
1509
- if (!e.objectStoreNames.contains(u.MESSAGES)) {
1510
- const t = e.createObjectStore(u.MESSAGES, { keyPath: "id" });
1511
- t.createIndex("channel", "channel", { unique: !1 }), t.createIndex("status", "status", { unique: !1 }), t.createIndex("recipient", "recipient", { unique: !1 }), t.createIndex("createdAt", "createdAt", { unique: !1 }), t.createIndex("channel_status", ["channel", "status"], { unique: !1 });
1512
- }
1513
- if (!e.objectStoreNames.contains(u.MAILBOX)) {
1514
- const t = e.createObjectStore(u.MAILBOX, { keyPath: "id" });
1515
- t.createIndex("channel", "channel", { unique: !1 }), t.createIndex("priority", "priority", { unique: !1 }), t.createIndex("expiresAt", "expiresAt", { unique: !1 });
1516
- }
1517
- if (!e.objectStoreNames.contains(u.PENDING)) {
1518
- const t = e.createObjectStore(u.PENDING, { keyPath: "id" });
1519
- t.createIndex("channel", "channel", { unique: !1 }), t.createIndex("createdAt", "createdAt", { unique: !1 });
1520
- }
1521
- if (!e.objectStoreNames.contains(u.EXCHANGE)) {
1522
- const t = e.createObjectStore(u.EXCHANGE, { keyPath: "id" });
1523
- t.createIndex("key", "key", { unique: !0 }), t.createIndex("owner", "owner", { unique: !1 });
1524
- }
1525
- e.objectStoreNames.contains(u.TRANSACTIONS) || e.createObjectStore(u.TRANSACTIONS, { keyPath: "id" }).createIndex("createdAt", "createdAt", { unique: !1 });
1526
- }
1527
- async defer(e, t = {}) {
1528
- const n = await this.open(), s = {
1529
- id: d(),
1530
- channel: e.channel,
1531
- sender: e.sender ?? this._channelName,
1532
- recipient: e.channel,
1533
- type: e.type,
1534
- payload: e.payload,
1535
- status: "pending",
1536
- priority: t.priority ?? 0,
1537
- createdAt: Date.now(),
1538
- updatedAt: Date.now(),
1539
- expiresAt: t.expiresIn ? Date.now() + t.expiresIn : null,
1540
- retryCount: 0,
1541
- maxRetries: t.maxRetries ?? 3,
1542
- metadata: t.metadata
1543
- };
1544
- return new Promise((r, i) => {
1545
- const o = n.transaction([u.MESSAGES, u.MAILBOX], "readwrite"), a = o.objectStore(u.MESSAGES), c = o.objectStore(u.MAILBOX);
1546
- a.add(s), c.add(s), o.oncomplete = () => {
1547
- this._messageUpdates.next(s), r(s.id);
1548
- }, o.onerror = () => i(/* @__PURE__ */ new Error("Failed to defer message"));
1549
- });
1550
- }
1551
- async getDeferredMessages(e, t = {}) {
1552
- const n = await this.open();
1553
- return new Promise((s, r) => {
1554
- const i = n.transaction(u.MESSAGES, "readonly").objectStore(u.MESSAGES), o = t.status ? i.index("channel_status") : i.index("channel"), a = t.status ? IDBKeyRange.only([e, t.status]) : IDBKeyRange.only(e), c = o.getAll(a, t.limit);
1555
- c.onsuccess = () => {
1556
- let l = c.result;
1557
- t.offset && (l = l.slice(t.offset)), s(l);
1558
- }, c.onerror = () => r(/* @__PURE__ */ new Error("Failed to get deferred messages"));
1559
- });
1560
- }
1561
- async processNextPending(e) {
1562
- const t = await this.open();
1563
- return new Promise((n, s) => {
1564
- const r = t.transaction(u.MESSAGES, "readwrite").objectStore(u.MESSAGES).index("channel_status").openCursor(IDBKeyRange.only([e, "pending"]));
1565
- r.onsuccess = () => {
1566
- const i = r.result;
1567
- if (i) {
1568
- const o = i.value;
1569
- o.status = "processing", o.updatedAt = Date.now(), i.update(o), this._messageUpdates.next(o), n(o);
1570
- } else n(null);
1571
- }, r.onerror = () => s(/* @__PURE__ */ new Error("Failed to process pending message"));
1572
- });
1573
- }
1574
- async markDelivered(e) {
1575
- await this._updateMessageStatus(e, "delivered");
1576
- }
1577
- async markFailed(e) {
1578
- const t = await this.open();
1579
- return new Promise((n, s) => {
1580
- const r = t.transaction(u.MESSAGES, "readwrite").objectStore(u.MESSAGES), i = r.get(e);
1581
- i.onsuccess = () => {
1582
- const o = i.result;
1583
- if (!o) {
1584
- n(!1);
1585
- return;
1586
- }
1587
- o.retryCount++, o.updatedAt = Date.now(), o.retryCount < o.maxRetries ? o.status = "pending" : o.status = "failed", r.put(o), this._messageUpdates.next(o), n(o.status === "pending");
1588
- }, i.onerror = () => s(/* @__PURE__ */ new Error("Failed to mark message as failed"));
1589
- });
1590
- }
1591
- async _updateMessageStatus(e, t) {
1592
- const n = await this.open();
1593
- return new Promise((s, r) => {
1594
- const i = n.transaction(u.MESSAGES, "readwrite").objectStore(u.MESSAGES), o = i.get(e);
1595
- o.onsuccess = () => {
1596
- const a = o.result;
1597
- a && (a.status = t, a.updatedAt = Date.now(), i.put(a), this._messageUpdates.next(a)), s();
1598
- }, o.onerror = () => r(/* @__PURE__ */ new Error("Failed to update message status"));
1599
- });
1600
- }
1601
- async getMailbox(e, t = {}) {
1602
- const n = await this.open();
1603
- return new Promise((s, r) => {
1604
- const i = n.transaction(u.MAILBOX, "readonly").objectStore(u.MAILBOX).index("channel").getAll(IDBKeyRange.only(e), t.limit);
1605
- i.onsuccess = () => {
1606
- let o = i.result;
1607
- t.sortBy === "priority" ? o.sort((a, c) => c.priority - a.priority) : o.sort((a, c) => c.createdAt - a.createdAt), s(o);
1608
- }, i.onerror = () => r(/* @__PURE__ */ new Error("Failed to get mailbox"));
1609
- });
1610
- }
1611
- async getMailboxStats(e) {
1612
- const t = await this.getDeferredMessages(e), n = {
1613
- total: t.length,
1614
- pending: 0,
1615
- processing: 0,
1616
- delivered: 0,
1617
- failed: 0,
1618
- expired: 0
1619
- }, s = Date.now();
1620
- for (const r of t) r.expiresAt && r.expiresAt < s ? n.expired++ : n[r.status]++;
1621
- return n;
1622
- }
1623
- async clearMailbox(e) {
1624
- const t = await this.open();
1625
- return new Promise((n, s) => {
1626
- const r = t.transaction(u.MAILBOX, "readwrite"), i = r.objectStore(u.MAILBOX).index("channel");
1627
- let o = 0;
1628
- const a = i.openCursor(IDBKeyRange.only(e));
1629
- a.onsuccess = () => {
1630
- const c = a.result;
1631
- c && (c.delete(), o++, c.continue());
1632
- }, r.oncomplete = () => n(o), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to clear mailbox"));
1633
- });
1634
- }
1635
- async registerPending(e) {
1636
- const t = await this.open(), n = {
1637
- id: d(),
1638
- channel: this._channelName,
1639
- type: e.type,
1640
- data: e.data,
1641
- metadata: e.metadata,
1642
- createdAt: Date.now(),
1643
- status: "pending"
1644
- };
1645
- return new Promise((s, r) => {
1646
- const i = t.transaction(u.PENDING, "readwrite");
1647
- i.objectStore(u.PENDING).add(n), i.oncomplete = () => s(n.id), i.onerror = () => r(/* @__PURE__ */ new Error("Failed to register pending operation"));
1648
- });
1649
- }
1650
- async getPendingOperations() {
1651
- const e = await this.open();
1652
- return new Promise((t, n) => {
1653
- const s = e.transaction(u.PENDING, "readonly").objectStore(u.PENDING).index("channel").getAll(IDBKeyRange.only(this._channelName));
1654
- s.onsuccess = () => t(s.result), s.onerror = () => n(/* @__PURE__ */ new Error("Failed to get pending operations"));
1655
- });
1656
- }
1657
- async completePending(e) {
1658
- const t = await this.open();
1659
- return new Promise((n, s) => {
1660
- const r = t.transaction(u.PENDING, "readwrite");
1661
- r.objectStore(u.PENDING).delete(e), r.oncomplete = () => n(), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to complete pending operation"));
1662
- });
1663
- }
1664
- async awaitPending(e, t = {}) {
1665
- const n = t.timeout ?? 3e4, s = t.pollInterval ?? 100, r = Date.now();
1666
- for (; Date.now() - r < n;) {
1667
- const i = await this._getPendingById(e);
1668
- if (!i) return null;
1669
- if (i.status === "completed") return await this.completePending(e), i.result;
1670
- await new Promise((o) => setTimeout(o, s));
1671
- }
1672
- throw new Error(`Pending operation ${e} timed out`);
1673
- }
1674
- async _getPendingById(e) {
1675
- const t = await this.open();
1676
- return new Promise((n, s) => {
1677
- const r = t.transaction(u.PENDING, "readonly").objectStore(u.PENDING).get(e);
1678
- r.onsuccess = () => n(r.result ?? null), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to get pending operation"));
1679
- });
1680
- }
1681
- async exchangePut(e, t, n = {}) {
1682
- const s = await this.open(), r = {
1683
- id: d(),
1684
- key: e,
1685
- value: t,
1686
- owner: this._channelName,
1687
- sharedWith: n.sharedWith ?? ["*"],
1688
- version: 1,
1689
- createdAt: Date.now(),
1690
- updatedAt: Date.now()
1691
- };
1692
- return new Promise((i, o) => {
1693
- const a = s.transaction(u.EXCHANGE, "readwrite"), c = a.objectStore(u.EXCHANGE), l = c.index("key").get(e);
1694
- l.onsuccess = () => {
1695
- const _ = l.result;
1696
- _ && (r.id = _.id, r.version = _.version + 1, r.createdAt = _.createdAt), c.put(r);
1697
- }, a.oncomplete = () => {
1698
- this._exchangeUpdates.next(r), i(r.id);
1699
- }, a.onerror = () => o(/* @__PURE__ */ new Error("Failed to put exchange data"));
1700
- });
1701
- }
1702
- async exchangeGet(e) {
1703
- const t = await this.open();
1704
- return new Promise((n, s) => {
1705
- const r = t.transaction(u.EXCHANGE, "readonly").objectStore(u.EXCHANGE).index("key").get(e);
1706
- r.onsuccess = () => {
1707
- const i = r.result;
1708
- if (!i) {
1709
- n(null);
1710
- return;
1711
- }
1712
- if (!this._canAccessExchange(i)) {
1713
- n(null);
1714
- return;
1715
- }
1716
- n(i.value);
1717
- }, r.onerror = () => s(/* @__PURE__ */ new Error("Failed to get exchange data"));
1718
- });
1719
- }
1720
- async exchangeDelete(e) {
1721
- const t = await this.open();
1722
- return new Promise((n, s) => {
1723
- const r = t.transaction(u.EXCHANGE, "readwrite"), i = r.objectStore(u.EXCHANGE), o = i.index("key").get(e);
1724
- o.onsuccess = () => {
1725
- const a = o.result;
1726
- if (!a) {
1727
- n(!1);
1728
- return;
1729
- }
1730
- if (a.owner !== this._channelName) {
1731
- n(!1);
1732
- return;
1733
- }
1734
- i.delete(a.id);
1735
- }, r.oncomplete = () => n(!0), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to delete exchange data"));
1736
- });
1737
- }
1738
- async exchangeLock(e, t = {}) {
1739
- const n = await this.open(), s = t.timeout ?? 3e4;
1740
- return new Promise((r, i) => {
1741
- const o = n.transaction(u.EXCHANGE, "readwrite"), a = o.objectStore(u.EXCHANGE), c = a.index("key").get(e);
1742
- c.onsuccess = () => {
1743
- const l = c.result;
1744
- if (!l) {
1745
- r(!1);
1746
- return;
1747
- }
1748
- if (l.lock && l.lock.holder !== this._channelName && l.lock.expiresAt > Date.now()) {
1749
- r(!1);
1750
- return;
1751
- }
1752
- l.lock = {
1753
- holder: this._channelName,
1754
- acquiredAt: Date.now(),
1755
- expiresAt: Date.now() + s
1756
- }, l.updatedAt = Date.now(), a.put(l);
1757
- }, o.oncomplete = () => r(!0), o.onerror = () => i(/* @__PURE__ */ new Error("Failed to acquire lock"));
1758
- });
1759
- }
1760
- async exchangeUnlock(e) {
1761
- const t = await this.open();
1762
- return new Promise((n, s) => {
1763
- const r = t.transaction(u.EXCHANGE, "readwrite"), i = r.objectStore(u.EXCHANGE), o = i.index("key").get(e);
1764
- o.onsuccess = () => {
1765
- const a = o.result;
1766
- a && a.lock?.holder === this._channelName && (delete a.lock, a.updatedAt = Date.now(), i.put(a));
1767
- }, r.oncomplete = () => n(), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to release lock"));
1768
- });
1769
- }
1770
- _canAccessExchange(e) {
1771
- return e.owner === this._channelName || e.sharedWith.includes("*") ? !0 : e.sharedWith.includes(this._channelName);
1772
- }
1773
- async beginTransaction() {
1774
- return new mt(this);
1775
- }
1776
- async executeTransaction(e) {
1777
- const t = await this.open(), n = new Set(e.map((s) => s.store));
1778
- return new Promise((s, r) => {
1779
- const i = t.transaction(Array.from(n), "readwrite");
1780
- for (const o of e) {
1781
- const a = i.objectStore(o.store);
1782
- switch (o.type) {
1783
- case "put":
1784
- o.value !== void 0 && a.put(o.value);
1785
- break;
1786
- case "delete":
1787
- o.key !== void 0 && a.delete(o.key);
1788
- break;
1789
- case "update": if (o.key !== void 0) {
1790
- const c = a.get(o.key);
1791
- c.onsuccess = () => {
1792
- c.result && o.value && a.put({
1793
- ...c.result,
1794
- ...o.value
1795
- });
1796
- };
1797
- }
1798
- }
1799
- }
1800
- i.oncomplete = () => s(), i.onerror = () => r(/* @__PURE__ */ new Error("Transaction failed"));
1801
- });
1802
- }
1803
- onMessageUpdate(e) {
1804
- return this._messageUpdates.subscribe({ next: e });
1805
- }
1806
- onExchangeUpdate(e) {
1807
- return this._exchangeUpdates.subscribe({ next: e });
1808
- }
1809
- async cleanupExpired() {
1810
- const e = await this.open(), t = Date.now();
1811
- return new Promise((n, s) => {
1812
- const r = e.transaction([u.MESSAGES, u.MAILBOX], "readwrite"), i = r.objectStore(u.MESSAGES), o = r.objectStore(u.MAILBOX);
1813
- let a = 0;
1814
- const c = i.openCursor();
1815
- c.onsuccess = () => {
1816
- const _ = c.result;
1817
- if (_) {
1818
- const f = _.value;
1819
- f.expiresAt && f.expiresAt < t && (_.delete(), a++), _.continue();
1820
- }
1821
- };
1822
- const l = o.openCursor();
1823
- l.onsuccess = () => {
1824
- const _ = l.result;
1825
- if (_) {
1826
- const f = _.value;
1827
- f.expiresAt && f.expiresAt < t && (_.delete(), a++), _.continue();
1828
- }
1829
- }, r.oncomplete = () => n(a), r.onerror = () => s(/* @__PURE__ */ new Error("Failed to cleanup expired"));
1830
- });
1831
- }
1832
- }, mt = class {
1833
- _storage;
1834
- _operations = [];
1835
- _isCommitted = !1;
1836
- _isRolledBack = !1;
1837
- constructor(e) {
1838
- this._storage = e;
1839
- }
1840
- put(e, t) {
1841
- return this._checkState(), this._operations.push({
1842
- id: d(),
1843
- type: "put",
1844
- store: e,
1845
- value: t,
1846
- timestamp: Date.now()
1847
- }), this;
1848
- }
1849
- delete(e, t) {
1850
- return this._checkState(), this._operations.push({
1851
- id: d(),
1852
- type: "delete",
1853
- store: e,
1854
- key: t,
1855
- timestamp: Date.now()
1856
- }), this;
1857
- }
1858
- update(e, t, n) {
1859
- return this._checkState(), this._operations.push({
1860
- id: d(),
1861
- type: "update",
1862
- store: e,
1863
- key: t,
1864
- value: n,
1865
- timestamp: Date.now()
1866
- }), this;
1867
- }
1868
- async commit() {
1869
- if (this._checkState(), this._operations.length === 0) {
1870
- this._isCommitted = !0;
1871
- return;
1872
- }
1873
- await this._storage.executeTransaction(this._operations), this._isCommitted = !0;
1874
- }
1875
- rollback() {
1876
- this._operations = [], this._isRolledBack = !0;
1877
- }
1878
- get operationCount() {
1879
- return this._operations.length;
1880
- }
1881
- _checkState() {
1882
- if (this._isCommitted) throw new Error("Transaction already committed");
1883
- if (this._isRolledBack) throw new Error("Transaction already rolled back");
1884
- }
1885
- };
1886
- const j = /* @__PURE__ */ new Map();
1887
- function wt(e) {
1888
- return j.has(e) || j.set(e, new gt(e)), j.get(e);
1889
- }
1890
- const Se = he(), bt = Se.length > 0 ? new URL("../transport/Worker.ts", Se) : "";
1891
- var xe = class {
1892
- _channel;
1893
- _context;
1894
- _options;
1895
- _connection;
1896
- _storage;
1897
- constructor(e, t, n = {}) {
1898
- this._channel = e, this._context = t, this._options = n, this._connection = pt(e), this._storage = wt(e);
1899
- }
1900
- async request(e, t, n, s = {}) {
1901
- let r = typeof e == "string" ? [e] : e, i = t, o = n;
1902
- return Array.isArray(t) && ke(e) && (s = n, o = t, i = e, r = []), this._context.getHost()?.request(r, i, o, s, this._channel);
1903
- }
1904
- async doImportModule(e, t = {}) {
1905
- return this.request([], h.IMPORT, [e], t);
1906
- }
1907
- async deferMessage(e, t = {}) {
1908
- return this._storage.defer({
1909
- channel: this._channel,
1910
- sender: this._context.hostName,
1911
- type: "request",
1912
- payload: e
1913
- }, t);
1914
- }
1915
- async getPendingMessages() {
1916
- return this._storage.getDeferredMessages(this._channel, { status: "pending" });
1917
- }
1918
- get connection() {
1919
- return this._connection;
1920
- }
1921
- get channelName() {
1922
- return this._channel;
1923
- }
1924
- get context() {
1925
- return this._context;
1926
- }
1927
- }, P = class {
1928
- _channel;
1929
- _context;
1930
- _options;
1931
- _connection;
1932
- _unified;
1933
- get _forResolves() {
1934
- return this._unified.__getPrivate("_pending");
1935
- }
1936
- get _subscriptions() {
1937
- return this._unified.__getPrivate("_subscriptions");
1938
- }
1939
- get _broadcasts() {
1940
- return this._unified.__getPrivate("_transports");
1941
- }
1942
- constructor(e, t, n = {}) {
1943
- this._channel = e, this._context = t, this._options = n, this._connection = Ce().getOrCreate(e, "internal", n), this._unified = new ue({
1944
- name: e,
1945
- autoListen: !1,
1946
- timeout: n?.timeout
1947
- });
1948
- }
1949
- createRemoteChannel(e, t = {}, n) {
1950
- const s = St(n ?? this._context.$createOrUseExistingRemote(e, t, n ?? null)?.messageChannel?.port1), r = Pe(s?.target ?? s);
1951
- return this._unified.listen(s?.target, { targetChannel: e }), s && (this._broadcasts?.set?.(e, s), r === "self" && typeof postMessage > "u" || this._unified.connect(s, { targetChannel: e }), this._context.$registerConnection({
1952
- localChannel: this._channel,
1953
- remoteChannel: e,
1954
- sender: this._channel,
1955
- direction: "outgoing",
1956
- transportType: r
1957
- }), this.notifyChannel(e, {
1958
- contextId: this._context.id,
1959
- contextName: this._context.hostName
1960
- }, "connect")), new xe(e, this._context, t);
1961
- }
1962
- getChannel() {
1963
- return this._channel;
1964
- }
1965
- get connection() {
1966
- return this._connection;
1967
- }
1968
- request(e, t, n, s = {}, r = "worker") {
1969
- let i = typeof e == "string" ? [e] : e, o = n;
1970
- return Array.isArray(t) && ke(e) && (r = s, s = n, o = t, t = e, i = []), this._unified.invoke(r, t, i ?? [], Array.isArray(o) ? o : [o]);
1971
- }
1972
- resolveResponse(e, t) {
1973
- this._forResolves.get(e)?.resolve?.(t);
1974
- const n = this._forResolves.get(e)?.promise;
1975
- return this._forResolves.delete(e), n;
1976
- }
1977
- async handleAndResponse(e, t, n) {}
1978
- notifyChannel(e, t = {}, n = "notify") {
1979
- return this._unified.notify(e, {
1980
- ...t,
1981
- from: this._channel,
1982
- to: e
1983
- }, n);
1984
- }
1985
- getConnectedChannels() {
1986
- return this._unified.connectedChannels;
1987
- }
1988
- close() {
1989
- this._subscriptions.forEach((e) => e.unsubscribe()), this._forResolves.clear(), this._broadcasts?.values?.()?.forEach((e) => e.close?.()), this._broadcasts?.clear?.(), this._unified.close();
1990
- }
1991
- get unified() {
1992
- return this._unified;
1993
- }
1994
- }, Ct = class {
1995
- _options;
1996
- _id = d();
1997
- _hostName;
1998
- _host = null;
1999
- _endpoints = /* @__PURE__ */ new Map();
2000
- _unifiedByChannel = /* @__PURE__ */ new Map();
2001
- _unifiedConnectionSubs = /* @__PURE__ */ new Map();
2002
- _remoteChannels = /* @__PURE__ */ new Map();
2003
- _deferredChannels = /* @__PURE__ */ new Map();
2004
- _connectionEvents = new y({ bufferSize: 200 });
2005
- _connectionRegistry = new le(() => d(), (e) => this._emitConnectionEvent(e));
2006
- _closed = !1;
2007
- _globalSelf = null;
2008
- constructor(e = {}) {
2009
- this._options = e, this._hostName = e.name ?? `ctx-${this._id.slice(0, 8)}`, e.useGlobalSelf !== !1 && (this._globalSelf = typeof globalThis < "u" ? globalThis : typeof self < "u" ? self : null);
2010
- }
2011
- initHost(e) {
2012
- if (this._host && !e) return this._host;
2013
- const t = e ?? this._hostName;
2014
- if (this._hostName = t, this._endpoints.has(t)) return this._host = this._endpoints.get(t).handler, this._host;
2015
- this._host = new P(t, this, this._options.defaultOptions);
2016
- const n = {
2017
- name: t,
2018
- handler: this._host,
2019
- connection: this._host.connection,
2020
- subscriptions: [],
2021
- ready: Promise.resolve(null),
2022
- unified: this._host.unified
2023
- };
2024
- return this._endpoints.set(t, n), this._registerUnifiedChannel(t, this._host.unified), this._host;
2025
- }
2026
- getHost() {
2027
- return this._host ?? this.initHost();
2028
- }
2029
- get hostName() {
2030
- return this._hostName;
2031
- }
2032
- get id() {
2033
- return this._id;
2034
- }
2035
- get onConnection() {
2036
- return this._connectionEvents;
2037
- }
2038
- subscribeConnections(e) {
2039
- return this._connectionEvents.subscribe(e);
2040
- }
2041
- notifyConnections(e = {}, t = {}) {
2042
- let n = 0;
2043
- for (const s of this._endpoints.values()) {
2044
- const r = s.handler.getConnectedChannels();
2045
- for (const i of r) {
2046
- if (t.localChannel && t.localChannel !== s.name || t.remoteChannel && t.remoteChannel !== i) continue;
2047
- const o = this.queryConnections({
2048
- localChannel: s.name,
2049
- remoteChannel: i,
2050
- status: "active"
2051
- })[0];
2052
- t.sender && o?.sender !== t.sender || t.transportType && o?.transportType !== t.transportType || t.channel && t.channel !== s.name && t.channel !== i || s.handler.notifyChannel(i, e, "notify") && n++;
2053
- }
2054
- }
2055
- return n;
2056
- }
2057
- queryConnections(e = {}) {
2058
- return this._connectionRegistry.query(e).map((t) => ({
2059
- ...t,
2060
- contextId: this._id
2061
- }));
2062
- }
2063
- createChannel(e, t = {}) {
2064
- if (this._endpoints.has(e)) return this._endpoints.get(e);
2065
- const n = new P(e, this, {
2066
- ...this._options.defaultOptions,
2067
- ...t
2068
- }), s = {
2069
- name: e,
2070
- handler: n,
2071
- connection: n.connection,
2072
- subscriptions: [],
2073
- ready: Promise.resolve(null),
2074
- unified: n.unified
2075
- };
2076
- return this._endpoints.set(e, s), this._registerUnifiedChannel(e, n.unified), s;
2077
- }
2078
- createChannels(e, t = {}) {
2079
- const n = /* @__PURE__ */ new Map();
2080
- for (const s of e) n.set(s, this.createChannel(s, t));
2081
- return n;
2082
- }
2083
- getChannel(e) {
2084
- return this._endpoints.get(e);
2085
- }
2086
- getOrCreateChannel(e, t = {}) {
2087
- return this._endpoints.get(e) ?? this.createChannel(e, t);
2088
- }
2089
- hasChannel(e) {
2090
- return this._endpoints.has(e);
2091
- }
2092
- getChannelNames() {
2093
- return [...this._endpoints.keys()];
2094
- }
2095
- get size() {
2096
- return this._endpoints.size;
2097
- }
2098
- defer(e, t) {
2099
- this._deferredChannels.set(e, t);
2100
- }
2101
- async initDeferred(e) {
2102
- const t = this._deferredChannels.get(e);
2103
- if (!t) return null;
2104
- const n = await t();
2105
- return this._endpoints.set(e, n), this._deferredChannels.delete(e), n;
2106
- }
2107
- isDeferred(e) {
2108
- return this._deferredChannels.has(e);
2109
- }
2110
- async getChannelAsync(e) {
2111
- return this._endpoints.has(e) ? this._endpoints.get(e) : this._deferredChannels.has(e) ? this.initDeferred(e) : null;
2112
- }
2113
- async addWorker(e, t, n = {}) {
2114
- const s = ve(t);
2115
- if (!s) throw new Error(`Failed to create worker for channel: ${e}`);
2116
- const r = new P(e, this, {
2117
- ...this._options.defaultOptions,
2118
- ...n
2119
- }), i = r.createRemoteChannel(e, n, s), o = {
2120
- name: e,
2121
- handler: r,
2122
- connection: r.connection,
2123
- subscriptions: [],
2124
- transportType: "worker",
2125
- ready: Promise.resolve(i),
2126
- unified: r.unified
2127
- };
2128
- return this._endpoints.set(e, o), this._registerUnifiedChannel(e, r.unified), this._remoteChannels.set(e, {
2129
- channel: e,
2130
- context: this,
2131
- remote: Promise.resolve(i),
2132
- transport: s,
2133
- transportType: "worker"
2134
- }), o;
2135
- }
2136
- async addPort(e, t, n = {}) {
2137
- const s = new P(e, this, {
2138
- ...this._options.defaultOptions,
2139
- ...n
2140
- });
2141
- t.start?.();
2142
- const r = s.createRemoteChannel(e, n, t), i = {
2143
- name: e,
2144
- handler: s,
2145
- connection: s.connection,
2146
- subscriptions: [],
2147
- transportType: "message-port",
2148
- ready: Promise.resolve(r),
2149
- unified: s.unified
2150
- };
2151
- return this._endpoints.set(e, i), this._registerUnifiedChannel(e, s.unified), this._remoteChannels.set(e, {
2152
- channel: e,
2153
- context: this,
2154
- remote: Promise.resolve(r),
2155
- transport: t,
2156
- transportType: "message-port"
2157
- }), i;
2158
- }
2159
- async addBroadcast(e, t, n = {}) {
2160
- const s = new BroadcastChannel(t ?? e), r = new P(e, this, {
2161
- ...this._options.defaultOptions,
2162
- ...n
2163
- }), i = r.createRemoteChannel(e, n, s), o = {
2164
- name: e,
2165
- handler: r,
2166
- connection: r.connection,
2167
- subscriptions: [],
2168
- transportType: "broadcast",
2169
- ready: Promise.resolve(i),
2170
- unified: r.unified
2171
- };
2172
- return this._endpoints.set(e, o), this._registerUnifiedChannel(e, r.unified), this._remoteChannels.set(e, {
2173
- channel: e,
2174
- context: this,
2175
- remote: Promise.resolve(i),
2176
- transport: s,
2177
- transportType: "broadcast"
2178
- }), o;
2179
- }
2180
- addSelfChannel(e, t = {}) {
2181
- const n = new P(e, this, {
2182
- ...this._options.defaultOptions,
2183
- ...t
2184
- }), s = this._globalSelf ?? (typeof self < "u" ? self : null), r = {
2185
- name: e,
2186
- handler: n,
2187
- connection: n.connection,
2188
- subscriptions: [],
2189
- transportType: "self",
2190
- ready: Promise.resolve(s ? n.createRemoteChannel(e, t, s) : null),
2191
- unified: n.unified
2192
- };
2193
- return this._endpoints.set(e, r), this._registerUnifiedChannel(e, n.unified), r;
2194
- }
2195
- async addTransport(e, t) {
2196
- const n = t.options ?? {};
2197
- switch (t.type) {
2198
- case "worker":
2199
- if (!t.worker) throw new Error("Worker required for worker transport");
2200
- return this.addWorker(e, t.worker, n);
2201
- case "message-port":
2202
- if (!t.port) throw new Error("Port required for message-port transport");
2203
- return this.addPort(e, t.port, n);
2204
- case "broadcast":
2205
- const s = typeof t.broadcast == "string" ? t.broadcast : void 0;
2206
- return this.addBroadcast(e, s, n);
2207
- case "self": return this.addSelfChannel(e, n);
2208
- default: return this.createChannel(e, n);
2209
- }
2210
- }
2211
- createChannelPair(e, t, n = {}) {
2212
- const s = new MessageChannel(), r = new P(e, this, {
2213
- ...this._options.defaultOptions,
2214
- ...n
2215
- }), i = new P(t, this, {
2216
- ...this._options.defaultOptions,
2217
- ...n
2218
- });
2219
- s.port1.start(), s.port2.start();
2220
- const o = Promise.resolve(r.createRemoteChannel(t, n, s.port1)), a = Promise.resolve(i.createRemoteChannel(e, n, s.port2)), c = {
2221
- name: e,
2222
- handler: r,
2223
- connection: r.connection,
2224
- subscriptions: [],
2225
- transportType: "message-port",
2226
- ready: o,
2227
- unified: r.unified
2228
- }, l = {
2229
- name: t,
2230
- handler: i,
2231
- connection: i.connection,
2232
- subscriptions: [],
2233
- transportType: "message-port",
2234
- ready: a,
2235
- unified: i.unified
2236
- };
2237
- return this._endpoints.set(e, c), this._endpoints.set(t, l), this._registerUnifiedChannel(e, r.unified), this._registerUnifiedChannel(t, i.unified), {
2238
- channel1: c,
2239
- channel2: l,
2240
- messageChannel: s
2241
- };
2242
- }
2243
- get globalSelf() {
2244
- return this._globalSelf;
2245
- }
2246
- async connectRemote(e, t = {}, n) {
2247
- return this.initHost(), this._host.createRemoteChannel(e, t, n);
2248
- }
2249
- async importModuleInChannel(e, t, n = {}, s) {
2250
- return (await this.connectRemote(e, n.channelOptions, s))?.doImportModule?.(t, n.importOptions);
2251
- }
2252
- $createOrUseExistingRemote(e, t = {}, n) {
2253
- if (e == null || n) return null;
2254
- if (this._remoteChannels.has(e)) return this._remoteChannels.get(e);
2255
- const s = new MessageChannel(), r = re(new Promise((o) => {
2256
- const a = ve(bt);
2257
- a?.addEventListener?.("message", (c) => {
2258
- c.data.type === "channelCreated" && (s.port1?.start?.(), o(new xe(c.data.channel, this, t)));
2259
- }), a?.postMessage?.({
2260
- type: "createChannel",
2261
- channel: e,
2262
- sender: this._hostName,
2263
- options: t,
2264
- messagePort: s.port2
2265
- }, { transfer: [s.port2] });
2266
- })), i = {
2267
- channel: e,
2268
- context: this,
2269
- messageChannel: s,
2270
- remote: r
2271
- };
2272
- return this._remoteChannels.set(e, i), i;
2273
- }
2274
- $registerConnection(e) {
2275
- return {
2276
- ...this._connectionRegistry.register(e),
2277
- contextId: this._id
2278
- };
2279
- }
2280
- $markNotified(e) {
2281
- const t = this._connectionRegistry.register({
2282
- localChannel: e.localChannel,
2283
- remoteChannel: e.remoteChannel,
2284
- sender: e.sender,
2285
- direction: e.direction,
2286
- transportType: e.transportType
2287
- });
2288
- this._connectionRegistry.markNotified(t, e.payload);
2289
- }
2290
- $observeSignal(e) {
2291
- const t = (e.payload?.type, "incoming");
2292
- this.$markNotified({
2293
- localChannel: e.localChannel,
2294
- remoteChannel: e.remoteChannel,
2295
- sender: e.sender,
2296
- direction: t,
2297
- transportType: e.transportType,
2298
- payload: e.payload
2299
- });
2300
- }
2301
- $forwardUnifiedConnectionEvent(e, t) {
2302
- const n = t.connection.transportType ?? "internal", s = this._connectionRegistry.register({
2303
- localChannel: t.connection.localChannel || e,
2304
- remoteChannel: t.connection.remoteChannel,
2305
- sender: t.connection.sender,
2306
- direction: t.connection.direction,
2307
- transportType: n,
2308
- metadata: t.connection.metadata
2309
- });
2310
- t.type === "notified" ? this._connectionRegistry.markNotified(s, t.payload) : t.type === "disconnected" && this._connectionRegistry.closeByChannel(t.connection.localChannel);
2311
- }
2312
- closeChannel(e) {
2313
- const t = this._endpoints.get(e);
2314
- return t ? (t.subscriptions.forEach((n) => n.unsubscribe()), t.handler.close(), t.transport?.detach(), this._unifiedConnectionSubs.get(e)?.unsubscribe(), this._unifiedConnectionSubs.delete(e), this._unifiedByChannel.delete(e), this._endpoints.delete(e), e === this._hostName && (this._host = null), this._connectionRegistry.closeByChannel(e), !0) : !1;
2315
- }
2316
- close() {
2317
- if (!this._closed) {
2318
- this._closed = !0;
2319
- for (const [e] of this._endpoints) this.closeChannel(e);
2320
- this._remoteChannels.clear(), this._host = null, this._unifiedConnectionSubs.forEach((e) => e.unsubscribe()), this._unifiedConnectionSubs.clear(), this._unifiedByChannel.clear(), this._connectionRegistry.clear(), this._connectionEvents.complete();
2321
- }
2322
- }
2323
- get closed() {
2324
- return this._closed;
2325
- }
2326
- _registerUnifiedChannel(e, t) {
2327
- this._unifiedByChannel.set(e, t), this._unifiedConnectionSubs.get(e)?.unsubscribe();
2328
- const n = t.subscribeConnections((s) => {
2329
- this.$forwardUnifiedConnectionEvent(e, s);
2330
- });
2331
- this._unifiedConnectionSubs.set(e, n);
2332
- }
2333
- _emitConnectionEvent(e) {
2334
- this._connectionEvents.next({
2335
- ...e,
2336
- connection: {
2337
- ...e.connection,
2338
- contextId: this._id
2339
- }
2340
- });
2341
- }
2342
- };
2343
- function ke(e) {
2344
- return [...Object.values(h)].includes(e);
2345
- }
2346
- function St(e) {
2347
- if (!e) return null;
2348
- if (Ee(e)) return e;
2349
- const t = e, n = Pe(t);
2350
- return {
2351
- target: t,
2352
- targetChannel: "unknown",
2353
- transportType: n === "internal" ? "self" : n,
2354
- sender: (s, r) => {
2355
- if (typeof WebSocket < "u" && t instanceof WebSocket) {
2356
- t.send(JSON.stringify(s));
2357
- return;
2358
- }
2359
- t.postMessage?.(s, r?.length ? { transfer: r } : void 0);
2360
- },
2361
- postMessage: (s, r) => {
2362
- t.postMessage?.(s, r);
2363
- },
2364
- addEventListener: t.addEventListener?.bind(t),
2365
- removeEventListener: t.removeEventListener?.bind(t),
2366
- start: t.start?.bind(t),
2367
- close: t.close?.bind(t)
2368
- };
2369
- }
2370
- function Ee(e) {
2371
- return !!e && typeof e == "object" && "target" in e && typeof e.postMessage == "function";
2372
- }
2373
- function Pe(e) {
2374
- const t = Ee(e) ? e.target : e;
2375
- return t ? t === "chrome-runtime" ? "chrome-runtime" : t === "chrome-tabs" ? "chrome-tabs" : t === "chrome-port" ? "chrome-port" : t === "chrome-external" ? "chrome-external" : typeof MessagePort < "u" && t instanceof MessagePort ? "message-port" : typeof BroadcastChannel < "u" && t instanceof BroadcastChannel ? "broadcast" : typeof Worker < "u" && t instanceof Worker ? "worker" : typeof WebSocket < "u" && t instanceof WebSocket ? "websocket" : typeof chrome < "u" && typeof t == "object" && t && typeof t.postMessage == "function" && t.onMessage?.addListener ? "chrome-port" : typeof self < "u" && t === self ? "self" : "internal" : "internal";
2376
- }
2377
- function ve(e) {
2378
- if (e instanceof Worker) return e;
2379
- if (e instanceof URL) return new Worker(e.href, { type: "module" });
2380
- if (typeof e == "function") try {
2381
- return new e({ type: "module" });
2382
- } catch {
2383
- return e({ type: "module" });
2384
- }
2385
- return typeof e == "string" ? e.startsWith("/") ? new Worker(de(e.replace(/^\//, "./")), { type: "module" }) : URL.canParse(e) || e.startsWith("./") ? new Worker(de(e), { type: "module" }) : new Worker(URL.createObjectURL(new Blob([e], { type: "application/javascript" })), { type: "module" }) : e instanceof Blob || e instanceof File ? new Worker(URL.createObjectURL(e), { type: "module" }) : e ?? (typeof self < "u" ? self : null);
2386
- }
2387
- const xt = /* @__PURE__ */ new Map();
2388
- function kt(e = {}) {
2389
- const t = new Ct(e);
2390
- return e.name && xt.set(e.name, t), t;
2391
- }
2392
- var Et = class {
2393
- _context;
2394
- _config;
2395
- _subscriptions = [];
2396
- _incomingConnections = new y({ bufferSize: 100 });
2397
- _channelCreated = new y({ bufferSize: 100 });
2398
- _channelClosed = new y();
2399
- constructor(e = {}) {
2400
- this._config = {
2401
- name: e.name ?? "worker",
2402
- workerName: e.workerName ?? `worker-${d().slice(0, 8)}`,
2403
- autoAcceptChannels: e.autoAcceptChannels ?? !0,
2404
- allowedChannels: e.allowedChannels ?? [],
2405
- maxChannels: e.maxChannels ?? 100,
2406
- autoConnect: e.autoConnect ?? !0,
2407
- useGlobalSelf: !0,
2408
- defaultOptions: e.defaultOptions ?? {},
2409
- isolatedStorage: e.isolatedStorage ?? !1,
2410
- ...e
2411
- }, this._context = kt({
2412
- name: this._config.name,
2413
- useGlobalSelf: !0,
2414
- defaultOptions: e.defaultOptions
2415
- }), this._setupMessageListener();
2416
- }
2417
- get onConnection() {
2418
- return this._incomingConnections;
2419
- }
2420
- get onChannelCreated() {
2421
- return this._channelCreated;
2422
- }
2423
- get onChannelClosed() {
2424
- return this._channelClosed;
2425
- }
2426
- subscribeConnections(e) {
2427
- return this._incomingConnections.subscribe(e);
2428
- }
2429
- subscribeChannelCreated(e) {
2430
- return this._channelCreated.subscribe(e);
2431
- }
2432
- acceptConnection(e) {
2433
- if (!this._canAcceptChannel(e.channel)) return null;
2434
- const t = this._context.createChannel(e.channel, e.options);
2435
- return e.port && (e.port.start?.(), t.handler.createRemoteChannel(e.sender, e.options, e.port)), this._channelCreated.next({
2436
- channel: e.channel,
2437
- endpoint: t,
2438
- sender: e.sender,
2439
- timestamp: Date.now()
2440
- }), this._postChannelCreated(e.channel, e.sender, e.id), t;
2441
- }
2442
- createChannel(e, t) {
2443
- return this._context.createChannel(e, t);
2444
- }
2445
- getChannel(e) {
2446
- return this._context.getChannel(e);
2447
- }
2448
- hasChannel(e) {
2449
- return this._context.hasChannel(e);
2450
- }
2451
- getChannelNames() {
2452
- return this._context.getChannelNames();
2453
- }
2454
- queryConnections(e = {}) {
2455
- return this._context.queryConnections(e);
2456
- }
2457
- notifyConnections(e = {}, t = {}) {
2458
- return this._context.notifyConnections(e, t);
2459
- }
2460
- closeChannel(e) {
2461
- const t = this._context.closeChannel(e);
2462
- return t && this._channelClosed.next({
2463
- channel: e,
2464
- timestamp: Date.now()
2465
- }), t;
2466
- }
2467
- get context() {
2468
- return this._context;
2469
- }
2470
- get config() {
2471
- return this._config;
2472
- }
2473
- _setupMessageListener() {
2474
- addEventListener("message", ((e) => {
2475
- this._handleIncomingMessage(e);
2476
- }));
2477
- }
2478
- _handleIncomingMessage(e) {
2479
- const t = e.data;
2480
- if (!(!t || typeof t != "object")) switch (t.type) {
2481
- case "createChannel":
2482
- this._handleCreateChannel(t);
2483
- break;
2484
- case "connectChannel":
2485
- this._handleConnectChannel(t);
2486
- break;
2487
- case "addPort":
2488
- this._handleAddPort(t);
2489
- break;
2490
- case "listChannels":
2491
- this._handleListChannels(t);
2492
- break;
2493
- case "closeChannel":
2494
- this._handleCloseChannel(t);
2495
- break;
2496
- case "ping":
2497
- postMessage({
2498
- type: "pong",
2499
- id: t.id,
2500
- timestamp: Date.now()
2501
- });
2502
- break;
2503
- default: t.channel && this._context.hasChannel(t.channel) && this._context.getChannel(t.channel)?.handler?.handleAndResponse?.(t.payload, t.reqId);
2504
- }
2505
- }
2506
- _handleCreateChannel(e) {
2507
- const t = {
2508
- id: e.reqId ?? d(),
2509
- channel: e.channel,
2510
- sender: e.sender ?? "unknown",
2511
- type: "channel",
2512
- port: e.messagePort,
2513
- timestamp: Date.now(),
2514
- options: e.options
2515
- };
2516
- this._incomingConnections.next(t), this._config.autoAcceptChannels && this.acceptConnection(t);
2517
- }
2518
- _handleConnectChannel(e) {
2519
- const t = {
2520
- id: e.reqId ?? d(),
2521
- channel: e.channel,
2522
- sender: e.sender ?? "unknown",
2523
- type: e.portType ?? "channel",
2524
- port: e.port,
2525
- timestamp: Date.now(),
2526
- options: e.options
2527
- };
2528
- if (this._incomingConnections.next(t), this._config.autoAcceptChannels && this._canAcceptChannel(e.channel)) {
2529
- const n = this._context.getOrCreateChannel(e.channel, e.options);
2530
- e.port && (e.port.start?.(), n.handler.createRemoteChannel(e.sender, e.options, e.port)), postMessage({
2531
- type: "channelConnected",
2532
- channel: e.channel,
2533
- reqId: e.reqId
2534
- });
2535
- }
2536
- }
2537
- _handleAddPort(e) {
2538
- if (!e.port || !e.channel) return;
2539
- const t = {
2540
- id: e.reqId ?? d(),
2541
- channel: e.channel,
2542
- sender: e.sender ?? "unknown",
2543
- type: "port",
2544
- port: e.port,
2545
- timestamp: Date.now(),
2546
- options: e.options
2547
- };
2548
- this._incomingConnections.next(t), this._config.autoAcceptChannels && this.acceptConnection(t);
2549
- }
2550
- _handleListChannels(e) {
2551
- postMessage({
2552
- type: "channelList",
2553
- channels: this.getChannelNames(),
2554
- reqId: e.reqId
2555
- });
2556
- }
2557
- _handleCloseChannel(e) {
2558
- e.channel && (this.closeChannel(e.channel), postMessage({
2559
- type: "channelClosed",
2560
- channel: e.channel,
2561
- reqId: e.reqId
2562
- }));
2563
- }
2564
- _canAcceptChannel(e) {
2565
- return this._context.size >= this._config.maxChannels ? !1 : this._config.allowedChannels.length > 0 ? this._config.allowedChannels.includes(e) : !0;
2566
- }
2567
- _postChannelCreated(e, t, n) {
2568
- postMessage({
2569
- type: "channelCreated",
2570
- channel: e,
2571
- sender: t,
2572
- reqId: n,
2573
- timestamp: Date.now()
2574
- });
2575
- }
2576
- close() {
2577
- this._subscriptions.forEach((e) => e.unsubscribe()), this._subscriptions = [], this._incomingConnections.complete(), this._channelCreated.complete(), this._channelClosed.complete(), this._context.close();
2578
- }
2579
- };
2580
- let J = null;
2581
- function Pt(e) {
2582
- return J || (J = new Et(e)), J;
2583
- }
2584
- Pt({ name: "worker" });
2585
- var W = class {
2586
- _channelName;
2587
- _config;
2588
- _port;
2589
- _subs = /* @__PURE__ */ new Set();
2590
- _pending = /* @__PURE__ */ new Map();
2591
- _listening = !1;
2592
- _cleanup = null;
2593
- _portId = d();
2594
- _state = new y();
2595
- _keepAliveTimer = null;
2596
- constructor(e, t, n = {}) {
2597
- this._channelName = t, this._config = n, this._port = e, this._setupPort(), n.autoStart !== !1 && this.start();
2598
- }
2599
- _setupPort() {
2600
- const e = (n) => {
2601
- const s = n.data;
2602
- if (s.type === "response" && s.reqId) {
2603
- const r = this._pending.get(s.reqId);
2604
- if (r) {
2605
- this._pending.delete(s.reqId), s.payload?.error ? r.reject(new Error(s.payload.error)) : r.resolve(s.payload?.result ?? s.payload);
2606
- return;
2607
- }
2608
- }
2609
- if (s.type === "signal" && s.payload?.action === "ping") {
2610
- this.send({
2611
- id: d(),
2612
- channel: this._channelName,
2613
- sender: this._portId,
2614
- type: "signal",
2615
- payload: { action: "pong" }
2616
- });
2617
- return;
2618
- }
2619
- s.portId = s.portId ?? this._portId;
2620
- for (const r of this._subs) try {
2621
- r.next?.(s);
2622
- } catch (i) {
2623
- r.error?.(i);
2624
- }
2625
- }, t = () => {
2626
- this._state.next("error");
2627
- const n = /* @__PURE__ */ new Error("Port error");
2628
- for (const s of this._subs) s.error?.(n);
2629
- };
2630
- this._port.addEventListener("message", e), this._port.addEventListener("messageerror", t), this._cleanup = () => {
2631
- this._port.removeEventListener("message", e), this._port.removeEventListener("messageerror", t);
2632
- };
2633
- }
2634
- start() {
2635
- this._listening || (this._port.start(), this._listening = !0, this._state.next("ready"), this._config.keepAlive && this._startKeepAlive());
2636
- }
2637
- send(e, t) {
2638
- const { transferable: n, ...s } = e;
2639
- this._port.postMessage({
2640
- ...s,
2641
- portId: this._portId
2642
- }, t ?? []);
2643
- }
2644
- request(e) {
2645
- const t = e.reqId ?? d();
2646
- return new Promise((n, s) => {
2647
- const r = setTimeout(() => {
2648
- this._pending.delete(t), s(/* @__PURE__ */ new Error("Request timeout"));
2649
- }, this._config.timeout ?? 3e4);
2650
- this._pending.set(t, {
2651
- resolve: (i) => {
2652
- clearTimeout(r), n(i);
2653
- },
2654
- reject: (i) => {
2655
- clearTimeout(r), s(i);
2656
- },
2657
- timestamp: Date.now()
2658
- }), this.send({
2659
- ...e,
2660
- reqId: t,
2661
- type: "request"
2662
- });
2663
- });
2664
- }
2665
- subscribe(e) {
2666
- const t = typeof e == "function" ? { next: e } : e;
2667
- return this._subs.add(t), {
2668
- closed: !1,
2669
- unsubscribe: () => {
2670
- this._subs.delete(t);
2671
- }
2672
- };
2673
- }
2674
- _startKeepAlive() {
2675
- this._keepAliveTimer = setInterval(() => {
2676
- this.send({
2677
- id: d(),
2678
- channel: this._channelName,
2679
- sender: this._portId,
2680
- type: "signal",
2681
- payload: { action: "ping" }
2682
- });
2683
- }, this._config.keepAliveInterval ?? 3e4);
2684
- }
2685
- close() {
2686
- this._keepAliveTimer && (clearInterval(this._keepAliveTimer), this._keepAliveTimer = null), this._cleanup?.(), this._subs.forEach((e) => e.complete?.()), this._subs.clear(), this._port.close(), this._state.next("closed");
2687
- }
2688
- get port() {
2689
- return this._port;
2690
- }
2691
- get portId() {
2692
- return this._portId;
2693
- }
2694
- get isListening() {
2695
- return this._listening;
2696
- }
2697
- get state() {
2698
- return this._state;
2699
- }
2700
- get channelName() {
2701
- return this._channelName;
2702
- }
2703
- };
2704
- function Q(e, t) {
2705
- const n = new MessageChannel();
2706
- return {
2707
- local: new W(n.port1, e, t),
2708
- remote: n.port2,
2709
- transfer: () => n.port2
2710
- };
2711
- }
2712
- var Te = class {
2713
- _target;
2714
- _channelName;
2715
- _config;
2716
- _transport = null;
2717
- _state = new y();
2718
- _handshakeComplete = !1;
2719
- constructor(e, t, n = {}) {
2720
- this._target = e, this._channelName = t, this._config = n;
2721
- }
2722
- async connect() {
2723
- if (this._transport && this._handshakeComplete) return this._transport;
2724
- this._state.next("connecting");
2725
- const { local: e, remote: t } = Q(this._channelName, this._config);
2726
- return this._target.postMessage({
2727
- type: "port-connect",
2728
- channelName: this._channelName,
2729
- portId: e.portId
2730
- }, this._config.targetOrigin ?? "*", [t]), new Promise((n, s) => {
2731
- const r = setTimeout(() => {
2732
- s(/* @__PURE__ */ new Error("Handshake timeout")), this._state.next("error");
2733
- }, this._config.handshakeTimeout ?? 1e4), i = e.subscribe({ next: (o) => {
2734
- o.type === "signal" && o.payload?.action === "handshake-ack" && (clearTimeout(r), this._handshakeComplete = !0, this._transport = e, this._state.next("connected"), i.unsubscribe(), n(e));
2735
- } });
2736
- });
2737
- }
2738
- static listen(e, t, n) {
2739
- const s = (r) => {
2740
- if (r.data?.type !== "port-connect" || r.data?.channelName !== e || !r.ports[0]) return;
2741
- const i = new W(r.ports[0], e, n);
2742
- i.send({
2743
- id: d(),
2744
- channel: e,
2745
- sender: i.portId,
2746
- type: "signal",
2747
- payload: { action: "handshake-ack" }
2748
- }), t(i);
2749
- };
2750
- return globalThis.addEventListener("message", s), () => globalThis.removeEventListener("message", s);
2751
- }
2752
- disconnect() {
2753
- this._transport?.close(), this._transport = null, this._handshakeComplete = !1, this._state.next("disconnected");
2754
- }
2755
- get isConnected() {
2756
- return this._handshakeComplete;
2757
- }
2758
- get state() {
2759
- return this._state;
2760
- }
2761
- get transport() {
2762
- return this._transport;
2763
- }
2764
- };
2765
- Te.listen;
2766
- const Re = (e, t = "worker") => {
2767
- const n = ot(t ?? "worker");
2768
- return Object.keys(e).forEach((s) => {
2769
- e[s];
2770
- }), n;
2771
- };
2772
- var At = Ne({
2773
- getDirHandle: () => O,
2774
- getFileSystemRoot: () => A,
2775
- handlers: () => v,
2776
- normalizePath: () => I,
2777
- resolveFileSystemHandle: () => Ae
2778
- }), B, q, A, I, Ae, O, v, Ie, M, Oe = De((() => {
2779
- B = /* @__PURE__ */ new Map(), q = /* @__PURE__ */ new Map(), A = async (e = "") => e && B.has(e) ? B.get(e) : await navigator.storage.getDirectory(), I = (e) => e?.trim?.()?.replace(/\/+/g, "/") || "/", Ae = async (e, t, n = !1) => {
2780
- const s = I(t).split("/").filter((i) => i && i !== ".");
2781
- let r = e;
2782
- for (let i = 0; i < s.length; i++) {
2783
- const o = s[i];
2784
- if (i === s.length - 1) try {
2785
- return await r.getDirectoryHandle(o, { create: n });
2786
- } catch {
2787
- try {
2788
- return await r.getFileHandle(o, { create: n });
2789
- } catch (a) {
2790
- if (n) throw a;
2791
- return null;
2792
- }
2793
- }
2794
- else r = await r.getDirectoryHandle(o, { create: n });
2795
- }
2796
- return r;
2797
- }, O = async (e, t, n) => {
2798
- const s = I(t).split("/").filter((i) => i);
2799
- let r = e;
2800
- for (const i of s) r = await r.getDirectoryHandle(i, { create: n });
2801
- return r;
2802
- }, v = {
2803
- mount: async ({ id: e, handle: t }) => (B.set(e, t), !0),
2804
- unmount: async ({ id: e }) => (B.delete(e), !0),
2805
- readDirectory: async ({ rootId: e, path: t, create: n }) => {
2806
- try {
2807
- const s = await A(e), r = await O(s, t, n), i = [];
2808
- for await (const [o, a] of r.entries()) i.push([o, a]);
2809
- return i;
2810
- } catch (s) {
2811
- return console.warn("Worker readDirectory error:", s), [];
2812
- }
2813
- },
2814
- readFile: async ({ rootId: e, path: t, type: n }) => {
2815
- try {
2816
- const s = await A(e), r = I(t).split("/").filter((c) => c), i = r.pop(), o = r.join("/"), a = await (await (await O(s, o, !1)).getFileHandle(i, { create: !1 })).getFile();
2817
- return n === "text" ? await a.text() : n === "arrayBuffer" ? await a.arrayBuffer() : a;
2818
- } catch (s) {
2819
- return console.warn("Worker readFile error:", s), null;
2820
- }
2821
- },
2822
- writeFile: async ({ rootId: e, path: t, data: n }) => {
2823
- try {
2824
- const s = await A(e), r = I(t).split("/").filter((c) => c), i = r.pop(), o = r.join("/"), a = await (await (await O(s, o, !0)).getFileHandle(i, { create: !0 })).createWritable();
2825
- return await a.write(n), await a.close(), !0;
2826
- } catch (s) {
2827
- return console.warn("Worker writeFile error:", s), !1;
2828
- }
2829
- },
2830
- remove: async ({ rootId: e, path: t, recursive: n }) => {
2831
- try {
2832
- const s = await A(e), r = I(t).split("/").filter((a) => a), i = r.pop(), o = r.join("/");
2833
- return await (await O(s, o, !1)).removeEntry(i, { recursive: n }), !0;
2834
- } catch {
2835
- return !1;
2836
- }
2837
- },
2838
- observe: async ({ rootId: e, path: t, id: n }) => {
2839
- try {
2840
- if (q.has(n)) return !0;
2841
- const s = await A(e), r = await O(s, t, !1);
2842
- if (typeof FileSystemObserver < "u") {
2843
- const i = new FileSystemObserver((o) => {
2844
- const a = o.map((c) => {
2845
- const l = c.changedHandle?.name || c.relativePathComponents?.at(-1);
2846
- return {
2847
- type: c.type,
2848
- name: l,
2849
- kind: c.changedHandle?.kind || (l?.includes(".") ? "file" : "directory"),
2850
- handle: c.changedHandle,
2851
- path: c.relativePathComponents.join("/")
2852
- };
2853
- });
2854
- self.postMessage({
2855
- type: "observation",
2856
- id: n,
2857
- changes: a
2858
- });
2859
- });
2860
- return i.observe(r), q.set(n, i), !0;
2861
- }
2862
- return !1;
2863
- } catch {
2864
- return !1;
2865
- }
2866
- },
2867
- unobserve: async ({ id: e }) => {
2868
- const t = q.get(e);
2869
- return t && (t.disconnect(), q.delete(e)), !0;
2870
- },
2871
- copy: async ({ from: e, to: t }) => {
2872
- try {
2873
- const n = async (s, r) => {
2874
- if (s.kind === "directory") for await (const [i, o] of s.entries()) if (o.kind === "directory") {
2875
- const a = await r.getDirectoryHandle(i, { create: !0 });
2876
- await n(o, a);
2877
- } else {
2878
- const a = await o.getFile(), c = await (await r.getFileHandle(i, { create: !0 })).createWritable();
2879
- await c.write(a), await c.close();
2880
- }
2881
- else {
2882
- const i = await s.getFile(), o = await r.createWritable();
2883
- await o.write(i), await o.close();
2884
- }
2885
- };
2886
- return await n(e, t), !0;
2887
- } catch (n) {
2888
- return console.warn("Worker copy error:", n), !1;
2889
- }
2890
- }
2891
- }, Ie = "opfs-sw-bridge-v1", M = null;
2892
- try {
2893
- typeof BroadcastChannel < "u" && (M = new BroadcastChannel(Ie), M.onmessage = async (e) => {
2894
- const t = e?.data || {};
2895
- if (!t || typeof t != "object" || t?.type !== "opfs-sw-request") return;
2896
- const n = String(t?.requestId || ""), s = String(t?.action || ""), r = t?.payload;
2897
- if (!n || !s) return;
2898
- const i = v[s];
2899
- if (!i) {
2900
- M?.postMessage?.({
2901
- type: "opfs-sw-response",
2902
- requestId: n,
2903
- ok: !1,
2904
- error: `Unknown operation type: ${s}`
2905
- });
2906
- return;
2907
- }
2908
- try {
2909
- const o = await i(r);
2910
- M?.postMessage?.({
2911
- type: "opfs-sw-response",
2912
- requestId: n,
2913
- ok: !0,
2914
- result: o
2915
- });
2916
- } catch (o) {
2917
- M?.postMessage?.({
2918
- type: "opfs-sw-response",
2919
- requestId: n,
2920
- ok: !1,
2921
- error: o?.message || String(o)
2922
- });
2923
- }
2924
- });
2925
- } catch {
2926
- M = null;
2927
- }
2928
- self.addEventListener("message", async (e) => {
2929
- if (!e.data || typeof e.data != "object") return;
2930
- const { id: t, type: n, payload: s } = e.data;
2931
- if (v[n]) try {
2932
- const r = await v[n](s);
2933
- self.postMessage({
2934
- id: t,
2935
- result: r
2936
- });
2937
- } catch (r) {
2938
- self.postMessage({
2939
- id: t,
2940
- error: r?.message || String(r)
2941
- });
2942
- }
2943
- else t && self.postMessage({
2944
- id: t,
2945
- error: `Unknown operation type: ${n}`
2946
- });
2947
- });
2948
- }));
2949
- Oe(), v && Re(v);
2950
- const It = async (e) => {
2951
- try {
2952
- if (e.type === "batch") {
2953
- const t = [];
2954
- for (const n of e.payload) {
2955
- const s = await Me(n);
2956
- t.push(s);
2957
- }
2958
- return t;
2959
- } else return await Me(e);
2960
- } catch (t) {
2961
- throw console.error("[OPFS Worker] Message processing error:", t), t;
2962
- }
2963
- }, Me = async (e) => {
2964
- const t = v[e.type];
2965
- if (!t) throw new Error(`Unknown message type: ${e.type}`);
2966
- return await t(e.payload);
2967
- };
2968
- globalThis.processMessage = It, (async () => {
2969
- try {
2970
- const e = (await Promise.resolve().then(() => (Oe(), At))).handlers;
2971
- e && Re(e), console.log("[OPFS Worker] Initialized with handlers:", Object.keys(e || {}));
2972
- } catch (e) {
2973
- console.error("[OPFS Worker] Failed to initialize:", e);
2974
- }
2975
- })();
2976
- })();