@tradalab/mediakit 2.9.1 → 2.10.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.
@@ -7509,21 +7509,1141 @@
7509
7509
 
7510
7510
  // src/assets.ts
7511
7511
  var ASSET_BASE = "/mediakit/";
7512
+ var ASSETS = [
7513
+ { path: "mediakit.wasm", part: "core", source: { from: "dist", file: "mediakit.wasm" } },
7514
+ { path: "wasm_exec.js", part: "core", source: { from: "dist", file: "wasm_exec.js" } },
7515
+ { path: "worker.js", part: "core", source: { from: "dist", file: "worker.js" } },
7516
+ { path: "worker.js.map", part: "core", source: { from: "dist", file: "worker.js.map" }, debug: true },
7517
+ { path: "detect-worker.js", part: "core", source: { from: "dist", file: "detect-worker.js" } },
7518
+ { path: "detect-worker.js.map", part: "core", source: { from: "dist", file: "detect-worker.js.map" }, debug: true },
7519
+ { path: "whiten_pink.png", part: "core", source: { from: "dist", file: "whiten_pink.png" } },
7520
+ { path: "NOTICE", part: "core", source: { from: "dist", file: "NOTICE" } },
7521
+ { path: "mp/", part: "core", source: { from: "peer-dir", name: "@mediapipe/tasks-vision", dir: "wasm", skip: "_module_" } },
7522
+ {
7523
+ path: "selfie_segmenter.tflite",
7524
+ part: "person",
7525
+ source: { from: "model", url: "https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_segmenter/float16/latest/selfie_segmenter.tflite" }
7526
+ },
7527
+ {
7528
+ path: "selfie_multiclass_256x256.tflite",
7529
+ part: "classes",
7530
+ source: {
7531
+ from: "model",
7532
+ url: "https://storage.googleapis.com/mediapipe-models/image_segmenter/selfie_multiclass_256x256/float32/latest/selfie_multiclass_256x256.tflite"
7533
+ }
7534
+ },
7535
+ {
7536
+ path: "face_landmarker.task",
7537
+ part: "face",
7538
+ source: { from: "model", url: "https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/latest/face_landmarker.task" }
7539
+ },
7540
+ { path: "face_cover.onnx", part: "cover", source: { from: "dist", file: "face_cover.onnx" } },
7541
+ { path: "ort/ort-wasm-simd-threaded.wasm", part: "cover", source: { from: "peer", name: "onnxruntime-web", file: "dist/ort-wasm-simd-threaded.wasm" } },
7542
+ { path: "ort/ort-wasm-simd-threaded.mjs", part: "cover", source: { from: "peer", name: "onnxruntime-web", file: "dist/ort-wasm-simd-threaded.mjs" } }
7543
+ ];
7512
7544
  function assetUrl(path) {
7513
7545
  return ASSET_BASE + path;
7514
7546
  }
7515
7547
 
7548
+ // node_modules/.pnpm/@tradalab+tskit@0.3.0/node_modules/@tradalab/tskit/dist/chunk-PFK4SOUW.js
7549
+ var FETCH_SHARE = 0.9;
7550
+ var DEFAULT_INTERVAL_MS = 100;
7551
+ var EMPTY_PROGRESS = Object.freeze({ loaded: 0, total: 0, done: 0, failed: 0, building: 0, items: 0, ratio: 1 });
7552
+ var ProgressTracker = class {
7553
+ entries = /* @__PURE__ */ new Map();
7554
+ listeners = /* @__PURE__ */ new Set();
7555
+ intervalMs;
7556
+ now;
7557
+ told = Number.NEGATIVE_INFINITY;
7558
+ constructor(opts = {}) {
7559
+ this.intervalMs = opts.intervalMs ?? DEFAULT_INTERVAL_MS;
7560
+ this.now = opts.now ?? (() => performance.now());
7561
+ }
7562
+ item(id, size) {
7563
+ const e2 = { phase: "waiting", loaded: 0, size, error: "" };
7564
+ this.entries.set(id, e2);
7565
+ this.tell(true);
7566
+ const settled = () => e2.phase === "ready" || e2.phase === "failed";
7567
+ return {
7568
+ size: (bytes) => {
7569
+ if (settled()) return;
7570
+ e2.size = bytes !== null && bytes >= 0 ? bytes : null;
7571
+ this.tell(false);
7572
+ },
7573
+ bytes: (n2) => {
7574
+ if (settled()) return;
7575
+ e2.phase = "fetching";
7576
+ e2.loaded += n2;
7577
+ this.tell(false);
7578
+ },
7579
+ rollback: () => {
7580
+ if (settled()) return;
7581
+ e2.loaded = 0;
7582
+ this.tell(true);
7583
+ },
7584
+ building: () => {
7585
+ if (settled()) return;
7586
+ e2.phase = "building";
7587
+ this.tell(true);
7588
+ },
7589
+ ready: () => {
7590
+ if (settled()) return;
7591
+ e2.phase = "ready";
7592
+ this.tell(true);
7593
+ },
7594
+ fail: (reason) => {
7595
+ if (settled()) return;
7596
+ e2.phase = "failed";
7597
+ e2.error = reason;
7598
+ e2.loaded = 0;
7599
+ e2.size = 0;
7600
+ this.tell(true);
7601
+ }
7602
+ };
7603
+ }
7604
+ get(id) {
7605
+ return this.entries.get(id);
7606
+ }
7607
+ snapshot() {
7608
+ const all = [...this.entries.values()];
7609
+ if (all.length === 0) return { ...EMPTY_PROGRESS };
7610
+ const known = all.every((e2) => typeof e2.size === "number");
7611
+ const total = known ? all.reduce((a2, e2) => a2 + e2.size, 0) : 0;
7612
+ const raw = all.reduce((a2, e2) => a2 + e2.loaded, 0);
7613
+ let share = 0;
7614
+ for (const e2 of all) share += itemRatio(e2);
7615
+ return {
7616
+ loaded: total ? Math.min(raw, total) : raw,
7617
+ total,
7618
+ done: all.filter((e2) => e2.phase === "ready" || e2.phase === "failed").length,
7619
+ failed: all.filter((e2) => e2.phase === "failed").length,
7620
+ building: all.filter((e2) => e2.phase === "building").length,
7621
+ items: all.length,
7622
+ ratio: share / all.length
7623
+ };
7624
+ }
7625
+ subscribe(listener) {
7626
+ this.listeners.add(listener);
7627
+ return () => this.listeners.delete(listener);
7628
+ }
7629
+ /** Tells every listener the current progress now, whatever the interval. */
7630
+ flush() {
7631
+ this.tell(true);
7632
+ }
7633
+ tell(force) {
7634
+ if (this.listeners.size === 0) return;
7635
+ const t2 = this.now();
7636
+ if (!force && t2 - this.told < this.intervalMs) return;
7637
+ this.told = t2;
7638
+ const p2 = this.snapshot();
7639
+ for (const l2 of [...this.listeners]) {
7640
+ try {
7641
+ l2(p2);
7642
+ } catch (err) {
7643
+ this.listeners.delete(l2);
7644
+ console.error("tskit: a progress listener threw and was removed", err);
7645
+ }
7646
+ }
7647
+ }
7648
+ };
7649
+ function itemRatio(e2) {
7650
+ if (e2.phase === "ready" || e2.phase === "failed") return 1;
7651
+ if (e2.phase === "building") return FETCH_SHARE;
7652
+ if (typeof e2.size === "number" && e2.size > 0) return FETCH_SHARE * Math.min(1, e2.loaded / e2.size);
7653
+ return 0;
7654
+ }
7655
+
7656
+ // node_modules/.pnpm/@tradalab+tskit@0.3.0/node_modules/@tradalab/tskit/dist/chunk-QNVFDCFJ.js
7657
+ var Retainer = class {
7658
+ constructor(opts) {
7659
+ this.opts = opts;
7660
+ this.keepMs = opts.keepMs ?? 0;
7661
+ this.setTimer = opts.setTimer ?? unrefTimer;
7662
+ this.clearTimer = opts.clearTimer ?? ((id) => clearTimeout(id));
7663
+ }
7664
+ opts;
7665
+ entries = /* @__PURE__ */ new Map();
7666
+ keepMs;
7667
+ setTimer;
7668
+ clearTimer;
7669
+ async acquire(key, signal) {
7670
+ signal?.throwIfAborted();
7671
+ let e2 = this.entries.get(key);
7672
+ if (!e2) {
7673
+ const abort = new AbortController();
7674
+ const entry2 = { refs: 0, abort, settled: false, hasValue: false, promise: void 0 };
7675
+ entry2.promise = this.opts.create(key, abort.signal).then(
7676
+ (v2) => {
7677
+ entry2.settled = true;
7678
+ entry2.value = v2;
7679
+ entry2.hasValue = true;
7680
+ if (this.entries.get(key) !== entry2) void this.dispose(key, entry2);
7681
+ return v2;
7682
+ },
7683
+ (err) => {
7684
+ entry2.settled = true;
7685
+ if (this.entries.get(key) === entry2) this.entries.delete(key);
7686
+ throw err;
7687
+ }
7688
+ );
7689
+ entry2.promise.catch(() => {
7690
+ });
7691
+ this.entries.set(key, entry2);
7692
+ e2 = entry2;
7693
+ }
7694
+ if (e2.timer !== void 0) {
7695
+ this.clearTimer(e2.timer);
7696
+ e2.timer = void 0;
7697
+ }
7698
+ e2.refs++;
7699
+ const entry = e2;
7700
+ let value;
7701
+ try {
7702
+ value = await waitFor(entry.promise, signal, entry.abort.signal);
7703
+ } catch (err) {
7704
+ this.release(key, entry);
7705
+ throw err;
7706
+ }
7707
+ if (this.entries.get(key) !== entry) {
7708
+ throw new DOMException(`${key} was cleared while it was being created`, "AbortError");
7709
+ }
7710
+ let released = false;
7711
+ return {
7712
+ value,
7713
+ release: () => {
7714
+ if (released) return;
7715
+ released = true;
7716
+ this.release(key, entry);
7717
+ }
7718
+ };
7719
+ }
7720
+ state(key) {
7721
+ const e2 = this.entries.get(key);
7722
+ if (!e2) return void 0;
7723
+ if (!e2.settled) return "creating";
7724
+ return e2.refs > 0 ? "live" : "kept";
7725
+ }
7726
+ refs(key) {
7727
+ return this.entries.get(key)?.refs ?? 0;
7728
+ }
7729
+ keys() {
7730
+ return [...this.entries.keys()];
7731
+ }
7732
+ async clear() {
7733
+ const all = [...this.entries.entries()];
7734
+ this.entries.clear();
7735
+ await Promise.all(all.map(([key, e2]) => this.drop(key, e2)));
7736
+ }
7737
+ release(key, e2) {
7738
+ e2.refs--;
7739
+ if (e2.refs > 0 || this.entries.get(key) !== e2) return;
7740
+ if (!e2.settled) {
7741
+ this.entries.delete(key);
7742
+ e2.abort.abort(new DOMException(`every caller of ${key} gave up before it was ready`, "AbortError"));
7743
+ return;
7744
+ }
7745
+ if (this.keepMs === Number.POSITIVE_INFINITY) return;
7746
+ if (this.keepMs <= 0) {
7747
+ this.entries.delete(key);
7748
+ void this.drop(key, e2);
7749
+ return;
7750
+ }
7751
+ e2.timer = this.setTimer(() => {
7752
+ e2.timer = void 0;
7753
+ if (e2.refs > 0 || this.entries.get(key) !== e2) return;
7754
+ this.entries.delete(key);
7755
+ void this.drop(key, e2);
7756
+ }, this.keepMs);
7757
+ }
7758
+ async drop(key, e2) {
7759
+ if (e2.timer !== void 0) {
7760
+ this.clearTimer(e2.timer);
7761
+ e2.timer = void 0;
7762
+ }
7763
+ if (!e2.settled) {
7764
+ e2.abort.abort(new DOMException(`${key} was cleared while it was being created`, "AbortError"));
7765
+ return;
7766
+ }
7767
+ await this.dispose(key, e2);
7768
+ }
7769
+ async dispose(key, e2) {
7770
+ if (!e2.hasValue) return;
7771
+ e2.hasValue = false;
7772
+ const value = e2.value;
7773
+ e2.value = void 0;
7774
+ try {
7775
+ await this.opts.dispose(value, key);
7776
+ } catch (err) {
7777
+ console.error(`tskit: disposing ${key} threw`, err);
7778
+ }
7779
+ }
7780
+ };
7781
+ function waitFor(p2, ...signals) {
7782
+ const live = signals.filter((s2) => s2 !== void 0);
7783
+ return new Promise((resolve, reject) => {
7784
+ const stop = () => {
7785
+ for (const s2 of live) s2.removeEventListener("abort", onAbort);
7786
+ };
7787
+ const onAbort = (ev) => {
7788
+ stop();
7789
+ const s2 = ev.target;
7790
+ reject(s2.reason ?? new DOMException("aborted", "AbortError"));
7791
+ };
7792
+ for (const s2 of live) s2.addEventListener("abort", onAbort, { once: true });
7793
+ p2.then(
7794
+ (v2) => {
7795
+ stop();
7796
+ resolve(v2);
7797
+ },
7798
+ (err) => {
7799
+ stop();
7800
+ reject(err);
7801
+ }
7802
+ );
7803
+ });
7804
+ }
7805
+ function unrefTimer(fn2, ms2) {
7806
+ const t2 = setTimeout(fn2, ms2);
7807
+ t2.unref?.();
7808
+ return t2;
7809
+ }
7810
+
7811
+ // node_modules/.pnpm/@tradalab+tskit@0.3.0/node_modules/@tradalab/tskit/dist/chunk-T3PNHVKJ.js
7812
+ var FetchError = class extends Error {
7813
+ constructor(url, failure, retryable, message2, status, options) {
7814
+ super(`tskit: ${url}: ${message2}`, options);
7815
+ this.url = url;
7816
+ this.failure = failure;
7817
+ this.retryable = retryable;
7818
+ this.status = status;
7819
+ this.name = "FetchError";
7820
+ }
7821
+ url;
7822
+ failure;
7823
+ retryable;
7824
+ status;
7825
+ };
7826
+ var DEFAULT_STALL_MS = 15e3;
7827
+ var DEFAULT_RETRIES = 2;
7828
+ var DEFAULT_BACKOFF_MS = 500;
7829
+ async function fetchBytes(url, opts) {
7830
+ const retries = opts.retries ?? DEFAULT_RETRIES;
7831
+ const backoff = opts.backoffMs ?? DEFAULT_BACKOFF_MS;
7832
+ const sleep = opts.sleep ?? abortableSleep;
7833
+ for (let attempt = 0; ; attempt++) {
7834
+ try {
7835
+ const bytes = await attemptOnce(url, opts);
7836
+ if (opts.sha256) await verify(url, bytes, opts.sha256);
7837
+ return bytes;
7838
+ } catch (err) {
7839
+ const e2 = asFetchError(url, err, opts.signal);
7840
+ if (!e2.retryable || attempt >= retries) throw e2;
7841
+ opts.onRetry?.(attempt + 1, e2);
7842
+ await sleep(backoff * 2 ** attempt, opts.signal).catch((reason) => {
7843
+ throw new FetchError(url, "aborted", false, "aborted", void 0, { cause: reason });
7844
+ });
7845
+ }
7846
+ }
7847
+ }
7848
+ function usableSize(res) {
7849
+ const encoding = res.headers.get("content-encoding");
7850
+ if (encoding && encoding !== "identity") return null;
7851
+ const header = res.headers.get("content-length");
7852
+ if (header === null || header.trim() === "") return null;
7853
+ const n2 = Number(header);
7854
+ return Number.isInteger(n2) && n2 >= 0 ? n2 : null;
7855
+ }
7856
+ async function attemptOnce(url, opts) {
7857
+ const stallMs = opts.stallMs ?? DEFAULT_STALL_MS;
7858
+ const local = new AbortController();
7859
+ const outer = opts.signal;
7860
+ const onOuter = () => local.abort(outer?.reason);
7861
+ if (outer?.aborted) throw new FetchError(url, "aborted", false, "aborted", void 0, { cause: outer.reason });
7862
+ outer?.addEventListener("abort", onOuter, { once: true });
7863
+ let stalled = false;
7864
+ let timer;
7865
+ const arm = () => {
7866
+ if (timer !== void 0) clearTimeout(timer);
7867
+ timer = setTimeout(() => {
7868
+ stalled = true;
7869
+ local.abort(new DOMException("stalled", "TimeoutError"));
7870
+ }, stallMs);
7871
+ };
7872
+ let got = 0;
7873
+ try {
7874
+ arm();
7875
+ const init = { signal: local.signal };
7876
+ if (opts.priority) init.priority = opts.priority;
7877
+ const res = await opts.fetch(url, init);
7878
+ if (!res.ok) {
7879
+ await res.body?.cancel().catch(() => {
7880
+ });
7881
+ const retryable = res.status >= 500 || res.status === 408 || res.status === 429;
7882
+ throw new FetchError(url, "status", retryable, `HTTP ${res.status}`, res.status);
7883
+ }
7884
+ const size = usableSize(res);
7885
+ opts.onSize?.(size);
7886
+ const reader = res.body?.getReader();
7887
+ if (reader) {
7888
+ const cancel = () => void reader.cancel(local.signal.reason).catch(() => {
7889
+ });
7890
+ if (local.signal.aborted) cancel();
7891
+ else local.signal.addEventListener("abort", cancel, { once: true });
7892
+ }
7893
+ if (!reader) {
7894
+ const all = new Uint8Array(await res.arrayBuffer());
7895
+ opts.onBytes?.(all.byteLength);
7896
+ return all;
7897
+ }
7898
+ const chunks = [];
7899
+ for (; ; ) {
7900
+ arm();
7901
+ const { done, value } = await reader.read();
7902
+ if (local.signal.aborted) throw local.signal.reason;
7903
+ if (done) break;
7904
+ chunks.push(value);
7905
+ got += value.byteLength;
7906
+ opts.onBytes?.(value.byteLength);
7907
+ }
7908
+ return join(chunks, got);
7909
+ } catch (err) {
7910
+ if (got > 0) opts.onBytes?.(-got);
7911
+ if (stalled) throw new FetchError(url, "stall", true, `no bytes for ${stallMs} ms`, void 0, { cause: err });
7912
+ throw err;
7913
+ } finally {
7914
+ if (timer !== void 0) clearTimeout(timer);
7915
+ outer?.removeEventListener("abort", onOuter);
7916
+ }
7917
+ }
7918
+ function asFetchError(url, err, signal) {
7919
+ if (err instanceof FetchError) return err;
7920
+ if (signal?.aborted) return new FetchError(url, "aborted", false, "aborted", void 0, { cause: err });
7921
+ return new FetchError(url, "network", true, err instanceof Error ? err.message : String(err), void 0, { cause: err });
7922
+ }
7923
+ async function verify(url, bytes, expected) {
7924
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
7925
+ const hex = [...digest].map((b2) => b2.toString(16).padStart(2, "0")).join("");
7926
+ if (hex !== expected.toLowerCase()) {
7927
+ throw new FetchError(url, "integrity", false, `sha256 ${hex} is not the expected ${expected}`);
7928
+ }
7929
+ }
7930
+ function join(chunks, n2) {
7931
+ if (chunks.length === 1) return chunks[0];
7932
+ const out = new Uint8Array(n2);
7933
+ let at2 = 0;
7934
+ for (const c2 of chunks) {
7935
+ out.set(c2, at2);
7936
+ at2 += c2.byteLength;
7937
+ }
7938
+ return out;
7939
+ }
7940
+ function abortableSleep(ms2, signal) {
7941
+ return new Promise((resolve, reject) => {
7942
+ if (signal?.aborted) return reject(signal.reason);
7943
+ const t2 = setTimeout(() => {
7944
+ signal?.removeEventListener("abort", onAbort);
7945
+ resolve();
7946
+ }, ms2);
7947
+ const onAbort = () => {
7948
+ clearTimeout(t2);
7949
+ reject(signal.reason);
7950
+ };
7951
+ signal?.addEventListener("abort", onAbort, { once: true });
7952
+ });
7953
+ }
7954
+
7955
+ // node_modules/.pnpm/@tradalab+tskit@0.3.0/node_modules/@tradalab/tskit/dist/chunk-7P5XCNQW.js
7956
+ var KEY_BASE = "https://tskit.invalid/";
7957
+ function cacheName(name, version) {
7958
+ return `${name}-v${version}`;
7959
+ }
7960
+ async function openByteStore(opts) {
7961
+ const full = cacheName(opts.name, opts.version);
7962
+ const storage = opts.caches === void 0 ? globalCaches() : opts.caches;
7963
+ if (storage) {
7964
+ try {
7965
+ const cache = await storage.open(full);
7966
+ return cacheStore(storage, cache, opts.name, full);
7967
+ } catch (err) {
7968
+ console.warn(`tskit: Cache Storage refused ${full}, keeping bytes in memory for this page`, err);
7969
+ }
7970
+ }
7971
+ return memoryStore(full);
7972
+ }
7973
+ async function storageUsage() {
7974
+ const s2 = globalThis.navigator?.storage;
7975
+ if (!s2) return { usage: null, quota: null, persisted: null };
7976
+ const [est, persisted] = await Promise.all([
7977
+ s2.estimate?.().catch(() => void 0),
7978
+ s2.persisted?.().catch(() => null) ?? Promise.resolve(null)
7979
+ ]);
7980
+ return { usage: est?.usage ?? null, quota: est?.quota ?? null, persisted: persisted ?? null };
7981
+ }
7982
+ function globalCaches() {
7983
+ return globalThis.caches ?? null;
7984
+ }
7985
+ function toRequest(key) {
7986
+ return KEY_BASE + encodeURIComponent(key);
7987
+ }
7988
+ function fromRequest(url) {
7989
+ return url.startsWith(KEY_BASE) ? decodeURIComponent(url.slice(KEY_BASE.length)) : null;
7990
+ }
7991
+ function cacheStore(storage, cache, prefix, full) {
7992
+ return {
7993
+ kind: "cache",
7994
+ name: full,
7995
+ async get(key) {
7996
+ const r2 = await cache.match(toRequest(key));
7997
+ return r2 ? new Uint8Array(await r2.arrayBuffer()) : null;
7998
+ },
7999
+ async put(key, bytes, type = "application/octet-stream") {
8000
+ await cache.put(
8001
+ toRequest(key),
8002
+ new Response(bytes, { headers: { "content-type": type, "content-length": String(bytes.byteLength) } })
8003
+ );
8004
+ },
8005
+ delete: (key) => cache.delete(toRequest(key)),
8006
+ async keys() {
8007
+ const reqs = await cache.keys();
8008
+ return reqs.map((r2) => fromRequest(r2.url)).filter((k3) => k3 !== null);
8009
+ },
8010
+ async clear() {
8011
+ for (const r2 of await cache.keys()) await cache.delete(r2);
8012
+ },
8013
+ async purgeOld() {
8014
+ const stale = (await storage.keys()).filter((n2) => n2 !== full && n2.startsWith(`${prefix}-v`));
8015
+ await Promise.all(stale.map((n2) => storage.delete(n2)));
8016
+ return stale;
8017
+ }
8018
+ };
8019
+ }
8020
+ function memoryStore(full) {
8021
+ const m2 = /* @__PURE__ */ new Map();
8022
+ return {
8023
+ kind: "memory",
8024
+ name: full,
8025
+ get: async (key) => m2.get(key)?.slice() ?? null,
8026
+ put: async (key, bytes) => {
8027
+ m2.set(key, bytes.slice());
8028
+ },
8029
+ delete: async (key) => m2.delete(key),
8030
+ keys: async () => [...m2.keys()],
8031
+ clear: async () => m2.clear(),
8032
+ purgeOld: async () => []
8033
+ };
8034
+ }
8035
+
8036
+ // node_modules/.pnpm/@tradalab+tskit@0.3.0/node_modules/@tradalab/tskit/dist/assets.js
8037
+ var TAG = "tskit/assets";
8038
+ function isTagged(data) {
8039
+ return typeof data === "object" && data !== null && data.tag === TAG;
8040
+ }
8041
+ function isAssetsMessage(data) {
8042
+ return isTagged(data);
8043
+ }
8044
+ function newRealm() {
8045
+ const c2 = globalThis.crypto;
8046
+ return c2?.randomUUID?.() ?? `${Date.now().toString(36)}-${Math.random().toString(36).slice(2)}`;
8047
+ }
8048
+ function applyPhase(phases, m2) {
8049
+ let realm = phases.get(m2.realm);
8050
+ if (!realm) phases.set(m2.realm, realm = /* @__PURE__ */ new Map());
8051
+ if (m2.phase === "disposed") realm.delete(m2.id);
8052
+ else realm.set(m2.id, { phase: m2.phase, error: m2.error ?? "" });
8053
+ if (realm.size === 0) phases.delete(m2.realm);
8054
+ }
8055
+ var LOW_MEMORY_GB = 4;
8056
+ var KEEP_MS = 3e4;
8057
+ function defaultKeepMs(deviceMemory) {
8058
+ const gb = deviceMemory ?? globalThis.navigator?.deviceMemory;
8059
+ return typeof gb === "number" && gb <= LOW_MEMORY_GB ? 0 : KEEP_MS;
8060
+ }
8061
+ var Assets = class {
8062
+ constructor(opts) {
8063
+ this.opts = opts;
8064
+ for (const s2 of opts.manifest) {
8065
+ if (this.specs.has(s2.id)) throw new Error(`tskit: asset ${s2.id} is declared twice`);
8066
+ this.specs.set(s2.id, s2);
8067
+ this.states.set(s2.id, { phase: "idle", loaded: 0, size: s2.size, cached: false, error: "" });
8068
+ this.stamps.set(s2.id, 0);
8069
+ }
8070
+ this.store = opts.store ? Promise.resolve(opts.store) : openByteStore({ name: opts.name, version: opts.version, caches: opts.caches });
8071
+ this.retainer = new Retainer({
8072
+ keepMs: opts.keepMs ?? defaultKeepMs(),
8073
+ create: (id, signal) => this.create(id, signal),
8074
+ dispose: async (value, id) => {
8075
+ const rt3 = this.runtimes.get(id);
8076
+ this.runtimes.delete(id);
8077
+ this.set(id, { phase: "idle", loaded: 0 });
8078
+ await rt3?.dispose(value);
8079
+ }
8080
+ });
8081
+ this.downloads = new Retainer({
8082
+ create: (id, signal) => this.download(this.spec(id), signal),
8083
+ dispose: () => {
8084
+ }
8085
+ });
8086
+ }
8087
+ opts;
8088
+ specs = /* @__PURE__ */ new Map();
8089
+ states = /* @__PURE__ */ new Map();
8090
+ listeners = /* @__PURE__ */ new Set();
8091
+ runtimes = /* @__PURE__ */ new Map();
8092
+ sinks = /* @__PURE__ */ new Map();
8093
+ stamps = /* @__PURE__ */ new Map();
8094
+ views = /* @__PURE__ */ new Map();
8095
+ given = /* @__PURE__ */ new WeakSet();
8096
+ retainer;
8097
+ downloads;
8098
+ store;
8099
+ rev = 0;
8100
+ remote = /* @__PURE__ */ new Map();
8101
+ served = /* @__PURE__ */ new Map();
8102
+ snap = null;
8103
+ spec(id) {
8104
+ const s2 = this.specs.get(id);
8105
+ if (!s2) throw new Error(`tskit: asset ${id} is not in the manifest`);
8106
+ return s2;
8107
+ }
8108
+ state(id) {
8109
+ this.spec(id);
8110
+ const s2 = this.states.get(id);
8111
+ const local = this.retainer.state(id);
8112
+ const kept = s2.phase === "ready" && local === "kept";
8113
+ const far = local === void 0 ? this.remotePhase(id) : null;
8114
+ const key = `${this.stamps.get(id)}:${kept}:${far?.phase ?? ""}:${far?.error ?? ""}`;
8115
+ const cached = this.views.get(id);
8116
+ if (cached && cached.key === key) return cached.view;
8117
+ const phase = kept ? "kept" : far ? far.phase : s2.phase;
8118
+ const view = Object.freeze({ ...s2, phase, error: far?.error || s2.error });
8119
+ this.views.set(id, { key, view });
8120
+ return view;
8121
+ }
8122
+ snapshot() {
8123
+ if (this.snap && this.snap.rev === this.rev) return this.snap.view;
8124
+ const out = {};
8125
+ for (const id of this.specs.keys()) out[id] = this.state(id);
8126
+ this.snap = { rev: this.rev, view: Object.freeze(out) };
8127
+ return this.snap.view;
8128
+ }
8129
+ get revision() {
8130
+ return this.rev;
8131
+ }
8132
+ subscribe(listener) {
8133
+ this.listeners.add(listener);
8134
+ return () => this.listeners.delete(listener);
8135
+ }
8136
+ async bytes(id, signal, item) {
8137
+ const spec = this.spec(id);
8138
+ if (spec.cacheable !== false) {
8139
+ const hit = await (await this.store).get(id);
8140
+ if (hit) {
8141
+ this.set(id, { cached: true, size: hit.byteLength, loaded: hit.byteLength });
8142
+ item?.size(hit.byteLength);
8143
+ item?.bytes(hit.byteLength);
8144
+ return hit;
8145
+ }
8146
+ }
8147
+ let sinks = this.sinks.get(id);
8148
+ if (!sinks) this.sinks.set(id, sinks = /* @__PURE__ */ new Set());
8149
+ if (item) {
8150
+ const now = this.states.get(id);
8151
+ if (this.downloads.state(id) === "creating") {
8152
+ if (typeof now.size === "number" || now.size === null) item.size(now.size);
8153
+ if (now.loaded > 0) item.bytes(now.loaded);
8154
+ }
8155
+ sinks.add(item);
8156
+ }
8157
+ try {
8158
+ const h2 = await this.downloads.acquire(id, signal);
8159
+ const bytes = h2.value;
8160
+ h2.release();
8161
+ if (this.given.has(bytes)) return bytes.slice();
8162
+ this.given.add(bytes);
8163
+ return bytes;
8164
+ } finally {
8165
+ if (item) sinks.delete(item);
8166
+ }
8167
+ }
8168
+ async acquire(id, runtime, signal) {
8169
+ this.spec(id);
8170
+ if (!this.runtimes.has(id)) this.runtimes.set(id, runtime);
8171
+ const h2 = await this.retainer.acquire(id, signal);
8172
+ this.emit();
8173
+ let released = false;
8174
+ return {
8175
+ value: h2.value,
8176
+ release: () => {
8177
+ if (released) return;
8178
+ released = true;
8179
+ h2.release();
8180
+ this.emit();
8181
+ }
8182
+ };
8183
+ }
8184
+ serve(port) {
8185
+ const existing = this.served.get(port);
8186
+ if (existing) return existing;
8187
+ const phases = /* @__PURE__ */ new Map();
8188
+ this.remote.set(port, phases);
8189
+ const onMessage = (ev) => {
8190
+ const m2 = ev.data;
8191
+ if (!isTagged(m2)) return;
8192
+ if (m2.t === "need") void this.answer(port, m2);
8193
+ else if (m2.t === "phase") {
8194
+ if (!this.specs.has(m2.id)) return;
8195
+ applyPhase(phases, m2);
8196
+ this.emit();
8197
+ } else if (m2.t === "bye") {
8198
+ if (phases.delete(m2.realm)) this.emit();
8199
+ }
8200
+ };
8201
+ const close = () => {
8202
+ if (this.served.get(port) !== close) return;
8203
+ this.served.delete(port);
8204
+ port.removeEventListener("message", onMessage);
8205
+ if (this.remote.delete(port)) this.emit();
8206
+ };
8207
+ this.served.set(port, close);
8208
+ port.addEventListener("message", onMessage);
8209
+ port.start?.();
8210
+ return close;
8211
+ }
8212
+ async bytesFor(ids, signal) {
8213
+ const out = {};
8214
+ await Promise.all(ids.map(async (id) => out[id] = (await this.bytes(id, signal)).slice()));
8215
+ return out;
8216
+ }
8217
+ async preload(ids, onProgress, signal) {
8218
+ const tracker = new ProgressTracker();
8219
+ const items = ids.map((id) => tracker.item(id, this.spec(id).size));
8220
+ const stop = onProgress ? tracker.subscribe(onProgress) : () => {
8221
+ };
8222
+ tracker.flush();
8223
+ try {
8224
+ await Promise.all(
8225
+ ids.map(async (id, i2) => {
8226
+ const item = items[i2];
8227
+ try {
8228
+ await this.bytes(id, signal, item);
8229
+ item.ready();
8230
+ } catch (err) {
8231
+ item.fail(err instanceof Error ? err.message : String(err));
8232
+ }
8233
+ })
8234
+ );
8235
+ return tracker.snapshot();
8236
+ } finally {
8237
+ stop();
8238
+ }
8239
+ }
8240
+ progress(ids = [...this.specs.keys()]) {
8241
+ const tracker = new ProgressTracker();
8242
+ for (const id of ids) {
8243
+ const s2 = this.states.get(id);
8244
+ if (!s2) continue;
8245
+ const item = tracker.item(id, s2.size);
8246
+ if (s2.loaded) item.bytes(s2.loaded);
8247
+ if (s2.phase === "building") item.building();
8248
+ if (s2.phase === "ready" || s2.phase === "idle" && s2.cached) item.ready();
8249
+ if (s2.phase === "failed") item.fail(s2.error);
8250
+ }
8251
+ return tracker.snapshot();
8252
+ }
8253
+ async usage() {
8254
+ const store = await this.store;
8255
+ const [u2, cached] = await Promise.all([storageUsage(), store.keys()]);
8256
+ return { ...u2, store: store.kind, cached };
8257
+ }
8258
+ async purgeOld() {
8259
+ return (await this.store).purgeOld();
8260
+ }
8261
+ async clear() {
8262
+ await this.downloads.clear();
8263
+ await this.retainer.clear();
8264
+ await (await this.store).clear();
8265
+ for (const id of this.specs.keys()) this.set(id, { phase: "idle", loaded: 0, cached: false, error: "" });
8266
+ }
8267
+ remotePhase(id) {
8268
+ let building = false;
8269
+ let ready = false;
8270
+ let failed = "";
8271
+ for (const phases of this.remote.values()) for (const realm of phases.values()) {
8272
+ const p2 = realm.get(id);
8273
+ if (!p2) continue;
8274
+ if (p2.phase === "building") building = true;
8275
+ else if (p2.phase === "ready") ready = true;
8276
+ else if (p2.phase === "failed") failed ||= p2.error || "failed";
8277
+ }
8278
+ if (building) return { phase: "building", error: "" };
8279
+ if (ready) return { phase: "ready", error: "" };
8280
+ if (failed) return { phase: "failed", error: failed };
8281
+ return null;
8282
+ }
8283
+ async answer(port, m2) {
8284
+ const reply = (d2, transfer = []) => port.postMessage({ tag: TAG, t: "have", req: m2.req, id: m2.id, ...d2 }, transfer);
8285
+ try {
8286
+ const bytes = await this.bytes(m2.id);
8287
+ const store = await this.store;
8288
+ if (m2.caches && store.kind === "cache" && this.spec(m2.id).cacheable !== false) return reply({ via: "cache" });
8289
+ const copy = bytes.slice();
8290
+ reply({ via: "bytes", bytes: copy }, [copy.buffer]);
8291
+ } catch (err) {
8292
+ reply({ via: "bytes", error: describe(err) });
8293
+ }
8294
+ }
8295
+ async download(spec, signal) {
8296
+ const id = spec.id;
8297
+ const sinks = () => this.sinks.get(id) ?? /* @__PURE__ */ new Set();
8298
+ this.set(id, { phase: "fetching", loaded: 0, error: "" });
8299
+ let bytes;
8300
+ try {
8301
+ bytes = await fetchBytes(spec.url, {
8302
+ fetch: this.opts.fetch,
8303
+ signal,
8304
+ sha256: spec.sha256,
8305
+ stallMs: this.opts.stallMs,
8306
+ retries: this.opts.retries,
8307
+ onSize: (n2) => {
8308
+ const size = n2 ?? (spec.size === void 0 ? null : spec.size);
8309
+ for (const it2 of sinks()) it2.size(size);
8310
+ this.set(id, { size });
8311
+ },
8312
+ onBytes: (n2) => {
8313
+ for (const it2 of sinks()) {
8314
+ if (n2 < 0) it2.rollback();
8315
+ else it2.bytes(n2);
8316
+ }
8317
+ this.set(id, { loaded: Math.max(0, this.states.get(id).loaded + n2) });
8318
+ }
8319
+ });
8320
+ } catch (err) {
8321
+ if (isAbort(err, signal)) this.set(id, { phase: "idle", loaded: 0, error: "" });
8322
+ else this.set(id, { phase: "failed", loaded: 0, error: describe(err) });
8323
+ throw err;
8324
+ }
8325
+ const next = this.retainer.state(id) === "creating" ? "building" : "idle";
8326
+ this.set(id, { phase: next, size: bytes.byteLength, loaded: bytes.byteLength });
8327
+ if (spec.cacheable !== false) {
8328
+ try {
8329
+ await (await this.store).put(id, bytes, spec.type);
8330
+ this.set(id, { cached: true });
8331
+ } catch (err) {
8332
+ console.warn(`tskit: could not cache ${id}`, err);
8333
+ }
8334
+ }
8335
+ return bytes;
8336
+ }
8337
+ async create(id, signal) {
8338
+ const rt3 = this.runtimes.get(id);
8339
+ if (!rt3) throw new Error(`tskit: no runtime for ${id}`);
8340
+ try {
8341
+ this.set(id, { phase: "fetching", error: "" });
8342
+ const bytes = await this.bytes(id, signal);
8343
+ this.set(id, { phase: "building" });
8344
+ const value = await rt3.build(bytes, { id, signal });
8345
+ this.set(id, { phase: "ready" });
8346
+ return value;
8347
+ } catch (err) {
8348
+ this.runtimes.delete(id);
8349
+ if (isAbort(err, signal)) this.set(id, { phase: "idle", error: "" });
8350
+ else this.set(id, { phase: "failed", error: describe(err) });
8351
+ throw err;
8352
+ }
8353
+ }
8354
+ set(id, patch) {
8355
+ const s2 = this.states.get(id);
8356
+ if (!s2) return;
8357
+ Object.assign(s2, patch);
8358
+ this.stamps.set(id, (this.stamps.get(id) ?? 0) + 1);
8359
+ this.emit();
8360
+ }
8361
+ emit() {
8362
+ this.rev++;
8363
+ for (const l2 of [...this.listeners]) {
8364
+ try {
8365
+ l2();
8366
+ } catch (err) {
8367
+ this.listeners.delete(l2);
8368
+ console.error("tskit: an assets listener threw and was removed", err);
8369
+ }
8370
+ }
8371
+ }
8372
+ };
8373
+ function createAssets(opts) {
8374
+ return new Assets(opts);
8375
+ }
8376
+ var AssetsClient = class {
8377
+ constructor(port, opts) {
8378
+ this.port = port;
8379
+ this.store = opts.store ? Promise.resolve(opts.store) : openByteStore({ name: opts.name, version: opts.version, caches: opts.caches });
8380
+ this.retainer = new Retainer({
8381
+ keepMs: opts.keepMs ?? defaultKeepMs(),
8382
+ create: (id, signal) => this.create(id, signal),
8383
+ dispose: async (value, id) => {
8384
+ const rt3 = this.runtimes.get(id);
8385
+ this.runtimes.delete(id);
8386
+ this.report(id, "disposed");
8387
+ await rt3?.dispose(value);
8388
+ }
8389
+ });
8390
+ port.addEventListener("message", this.onMessage);
8391
+ port.start?.();
8392
+ }
8393
+ port;
8394
+ waiting = /* @__PURE__ */ new Map();
8395
+ retainer;
8396
+ runtimes = /* @__PURE__ */ new Map();
8397
+ store;
8398
+ req = 0;
8399
+ closed = false;
8400
+ closing = false;
8401
+ realm = newRealm();
8402
+ children = /* @__PURE__ */ new Map();
8403
+ viaCache = /* @__PURE__ */ new Set();
8404
+ inflight = /* @__PURE__ */ new Map();
8405
+ onMessage = (ev) => {
8406
+ const m2 = ev.data;
8407
+ if (!isTagged(m2) || m2.t !== "have") return;
8408
+ const w2 = this.waiting.get(m2.req);
8409
+ if (!w2) return;
8410
+ this.waiting.delete(m2.req);
8411
+ w2.resolve(m2);
8412
+ };
8413
+ async bytes(id, signal) {
8414
+ signal?.throwIfAborted();
8415
+ let entry = this.inflight.get(id);
8416
+ if (!entry) {
8417
+ const e2 = { waiters: 0, done: void 0 };
8418
+ e2.done = this.load(id).then((bytes) => ({ bytes, shared: e2.waiters > 1 }));
8419
+ e2.done.catch(() => {
8420
+ }).finally(() => {
8421
+ if (this.inflight.get(id) === e2) this.inflight.delete(id);
8422
+ });
8423
+ this.inflight.set(id, e2);
8424
+ entry = e2;
8425
+ }
8426
+ entry.waiters++;
8427
+ let left = false;
8428
+ const leave = () => {
8429
+ if (left) return;
8430
+ left = true;
8431
+ entry.waiters--;
8432
+ };
8433
+ try {
8434
+ const { bytes, shared } = await raceAbort(entry.done, signal, leave);
8435
+ return shared ? bytes.slice() : bytes;
8436
+ } finally {
8437
+ leave();
8438
+ }
8439
+ }
8440
+ async load(id) {
8441
+ const store = await this.store;
8442
+ const d2 = await this.ask(id, store.kind === "cache");
8443
+ if (d2.via === "cache") {
8444
+ const hit = await store.get(id);
8445
+ if (hit) {
8446
+ this.viaCache.add(id);
8447
+ return hit;
8448
+ }
8449
+ const again = await this.ask(id, false);
8450
+ this.viaCache.delete(id);
8451
+ return this.unwrap(id, again);
8452
+ }
8453
+ this.viaCache.delete(id);
8454
+ return this.unwrap(id, d2);
8455
+ }
8456
+ async acquire(id, runtime, signal) {
8457
+ if (this.closing) throw new DOMException("assets client closed", "AbortError");
8458
+ if (!this.runtimes.has(id)) this.runtimes.set(id, runtime);
8459
+ const h2 = await this.retainer.acquire(id, signal);
8460
+ return { value: h2.value, release: () => h2.release() };
8461
+ }
8462
+ report(id, phase, error) {
8463
+ if (this.closed) return;
8464
+ this.port.postMessage({ tag: TAG, t: "phase", realm: this.realm, id, phase, error });
8465
+ }
8466
+ /** Serves a worker started from this realm through this client: it asks the page, and the page sees its builds. */
8467
+ serve(port) {
8468
+ const existing = this.children.get(port);
8469
+ if (existing) return existing.close;
8470
+ const realms = /* @__PURE__ */ new Set();
8471
+ const onMessage = (ev) => {
8472
+ const m2 = ev.data;
8473
+ if (!isTagged(m2)) return;
8474
+ if (m2.t === "need") void this.relay(port, m2);
8475
+ else if (m2.t === "phase" || m2.t === "bye") {
8476
+ if (m2.t === "phase") realms.add(m2.realm);
8477
+ else realms.delete(m2.realm);
8478
+ if (!this.closed) this.port.postMessage(m2);
8479
+ }
8480
+ };
8481
+ const close = () => {
8482
+ if (this.children.get(port)?.close !== close) return;
8483
+ this.children.delete(port);
8484
+ port.removeEventListener("message", onMessage);
8485
+ if (!this.closed) for (const r2 of realms) this.port.postMessage({ tag: TAG, t: "bye", realm: r2 });
8486
+ };
8487
+ this.children.set(port, { close, realms });
8488
+ port.addEventListener("message", onMessage);
8489
+ port.start?.();
8490
+ return close;
8491
+ }
8492
+ async close() {
8493
+ if (this.closing) return;
8494
+ this.closing = true;
8495
+ await this.retainer.clear();
8496
+ for (const child of [...this.children.values()]) child.close();
8497
+ this.closed = true;
8498
+ this.port.postMessage({ tag: TAG, t: "bye", realm: this.realm });
8499
+ this.port.removeEventListener("message", this.onMessage);
8500
+ for (const w2 of this.waiting.values()) w2.reject(new DOMException("assets client closed", "AbortError"));
8501
+ this.waiting.clear();
8502
+ }
8503
+ ask(id, caches) {
8504
+ if (this.closing) return Promise.reject(new DOMException("assets client closed", "AbortError"));
8505
+ const req = ++this.req;
8506
+ return new Promise((resolve, reject) => {
8507
+ this.waiting.set(req, { resolve, reject });
8508
+ this.port.postMessage({ tag: TAG, t: "need", req, id, caches });
8509
+ });
8510
+ }
8511
+ async relay(port, m2) {
8512
+ const reply = (d2, transfer = []) => port.postMessage({ tag: TAG, t: "have", req: m2.req, id: m2.id, ...d2 }, transfer);
8513
+ try {
8514
+ const bytes = await this.bytes(m2.id);
8515
+ if (m2.caches && this.viaCache.has(m2.id)) return reply({ via: "cache" });
8516
+ const copy = bytes.slice();
8517
+ reply({ via: "bytes", bytes: copy }, [copy.buffer]);
8518
+ } catch (err) {
8519
+ reply({ via: "bytes", error: describe(err) });
8520
+ }
8521
+ }
8522
+ unwrap(id, d2) {
8523
+ if (d2.error) throw new Error(d2.error);
8524
+ if (!d2.bytes) throw new Error(`tskit: ${id} came back without bytes`);
8525
+ return d2.bytes;
8526
+ }
8527
+ async create(id, signal) {
8528
+ const rt3 = this.runtimes.get(id);
8529
+ if (!rt3) throw new Error(`tskit: no runtime for ${id}`);
8530
+ try {
8531
+ const bytes = await this.bytes(id, signal);
8532
+ this.report(id, "building");
8533
+ const value = await rt3.build(bytes, { id, signal });
8534
+ this.report(id, "ready");
8535
+ return value;
8536
+ } catch (err) {
8537
+ this.runtimes.delete(id);
8538
+ if (isAbort(err, signal)) this.report(id, "disposed");
8539
+ else this.report(id, "failed", describe(err));
8540
+ throw err;
8541
+ }
8542
+ }
8543
+ };
8544
+ function connectAssets(port, opts) {
8545
+ return new AssetsClient(port, opts);
8546
+ }
8547
+ function raceAbort(p2, signal, onAbort) {
8548
+ if (!signal) return p2;
8549
+ return new Promise((resolve, reject) => {
8550
+ const abort = () => {
8551
+ onAbort();
8552
+ reject(signal.reason ?? new DOMException("aborted", "AbortError"));
8553
+ };
8554
+ signal.addEventListener("abort", abort, { once: true });
8555
+ p2.then(
8556
+ (v2) => {
8557
+ signal.removeEventListener("abort", abort);
8558
+ resolve(v2);
8559
+ },
8560
+ (err) => {
8561
+ signal.removeEventListener("abort", abort);
8562
+ reject(err);
8563
+ }
8564
+ );
8565
+ });
8566
+ }
8567
+ function isAbort(err, signal) {
8568
+ if (signal.aborted) return true;
8569
+ if (err instanceof FetchError) return err.failure === "aborted";
8570
+ return err instanceof DOMException && err.name === "AbortError";
8571
+ }
8572
+ function describe(err) {
8573
+ if (err instanceof Error) return err.message;
8574
+ return String(err);
8575
+ }
8576
+
8577
+ // src/res.ts
8578
+ var RES_NAME = "mediakit";
8579
+ var RES_VERSION = true ? "2.10.0" : "dev";
8580
+ var MP_RUNTIME = ["vision_wasm_internal.js", "vision_wasm_internal.wasm", "vision_wasm_nosimd_internal.js", "vision_wasm_nosimd_internal.wasm"];
8581
+ var NOT_FETCHED = /* @__PURE__ */ new Set(["worker.js", "detect-worker.js", "NOTICE"]);
8582
+ var TYPES = {
8583
+ js: "text/javascript",
8584
+ mjs: "text/javascript",
8585
+ wasm: "application/wasm",
8586
+ png: "image/png"
8587
+ };
8588
+ function typeOf(path) {
8589
+ return TYPES[path.slice(path.lastIndexOf(".") + 1)] ?? "application/octet-stream";
8590
+ }
8591
+ function resourceManifest() {
8592
+ const specs = [];
8593
+ for (const a2 of ASSETS) {
8594
+ if (a2.debug || a2.path.endsWith("/") || NOT_FETCHED.has(a2.path)) continue;
8595
+ specs.push({ id: a2.path, url: assetUrl(a2.path), type: typeOf(a2.path), group: a2.part });
8596
+ }
8597
+ for (const f2 of MP_RUNTIME) specs.push({ id: `mp/${f2}`, url: assetUrl(`mp/${f2}`), type: typeOf(f2), group: "mp" });
8598
+ return specs;
8599
+ }
8600
+ var source = null;
8601
+ var urls = /* @__PURE__ */ new Map();
8602
+ function resources() {
8603
+ if (!source) {
8604
+ const owner = createAssets({ manifest: resourceManifest(), name: RES_NAME, version: RES_VERSION, fetch: (u2, i2) => fetch(u2, i2) });
8605
+ owner.purgeOld().catch((err) => console.warn("mediakit: could not delete the files of older versions", err));
8606
+ source = owner;
8607
+ }
8608
+ return source;
8609
+ }
8610
+ function connectResources(port) {
8611
+ source = connectAssets(port, { name: RES_NAME, version: RES_VERSION });
8612
+ }
8613
+ function resourceId(pathOrUrl) {
8614
+ return pathOrUrl.startsWith(ASSET_BASE) ? pathOrUrl.slice(ASSET_BASE.length) : pathOrUrl;
8615
+ }
8616
+ function resourceBytes(id, signal) {
8617
+ return resources().bytes(id, signal);
8618
+ }
8619
+ function resourceUrl(id) {
8620
+ let p2 = urls.get(id);
8621
+ if (!p2) {
8622
+ p2 = resourceBytes(id).then((b2) => URL.createObjectURL(new Blob([b2], { type: typeOf(id) })));
8623
+ p2.catch(() => urls.delete(id));
8624
+ urls.set(id, p2);
8625
+ }
8626
+ return p2;
8627
+ }
8628
+
7516
8629
  // src/mp.ts
7517
8630
  var MP_DIR = assetUrl("mp");
7518
- var MODEL_URL = {
7519
- person: assetUrl("selfie_segmenter.tflite"),
7520
- classes: assetUrl("selfie_multiclass_256x256.tflite"),
7521
- face: assetUrl("face_landmarker.task")
7522
- };
7523
8631
  var LOAD_MS = 6e4;
7524
8632
  var fileset = null;
8633
+ var MODEL_ID = {
8634
+ person: "selfie_segmenter.tflite",
8635
+ classes: "selfie_multiclass_256x256.tflite",
8636
+ face: "face_landmarker.task"
8637
+ };
8638
+ function modelBytes(model) {
8639
+ return resourceBytes(MODEL_ID[model]);
8640
+ }
7525
8641
  function visionFileset() {
7526
- fileset ??= uh.forVisionTasks(MP_DIR).catch((e2) => {
8642
+ fileset ??= (async () => {
8643
+ const base = await uh.forVisionTasks(MP_DIR);
8644
+ const [loader, binary] = await Promise.all([resourceUrl(resourceId(base.wasmLoaderPath)), resourceUrl(resourceId(base.wasmBinaryPath))]);
8645
+ return { ...base, wasmLoaderPath: loader, wasmBinaryPath: binary };
8646
+ })().catch((e2) => {
7527
8647
  fileset = null;
7528
8648
  throw e2;
7529
8649
  });
@@ -7580,7 +8700,7 @@
7580
8700
  async function createFaceDetector(canvas, maxFaces, delegate = "GPU", mode = "VIDEO") {
7581
8701
  const fileset2 = await visionFileset();
7582
8702
  const landmarker = await yc.createFromOptions(fileset2, {
7583
- baseOptions: { modelAssetPath: MODEL_URL.face, delegate },
8703
+ baseOptions: { modelAssetBuffer: await modelBytes("face"), delegate },
7584
8704
  canvas,
7585
8705
  runningMode: mode,
7586
8706
  // As many as the core tracks: one landmark pass returns them all, so the cost of a second
@@ -7614,8 +8734,6 @@
7614
8734
  }
7615
8735
 
7616
8736
  // src/cover.ts
7617
- var COVER_MODEL_URL = assetUrl("face_cover.onnx");
7618
- var ORT_DIR = assetUrl("ort/");
7619
8737
  var INPUT = 96;
7620
8738
  var CROP_SCALE = 1.5;
7621
8739
  var OVAL = [10, 338, 297, 332, 284, 251, 389, 356, 454, 323, 361, 288, 397, 365, 379, 378, 400, 377, 152, 148, 176, 149, 150, 136, 172, 58, 132, 93, 234, 127, 162, 21, 54, 103, 67, 109];
@@ -7686,9 +8804,15 @@
7686
8804
  }
7687
8805
  }
7688
8806
  async function createFaceCover() {
7689
- Y.wasm.wasmPaths = ORT_DIR;
8807
+ const [binary, glue, model] = await Promise.all([
8808
+ resourceBytes("ort/ort-wasm-simd-threaded.wasm"),
8809
+ resourceUrl("ort/ort-wasm-simd-threaded.mjs"),
8810
+ resourceBytes("face_cover.onnx")
8811
+ ]);
8812
+ Y.wasm.wasmBinary = binary;
8813
+ Y.wasm.wasmPaths = { mjs: glue };
7690
8814
  Y.wasm.numThreads = 1;
7691
- const session = await gs.create(COVER_MODEL_URL, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
8815
+ const session = await gs.create(model, { executionProviders: ["wasm"], graphOptimizationLevel: "all" });
7692
8816
  const crop = new OffscreenCanvas(INPUT, INPUT);
7693
8817
  const ctx = crop.getContext("2d", { willReadFrequently: true });
7694
8818
  const input = new Float32Array(3 * INPUT * INPUT);
@@ -7741,7 +8865,7 @@
7741
8865
  async function createMaskReader(canvas, model, delegate) {
7742
8866
  const fileset2 = await visionFileset();
7743
8867
  const segmenter = await $c.createFromOptions(fileset2, {
7744
- baseOptions: { modelAssetPath: MODEL_URL[model], delegate },
8868
+ baseOptions: { modelAssetBuffer: await modelBytes(model), delegate },
7745
8869
  canvas,
7746
8870
  runningMode: "VIDEO",
7747
8871
  outputCategoryMask: true,
@@ -7767,6 +8891,7 @@
7767
8891
  // src/detect-worker/entry.ts
7768
8892
  var DELEGATE = "CPU";
7769
8893
  var scope = self;
8894
+ connectResources(self);
7770
8895
  var face = null;
7771
8896
  var lm = new Float32Array(0);
7772
8897
  var cover = null;
@@ -7802,6 +8927,7 @@
7802
8927
  }
7803
8928
  var message = (err) => String(err?.message ?? err);
7804
8929
  scope.onmessage = async (e2) => {
8930
+ if (isAssetsMessage(e2.data)) return;
7805
8931
  const m2 = e2.data;
7806
8932
  switch (m2.t) {
7807
8933
  case "initFace":