@fest-lib/fl-ui 0.1.1

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