@flaxia/node 0.5.1 → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,7 +1,8 @@
1
- import { A as e, C as t, D as n, E as r, S as i, T as a, _ as o, b as s, d as c, g as l, i as u, n as d, o as f, p, r as m, s as h, w as g } from "./assets/webgpuProbe.js";
2
- import { t as _ } from "./assets/egress-guard.js";
1
+ import { A as e, C as t, D as n, E as r, M as i, N as a, S as o, T as s, c, f as l, g as u, i as d, j as f, n as p, o as m, r as h, u as g, v as _, w as v } from "./assets/webgpuProbe.js";
2
+ import { t as ee } from "./assets/egress-guard.js";
3
+ import { a as y, n as te, o as b, r as ne, t as re } from "./assets/ai-inference.js";
3
4
  //#region src/consent/notice.ts
4
- var v = {
5
+ var x = {
5
6
  summary: "同意すると、このブラウザは第三者から依頼された処理をバックグラウンドで実行します。",
6
7
  items: [
7
8
  "実行する処理: 顧客(第三者)が依頼したワークロード。任意の WebAssembly コンテナの実行や、画像の NSFW(成人向け)判定などを含みます。",
@@ -12,34 +13,34 @@ var v = {
12
13
  acceptGateHint: "開示内容を確認できるよう、「同意して開始」はしばらくの間押せません。",
13
14
  acceptLabel: "同意して開始",
14
15
  rejectLabel: "拒否"
15
- }, y = 4320 * 60 * 60 * 1e3, b = "flaxia_consent_record", x = "flaxia_consent_granted", ee = "flaxia_consent_expiry", S = "flaxia_consent_denied", C = 1, te = 1e4, w = 2e3, ne = "flaxia-consent-integrity", re = 1, T = "keys", E = "consent-hmac-sha256-v1", ie = (...e) => console.warn("[flaxia-node]", ...e), ae = /* @__PURE__ */ new Map();
16
- function oe(e) {
16
+ }, ie = 4320 * 60 * 60 * 1e3, S = "flaxia_consent_record", ae = "flaxia_consent_granted", oe = "flaxia_consent_expiry", C = "flaxia_consent_denied", se = 1, ce = 1e4, le = 2e3, ue = "flaxia-consent-integrity", de = 1, w = "keys", fe = "consent-hmac-sha256-v1", pe = (...e) => console.warn("[flaxia-node]", ...e), me = /* @__PURE__ */ new Map();
17
+ function he(e) {
17
18
  try {
18
19
  return localStorage.getItem(e);
19
20
  } catch {
20
- return ae.get(e) ?? null;
21
+ return me.get(e) ?? null;
21
22
  }
22
23
  }
23
- function se(e, t) {
24
+ function ge(e, t) {
24
25
  try {
25
26
  localStorage.setItem(e, t);
26
27
  } catch {
27
- ae.set(e, t);
28
+ me.set(e, t);
28
29
  }
29
30
  }
30
- function D(e) {
31
+ function T(e) {
31
32
  try {
32
33
  localStorage.removeItem(e);
33
34
  } catch {
34
- ae.delete(e);
35
+ me.delete(e);
35
36
  }
36
37
  }
37
- function ce(e) {
38
+ function _e(e) {
38
39
  return new Promise((t, n) => {
39
40
  e.onsuccess = () => t(e.result), e.onerror = () => n(e.error ?? /* @__PURE__ */ Error("IndexedDB request failed"));
40
41
  });
41
42
  }
42
- function le() {
43
+ function E() {
43
44
  return new Promise((e, t) => {
44
45
  let n;
45
46
  try {
@@ -53,37 +54,37 @@ function le() {
53
54
  }
54
55
  let r;
55
56
  try {
56
- r = n.open(ne, re);
57
+ r = n.open(ue, de);
57
58
  } catch (e) {
58
59
  t(e);
59
60
  return;
60
61
  }
61
62
  r.onupgradeneeded = () => {
62
63
  let e = r.result;
63
- e.objectStoreNames.contains(T) || e.createObjectStore(T);
64
+ e.objectStoreNames.contains(w) || e.createObjectStore(w);
64
65
  }, r.onsuccess = () => e(r.result), r.onerror = () => t(r.error ?? /* @__PURE__ */ Error("IndexedDB open failed")), r.onblocked = () => t(/* @__PURE__ */ Error("IndexedDB open blocked"));
65
66
  });
66
67
  }
67
- function ue(e) {
68
+ function ve(e) {
68
69
  if (!e || typeof e != "object") return !1;
69
70
  let t = e;
70
71
  return t.type === "secret" && t.algorithm?.name === "HMAC";
71
72
  }
72
- var de = {
73
+ var ye = {
73
74
  async load() {
74
- let e = await le();
75
+ let e = await E();
75
76
  try {
76
- let t = await ce(e.transaction(T, "readonly").objectStore(T).get(E));
77
- return ue(t) ? t : null;
77
+ let t = await _e(e.transaction(w, "readonly").objectStore(w).get(fe));
78
+ return ve(t) ? t : null;
78
79
  } finally {
79
80
  e.close();
80
81
  }
81
82
  },
82
83
  async save(e) {
83
- let t = await le();
84
+ let t = await E();
84
85
  try {
85
- let n = t.transaction(T, "readwrite");
86
- n.objectStore(T).put(e, E), await new Promise((e, t) => {
86
+ let n = t.transaction(w, "readwrite");
87
+ n.objectStore(w).put(e, fe), await new Promise((e, t) => {
87
88
  n.oncomplete = () => e(), n.onerror = () => t(n.error ?? /* @__PURE__ */ Error("IndexedDB write failed")), n.onabort = () => t(n.error ?? /* @__PURE__ */ Error("IndexedDB write aborted"));
88
89
  });
89
90
  } finally {
@@ -91,10 +92,10 @@ var de = {
91
92
  }
92
93
  },
93
94
  async clear() {
94
- let e = await le();
95
+ let e = await E();
95
96
  try {
96
- let t = e.transaction(T, "readwrite");
97
- t.objectStore(T).delete(E), await new Promise((e, n) => {
97
+ let t = e.transaction(w, "readwrite");
98
+ t.objectStore(w).delete(fe), await new Promise((e, n) => {
98
99
  t.oncomplete = () => e(), t.onerror = () => n(t.error ?? /* @__PURE__ */ Error("IndexedDB delete failed")), t.onabort = () => n(t.error ?? /* @__PURE__ */ Error("IndexedDB delete aborted"));
99
100
  });
100
101
  } finally {
@@ -102,7 +103,7 @@ var de = {
102
103
  }
103
104
  }
104
105
  };
105
- function fe(e, t, n) {
106
+ function be(e, t, n) {
106
107
  return new Promise((r) => {
107
108
  let i = !1, a, o = (e) => {
108
109
  i || (i = !0, a !== void 0 && clearTimeout(a), r(e));
@@ -110,26 +111,26 @@ function fe(e, t, n) {
110
111
  a = setTimeout(() => o(t), n), e.then((e) => o(e), () => o(t));
111
112
  });
112
113
  }
113
- var pe = de, O = null, k = null, A = !1, j = !1, M = null, N = 0, P = 0, F = null, me = !1;
114
- function he() {
114
+ var xe = ye, D = null, O = null, k = !1, A = !1, j = null, M = 0, N = 0, P = null, Se = !1;
115
+ function Ce() {
115
116
  try {
116
117
  let e = globalThis.location?.origin;
117
118
  if (typeof e == "string" && e.length > 0) return e;
118
119
  } catch {}
119
120
  return "unknown";
120
121
  }
121
- var ge = he, _e = () => ge(), ve = {
122
+ var we = Ce, Te = () => we(), Ee = {
122
123
  name: "HMAC",
123
124
  hash: "SHA-256"
124
125
  };
125
- function I() {
126
+ function F() {
126
127
  try {
127
128
  let e = globalThis.crypto?.subtle;
128
129
  if (e && typeof e.generateKey == "function" && typeof e.sign == "function" && typeof e.verify == "function") return e;
129
130
  } catch {}
130
131
  return null;
131
132
  }
132
- function ye(e) {
133
+ function De(e) {
133
134
  let t = new TextEncoder().encode(JSON.stringify([
134
135
  e.v,
135
136
  e.noticeVersion,
@@ -139,12 +140,12 @@ function ye(e) {
139
140
  ])), n = new Uint8Array(t.byteLength);
140
141
  return n.set(t), n;
141
142
  }
142
- function be(e) {
143
+ function Oe(e) {
143
144
  let t = "";
144
145
  for (let n of e) t += String.fromCharCode(n);
145
146
  return btoa(t).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
146
147
  }
147
- function xe(e) {
148
+ function ke(e) {
148
149
  try {
149
150
  let t = e.replace(/-/g, "+").replace(/_/g, "/"), n = t + "=".repeat((4 - t.length % 4) % 4), r = atob(n), i = new Uint8Array(r.length);
150
151
  for (let e = 0; e < r.length; e += 1) i[e] = r.charCodeAt(e);
@@ -153,40 +154,40 @@ function xe(e) {
153
154
  return null;
154
155
  }
155
156
  }
156
- async function Se() {
157
- let e = await fe(pe.load(), null, w);
157
+ async function Ae() {
158
+ let e = await be(xe.load(), null, le);
158
159
  if (e) return e;
159
- let t = I();
160
+ let t = F();
160
161
  if (!t) return null;
161
162
  try {
162
- let e = await t.generateKey(ve, !1, ["sign", "verify"]);
163
- return await fe(pe.save(e), void 0, w), e;
163
+ let e = await t.generateKey(Ee, !1, ["sign", "verify"]);
164
+ return await be(xe.save(e), void 0, le), e;
164
165
  } catch {
165
166
  return null;
166
167
  }
167
168
  }
168
- async function Ce(e) {
169
- let t = I();
170
- if (!t || !O) return null;
169
+ async function je(e) {
170
+ let t = F();
171
+ if (!t || !D) return null;
171
172
  try {
172
- let n = await t.sign("HMAC", O, ye(e));
173
- return be(new Uint8Array(n));
173
+ let n = await t.sign("HMAC", D, De(e));
174
+ return Oe(new Uint8Array(n));
174
175
  } catch {
175
176
  return null;
176
177
  }
177
178
  }
178
- async function we(e) {
179
- let t = I();
180
- if (!t || !O || !e.mac) return !1;
181
- let n = xe(e.mac);
179
+ async function Me(e) {
180
+ let t = F();
181
+ if (!t || !D || !e.mac) return !1;
182
+ let n = ke(e.mac);
182
183
  if (!n) return !1;
183
184
  try {
184
- return await t.verify("HMAC", O, n, ye(e));
185
+ return await t.verify("HMAC", D, n, De(e));
185
186
  } catch {
186
187
  return !1;
187
188
  }
188
189
  }
189
- function Te(e) {
190
+ function Ne(e) {
190
191
  if (!e) return null;
191
192
  try {
192
193
  let t = JSON.parse(e);
@@ -204,128 +205,128 @@ function Te(e) {
204
205
  return null;
205
206
  }
206
207
  }
207
- function Ee(e, t) {
208
+ function Pe(e, t) {
208
209
  return !(!Number.isFinite(e.grantedAt) || !Number.isFinite(e.expiry) || e.expiry <= t || e.grantedAt > e.expiry || e.expiry - e.grantedAt > 15552e6);
209
210
  }
210
- function De(e) {
211
- return e.v === C && e.noticeVersion === 2 && e.origin === _e();
211
+ function I(e) {
212
+ return e.v === se && e.noticeVersion === 2 && e.origin === Te();
212
213
  }
213
- function Oe() {
214
- return Te(oe(b));
214
+ function Fe() {
215
+ return Ne(he(S));
215
216
  }
216
- function ke(e) {
217
- se(b, JSON.stringify(e));
217
+ function Ie(e) {
218
+ ge(S, JSON.stringify(e));
218
219
  }
219
220
  function L() {
220
- D(b);
221
+ T(S);
221
222
  }
222
223
  function R() {
223
- D(x), D(ee);
224
+ T(ae), T(oe);
224
225
  }
225
- var Ae = () => {
226
- let e = k;
227
- return !e || !A ? !1 : Ee(e, Date.now()) && De(e);
228
- }, je = () => oe(S) === "true", z = () => Ae() ? "granted" : je() ? "denied" : "unset", B = () => (M ||= Me(), M);
229
- async function Me() {
230
- let e = ++N, t = P, n = null;
226
+ var Le = () => {
227
+ let e = O;
228
+ return !e || !k ? !1 : Pe(e, Date.now()) && I(e);
229
+ }, Re = () => he(C) === "true", z = () => Le() ? "granted" : Re() ? "denied" : "unset", B = () => (j ||= ze(), j);
230
+ async function ze() {
231
+ let e = ++M, t = N, n = null;
231
232
  try {
232
- n = await Se();
233
+ n = await Ae();
233
234
  } catch {
234
235
  n = null;
235
236
  }
236
- if (e !== N) return z();
237
- O = n, R();
238
- let r = Oe();
239
- return r !== null && await we(r) && Ee(r, Date.now()) && De(r) && r ? t === P && e === N && (k = r, A = !0) : r && !j && (L(), t === P && e === N && (k = null, A = !1)), z();
237
+ if (e !== M) return z();
238
+ D = n, R();
239
+ let r = Fe();
240
+ return r !== null && await Me(r) && Pe(r, Date.now()) && I(r) && r ? t === N && e === M && (O = r, k = !0) : r && !A && (L(), t === N && e === M && (O = null, k = !1)), z();
240
241
  }
241
- function Ne() {
242
- let e = F;
243
- return F = null, e && Date.now() - e.at <= te ? {
242
+ function Be() {
243
+ let e = P;
244
+ return P = null, e && Date.now() - e.at <= ce ? {
244
245
  noticeVersion: e.noticeVersion,
245
246
  source: "user-gesture"
246
- } : me ? {
247
+ } : Se ? {
247
248
  noticeVersion: 2,
248
249
  source: "host-managed"
249
250
  } : null;
250
251
  }
251
- function Pe(e) {
252
- return typeof e != "number" || !Number.isFinite(e) || e <= 0 ? y : Math.min(Math.floor(e), y);
252
+ function Ve(e) {
253
+ return typeof e != "number" || !Number.isFinite(e) || e <= 0 ? ie : Math.min(Math.floor(e), ie);
253
254
  }
254
- function Fe(e, t) {
255
+ function He(e, t) {
255
256
  let n = Date.now();
256
257
  return {
257
- v: C,
258
+ v: se,
258
259
  noticeVersion: e,
259
- origin: _e(),
260
+ origin: Te(),
260
261
  grantedAt: n,
261
- expiry: n + Pe(t),
262
+ expiry: n + Ve(t),
262
263
  mac: ""
263
264
  };
264
265
  }
265
- function Ie(e, t) {
266
- D(S), R();
267
- let n = Fe(e.noticeVersion, t);
268
- return k = n, A = !0, j = !0, P += 1, ke(n), n;
266
+ function Ue(e, t) {
267
+ T(C), R();
268
+ let n = He(e.noticeVersion, t);
269
+ return O = n, k = !0, A = !0, N += 1, Ie(n), n;
269
270
  }
270
- async function Le(e) {
271
+ async function We(e) {
271
272
  try {
272
- if (await B(), k !== e) return;
273
- let t = await Ce(e);
274
- if (k !== e) return;
273
+ if (await B(), O !== e) return;
274
+ let t = await je(e);
275
+ if (O !== e) return;
275
276
  if (!t) {
276
- L(), j = !1;
277
+ L(), A = !1;
277
278
  return;
278
279
  }
279
280
  let n = {
280
281
  ...e,
281
282
  mac: t
282
283
  };
283
- k = n, A = !0, ke(n), j = !1;
284
+ O = n, k = !0, Ie(n), A = !1;
284
285
  } catch {
285
- k === e && (L(), j = !1);
286
+ O === e && (L(), A = !1);
286
287
  }
287
288
  }
288
- var Re = () => {
289
- let e = Ne();
289
+ var Ge = () => {
290
+ let e = Be();
290
291
  if (!e) {
291
- ie("refusing programmatic consent grant: consent requires the built-in banner to be rendered and accepted by the visitor (see setHostManagedConsentAllowed for host-managed UIs)");
292
+ pe("refusing programmatic consent grant: consent requires the built-in banner to be rendered and accepted by the visitor (see setHostManagedConsentAllowed for host-managed UIs)");
292
293
  return;
293
294
  }
294
- Le(Ie(e));
295
- }, ze = (e = 2) => {
296
- F = {
295
+ We(Ue(e));
296
+ }, Ke = (e = 2) => {
297
+ P = {
297
298
  noticeVersion: e,
298
299
  at: Date.now()
299
300
  };
300
- }, Be = (e) => {
301
- me = e === !0;
302
- }, Ve = () => {
303
- L(), R(), k = null, A = !1, j = !1, P += 1, se(S, "true");
304
- }, He = () => {
305
- L(), R(), D(S), k = null, A = !1, j = !1, F = null, O = null, N += 1, P += 1, M = null, fe(pe.clear(), void 0, w);
306
- }, Ue = oe, We = se, Ge = D;
307
- async function Ke() {
308
- let e = P, t = Oe();
301
+ }, qe = (e) => {
302
+ Se = e === !0;
303
+ }, Je = () => {
304
+ L(), R(), O = null, k = !1, A = !1, N += 1, ge(C, "true");
305
+ }, Ye = () => {
306
+ L(), R(), T(C), O = null, k = !1, A = !1, P = null, D = null, M += 1, N += 1, j = null, be(xe.clear(), void 0, le);
307
+ }, Xe = he, Ze = ge, V = T;
308
+ async function Qe() {
309
+ let e = N, t = Fe();
309
310
  if (!t) {
310
- k = null, A = !1;
311
+ O = null, k = !1;
311
312
  return;
312
313
  }
313
- if (!I()) return;
314
- if (!O) {
315
- M = null, await B();
314
+ if (!F()) return;
315
+ if (!D) {
316
+ j = null, await B();
316
317
  return;
317
318
  }
318
- let n = await we(t), r = Oe();
319
- if (e !== P || !r || JSON.stringify(r) !== JSON.stringify(t)) return;
320
- let i = n && Ee(t, Date.now()) && De(t);
321
- k = i ? t : null, A = i;
319
+ let n = await Me(t), r = Fe();
320
+ if (e !== N || !r || JSON.stringify(r) !== JSON.stringify(t)) return;
321
+ let i = n && Pe(t, Date.now()) && I(t);
322
+ O = i ? t : null, k = i;
322
323
  }
323
324
  try {
324
325
  typeof globalThis.addEventListener == "function" && globalThis.addEventListener("storage", (e) => {
325
- e.key !== null && e.key !== b && e.key !== S || (P += 1, Ke());
326
+ e.key !== null && e.key !== S && e.key !== C || (N += 1, Qe());
326
327
  });
327
328
  } catch {}
328
- var qe = () => {
329
+ var $e = () => {
329
330
  try {
330
331
  if (typeof crypto < "u" && typeof crypto.randomUUID == "function") return crypto.randomUUID();
331
332
  } catch {}
@@ -337,35 +338,35 @@ var qe = () => {
337
338
  B();
338
339
  //#endregion
339
340
  //#region src/consent/ConsentUI.ts
340
- var V = "#6366f1", Je = 1500, Ye = 1500, Xe = 6e4, Ze = 80, Qe = 40, $e = [
341
+ var H = "#6366f1", et = 1500, tt = 1500, nt = 6e4, rt = 80, it = 40, at = [
341
342
  "bottom-right",
342
343
  "bottom-left",
343
344
  "top-right",
344
345
  "top-left"
345
- ], et = /^#[0-9a-f]{3}$/i, tt = /^#[0-9a-f]{6}$/i, nt = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i, rt = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i, it = new Map((/* @__PURE__ */ "black.white.red.green.blue.indigo.violet.purple.teal.cyan.orange.pink.brown.gray.grey.slate.navy.maroon.olive.gold.crimson.tomato.salmon.coral.seagreen.steelblue.royalblue.dodgerblue.mediumseagreen.mediumpurple.rebeccapurple".split(".")).map((e) => [e, e]));
346
- function at(e) {
347
- if (typeof e != "string") return V;
346
+ ], ot = /^#[0-9a-f]{3}$/i, st = /^#[0-9a-f]{6}$/i, ct = /^rgb\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*\)$/i, lt = /^rgba\(\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(\d{1,3})\s*,\s*(0|1|0?\.\d+)\s*\)$/i, ut = new Map((/* @__PURE__ */ "black.white.red.green.blue.indigo.violet.purple.teal.cyan.orange.pink.brown.gray.grey.slate.navy.maroon.olive.gold.crimson.tomato.salmon.coral.seagreen.steelblue.royalblue.dodgerblue.mediumseagreen.mediumpurple.rebeccapurple".split(".")).map((e) => [e, e]));
347
+ function dt(e) {
348
+ if (typeof e != "string") return H;
348
349
  let t = e.trim();
349
- if (t.length === 0 || t.length > 64) return V;
350
- if (et.test(t) || tt.test(t)) return t.toLowerCase();
351
- let n = nt.exec(t);
350
+ if (t.length === 0 || t.length > 64) return H;
351
+ if (ot.test(t) || st.test(t)) return t.toLowerCase();
352
+ let n = ct.exec(t);
352
353
  if (n) {
353
354
  let [e, t, r] = n.slice(1).map(Number);
354
- return e <= 255 && t <= 255 && r <= 255 ? `rgb(${e}, ${t}, ${r})` : V;
355
+ return e <= 255 && t <= 255 && r <= 255 ? `rgb(${e}, ${t}, ${r})` : H;
355
356
  }
356
- let r = rt.exec(t);
357
+ let r = lt.exec(t);
357
358
  if (r) {
358
359
  let [e, t, n] = r.slice(1, 4).map(Number), i = Number(r[4]);
359
- return e <= 255 && t <= 255 && n <= 255 && i >= 0 && i <= 1 ? `rgba(${e}, ${t}, ${n}, ${i})` : V;
360
+ return e <= 255 && t <= 255 && n <= 255 && i >= 0 && i <= 1 ? `rgba(${e}, ${t}, ${n}, ${i})` : H;
360
361
  }
361
- return it.get(t.toLowerCase()) ?? V;
362
+ return ut.get(t.toLowerCase()) ?? H;
362
363
  }
363
- function ot(e, t, n) {
364
+ function ft(e, t, n) {
364
365
  if (typeof e != "string") return t;
365
366
  let r = e.replace(/[\u0000-\u001f\u007f-\u009f\u200b-\u200f\u202a-\u202e\u2066-\u2069]/g, "").replace(/\s+/g, " ").trim();
366
367
  return r.length === 0 ? t : r.length > n ? `${r.slice(0, n)}…` : r;
367
368
  }
368
- function st(e) {
369
+ function pt(e) {
369
370
  if (typeof e != "string" || e.trim().length === 0) return null;
370
371
  try {
371
372
  let t = new URL(e.trim());
@@ -374,41 +375,41 @@ function st(e) {
374
375
  return null;
375
376
  }
376
377
  }
377
- function ct(e) {
378
+ function mt(e) {
378
379
  return {
379
- brandName: ot(e?.brandName, "Flaxia Crowd", Ze),
380
- position: $e.includes(e?.position) ? e.position : "bottom-right",
381
- accentColor: at(e?.accentColor),
382
- acceptLabel: ot(e?.acceptLabel, v.acceptLabel, Qe),
383
- rejectLabel: ot(e?.rejectLabel, v.rejectLabel, Qe),
384
- privacyPolicyUrl: st(e?.privacyPolicyUrl),
385
- minVisibleMs: lt(e?.minVisibleMs)
380
+ brandName: ft(e?.brandName, "Flaxia Crowd", rt),
381
+ position: at.includes(e?.position) ? e.position : "bottom-right",
382
+ accentColor: dt(e?.accentColor),
383
+ acceptLabel: ft(e?.acceptLabel, x.acceptLabel, it),
384
+ rejectLabel: ft(e?.rejectLabel, x.rejectLabel, it),
385
+ privacyPolicyUrl: pt(e?.privacyPolicyUrl),
386
+ minVisibleMs: ht(e?.minVisibleMs)
386
387
  };
387
388
  }
388
- function lt(e) {
389
- return typeof e != "number" || !Number.isFinite(e) ? Je : Math.min(Math.max(Math.floor(e), Ye), Xe);
389
+ function ht(e) {
390
+ return typeof e != "number" || !Number.isFinite(e) ? et : Math.min(Math.max(Math.floor(e), tt), nt);
390
391
  }
391
- function ut(e, t) {
392
- return typeof t.minVisibleMs == "number" && Number.isFinite(t.minVisibleMs) ? Math.min(Math.max(Math.floor(t.minVisibleMs), 0), Xe) : e;
392
+ function gt(e, t) {
393
+ return typeof t.minVisibleMs == "number" && Number.isFinite(t.minVisibleMs) ? Math.min(Math.max(Math.floor(t.minVisibleMs), 0), nt) : e;
393
394
  }
394
- var dt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n padding: 20px;\n background: #fff;\n color: #1f2937;\n border: 1px solid #ccc;\n box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n z-index: 9999;\n border-radius: 8px;\n max-width: 300px;\n font-family: sans-serif;\n }\n .overlay h3 {\n margin: 0 0 8px;\n color: #111827;\n font-size: 16px;\n }\n .overlay p {\n margin: 0 0 12px;\n color: #4b5563;\n font-size: 14px;\n line-height: 1.4;\n }\n .overlay ul {\n margin: 0 0 12px;\n padding-left: 18px;\n color: #4b5563;\n font-size: 13px;\n line-height: 1.45;\n }\n .overlay li {\n margin-bottom: 6px;\n }\n .overlay .hint {\n margin: 0 0 8px;\n color: #6b7280;\n font-size: 12px;\n }\n .overlay .privacy {\n margin: 0 0 8px;\n font-size: 12px;\n }\n .overlay .privacy a {\n color: __flaxia_accent__;\n }\n button {\n background: __flaxia_accent__;\n color: white;\n border: none;\n padding: 10px 15px;\n border-radius: 4px;\n cursor: pointer;\n margin-top: 10px;\n width: 100%;\n font-size: 14px;\n }\n button:disabled {\n opacity: 0.6;\n cursor: default;\n }\n button.reject {\n background: transparent;\n color: #4b5563;\n border: 1px solid #ccc;\n }\n @media (prefers-color-scheme: dark) {\n .overlay {\n background: #1f2937;\n color: #f9fafb;\n border-color: #374151;\n box-shadow: 0 4px 6px rgba(0,0,0,0.4);\n }\n .overlay h3 {\n color: #f9fafb;\n }\n .overlay p,\n .overlay ul {\n color: #d1d5db;\n }\n .overlay .hint {\n color: #9ca3af;\n }\n button.reject {\n color: #d1d5db;\n border-color: #4b5563;\n }\n }\n", ft = class {
395
+ var _t = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n padding: 20px;\n background: #fff;\n color: #1f2937;\n border: 1px solid #ccc;\n box-shadow: 0 4px 6px rgba(0,0,0,0.1);\n z-index: 9999;\n border-radius: 8px;\n max-width: 300px;\n font-family: sans-serif;\n }\n .overlay h3 {\n margin: 0 0 8px;\n color: #111827;\n font-size: 16px;\n }\n .overlay p {\n margin: 0 0 12px;\n color: #4b5563;\n font-size: 14px;\n line-height: 1.4;\n }\n .overlay ul {\n margin: 0 0 12px;\n padding-left: 18px;\n color: #4b5563;\n font-size: 13px;\n line-height: 1.45;\n }\n .overlay li {\n margin-bottom: 6px;\n }\n .overlay .hint {\n margin: 0 0 8px;\n color: #6b7280;\n font-size: 12px;\n }\n .overlay .privacy {\n margin: 0 0 8px;\n font-size: 12px;\n }\n .overlay .privacy a {\n color: __flaxia_accent__;\n }\n button {\n background: __flaxia_accent__;\n color: white;\n border: none;\n padding: 10px 15px;\n border-radius: 4px;\n cursor: pointer;\n margin-top: 10px;\n width: 100%;\n font-size: 14px;\n }\n button:disabled {\n opacity: 0.6;\n cursor: default;\n }\n button.reject {\n background: transparent;\n color: #4b5563;\n border: 1px solid #ccc;\n }\n @media (prefers-color-scheme: dark) {\n .overlay {\n background: #1f2937;\n color: #f9fafb;\n border-color: #374151;\n box-shadow: 0 4px 6px rgba(0,0,0,0.4);\n }\n .overlay h3 {\n color: #f9fafb;\n }\n .overlay p,\n .overlay ul {\n color: #d1d5db;\n }\n .overlay .hint {\n color: #9ca3af;\n }\n button.reject {\n color: #d1d5db;\n border-color: #4b5563;\n }\n }\n", vt = class {
395
396
  constructor(e, t, n, r, i) {
396
- this.config = ct(t), this.options = i ?? {}, this.root = e.attachShadow({ mode: "closed" }), this.render(n, r);
397
+ this.config = mt(t), this.options = i ?? {}, this.root = e.attachShadow({ mode: "closed" }), this.render(n, r);
397
398
  }
398
399
  shadowRootForTesting() {
399
400
  return this.root;
400
401
  }
401
402
  render(e, t) {
402
403
  let { brandName: n, position: r, accentColor: i, acceptLabel: a, rejectLabel: o, privacyPolicyUrl: s } = this.config, [c, l] = r.split("-"), u = document.createElement("style");
403
- u.textContent = dt.replace(/__flaxia_accent__/g, i).replace("__flaxia_position__", `${c}: 20px; ${l}: 20px`);
404
+ u.textContent = _t.replace(/__flaxia_accent__/g, i).replace("__flaxia_position__", `${c}: 20px; ${l}: 20px`);
404
405
  let d = document.createElement("div");
405
406
  d.className = "overlay", d.setAttribute("role", "dialog"), d.setAttribute("aria-labelledby", "flaxia-consent-title");
406
407
  let f = document.createElement("h3");
407
408
  f.id = "flaxia-consent-title", f.textContent = n;
408
409
  let p = document.createElement("p");
409
- p.textContent = v.summary;
410
+ p.textContent = x.summary;
410
411
  let m = document.createElement("ul");
411
- for (let e of v.items) {
412
+ for (let e of x.items) {
412
413
  let t = document.createElement("li");
413
414
  t.textContent = e, m.appendChild(t);
414
415
  }
@@ -419,25 +420,25 @@ var dt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
419
420
  t.href = s, t.target = "_blank", t.rel = "noopener noreferrer", t.textContent = "プライバシーポリシー", e.appendChild(t), d.appendChild(e);
420
421
  }
421
422
  let h = document.createElement("p");
422
- h.className = "hint", h.textContent = v.acceptGateHint;
423
+ h.className = "hint", h.textContent = x.acceptGateHint;
423
424
  let g = document.createElement("button");
424
425
  g.id = "consent-btn", g.type = "button", g.textContent = a;
425
426
  let _ = document.createElement("button");
426
427
  _.id = "reject-btn", _.type = "button", _.className = "reject", _.textContent = o;
427
- let y = this.options.now ?? (() => Date.now()), b = this.options.schedule ?? ((e, t) => void setTimeout(e, t)), x = ut(this.config.minVisibleMs, this.options), ee = y() + x, S = x <= 0, C = !1;
428
- S || (g.disabled = !0, g.setAttribute("aria-disabled", "true"), b(() => {
429
- S = !0, g.disabled = !1, g.removeAttribute("aria-disabled"), h.remove();
430
- }, x));
431
- let te = (e) => {
432
- C || (C = !0, d.remove(), e?.());
428
+ let v = this.options.now ?? (() => Date.now()), ee = this.options.schedule ?? ((e, t) => void setTimeout(e, t)), y = gt(this.config.minVisibleMs, this.options), te = v() + y, b = y <= 0, ne = !1;
429
+ b || (g.disabled = !0, g.setAttribute("aria-disabled", "true"), ee(() => {
430
+ b = !0, g.disabled = !1, g.removeAttribute("aria-disabled"), h.remove();
431
+ }, y));
432
+ let re = (e) => {
433
+ ne || (ne = !0, d.remove(), e?.());
433
434
  };
434
435
  g.addEventListener("click", () => {
435
- !S || y() < ee || (ze(2), te(e));
436
+ !b || v() < te || (Ke(2), re(e));
436
437
  }), _.addEventListener("click", () => {
437
- te(t);
438
- }), S || d.appendChild(h), d.append(g, _), this.root.append(u, d);
438
+ re(t);
439
+ }), b || d.appendChild(h), d.append(g, _), this.root.append(u, d);
439
440
  }
440
- }, H = (...e) => console.log("[flaxia-node]", ...e), pt = class e {
441
+ }, U = (...e) => console.log("[flaxia-node]", ...e), yt = class e {
441
442
  static {
442
443
  this.MAX_PENDING_CONTROLS = 64;
443
444
  }
@@ -460,68 +461,73 @@ var dt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
460
461
  return;
461
462
  }
462
463
  let l = () => this.execute(e, t, n, r, i, a, s, c, o);
463
- this.active ? (H(`task queued id=${e} workload=${t} (active task running)`), this.queue.push({
464
+ this.active ? (U(`task queued id=${e} workload=${t} (active task running)`), this.queue.push({
464
465
  id: e,
465
466
  job: l,
466
467
  reject: c
467
468
  })) : l();
468
469
  });
469
470
  }
470
- execute(e, t, n, r, i, a, o, s, c) {
471
- let l = this.worker;
472
- if (!l) {
473
- s(/* @__PURE__ */ Error("Worker not available")), this.dequeue();
471
+ execute(e, t, n, r, a, s, c, l, u) {
472
+ let d = this.worker;
473
+ if (!d) {
474
+ l(/* @__PURE__ */ Error("Worker not available")), this.dequeue();
474
475
  return;
475
476
  }
476
- let u = r ?? this.defaultTimeoutMs, d = !1, f = performance.now();
477
- H(`task start id=${e} workload=${t} timeoutMs=${u}`);
478
- let p = (t) => {
479
- if (d) return;
480
- d = !0;
477
+ let f = r ?? this.defaultTimeoutMs, p = !1, m = performance.now();
478
+ U(`task start id=${e} workload=${t} timeoutMs=${f}`);
479
+ let h = (t) => {
480
+ if (p) return;
481
+ p = !0;
481
482
  let n = this.active;
482
483
  n && (clearTimeout(n.timer), n.removeListener()), this.active = null, this.pendingControls = this.pendingControls.filter((t) => t.taskId !== e), t(), this.dequeue();
483
- }, m = (n) => {
484
- let { id: r, type: a, result: l, error: u, token: d, cpuLoad: m } = n.data;
484
+ }, g = (n) => {
485
+ let { id: r, type: s, result: d, error: f, token: p, cpuLoad: g } = n.data;
485
486
  if (r === e) {
486
- if (g(n.data.modelCache) && (this._modelCacheSnapshot = n.data.modelCache), a === "token") {
487
- i?.(d);
487
+ if (i(n.data.modelCache) && (this._modelCacheSnapshot = n.data.modelCache), s === "token") {
488
+ a?.(p);
488
489
  return;
489
490
  }
490
- if (a === "heartbeat") {
491
- typeof m == "number" && Number.isFinite(m) && (this._lastCpuLoad = Math.min(1, Math.max(0, m)), this._hasCpuLoadSample = !0);
491
+ if (s === "heartbeat") {
492
+ typeof g == "number" && Number.isFinite(g) && (this._lastCpuLoad = Math.min(1, Math.max(0, g)), this._hasCpuLoadSample = !0);
492
493
  return;
493
494
  }
494
- if (a === "swarm-frame") {
495
- c?.onFrame?.(n.data.frame);
495
+ if (s === "swarm-frame") {
496
+ u?.onFrame?.(n.data.frame);
496
497
  return;
497
498
  }
498
- if (a === "swarm-message") {
499
- c?.onMessage?.(n.data.message);
499
+ if (s === "swarm-message") {
500
+ u?.onMessage?.(n.data.message);
500
501
  return;
501
502
  }
502
- a === "done" ? (H(`task done id=${e} workload=${t} durationMs=${Math.round(performance.now() - f)}`), p(() => o(l))) : a === "error" ? (H(`task failed id=${e} workload=${t} error=${u}`), p(() => s(Error(u)))) : (H(`task unknown-message id=${e} type=${String(a)}`), p(() => s(/* @__PURE__ */ Error(`Unknown message type: ${String(a)}`))));
503
+ if (s === "done") U(`task done id=${e} workload=${t} durationMs=${Math.round(performance.now() - m)}`), h(() => c(d));
504
+ else if (s === "error") {
505
+ U(`task failed id=${e} workload=${t} error=${f}`);
506
+ let r = typeof n.data.errorCode == "string" ? n.data.errorCode : "TASK_FAILED", i = typeof n.data.errorStatus == "number" ? n.data.errorStatus : 500, a = new o(String(f), r, i);
507
+ typeof n.data.detail == "string" && (a.detail = n.data.detail), h(() => l(a));
508
+ } else U(`task unknown-message id=${e} type=${String(s)}`), h(() => l(/* @__PURE__ */ Error(`Unknown message type: ${String(s)}`)));
503
509
  }
504
- }, h = () => l.removeEventListener("message", m), _ = setTimeout(() => {
505
- H(`task timeout id=${e} workload=${t} (worker terminated after ${u}ms)`), this.cleanupWorker(), p(() => s(/* @__PURE__ */ Error("TIMEOUT")));
506
- }, u);
510
+ }, _ = () => d.removeEventListener("message", g), v = setTimeout(() => {
511
+ U(`task timeout id=${e} workload=${t} (worker terminated after ${f}ms)`), this.cleanupWorker(), h(() => l(/* @__PURE__ */ Error("TIMEOUT")));
512
+ }, f);
507
513
  this.active = {
508
514
  id: e,
509
- resolve: o,
510
- reject: s,
511
- timer: _,
512
- worker: l,
513
- removeListener: h
514
- }, l.addEventListener("message", m);
515
+ resolve: c,
516
+ reject: l,
517
+ timer: v,
518
+ worker: d,
519
+ removeListener: _
520
+ }, d.addEventListener("message", g);
515
521
  try {
516
- l.postMessage({
522
+ d.postMessage({
517
523
  id: e,
518
524
  workload: t,
519
525
  payload: n,
520
- timeoutMs: u,
521
- config: a
526
+ timeoutMs: f,
527
+ config: s
522
528
  }), this.flushControls();
523
529
  } catch (e) {
524
- p(() => s(e instanceof Error ? e : Error(String(e))));
530
+ h(() => l(e instanceof Error ? e : Error(String(e))));
525
531
  }
526
532
  }
527
533
  flushControls() {
@@ -570,7 +576,7 @@ var dt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
570
576
  let n = this.queue.findIndex((t) => t.id === e);
571
577
  if (n >= 0) {
572
578
  let [r] = this.queue.splice(n, 1);
573
- return this.pendingControls = this.pendingControls.filter((t) => t.taskId !== e), H(`task aborted before start id=${e} reason=${t}`), r.reject(Error(t)), !0;
579
+ return this.pendingControls = this.pendingControls.filter((t) => t.taskId !== e), U(`task aborted before start id=${e} reason=${t}`), r.reject(Error(t)), !0;
574
580
  }
575
581
  if (this.active?.id !== e || !this.worker) return !1;
576
582
  try {
@@ -578,13 +584,13 @@ var dt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
578
584
  id: e,
579
585
  type: "abort",
580
586
  reason: t
581
- }), H(`task abort sent id=${e} reason=${t}`), !0;
587
+ }), U(`task abort sent id=${e} reason=${t}`), !0;
582
588
  } catch {
583
589
  return !1;
584
590
  }
585
591
  }
586
592
  handleWorkerError(e) {
587
- H(`worker error error=${e.message}`);
593
+ U(`worker error error=${e.message}`);
588
594
  let t = this.active;
589
595
  this.cleanupWorker(), t && (clearTimeout(t.timer), this.active = null, t.reject(e), this.dequeue());
590
596
  }
@@ -614,8 +620,8 @@ var dt = "\n .overlay {\n position: fixed;\n __flaxia_position__;\n pa
614
620
  let e = this._modelCacheSnapshot;
615
621
  return !e || e.expiresAt <= Date.now() ? null : e;
616
622
  }
617
- }, U = null, mt = null;
618
- function W(e, t, n, r, i, a) {
623
+ }, W = null, bt = null;
624
+ function G(e, t, n, r, i, a) {
619
625
  return {
620
626
  value: e,
621
627
  unit: t,
@@ -625,48 +631,48 @@ function W(e, t, n, r, i, a) {
625
631
  sampleCount: a
626
632
  };
627
633
  }
628
- function G(e, t, n) {
629
- return W(null, e, "unknown", t, t + n, 0);
634
+ function K(e, t, n) {
635
+ return G(null, e, "unknown", t, t + n, 0);
630
636
  }
631
- async function ht(e, t) {
632
- return e ? ((!U || U.expiresAt <= t) && (mt ||= d().then((e) => (U = e, e)).finally(() => {
633
- mt = null;
634
- }), U = await mt), U) : null;
637
+ async function xt(e, t) {
638
+ return e ? ((!W || W.expiresAt <= t) && (bt ||= p().then((e) => (W = e, e)).finally(() => {
639
+ bt = null;
640
+ }), W = await bt), W) : null;
635
641
  }
636
- async function gt(e) {
637
- let t = e.now ?? Date.now(), r = t + n, i = u(), a = i.bytes !== null && i.sampledAt !== null && t - i.sampledAt <= 864e5, s = Number.isFinite(e.deviceMemory) && e.deviceMemory > 0 && e.deviceMemory <= 1024, c = await ht(e.probeGpu === !0, t), l = c?.sampledAt ?? t, d = c?.expiresAt ?? t + 6e5;
642
+ async function St(e) {
643
+ let t = e.now ?? Date.now(), n = t + _, r = d(), i = r.bytes !== null && r.sampledAt !== null && t - r.sampledAt <= 864e5, a = Number.isFinite(e.deviceMemory) && e.deviceMemory > 0 && e.deviceMemory <= 1024, o = await xt(e.probeGpu === !0, t), s = o?.sampledAt ?? t, c = o?.expiresAt ?? t + 6e5;
638
644
  return {
639
645
  version: 1,
640
646
  sampledAt: t,
641
- expiresAt: r,
642
- cpuLoad: typeof e.cpuLoad == "number" && Number.isFinite(e.cpuLoad) && e.cpuLoad >= 0 && e.cpuLoad <= 1 ? W(e.cpuLoad, "ratio", "estimated", t, r, 1) : G("ratio", t, n),
643
- wasmMemoryLowerBound: a ? W(i.bytes, "bytes", "measured", i.sampledAt, i.sampledAt + o, 1) : G("bytes", t, o),
644
- deviceMemory: s ? W(e.deviceMemory, "GiB", "estimated", t, t + o, 1) : G("GiB", t, o),
647
+ expiresAt: n,
648
+ cpuLoad: typeof e.cpuLoad == "number" && Number.isFinite(e.cpuLoad) && e.cpuLoad >= 0 && e.cpuLoad <= 1 ? G(e.cpuLoad, "ratio", "estimated", t, n, 1) : K("ratio", t, _),
649
+ wasmMemoryLowerBound: i ? G(r.bytes, "bytes", "measured", r.sampledAt, r.sampledAt + u, 1) : K("bytes", t, u),
650
+ deviceMemory: a ? G(e.deviceMemory, "GiB", "estimated", t, t + u, 1) : K("GiB", t, u),
645
651
  gpu: {
646
- status: c?.status ?? "unknown",
647
- sampledAt: l,
648
- expiresAt: d,
649
- architecture: c?.architecture ? W(c.architecture, "text", "measured", l, d, 1) : G("text", l, p),
650
- maxStorageBufferBindingSize: c?.maxStorageBufferBindingSize !== null && c?.maxStorageBufferBindingSize !== void 0 ? W(c.maxStorageBufferBindingSize, "bytes", "measured", l, d, 1) : G("bytes", l, p),
651
- computeCompletionMs: c?.computeCompletionMs !== null && c?.computeCompletionMs !== void 0 ? W(c.computeCompletionMs, "ms", "measured", l, d, c.sampleCount) : G("ms", l, p),
652
- memoryBytes: G("bytes", l, p)
652
+ status: o?.status ?? "unknown",
653
+ sampledAt: s,
654
+ expiresAt: c,
655
+ architecture: o?.architecture ? G(o.architecture, "text", "measured", s, c, 1) : K("text", s, l),
656
+ maxStorageBufferBindingSize: o?.maxStorageBufferBindingSize !== null && o?.maxStorageBufferBindingSize !== void 0 ? G(o.maxStorageBufferBindingSize, "bytes", "measured", s, c, 1) : K("bytes", s, l),
657
+ computeCompletionMs: o?.computeCompletionMs !== null && o?.computeCompletionMs !== void 0 ? G(o.computeCompletionMs, "ms", "measured", s, c, o.sampleCount) : K("ms", s, l),
658
+ memoryBytes: K("bytes", s, l)
653
659
  }
654
660
  };
655
661
  }
656
662
  //#endregion
657
663
  //#region src/swarm/peer-quality.ts
658
- var _t = 15e3;
659
- function vt(e) {
664
+ var Ct = 15e3;
665
+ function wt(e) {
660
666
  let t = e.filter((e) => Number.isFinite(e) && e >= 0).slice(-5);
661
667
  if (!t.length) return [];
662
668
  let n = [...t].sort((e, t) => e - t), r = n[Math.floor(n.length / 2)], i = r + Math.max(20, r * 4);
663
669
  return t.filter((e) => e <= i);
664
670
  }
665
- function K(e, t) {
671
+ function q(e, t) {
666
672
  return !Number.isFinite(e) || e < 0 || !Number.isFinite(t) || t <= 0 ? null : e * 8 / t / 1e3;
667
673
  }
668
- function yt(e, t) {
669
- let n = vt(e);
674
+ function Tt(e, t) {
675
+ let n = wt(e);
670
676
  if (!n.length) return {
671
677
  value: null,
672
678
  sampledAt: t,
@@ -679,11 +685,11 @@ function yt(e, t) {
679
685
  sampleCount: n.length
680
686
  };
681
687
  }
682
- function bt(e, n, r, i, a) {
683
- let o = (e, t) => {
688
+ function Et(e, t, n, r, i) {
689
+ let o = (e, n) => {
684
690
  let r = (r) => {
685
- let i = t?.[r] ?? n;
686
- return n - i >= 6e4 ? yt([], n) : yt(e[r] ?? [], i);
691
+ let i = n?.[r] ?? t;
692
+ return t - i >= 6e4 ? Tt([], t) : Tt(e[r] ?? [], i);
687
693
  };
688
694
  return {
689
695
  rttMs: r("rttMs"),
@@ -695,16 +701,16 @@ function bt(e, n, r, i, a) {
695
701
  return {
696
702
  version: 1,
697
703
  peerNodeId: e,
698
- sampledAt: n,
699
- expiresAt: n + t,
700
- webRtc: o(r, a?.webRtc),
701
- application: o(i, a?.application)
704
+ sampledAt: t,
705
+ expiresAt: t + a,
706
+ webRtc: o(n, i?.webRtc),
707
+ application: o(r, i?.application)
702
708
  };
703
709
  }
704
710
  //#endregion
705
711
  //#region src/swarm/peer-transport.ts
706
- var xt = 5e3, q = 16 * 1024, St = l, Ct = 256 * 1024, wt = 1129860166, J = 16, Tt = 2, Et = 64, Dt = "flaxia-swarm-v1", Ot = "flaxia-peer-quality-v1", kt = 128, At = [{ urls: "stun:stun.cloudflare.com:3478" }];
707
- function jt() {
712
+ var Dt = 5e3, J = 16 * 1024, Ot = g, kt = 256 * 1024, At = 1129860166, Y = 16, jt = 2, Mt = 64, Nt = "flaxia-swarm-v1", Pt = "flaxia-peer-quality-v1", Ft = 128, It = [{ urls: "stun:stun.cloudflare.com:3478" }];
713
+ function Lt() {
708
714
  return {
709
715
  rttMs: [],
710
716
  jitterMs: [],
@@ -712,41 +718,41 @@ function jt() {
712
718
  receiveMbps: []
713
719
  };
714
720
  }
715
- function Mt(e) {
716
- if (e.byteLength < J || e.byteLength > 16400) return null;
721
+ function Rt(e) {
722
+ if (e.byteLength < Y || e.byteLength > 16400) return null;
717
723
  let t = new DataView(e);
718
- if (t.getUint32(0, !0) !== wt) return null;
724
+ if (t.getUint32(0, !0) !== At) return null;
719
725
  let n = t.getUint32(4, !0), r = t.getUint16(8, !0), i = t.getUint16(10, !0), a = t.getUint32(12, !0);
720
- if (a < 1 || a > St || i < 1 || i !== Math.ceil(a / 16384) || r >= i) return null;
721
- let o = Math.min(q, a - r * q);
722
- return e.byteLength - J === o ? {
726
+ if (a < 1 || a > Ot || i < 1 || i !== Math.ceil(a / 16384) || r >= i) return null;
727
+ let o = Math.min(J, a - r * J);
728
+ return e.byteLength - Y === o ? {
723
729
  messageId: n,
724
730
  index: r,
725
731
  count: i,
726
732
  totalBytes: a,
727
- payload: new Uint8Array(e, J)
733
+ payload: new Uint8Array(e, Y)
728
734
  } : null;
729
735
  }
730
- function Nt(e, t) {
731
- if (e.byteLength < 1 || e.byteLength > St) throw Error(`swarm peer frame size is outside 1..${St} bytes`);
732
- let n = Math.ceil(e.byteLength / q), r = [];
736
+ function zt(e, t) {
737
+ if (e.byteLength < 1 || e.byteLength > Ot) throw Error(`swarm peer frame size is outside 1..${Ot} bytes`);
738
+ let n = Math.ceil(e.byteLength / J), r = [];
733
739
  for (let i = 0; i < n; i++) {
734
- let a = i * q, o = Math.min(a + q, e.byteLength), s = new Uint8Array(e, a, o - a), c = new ArrayBuffer(J + s.byteLength), l = new DataView(c);
735
- l.setUint32(0, wt, !0), l.setUint32(4, t >>> 0, !0), l.setUint16(8, i, !0), l.setUint16(10, n, !0), l.setUint32(12, e.byteLength, !0), new Uint8Array(c, J).set(s), r.push(c);
740
+ let a = i * J, o = Math.min(a + J, e.byteLength), s = new Uint8Array(e, a, o - a), c = new ArrayBuffer(Y + s.byteLength), l = new DataView(c);
741
+ l.setUint32(0, At, !0), l.setUint32(4, t >>> 0, !0), l.setUint16(8, i, !0), l.setUint16(10, n, !0), l.setUint32(12, e.byteLength, !0), new Uint8Array(c, Y).set(s), r.push(c);
736
742
  }
737
743
  return r;
738
744
  }
739
- var Pt = class {
745
+ var Bt = class {
740
746
  constructor() {
741
747
  this.assemblies = /* @__PURE__ */ new Map();
742
748
  }
743
749
  accept(e, t = Date.now()) {
744
750
  this.expire(t);
745
- let n = Mt(e);
751
+ let n = Rt(e);
746
752
  if (!n) return null;
747
753
  let r = this.assemblies.get(n.messageId);
748
754
  if (!r) {
749
- if (this.assemblies.size >= Tt) return null;
755
+ if (this.assemblies.size >= jt) return null;
750
756
  r = {
751
757
  count: n.count,
752
758
  totalBytes: n.totalBytes,
@@ -776,9 +782,9 @@ var Pt = class {
776
782
  expire(e) {
777
783
  for (let [t, n] of this.assemblies) e - n.createdAt > 5e3 * 2 && this.assemblies.delete(t);
778
784
  }
779
- }, Ft = class {
785
+ }, Vt = class {
780
786
  constructor(e) {
781
- this.options = e, this.peers = /* @__PURE__ */ new Map(), this.reassembler = new Pt(), this.nextMessageId = 1, this.mode = "undecided", this.closed = !1, this.failed = !1, this.readyPromise = null, this.readyResolve = null, this.readyTimer = null, this.qualityTimer = null, this.samplingQuality = !1;
787
+ this.options = e, this.peers = /* @__PURE__ */ new Map(), this.reassembler = new Bt(), this.nextMessageId = 1, this.mode = "undecided", this.closed = !1, this.failed = !1, this.readyPromise = null, this.readyResolve = null, this.readyTimer = null, this.qualityTimer = null, this.samplingQuality = !1;
782
788
  }
783
789
  get selectedMode() {
784
790
  return this.mode;
@@ -792,15 +798,15 @@ var Pt = class {
792
798
  let e = [...new Set([this.options.previousNodeId, this.options.nextNodeId])].filter((e) => !!e && e !== this.options.nodeId);
793
799
  try {
794
800
  for (let t of e) {
795
- let e = (this.options.createPeerConnection ?? ((e) => new RTCPeerConnection(e)))({ iceServers: At }), n = {
801
+ let e = (this.options.createPeerConnection ?? ((e) => new RTCPeerConnection(e)))({ iceServers: It }), n = {
796
802
  nodeId: t,
797
803
  connection: e,
798
804
  channel: null,
799
805
  remoteDescriptionSet: !1,
800
806
  pendingCandidates: [],
801
807
  quality: {
802
- webRtc: jt(),
803
- application: jt()
808
+ webRtc: Lt(),
809
+ application: Lt()
804
810
  },
805
811
  qualitySampledAt: {
806
812
  webRtc: {},
@@ -830,7 +836,7 @@ var Pt = class {
830
836
  for (let e of this.peers.values()) {
831
837
  let { nodeId: t, connection: n } = e;
832
838
  if (this.options.nodeId.localeCompare(t) < 0) {
833
- this.bindChannel(e, n.createDataChannel(Dt, { ordered: !0 }));
839
+ this.bindChannel(e, n.createDataChannel(Nt, { ordered: !0 }));
834
840
  let r = await n.createOffer();
835
841
  if (this.closed || this.failed) return;
836
842
  await n.setLocalDescription(r);
@@ -872,7 +878,7 @@ var Pt = class {
872
878
  }
873
879
  } else if (t.candidate !== null) if (n.remoteDescriptionSet) await n.connection.addIceCandidate(t.candidate);
874
880
  else {
875
- if (n.pendingCandidates.length >= Et) throw Error("too many ICE candidates before remote description");
881
+ if (n.pendingCandidates.length >= Mt) throw Error("too many ICE candidates before remote description");
876
882
  n.pendingCandidates.push(t.candidate);
877
883
  }
878
884
  } catch (e) {
@@ -902,7 +908,7 @@ var Pt = class {
902
908
  }
903
909
  let r = this.nextMessageId++ >>> 0;
904
910
  try {
905
- for (let t of Nt(e, r)) {
911
+ for (let t of zt(e, r)) {
906
912
  if (await this.waitForBuffer(n), n.readyState !== "open") throw Error("swarm peer data channel closed while sending");
907
913
  n.send(t);
908
914
  }
@@ -923,7 +929,7 @@ var Pt = class {
923
929
  } catch {}
924
930
  return;
925
931
  }
926
- e.channel = t, t.binaryType = "arraybuffer", t.bufferedAmountLowThreshold = Ct / 2, t.onopen = () => this.resolveReadyIfOpen(), t.onmessage = (t) => {
932
+ e.channel = t, t.binaryType = "arraybuffer", t.bufferedAmountLowThreshold = kt / 2, t.onopen = () => this.resolveReadyIfOpen(), t.onmessage = (t) => {
927
933
  if (typeof t.data == "string") {
928
934
  this.handleQualityProbe(e, t.data);
929
935
  return;
@@ -949,7 +955,7 @@ var Pt = class {
949
955
  }
950
956
  async waitForBuffer(e) {
951
957
  e.bufferedAmount <= 262144 || await new Promise((t, n) => {
952
- let r = setTimeout(() => i(/* @__PURE__ */ Error("swarm peer send buffer stalled")), xt), i = (i) => {
958
+ let r = setTimeout(() => i(/* @__PURE__ */ Error("swarm peer send buffer stalled")), Dt), i = (i) => {
953
959
  clearTimeout(r), e.removeEventListener("bufferedamountlow", a), e.removeEventListener("close", o), i ? n(i) : t();
954
960
  }, a = () => i(), o = () => i(/* @__PURE__ */ Error("swarm peer data channel closed while backpressured"));
955
961
  e.addEventListener("bufferedamountlow", a, { once: !0 }), e.addEventListener("close", o, { once: !0 });
@@ -961,7 +967,7 @@ var Pt = class {
961
967
  this.peers.clear();
962
968
  }
963
969
  startQualitySampling() {
964
- this.qualityTimer || !this.options.onQuality || (this.samplePeerQuality(), this.qualityTimer = setInterval(() => void this.samplePeerQuality(), _t));
970
+ this.qualityTimer || !this.options.onQuality || (this.samplePeerQuality(), this.qualityTimer = setInterval(() => void this.samplePeerQuality(), Ct));
965
971
  }
966
972
  stopQualitySampling() {
967
973
  this.qualityTimer && clearInterval(this.qualityTimer), this.qualityTimer = null;
@@ -988,7 +994,7 @@ var Pt = class {
988
994
  };
989
995
  try {
990
996
  t.send(JSON.stringify({
991
- type: Ot,
997
+ type: Pt,
992
998
  kind: "ping",
993
999
  id: n
994
1000
  }));
@@ -997,7 +1003,7 @@ var Pt = class {
997
1003
  }
998
1004
  }
999
1005
  handleQualityProbe(e, t) {
1000
- if (t.length > kt) return;
1006
+ if (t.length > Ft) return;
1001
1007
  let n;
1002
1008
  try {
1003
1009
  let e = JSON.parse(t);
@@ -1006,12 +1012,12 @@ var Pt = class {
1006
1012
  } catch {
1007
1013
  return;
1008
1014
  }
1009
- if (n.type !== Ot || !Number.isSafeInteger(n.id) || n.id < 1) return;
1015
+ if (n.type !== Pt || !Number.isSafeInteger(n.id) || n.id < 1) return;
1010
1016
  if (n.kind === "ping") {
1011
1017
  if (e.channel?.readyState !== "open" || e.channel.bufferedAmount > 262144) return;
1012
1018
  try {
1013
1019
  e.channel.send(JSON.stringify({
1014
- type: Ot,
1020
+ type: Pt,
1015
1021
  kind: "pong",
1016
1022
  id: n.id
1017
1023
  }));
@@ -1034,10 +1040,10 @@ var Pt = class {
1034
1040
  this.sendQualityProbe(n);
1035
1041
  let r = this.monotonicNow();
1036
1042
  if (await this.sampleWebRtc(n, r), n.lastApplicationSampleAt !== void 0) {
1037
- let e = r - n.lastApplicationSampleAt, t = K(n.applicationBytesSent - n.lastApplicationBytesSent, e), i = K(n.applicationBytesReceived - n.lastApplicationBytesReceived, e);
1043
+ let e = r - n.lastApplicationSampleAt, t = q(n.applicationBytesSent - n.lastApplicationBytesSent, e), i = q(n.applicationBytesReceived - n.lastApplicationBytesReceived, e);
1038
1044
  t !== null && this.recordQuality(n, "application", "sendMbps", t), i !== null && this.recordQuality(n, "application", "receiveMbps", i);
1039
1045
  }
1040
- n.lastApplicationSampleAt = r, n.lastApplicationBytesSent = n.applicationBytesSent, n.lastApplicationBytesReceived = n.applicationBytesReceived, t.push(bt(n.nodeId, e, n.quality.webRtc, n.quality.application, n.qualitySampledAt));
1046
+ n.lastApplicationSampleAt = r, n.lastApplicationBytesSent = n.applicationBytesSent, n.lastApplicationBytesReceived = n.applicationBytesReceived, t.push(Et(n.nodeId, e, n.quality.webRtc, n.quality.application, n.qualitySampledAt));
1041
1047
  }
1042
1048
  t.length && this.options.onQuality(t.slice(0, 2));
1043
1049
  } finally {
@@ -1062,11 +1068,11 @@ var Pt = class {
1062
1068
  if (e.lastRtcSampleAt !== void 0) {
1063
1069
  let n = t - e.lastRtcSampleAt;
1064
1070
  if (d !== void 0 && e.lastRtcBytesSent !== void 0 && s === void 0) {
1065
- let t = K(d - e.lastRtcBytesSent, n);
1071
+ let t = q(d - e.lastRtcBytesSent, n);
1066
1072
  t !== null && this.recordQuality(e, "webRtc", "sendMbps", t);
1067
1073
  }
1068
1074
  if (f !== void 0 && e.lastRtcBytesReceived !== void 0 && c === void 0) {
1069
- let t = K(f - e.lastRtcBytesReceived, n);
1075
+ let t = q(f - e.lastRtcBytesReceived, n);
1070
1076
  t !== null && this.recordQuality(e, "webRtc", "receiveMbps", t);
1071
1077
  }
1072
1078
  }
@@ -1074,47 +1080,89 @@ var Pt = class {
1074
1080
  } catch {}
1075
1081
  }
1076
1082
  };
1077
- function It(e, t) {
1078
- if (!h(e)) return !1;
1079
- let n = e;
1080
- return n.type === "swarm-peer-signal" && n.taskId === t.taskId && n.sessionId === t.sessionId && n.attemptId === t.attemptId && n.toNodeId === t.nodeId && typeof n.fromNodeId == "string" && t.peers.includes(n.fromNodeId) && typeof n.signal == "object" && n.signal !== null;
1083
+ function Ht(e, t) {
1084
+ if (!n(e)) return !1;
1085
+ let r = e;
1086
+ return r.type === "swarm-peer-signal" && r.taskId === t.taskId && r.sessionId === t.sessionId && r.attemptId === t.attemptId && r.toNodeId === t.nodeId && typeof r.fromNodeId == "string" && t.peers.includes(r.fromNodeId) && typeof r.signal == "object" && r.signal !== null;
1081
1087
  }
1082
1088
  //#endregion
1083
1089
  //#region src/client/mobile-lifecycle.ts
1084
- var Lt = .25, Rt = .08, zt = .45;
1085
- function Bt(e, t) {
1086
- let n = e.batteryCharging === !1, r = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Lt, i = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Rt, a = e.effectiveType === "slow-2g" || e.effectiveType === "2g", o = r || a || e.saveData === !0;
1090
+ var Ut = .25, Wt = .08, Gt = .45;
1091
+ function Kt(e, t) {
1092
+ let n = e.batteryCharging === !1, r = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Ut, i = n && typeof e.batteryLevel == "number" && e.batteryLevel <= Wt, a = e.effectiveType === "slow-2g" || e.effectiveType === "2g", o = r || a || e.saveData === !0;
1087
1093
  return {
1088
1094
  suspend: e.hidden || e.pageHidden || !e.online || i,
1089
1095
  constrained: o,
1090
- maxCpuLoad: o ? Math.min(t ?? zt, zt) : t
1096
+ maxCpuLoad: o ? Math.min(t ?? Gt, Gt) : t
1091
1097
  };
1092
1098
  }
1093
1099
  //#endregion
1094
- //#region src/client/SignalingClient.ts
1095
- var Y = (...e) => console.log("[flaxia-node]", ...e), X = (...e) => console.error("[flaxia-node]", ...e);
1096
- function Z(e) {
1100
+ //#region src/client/light-preloader.ts
1101
+ var qt = "Xenova/m2m100_418M", Jt = class {
1102
+ constructor(e, t = {}, n = () => !1, r = async () => {}) {
1103
+ this.getConsentState = e, this.options = t, this.isPreloaded = n, this.preload = r, this.timer = null, this.idleHandle = null, this.preloading = !1, this.stopped = !1, this.model = t.model ?? "Xenova/m2m100_418M", this.task = t.task ?? "translation", this.dtype = t.dtype ?? "q4f16";
1104
+ }
1105
+ start() {
1106
+ if (this.stopped || this.getConsentState() !== "granted" || this.isUnconstrained() === !1 || this.isPreloaded(this.model) || this.preloading) return;
1107
+ let e = () => {
1108
+ this.idleHandle = null, this.preloadNow();
1109
+ };
1110
+ typeof requestIdleCallback == "function" ? this.idleHandle = requestIdleCallback(e, { timeout: 2e3 }) : this.timer = setTimeout(e, 1e3);
1111
+ }
1112
+ stop() {
1113
+ this.stopped = !0, this.idleHandle !== null && typeof cancelIdleCallback == "function" && cancelIdleCallback(this.idleHandle), this.timer && clearTimeout(this.timer), this.idleHandle = null, this.timer = null;
1114
+ }
1115
+ isUnconstrained() {
1116
+ try {
1117
+ let e = navigator, t = Kt({
1118
+ hidden: document.hidden,
1119
+ pageHidden: document.hidden,
1120
+ online: navigator.onLine !== !1,
1121
+ effectiveType: e.connection?.effectiveType,
1122
+ saveData: e.connection?.saveData
1123
+ }, void 0);
1124
+ return !t.constrained && !t.suspend;
1125
+ } catch {
1126
+ return !0;
1127
+ }
1128
+ }
1129
+ async preloadNow() {
1130
+ if (!(this.stopped || this.preloading) && this.getConsentState() === "granted" && this.isUnconstrained() !== !1 && !this.isPreloaded(this.model)) {
1131
+ this.preloading = !0;
1132
+ try {
1133
+ await this.preload({
1134
+ task: this.task,
1135
+ model: this.model,
1136
+ dtype: this.dtype
1137
+ }), this.options.onPreloaded?.();
1138
+ } catch {} finally {
1139
+ this.preloading = !1;
1140
+ }
1141
+ }
1142
+ }
1143
+ }, X = (...e) => console.log("[flaxia-node]", ...e), Z = (...e) => console.error("[flaxia-node]", ...e);
1144
+ function Q(e) {
1097
1145
  let t = /* @__PURE__ */ new Set();
1098
1146
  if (!Array.isArray(e)) return [];
1099
1147
  for (let n of e.slice(0, 32)) try {
1100
- let e = _(n);
1148
+ let e = ee(n);
1101
1149
  e.origin === n && t.add(e.origin);
1102
1150
  } catch {}
1103
1151
  return [...t];
1104
1152
  }
1105
- var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1106
- receiveSwarmEnvelope(t) {
1107
- let n = e(t);
1108
- !n || ![...this.swarmSessions.values()].includes(n.sessionId) || (this.swarmInboundChain = this.swarmInboundChain.then(async () => {
1109
- let e = this.swarmHopKeys.get(n.sessionId);
1153
+ var Yt = "flaxia_node_id", Xt = "flaxia_node_token", Zt = class {
1154
+ receiveSwarmEnvelope(e) {
1155
+ let t = f(e);
1156
+ !t || ![...this.swarmSessions.values()].includes(t.sessionId) || (this.swarmInboundChain = this.swarmInboundChain.then(async () => {
1157
+ let e = this.swarmHopKeys.get(t.sessionId);
1110
1158
  if (e && e.chainLength > 1) {
1111
- if (!n.mac || !e.inboundKey) return;
1112
- if (!await a(e.inboundKey, n.sessionId, n.frame, n.mac)) {
1113
- X(`swarm frame rejected: bad hop MAC sessionId=${n.sessionId}`);
1159
+ if (!t.mac || !e.inboundKey) return;
1160
+ if (!await v(e.inboundKey, t.sessionId, t.frame, t.mac)) {
1161
+ Z(`swarm frame rejected: bad hop MAC sessionId=${t.sessionId}`);
1114
1162
  return;
1115
1163
  }
1116
1164
  }
1117
- this.workerPool.sendFrame(n.frame);
1165
+ this.workerPool.sendFrame(t.frame);
1118
1166
  }).catch(() => {}));
1119
1167
  }
1120
1168
  ensureSwarmPeerTransport(e) {
@@ -1126,7 +1174,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1126
1174
  attemptId: r,
1127
1175
  peers: o
1128
1176
  });
1129
- let s = new Ft({
1177
+ let s = new Vt({
1130
1178
  sessionId: t,
1131
1179
  taskId: n,
1132
1180
  attemptId: r,
@@ -1163,7 +1211,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1163
1211
  }
1164
1212
  handleSwarmPeerSignal(e) {
1165
1213
  let t = typeof e.sessionId == "string" ? e.sessionId : "", n = this.swarmPeerMetadata.get(t), r = this.swarmPeerTransports.get(t);
1166
- !n || !r || !It(e, {
1214
+ !n || !r || !Ht(e, {
1167
1215
  ...n,
1168
1216
  sessionId: t,
1169
1217
  nodeId: this.nodeId
@@ -1173,7 +1221,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1173
1221
  this.swarmHopKeys.delete(e), this.swarmPeerTransports.get(e)?.close(), this.swarmPeerTransports.delete(e), this.swarmPeerMetadata.delete(e), this.swarmFailureReported.delete(e), this.retiredSwarmSessions.add(e), this.retiredSwarmSessions.size > 64 && this.retiredSwarmSessions.delete(this.retiredSwarmSessions.values().next().value);
1174
1222
  }
1175
1223
  constructor(e, t, n) {
1176
- this.config = e, this.workerPool = t, this.nodeId = n, this.ws = null, this.reconnectAttempts = 0, this.MAX_RECONNECT_DELAY = 3e4, this.destroyed = !1, this.suspended = !1, this.lifecycleCleanup = [], this.lifecyclePageHidden = !1, this.lifecycleOffline = !1, this.lifecycleEpoch = 0, this.batteryState = null, this.networkState = null, this.inflightTasks = /* @__PURE__ */ new Set(), this.abortedTasks = /* @__PURE__ */ new Set(), this.swarmSessions = /* @__PURE__ */ new Map(), this.retiredSwarmSessions = /* @__PURE__ */ new Set(), this.swarmHopKeys = /* @__PURE__ */ new Map(), this.swarmPeerTransports = /* @__PURE__ */ new Map(), this.swarmPeerMetadata = /* @__PURE__ */ new Map(), this.swarmFailureReported = /* @__PURE__ */ new Set(), this.swarmInboundChain = Promise.resolve(), this.swarmOutboundChain = Promise.resolve(), this.attempts = /* @__PURE__ */ new Map(), this.cachedToken = null;
1224
+ this.config = e, this.workerPool = t, this.nodeId = n, this.ws = null, this.reconnectAttempts = 0, this.MAX_RECONNECT_DELAY = 3e4, this.destroyed = !1, this.suspended = !1, this.lifecycleCleanup = [], this.lifecyclePageHidden = !1, this.lifecycleOffline = !1, this.lifecycleEpoch = 0, this.batteryState = null, this.networkState = null, this.inflightTasks = /* @__PURE__ */ new Set(), this.abortedTasks = /* @__PURE__ */ new Set(), this.lightPreloader = null, this.preloaderTask = null, this.swarmSessions = /* @__PURE__ */ new Map(), this.retiredSwarmSessions = /* @__PURE__ */ new Set(), this.swarmHopKeys = /* @__PURE__ */ new Map(), this.swarmPeerTransports = /* @__PURE__ */ new Map(), this.swarmPeerMetadata = /* @__PURE__ */ new Map(), this.swarmFailureReported = /* @__PURE__ */ new Set(), this.swarmInboundChain = Promise.resolve(), this.swarmOutboundChain = Promise.resolve(), this.attempts = /* @__PURE__ */ new Map(), this.cachedToken = null;
1177
1225
  }
1178
1226
  async connect() {
1179
1227
  if (this.destroyed) return;
@@ -1181,7 +1229,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1181
1229
  this.disconnect();
1182
1230
  return;
1183
1231
  }
1184
- if (Y(`connect nodeId=${this.nodeId}`), this.ws) {
1232
+ if (X(`connect nodeId=${this.nodeId}`), this.ws) {
1185
1233
  let e = this.ws;
1186
1234
  e.onclose = null;
1187
1235
  try {
@@ -1190,23 +1238,24 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1190
1238
  this.ws = null;
1191
1239
  }
1192
1240
  if (this.setupMobileLifecycleHandlers(), this.suspended) return;
1193
- let e = await this.obtainToken();
1241
+ let n = await this.obtainToken();
1194
1242
  if (this.destroyed || this.suspended) return;
1195
1243
  if (z() !== "granted") {
1196
- Y("connect cancelled because consent was revoked while obtaining a token");
1244
+ X("connect cancelled because consent was revoked while obtaining a token");
1197
1245
  return;
1198
1246
  }
1199
- if (!e) {
1200
- X("token acquisition failed; scheduling reconnect"), this.scheduleReconnect();
1247
+ if (!n) {
1248
+ Z("token acquisition failed; scheduling reconnect"), this.scheduleReconnect();
1201
1249
  return;
1202
1250
  }
1203
- let t = i(this.config.orchestratorUrl, "/crowd/signal"), n = new WebSocket(t, s(e.token));
1204
- n.binaryType = "arraybuffer", this.ws = n;
1205
- let r = !1;
1206
- n.onopen = () => {
1207
- r = !0, this.reconnectAttempts = 0, Y(`signal connected ${t}`), this.sendHeartbeat(n);
1208
- }, n.onmessage = async (e) => {
1209
- if (this.ws !== n) return;
1251
+ this.startLightPreloader();
1252
+ let r = t(this.config.orchestratorUrl, "/crowd/signal"), i = new WebSocket(r, e(n.token));
1253
+ i.binaryType = "arraybuffer", this.ws = i;
1254
+ let a = !1;
1255
+ i.onopen = () => {
1256
+ a = !0, this.reconnectAttempts = 0, X(`signal connected ${r}`), this.sendHeartbeat(i);
1257
+ }, i.onmessage = async (e) => {
1258
+ if (this.ws !== i) return;
1210
1259
  if (typeof e.data != "string") {
1211
1260
  this.receiveSwarmEnvelope(e.data);
1212
1261
  return;
@@ -1218,22 +1267,22 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1218
1267
  return;
1219
1268
  }
1220
1269
  if (t.type === "ping") {
1221
- this.sendHeartbeat(n);
1270
+ this.sendHeartbeat(i);
1222
1271
  return;
1223
1272
  }
1224
1273
  if (t.type === "task") {
1225
1274
  let e = t;
1226
- Y(`task received taskId=${e.taskId} workload=${e.workload} timeoutMs=${e.timeoutMs ?? "default"}`), typeof e.attemptId == "string" && this.attempts.set(e.taskId, e.attemptId);
1275
+ X(`task received taskId=${e.taskId} workload=${e.workload} timeoutMs=${e.timeoutMs ?? "default"}`), typeof e.attemptId == "string" && this.attempts.set(e.taskId, e.attemptId);
1227
1276
  let n = e.attemptId ?? this.attempts.get(e.taskId);
1228
1277
  try {
1229
1278
  await this.handleTask(e);
1230
1279
  } catch (r) {
1231
1280
  let i = r instanceof Error ? r.message : String(r);
1232
1281
  if (this.abortedTasks.delete(e.taskId)) {
1233
- Y(`task stopped on coordinator abort taskId=${e.taskId} error=${i}`);
1282
+ X(`task stopped on coordinator abort taskId=${e.taskId} error=${i}`);
1234
1283
  return;
1235
1284
  }
1236
- X(`task failed taskId=${e.taskId} workload=${e.workload} error=${i}`), this.send({
1285
+ Z(`task failed taskId=${e.taskId} workload=${e.workload} error=${i}`), this.send({
1237
1286
  type: "error",
1238
1287
  taskId: String(t.taskId ?? ""),
1239
1288
  error: i,
@@ -1288,10 +1337,10 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1288
1337
  this.handleAbort(t);
1289
1338
  return;
1290
1339
  }
1291
- }, n.onerror = () => {
1292
- this.ws === n && X("signal websocket error");
1293
- }, n.onclose = (e) => {
1294
- n.onclose = null, this.ws === n && (this.ws = null, r || (this.cachedToken = null), !this.destroyed && (Y(`signal disconnected code=${e.code} reason=${JSON.stringify(e.reason)} clean=${e.wasClean}; scheduling reconnect attempt=${this.reconnectAttempts + 1}`), this.scheduleReconnect()));
1340
+ }, i.onerror = () => {
1341
+ this.ws === i && Z("signal websocket error");
1342
+ }, i.onclose = (e) => {
1343
+ i.onclose = null, this.ws === i && (this.ws = null, a || (this.cachedToken = null), !this.destroyed && (X(`signal disconnected code=${e.code} reason=${JSON.stringify(e.reason)} clean=${e.wasClean}; scheduling reconnect attempt=${this.reconnectAttempts + 1}`), this.scheduleReconnect()));
1295
1344
  };
1296
1345
  }
1297
1346
  handleAbort(e) {
@@ -1300,11 +1349,11 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1300
1349
  let n = typeof e.error == "string" && e.error ? e.error : "aborted by the coordinator", r = this.swarmSessions.get(t);
1301
1350
  if (r && r !== e.sessionId) return;
1302
1351
  let i = r ?? t;
1303
- r && this.retireSwarmSession(r), this.workerPool.abort(i, n) && this.abortedTasks.add(i), Y(`task abort received taskId=${t} error=${n}`);
1352
+ r && this.retireSwarmSession(r), this.workerPool.abort(i, n) && this.abortedTasks.add(i), X(`task abort received taskId=${t} error=${n}`);
1304
1353
  }
1305
1354
  async sendHeartbeat(e) {
1306
1355
  if (this.ws !== e || e.readyState !== WebSocket.OPEN || z() !== "granted") return;
1307
- let t = (this.config.capabilities ?? ["ai-inference", "image-process"]).includes("swarm-inference") && this.config.allowModelDownload === !0, n = navigator.deviceMemory, r = await gt({
1356
+ let t = (this.config.capabilities ?? ["ai-inference", "image-process"]).includes("swarm-inference") && this.config.allowModelDownload === !0, n = navigator.deviceMemory, r = await St({
1308
1357
  cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1309
1358
  deviceMemory: n,
1310
1359
  probeGpu: t
@@ -1323,7 +1372,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1323
1372
  }, e);
1324
1373
  }
1325
1374
  disconnect() {
1326
- Y(`disconnect nodeId=${this.nodeId}`), this.destroyed = !0, this.suspended = !1, this.removeMobileLifecycleHandlers();
1375
+ X(`disconnect nodeId=${this.nodeId}`), this.destroyed = !0, this.suspended = !1, this.stopLightPreloader(), this.removeMobileLifecycleHandlers();
1327
1376
  try {
1328
1377
  this.ws?.close();
1329
1378
  } catch {}
@@ -1331,7 +1380,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1331
1380
  for (let e of this.swarmPeerTransports.values()) e.close();
1332
1381
  this.swarmPeerTransports.clear(), this.swarmPeerMetadata.clear();
1333
1382
  try {
1334
- delete window[Ut];
1383
+ delete window[Qt];
1335
1384
  } catch {}
1336
1385
  try {
1337
1386
  this.workerPool.terminate();
@@ -1339,7 +1388,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1339
1388
  }
1340
1389
  suspend() {
1341
1390
  if (!(this.suspended || this.destroyed)) {
1342
- if (Y("suspended (visibility or manual)"), this.suspended = !0, this.ws) {
1391
+ if (X("suspended (visibility or manual)"), this.suspended = !0, this.stopLightPreloader(), this.ws) {
1343
1392
  let e = this.ws;
1344
1393
  e.onclose = null;
1345
1394
  try {
@@ -1351,18 +1400,18 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1351
1400
  }
1352
1401
  }
1353
1402
  resume() {
1354
- !this.suspended || this.destroyed || (Y("resumed"), this.suspended = !1, this.workerPool.resume(), this.connect());
1403
+ !this.suspended || this.destroyed || (X("resumed"), this.suspended = !1, this.workerPool.resume(), this.connect());
1355
1404
  }
1356
1405
  async obtainToken() {
1357
1406
  let e = () => z() === "granted";
1358
1407
  if (!e()) return null;
1359
1408
  try {
1360
- if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 6e4) return Y(`token cached nodeId=${this.cachedToken.nodeId} expiresIn=${Math.round((this.cachedToken.expiresAt - Date.now()) / 1e3)}s`), this.cachedToken;
1361
- let t = f(), n = t >= m, r = this.config.capabilities ?? ["ai-inference", "image-process"], i = n ? [...r] : [];
1362
- Z(this.config.containerImageOrigins).length === 0 && (i = i.filter((e) => e !== "container"));
1409
+ if (this.cachedToken && this.cachedToken.expiresAt > Date.now() + 6e4) return X(`token cached nodeId=${this.cachedToken.nodeId} expiresIn=${Math.round((this.cachedToken.expiresAt - Date.now()) / 1e3)}s`), this.cachedToken;
1410
+ let t = m(), n = t >= h, r = this.config.capabilities ?? ["ai-inference", "image-process"], i = n ? [...r] : [];
1411
+ Q(this.config.containerImageOrigins).length === 0 && (i = i.filter((e) => e !== "container"));
1363
1412
  let a;
1364
1413
  if (n && r.includes("swarm-inference") && this.config.allowModelDownload === !0) {
1365
- let t = await gt({
1414
+ let t = await St({
1366
1415
  cpuLoad: this.workerPool.hasCpuLoadSample ? this.workerPool.lastCpuLoad : null,
1367
1416
  deviceMemory: navigator.deviceMemory,
1368
1417
  probeGpu: !0
@@ -1370,7 +1419,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1370
1419
  if (!e()) return null;
1371
1420
  t.gpu.status === "available" ? (a = { webgpu: !0 }, t.gpu.architecture.value && (a.gpuArchitecture = t.gpu.architecture.value), t.gpu.maxStorageBufferBindingSize.value !== null && (a.maxStorageBufferBindingSize = t.gpu.maxStorageBufferBindingSize.value)) : i = i.filter((e) => e !== "swarm-inference");
1372
1421
  } else i = i.filter((e) => e !== "swarm-inference");
1373
- Y(`register capability probe capable=${n} wasmMemoryBytes=${t} capabilities=${JSON.stringify(i)} webgpu=${a?.webgpu ?? !1}`);
1422
+ X(`register capability probe capable=${n} wasmMemoryBytes=${t} capabilities=${JSON.stringify(i)} webgpu=${a?.webgpu ?? !1}`);
1374
1423
  let o = this.config.orchestratorUrl.replace(/\/+$/, "");
1375
1424
  if (!e()) return null;
1376
1425
  let s = await fetch(`${o}/crowd/nodes/register`, {
@@ -1379,18 +1428,18 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1379
1428
  body: JSON.stringify({
1380
1429
  siteId: this.config.siteId,
1381
1430
  capabilities: i,
1382
- fileSources: Z(this.config.fileSourceOrigins).length > 0,
1383
- wasmMemoryBytes: f(),
1431
+ fileSources: Q(this.config.fileSourceOrigins).length > 0,
1432
+ wasmMemoryBytes: m(),
1384
1433
  deviceMemory: typeof navigator.deviceMemory == "number" ? navigator.deviceMemory : null,
1385
1434
  swarm: a
1386
1435
  })
1387
1436
  });
1388
1437
  if (!e()) return null;
1389
- if (!s.ok) return X(`node register failed HTTP ${s.status} (${o}/crowd/nodes/register)`), null;
1438
+ if (!s.ok) return Z(`node register failed HTTP ${s.status} (${o}/crowd/nodes/register)`), null;
1390
1439
  let c = await s.json();
1391
- return e() ? c.token ? (typeof c.nodeId == "string" && c.nodeId && (this.nodeId = c.nodeId), this.cachedToken = c, Y(`node registered nodeId=${this.nodeId} expiresIn=${Math.round((c.expiresAt - Date.now()) / 1e3)}s`), c) : (X("node register returned no token"), null) : null;
1440
+ return e() ? c.token ? (typeof c.nodeId == "string" && c.nodeId && (this.nodeId = c.nodeId), this.cachedToken = c, X(`node registered nodeId=${this.nodeId} expiresIn=${Math.round((c.expiresAt - Date.now()) / 1e3)}s`), c) : (Z("node register returned no token"), null) : null;
1392
1441
  } catch (e) {
1393
- return X("node register threw", e instanceof Error ? e.message : e), null;
1442
+ return Z("node register threw", e instanceof Error ? e.message : e), null;
1394
1443
  }
1395
1444
  }
1396
1445
  send(e) {
@@ -1404,15 +1453,15 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1404
1453
  let n = this.swarmHopKeys.get(e);
1405
1454
  if (n && n.chainLength > 1) {
1406
1455
  if (!n.outboundKey) {
1407
- X(`swarm frame not sent: no hop key sessionId=${e}`);
1456
+ Z(`swarm frame not sent: no hop key sessionId=${e}`);
1408
1457
  return;
1409
1458
  }
1410
- let i = await r(n.outboundKey, e, t), a = this.swarmPeerTransports.get(e);
1411
- (!a || !await a.sendFrame(i)) && this.sendBinary(i);
1459
+ let r = await s(n.outboundKey, e, t), i = this.swarmPeerTransports.get(e);
1460
+ (!i || !await i.sendFrame(r)) && this.sendBinary(r);
1412
1461
  return;
1413
1462
  }
1414
- let i = c(e, t), a = this.swarmPeerTransports.get(e);
1415
- (!a || !await a.sendFrame(i)) && this.sendBinary(i);
1463
+ let r = c(e, t), i = this.swarmPeerTransports.get(e);
1464
+ (!i || !await i.sendFrame(r)) && this.sendBinary(r);
1416
1465
  }).catch((t) => {
1417
1466
  let n = this.swarmPeerMetadata.get(e);
1418
1467
  !n || this.swarmFailureReported.has(e) || (this.swarmFailureReported.add(e), this.send({
@@ -1465,10 +1514,10 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1465
1514
  sessionId: n,
1466
1515
  payload: o,
1467
1516
  attemptId: a
1468
- }), Y(`swarm result sent taskId=${e} durationMs=${Math.round(performance.now() - r)}`);
1517
+ }), X(`swarm result sent taskId=${e} durationMs=${Math.round(performance.now() - r)}`);
1469
1518
  } catch (t) {
1470
1519
  let r = t instanceof Error ? t.message : String(t);
1471
- this.abortedTasks.delete(n) ? Y(`swarm stopped on coordinator abort taskId=${e} error=${r}`) : (X(`swarm failed taskId=${e} error=${r}`), this.send({
1520
+ this.abortedTasks.delete(n) ? X(`swarm stopped on coordinator abort taskId=${e} error=${r}`) : (Z(`swarm failed taskId=${e} error=${r}`), this.send({
1472
1521
  type: "error",
1473
1522
  taskId: e,
1474
1523
  sessionId: n,
@@ -1493,19 +1542,43 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1493
1542
  });
1494
1543
  }, {
1495
1544
  maxCpuLoad: this.effectiveMaxCpuLoad(),
1496
- fileSourceOrigins: Z(this.config.fileSourceOrigins),
1497
- containerImageOrigins: Z(this.config.containerImageOrigins)
1545
+ fileSourceOrigins: Q(this.config.fileSourceOrigins),
1546
+ containerImageOrigins: Q(this.config.containerImageOrigins)
1498
1547
  });
1499
1548
  this.send({
1500
1549
  type: "result",
1501
1550
  taskId: e.taskId,
1502
1551
  payload: i,
1503
1552
  attemptId: n
1504
- }), Y(`task result sent taskId=${e.taskId} workload=${e.workload} durationMs=${Math.round(performance.now() - t)}`);
1553
+ }), X(`task result sent taskId=${e.taskId} workload=${e.workload} durationMs=${Math.round(performance.now() - t)}`);
1505
1554
  } finally {
1506
1555
  this.inflightTasks.delete(e.taskId), this.attempts.delete(e.taskId);
1507
1556
  }
1508
1557
  }
1558
+ async runLocalAiInference(e, t) {
1559
+ if (!this.workerPool) throw new r("No running Crowd node on this device", "node_not_running");
1560
+ if (z() !== "granted") throw new r("Crowd consent is not granted", "consent_not_granted");
1561
+ let n = `local-${typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`;
1562
+ return await this.workerPool.run(n, "ai-inference", e, 3e5, t, {
1563
+ maxCpuLoad: this.effectiveMaxCpuLoad(),
1564
+ fileSourceOrigins: Q(this.config.fileSourceOrigins),
1565
+ containerImageOrigins: Q(this.config.containerImageOrigins)
1566
+ });
1567
+ }
1568
+ isAiModelPreloaded(e) {
1569
+ let t = this.workerPool.modelCacheSnapshot;
1570
+ return t ? t.entries.some((t) => t.modelId === e && t.state === "ready") : !1;
1571
+ }
1572
+ async preloadAiModel(e) {
1573
+ let t = `preload-${typeof crypto < "u" && "randomUUID" in crypto ? crypto.randomUUID() : `${Date.now()}-${Math.random()}`}`;
1574
+ await this.workerPool.run(t, "ai-preload", e, 3e5, void 0, { maxCpuLoad: this.effectiveMaxCpuLoad() });
1575
+ }
1576
+ startLightPreloader() {
1577
+ this.lightPreloader && this.lightPreloader.stop(), this.lightPreloader = new Jt(() => z(), { onPreloaded: () => {} }, (e) => this.isAiModelPreloaded(e), (e) => this.preloadAiModel(e)), this.lightPreloader.start();
1578
+ }
1579
+ stopLightPreloader() {
1580
+ this.lightPreloader && this.lightPreloader.stop(), this.lightPreloader = null;
1581
+ }
1509
1582
  listenForLifecycle(e, t, n) {
1510
1583
  e.addEventListener(t, n), this.lifecycleCleanup.push(() => e.removeEventListener(t, n));
1511
1584
  }
@@ -1540,7 +1613,7 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1540
1613
  this.batteryState = null, this.networkState = null;
1541
1614
  }
1542
1615
  mobileLifecycleDecision() {
1543
- return Bt({
1616
+ return Kt({
1544
1617
  hidden: document.hidden,
1545
1618
  pageHidden: this.lifecyclePageHidden,
1546
1619
  online: !this.lifecycleOffline && navigator.onLine !== !1,
@@ -1556,27 +1629,27 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1556
1629
  refreshMobileLifecycle() {
1557
1630
  this.mobileLifecycleDecision().suspend ? this.suspend() : this.suspended && this.resume();
1558
1631
  }
1559
- }, $ = "__flaxia_node_signal_client", Ut = "__flaxia_node_init_started", Wt = "__flaxia_node_controller", Gt = (e) => {
1632
+ }, $ = "__flaxia_node_signal_client", Qt = "__flaxia_node_init_started", $t = "__flaxia_node_controller", en = (e) => {
1560
1633
  if (z() !== "granted") {
1561
- X("refusing to start the node without a granted consent record");
1634
+ Z("refusing to start the node without a granted consent record");
1562
1635
  return;
1563
1636
  }
1564
1637
  let t = window[$];
1565
- t && t.disconnect(), Ge(Q);
1566
- let n = new URL("./worker.js", "" + import.meta.url).href, r = new pt(n), i = Ue(Vt);
1567
- i || (i = qe(), We(Vt, i));
1568
- let a = new Ht(e, r, i);
1638
+ t && t.disconnect(), V(Xt);
1639
+ let n = new URL("./worker.js", "" + import.meta.url).href, r = new yt(n), i = Xe(Yt);
1640
+ i || (i = $e(), Ze(Yt, i));
1641
+ let a = new Zt(e, r, i);
1569
1642
  window[$] = a, a.connect();
1570
- }, Kt = class {
1643
+ }, tn = class {
1571
1644
  constructor(e) {
1572
1645
  this.config = e;
1573
1646
  }
1574
1647
  start() {
1575
- this.isRunning() || !Ae() || Gt(this.config);
1648
+ this.isRunning() || !Le() || en(this.config);
1576
1649
  }
1577
1650
  stop() {
1578
1651
  let e = window[$];
1579
- e && e.disconnect(), delete window[$], delete window[Ut];
1652
+ e && e.disconnect(), delete window[$], delete window[Qt];
1580
1653
  }
1581
1654
  isRunning() {
1582
1655
  return !!window[$];
@@ -1585,37 +1658,51 @@ var Vt = "flaxia_node_id", Q = "flaxia_node_token", Ht = class {
1585
1658
  return z();
1586
1659
  }
1587
1660
  grant() {
1588
- Re();
1661
+ Ge();
1589
1662
  }
1590
1663
  deny() {
1591
- Ve(), this.stop(), Ge(Q);
1664
+ Je(), this.stop(), V(Xt);
1592
1665
  }
1593
1666
  clearConsent() {
1594
- He(), this.stop(), Ge(Q);
1667
+ Ye(), this.stop(), V(Xt);
1668
+ }
1669
+ async runLocalAiInference(e, t) {
1670
+ let n = window[$];
1671
+ if (!n || !this.isRunning()) throw new r("No running Crowd node on this device", "node_not_running");
1672
+ return n.runLocalAiInference(e, t);
1673
+ }
1674
+ isAiModelPreloaded(e) {
1675
+ let t = window[$];
1676
+ return t ? t.isAiModelPreloaded(e) : !1;
1677
+ }
1678
+ async preloadAiModel(e) {
1679
+ let t = window[$];
1680
+ if (!t) throw new r("No running Crowd node on this device", "node_not_running");
1681
+ await t.preloadAiModel(e);
1595
1682
  }
1596
- }, qt = (e) => {
1597
- let t = window[Wt];
1683
+ }, nn = (e) => {
1684
+ let t = window[$t];
1598
1685
  if (t) return t;
1599
- let n = new Kt(e);
1600
- window[Wt] = n, window[Ut] = !0;
1686
+ let n = new tn(e);
1687
+ window[$t] = n, window[Qt] = !0;
1601
1688
  let r = z();
1602
1689
  if (r === "granted") return n.start(), n;
1603
1690
  if (r === "denied") return n;
1604
1691
  if (e.consent.onConsentRequired) return e.consent.onConsentRequired({
1605
1692
  state: r,
1606
1693
  accept: () => {
1607
- Re(), n.start();
1694
+ Ge(), n.start();
1608
1695
  },
1609
1696
  reject: () => {
1610
- Ve();
1697
+ Je();
1611
1698
  }
1612
1699
  }), n;
1613
1700
  let i = document.createElement("div");
1614
- return i.id = "flaxia-consent-container", document.body.appendChild(i), new ft(i, e.consent, () => {
1615
- Re(), i.remove(), n.start();
1701
+ return i.id = "flaxia-consent-container", document.body.appendChild(i), new vt(i, e.consent, () => {
1702
+ Ge(), i.remove(), n.start();
1616
1703
  }, () => {
1617
- Ve(), i.remove();
1704
+ Je(), i.remove();
1618
1705
  }), n;
1619
1706
  };
1620
1707
  //#endregion
1621
- export { z as getFlaxiaNodeConsentState, qt as initFlaxiaNode, B as initFlaxiaNodeConsent, Be as setFlaxiaNodeHostManagedConsent };
1708
+ export { re as LIGHT_INFERENCE_TRANSLATE_DTYPE, qt as LIGHT_INFERENCE_TRANSLATE_MODEL, te as LIGHT_INFERENCE_TRANSLATE_MODEL_ID, ne as LIGHT_INFERENCE_TRANSLATE_TASK, z as getFlaxiaNodeConsentState, nn as initFlaxiaNode, B as initFlaxiaNodeConsent, y as isAiModelPreloaded, b as preloadAiModel, qe as setFlaxiaNodeHostManagedConsent };