@banou/ripple 0.0.3 → 0.0.7
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/README.md +141 -3
- package/build/_headers +14 -0
- package/build/api-Jq4OSTp1-B4uxQLLk.js +338 -0
- package/build/app.webmanifest +50 -65
- package/build/assets/empty-BvRk9kiK.js +0 -0
- package/build/assets/libtorrent-DS_9Yo8M.js +6 -0
- package/build/assets/sintel.torrent +0 -0
- package/build/assets/worker-SJZDGuG-.js +23 -0
- package/build/build-DEOZ3A7n.js +1846 -0
- package/build/index.js +44658 -1
- package/build/jassub/default.woff2 +0 -0
- package/build/jassub/fonts.js +1 -0
- package/build/jassub/jassub-assets.js +0 -0
- package/build/jassub/jassub-worker-modern.wasm +0 -0
- package/build/jassub/jassub-worker.js +1 -0
- package/build/jassub/jassub-worker.wasm +0 -0
- package/build/jassub/worker.js +148 -0
- package/build/libav-jspi.wasm +0 -0
- package/build/libav-worker.js +4823 -1564
- package/build/libav.wasm +0 -0
- package/build/remote-BLaEXLm6.js +209 -0
- package/build/sw.js +192 -0
- package/package.json +96 -81
- package/build/index-8227e1be.js +0 -121
- package/build/index-9a320571.js +0 -107
- package/build/io-worker-682dbf74.js +0 -3
- package/build/jassub-worker-modern.wasm +0 -0
- package/build/jassub-worker.js +0 -15
- package/build/settings-b282903e.js +0 -26
- package/build/shared-worker-c85a5375.js +0 -1484
- package/build/shared-worker.js +0 -1
- package/build/worker.js +0 -1
package/build/index-8227e1be.js
DELETED
|
@@ -1,121 +0,0 @@
|
|
|
1
|
-
var k = "osra-message", m = (e) => !!(globalThis.SharedArrayBuffer && e instanceof globalThis.SharedArrayBuffer), w = (e) => globalThis.ArrayBuffer && e instanceof globalThis.ArrayBuffer || globalThis.MessagePort && e instanceof globalThis.MessagePort || globalThis.ReadableStream && e instanceof globalThis.ReadableStream || globalThis.WritableStream && e instanceof globalThis.WritableStream || globalThis.TransformStream && e instanceof globalThis.TransformStream ? !0 : !!(globalThis.ImageBitmap && e instanceof globalThis.ImageBitmap), y = (e) => {
|
|
2
|
-
const r = [], t = (s) => m(s) ? void 0 : w(s) ? r.push(s) : Array.isArray(s) ? s.map(t) : s && typeof s == "object" ? Object.values(s).map(t) : void 0;
|
|
3
|
-
return t(e), r;
|
|
4
|
-
}, p = "__proxyFunctionPort__", C = (e) => {
|
|
5
|
-
const { port1: r, port2: t } = new MessageChannel();
|
|
6
|
-
return r.addEventListener("message", async (s) => {
|
|
7
|
-
try {
|
|
8
|
-
const o = await e(...s.data), a = i(o), n = y(a);
|
|
9
|
-
r.postMessage({ result: a }, { transfer: n });
|
|
10
|
-
} catch (o) {
|
|
11
|
-
r.postMessage({ error: o });
|
|
12
|
-
}
|
|
13
|
-
}), r.start(), t;
|
|
14
|
-
}, i = (e) => m(e) || w(e) ? e : typeof e == "function" ? { [p]: C(e) } : Array.isArray(e) ? e.map(i) : e && typeof e == "object" ? Object.fromEntries(Object.entries(e).map(([r, t]) => [
|
|
15
|
-
r,
|
|
16
|
-
i(t)
|
|
17
|
-
])) : e, F = (e) => (...r) => new Promise((t, s) => {
|
|
18
|
-
const o = i(r), a = y(o);
|
|
19
|
-
e.addEventListener("message", (n) => {
|
|
20
|
-
n.data.error ? s(n.data.error) : t(T(n.data.result));
|
|
21
|
-
}), e.start(), e.postMessage(o, { transfer: a });
|
|
22
|
-
}), T = (e) => m(e) || w(e) ? e : e && typeof e == "object" && e[p] ? F(e[p]) : Array.isArray(e) ? e.map(i) : e && typeof e == "object" ? Object.fromEntries(Object.entries(e).map(([r, t]) => [
|
|
23
|
-
r,
|
|
24
|
-
T(t)
|
|
25
|
-
])) : e, E = (e, { key: r = k } = { key: k }) => (t, s) => new Promise((o, a) => {
|
|
26
|
-
const { port1: n, port2: f } = new MessageChannel();
|
|
27
|
-
n.addEventListener("message", ({ data: l }) => {
|
|
28
|
-
if (l.error)
|
|
29
|
-
a(l.error);
|
|
30
|
-
else {
|
|
31
|
-
const M = T(l.result);
|
|
32
|
-
o(M);
|
|
33
|
-
}
|
|
34
|
-
n.close(), f.close();
|
|
35
|
-
}, { once: !0 }), n.start();
|
|
36
|
-
const R = i(s), _ = y(R);
|
|
37
|
-
e.postMessage({
|
|
38
|
-
source: r,
|
|
39
|
-
type: t,
|
|
40
|
-
data: R,
|
|
41
|
-
port: f
|
|
42
|
-
}, {
|
|
43
|
-
targetOrigin: "*",
|
|
44
|
-
transfer: [f, ..._ ?? []]
|
|
45
|
-
});
|
|
46
|
-
});
|
|
47
|
-
let A, b;
|
|
48
|
-
const x = () => (b = new Promise((e, r) => {
|
|
49
|
-
A = e;
|
|
50
|
-
}), b), I = x(), g = async (e) => {
|
|
51
|
-
e === I && x(), A(await e);
|
|
52
|
-
}, j = "https://fkn.app", B = globalThis.window === void 0, O = globalThis.document?.body.querySelector(`iframe[src="${`${j}/sandbox-api`}"]`), c = O ? void 0 : globalThis.document?.createElement("iframe");
|
|
53
|
-
c && (c.src = `${j}/sandbox-api`, c.style.display = "none", document.body.appendChild(c));
|
|
54
|
-
const h = globalThis.window?.parent === globalThis.window ? O ?? c : void 0, d = globalThis.window?.parent === globalThis.window ? h?.contentWindow : globalThis.window?.parent, u = (e) => g(e), S = () => b, L = async () => E(await S(), { key: "fkn-sandbox-api" })("API_PORT", {});
|
|
55
|
-
if (B) {
|
|
56
|
-
let e = !1;
|
|
57
|
-
b.then(() => {
|
|
58
|
-
e = !0;
|
|
59
|
-
}), setTimeout(() => {
|
|
60
|
-
e || console.warn("@fkn/lib's api target has not resolved after 250ms while in a worker, make sure to call `setApiTarget(messagePort)`");
|
|
61
|
-
}, 250);
|
|
62
|
-
} else {
|
|
63
|
-
if (!d)
|
|
64
|
-
throw new Error("Missing target window on non worker thread");
|
|
65
|
-
if (window.parent === window && !O) {
|
|
66
|
-
if (!h)
|
|
67
|
-
throw new Error("Missing appended iframe");
|
|
68
|
-
h.addEventListener("load", () => {
|
|
69
|
-
const e = setInterval(
|
|
70
|
-
() => E(d, { key: "fkn-sandbox" })("APP_READY", {}).then(() => {
|
|
71
|
-
g(d), clearInterval(e);
|
|
72
|
-
}),
|
|
73
|
-
10
|
|
74
|
-
);
|
|
75
|
-
});
|
|
76
|
-
} else
|
|
77
|
-
g(d);
|
|
78
|
-
}
|
|
79
|
-
const P = (e, r) => S().then(
|
|
80
|
-
(t) => E(t, { key: "fkn-sandbox-api" })(e, r)
|
|
81
|
-
), Y = async (e, r) => {
|
|
82
|
-
const t = e, s = r, { body: o, ...a } = await P("SERVER_PROXY_FETCH", { input: t, init: s });
|
|
83
|
-
return new Response(
|
|
84
|
-
o,
|
|
85
|
-
{
|
|
86
|
-
...a,
|
|
87
|
-
headers: {
|
|
88
|
-
...a.headers,
|
|
89
|
-
...a.headers && {
|
|
90
|
-
setCookie: a.headers["set-cookie"]
|
|
91
|
-
}
|
|
92
|
-
}
|
|
93
|
-
}
|
|
94
|
-
);
|
|
95
|
-
}, N = async ({ magnet: e, path: r, offset: t, end: s }) => {
|
|
96
|
-
const { body: o, ...a } = await P("TORRENT", { magnet: e, path: r, offset: t, end: s });
|
|
97
|
-
return new Response(
|
|
98
|
-
o,
|
|
99
|
-
{
|
|
100
|
-
...a,
|
|
101
|
-
headers: Object.fromEntries(a.headers)
|
|
102
|
-
}
|
|
103
|
-
);
|
|
104
|
-
}, D = async ({ magnet: e }) => {
|
|
105
|
-
const { body: r, ...t } = await P("TORRENT_FILE", { magnet: e });
|
|
106
|
-
return new Response(
|
|
107
|
-
r,
|
|
108
|
-
{
|
|
109
|
-
...t,
|
|
110
|
-
headers: Object.fromEntries(t.headers)
|
|
111
|
-
}
|
|
112
|
-
);
|
|
113
|
-
};
|
|
114
|
-
export {
|
|
115
|
-
L as E,
|
|
116
|
-
D as P,
|
|
117
|
-
S as b,
|
|
118
|
-
u as k,
|
|
119
|
-
Y as u,
|
|
120
|
-
N as v
|
|
121
|
-
};
|
package/build/index-9a320571.js
DELETED
|
@@ -1,107 +0,0 @@
|
|
|
1
|
-
const m = "osra-message", h = (e) => !!(globalThis.SharedArrayBuffer && e instanceof globalThis.SharedArrayBuffer), u = (e) => globalThis.ArrayBuffer && e instanceof globalThis.ArrayBuffer || globalThis.MessagePort && e instanceof globalThis.MessagePort || globalThis.ReadableStream && e instanceof globalThis.ReadableStream || globalThis.WritableStream && e instanceof globalThis.WritableStream || globalThis.TransformStream && e instanceof globalThis.TransformStream ? !0 : !!(globalThis.ImageBitmap && e instanceof globalThis.ImageBitmap), g = (e) => {
|
|
2
|
-
const r = [], s = (a) => h(a) ? void 0 : u(a) ? r.push(a) : Array.isArray(a) ? a.map(s) : a && typeof a == "object" ? Object.values(a).map(s) : void 0;
|
|
3
|
-
return s(e), r;
|
|
4
|
-
}, b = "__proxyFunctionPort__", j = (e) => {
|
|
5
|
-
const { port1: r, port2: s } = new MessageChannel();
|
|
6
|
-
return r.addEventListener("message", async (a) => {
|
|
7
|
-
try {
|
|
8
|
-
const i = await e(...a.data), o = p(i), n = g(o);
|
|
9
|
-
r.postMessage({ result: o }, { transfer: n });
|
|
10
|
-
} catch (i) {
|
|
11
|
-
r.postMessage({ error: i });
|
|
12
|
-
}
|
|
13
|
-
}), r.start(), s;
|
|
14
|
-
}, p = (e) => h(e) || u(e) ? e : typeof e == "function" ? { [b]: j(e) } : Array.isArray(e) ? e.map(p) : e && typeof e == "object" ? Object.fromEntries(
|
|
15
|
-
Object.entries(e).map(([r, s]) => [
|
|
16
|
-
r,
|
|
17
|
-
p(s)
|
|
18
|
-
])
|
|
19
|
-
) : e, w = (e) => (...r) => new Promise((s, a) => {
|
|
20
|
-
const i = p(r), o = g(i), n = (t) => {
|
|
21
|
-
t.data.error ? a(t.data.error) : s(d(t.data.result)), e.removeEventListener("message", n);
|
|
22
|
-
};
|
|
23
|
-
e.addEventListener("message", n), e.start(), e.postMessage(i, { transfer: o });
|
|
24
|
-
}), d = (e) => h(e) || u(e) ? e : e && typeof e == "object" && e[b] ? w(e[b]) : Array.isArray(e) ? e.map(p) : e && typeof e == "object" ? Object.fromEntries(
|
|
25
|
-
Object.entries(e).map(([r, s]) => [
|
|
26
|
-
r,
|
|
27
|
-
d(s)
|
|
28
|
-
])
|
|
29
|
-
) : e, O = ({
|
|
30
|
-
target: e,
|
|
31
|
-
resolvers: r,
|
|
32
|
-
filter: s,
|
|
33
|
-
map: a,
|
|
34
|
-
key: i = m,
|
|
35
|
-
proxyTarget: o
|
|
36
|
-
}) => {
|
|
37
|
-
const n = (t) => {
|
|
38
|
-
if (!t.data || typeof t.data != "object" || t.data?.source !== i || s && !s(t))
|
|
39
|
-
return;
|
|
40
|
-
if (o) {
|
|
41
|
-
const { type: M, data: T, port: v } = t.data, A = g(T);
|
|
42
|
-
o.postMessage(
|
|
43
|
-
{
|
|
44
|
-
source: i,
|
|
45
|
-
type: M,
|
|
46
|
-
data: T,
|
|
47
|
-
port: v
|
|
48
|
-
},
|
|
49
|
-
{
|
|
50
|
-
targetOrigin: "*",
|
|
51
|
-
transfer: [v, ...A ?? []]
|
|
52
|
-
}
|
|
53
|
-
);
|
|
54
|
-
return;
|
|
55
|
-
}
|
|
56
|
-
const { type: l, data: y, port: c } = t.data, f = r[l];
|
|
57
|
-
if (!f)
|
|
58
|
-
throw new Error(`Osra received a message of type "${String(l)}" but no resolver was found for type.`);
|
|
59
|
-
a ? f(...a(y, { event: t, type: l, port: c })) : f(y, { event: t, type: l, port: c });
|
|
60
|
-
};
|
|
61
|
-
return e.addEventListener("message", n), {
|
|
62
|
-
listener: n,
|
|
63
|
-
resolvers: r
|
|
64
|
-
};
|
|
65
|
-
}, S = (e, { key: r = m } = { key: m }) => (s, a) => new Promise((i, o) => {
|
|
66
|
-
const { port1: n, port2: t } = new MessageChannel();
|
|
67
|
-
n.addEventListener(
|
|
68
|
-
"message",
|
|
69
|
-
({ data: c }) => {
|
|
70
|
-
if (c.error)
|
|
71
|
-
o(c.error);
|
|
72
|
-
else {
|
|
73
|
-
const f = d(c.result);
|
|
74
|
-
i(f);
|
|
75
|
-
}
|
|
76
|
-
n.close(), t.close();
|
|
77
|
-
},
|
|
78
|
-
{ once: !0 }
|
|
79
|
-
), n.start();
|
|
80
|
-
const l = p(a), y = g(l);
|
|
81
|
-
e.postMessage(
|
|
82
|
-
{
|
|
83
|
-
source: r,
|
|
84
|
-
type: s,
|
|
85
|
-
data: l,
|
|
86
|
-
port: t
|
|
87
|
-
},
|
|
88
|
-
{
|
|
89
|
-
targetOrigin: "*",
|
|
90
|
-
transfer: [t, ...y ?? []]
|
|
91
|
-
}
|
|
92
|
-
);
|
|
93
|
-
}), E = (e) => async (r, s) => {
|
|
94
|
-
const { port: a } = s, i = d(r);
|
|
95
|
-
try {
|
|
96
|
-
const o = await e(i, s), n = p(o), t = g(n);
|
|
97
|
-
return a.postMessage({ result: n }, { transfer: t }), a.close(), o;
|
|
98
|
-
} catch (o) {
|
|
99
|
-
throw a.postMessage({ error: o }), a.close(), o;
|
|
100
|
-
}
|
|
101
|
-
};
|
|
102
|
-
export {
|
|
103
|
-
O as C,
|
|
104
|
-
E as D,
|
|
105
|
-
S as R,
|
|
106
|
-
g as b
|
|
107
|
-
};
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{R as z,D as H}from"./index-9a320571.js";import{o as lt,k as ht,E as ge,m as zt,n as it,q as me,O as ve,s as Jt,v as xt,w as Ee,d as Dt,p as Se,b as we,x as _e,y as rt,z as et,A as It,t as Te,__tla as __tla_0}from"./settings-b282903e.js";import{v as be,P as Re}from"./index-8227e1be.js";let le,zn,Vn;let __tla=Promise.all([(()=>{try{return __tla_0}catch{}})()]).then(async()=>{function xe(t){return lt(function(e,n){var s=!1;e.subscribe(ht(n,function(i){s=!0,n.next(i)},function(){s||n.next(t),n.complete()}))})}function De(t){return t<=0?function(){return ge}:lt(function(e,n){var s=0;e.subscribe(ht(n,function(i){++s<=t&&(n.next(i),t<=s&&n.complete())}))})}function Ie(t){return t===void 0&&(t=Ae),lt(function(e,n){var s=!1;e.subscribe(ht(n,function(i){s=!0,n.next(i)},function(){return s?n.complete():n.error(t())}))})}function Ae(){return new zt}function At(t,e){var n=arguments.length>=2;return function(s){return s.pipe(t?it(function(i,r){return t(i,r,s)}):me,De(1),n?xe(e):Ie(function(){return new zt}))}}function ke(){if(typeof globalThis<"u")return globalThis;if(typeof self<"u")return self;if(typeof window<"u")return window;if(typeof global<"u")return global}function Oe(){const t=ke();if(t.__xstate__)return t.__xstate__}const $e=t=>{if(typeof window>"u")return;const e=Oe();e&&e.register(t)};class kt{constructor(e){this._process=e,this._active=!1,this._current=null,this._last=null}start(){this._active=!0,this.flush()}clear(){this._current&&(this._current.next=null,this._last=this._current)}enqueue(e){const n={value:e,next:null};if(this._current){this._last.next=n,this._last=n;return}this._current=n,this._last=n,this._active&&this.flush()}flush(){for(;this._current;){const e=this._current;this._process(e.value),this._current=e.next}this._last=null}}const q=".",Me="",Gt="",Le="#",Fe="*",Kt="xstate.init",Ce="xstate.error",C="xstate.stop";function Ne(t,e){const n=e?`#${e}`:"";return{type:`xstate.after(${t})${n}`}}function ot(t,e){return{type:`xstate.done.state.${t}`,output:e}}function je(t,e){return{type:`xstate.done.actor.${t}`,output:e}}function k(t,e){return{type:`xstate.error.actor.${t}`,data:e}}function Vt(t){return{type:Kt,input:t}}function x(t){setTimeout(()=>{throw t})}const Pe=(()=>typeof Symbol=="function"&&Symbol.observable||"@@observable")();let Ue=0;function He(t){const e=new Map,n=new Map,s=new WeakMap,i=new Set,r={_bookId:()=>`x:${Ue++}`,_register:(o,a)=>(e.set(o,a),o),_unregister:o=>{e.delete(o.sessionId);const a=s.get(o);a!==void 0&&(n.delete(a),s.delete(o))},get:o=>n.get(o),_set:(o,a)=>{const c=n.get(o);if(c&&c!==a)throw new Error(`Actor with system ID '${o}' already exists.`);n.set(o,a),s.set(a,o)},inspect:o=>{i.add(o)},_sendInspectionEvent:o=>{const a={...o,rootId:t.sessionId};i.forEach(c=>c.next?.(a))},_relay:(o,a,c)=>{r._sendInspectionEvent({type:"@xstate.event",sourceRef:o,actorRef:a,event:c}),a._send(c)}};return r}function qt(t,e){const n=Ot(t),s=Ot(e);return typeof s=="string"?typeof n=="string"?s===n:!1:typeof n=="string"?n in s:Object.keys(n).every(i=>i in s?qt(n[i],s[i]):!1)}function Yt(t){try{return Qt(t)?t:t.split(q)}catch{throw new Error(`'${t}' is not a valid state path.`)}}function Ot(t){if(wn(t))return t.value;if(typeof t!="string")return t;const e=Yt(t);return Be(e)}function Be(t){if(t.length===1)return t[0];const e={};let n=e;for(let s=0;s<t.length-1;s++)if(s===t.length-2)n[t[s]]=t[s+1];else{const i=n;n={},i[t[s]]=n}return e}function $t(t,e){const n={},s=Object.keys(t);for(let i=0;i<s.length;i++){const r=s[i];n[r]=e(t[r],r,t,i)}return n}function Xt(t){return[].concat(...t)}function Zt(t){return Qt(t)?t:[t]}function S(t){return t===void 0?[]:Zt(t)}function at(t,e,n,s){return typeof t=="function"?t({context:e,event:n,self:s}):t}function Qt(t){return Array.isArray(t)}function We(t){return t.type.startsWith("xstate.error.actor")}function I(t){return Zt(t).map(e=>typeof e>"u"||typeof e=="string"?{target:e}:e)}function te(t){if(!(t===void 0||t===Me))return S(t)}function Mt(t,e,n){const s=typeof t=="object",i=s?t:void 0;return{next:(s?t.next:t)?.bind(i),error:(s?t.error:e)?.bind(i),complete:(s?t.complete:n)?.bind(i)}}function Lt(t,e){return`${t}[${e}]`}function pt(t,e){if(e.startsWith("xstate#")){const[,n]=e.match(/\[(\d+)\]$/),i=t.getStateNodeById(e.slice(7,-(n.length+2))).config.invoke;return(Array.isArray(i)?i[n]:i).src}return t.implementations.actors[e]}function ze(t){return[...new Set(Xt([...t._nodes.map(e=>e.ownEvents)]))]}const yt=1;let m=function(t){return t[t.NotStarted=0]="NotStarted",t[t.Running=1]="Running",t[t.Stopped=2]="Stopped",t}({});const Je={clock:{setTimeout:(t,e)=>setTimeout(t,e),clearTimeout:t=>clearTimeout(t)},logger:console.log.bind(console),devTools:!1};class Ge{constructor(e,n){this.logic=e,this._state=void 0,this.clock=void 0,this.options=void 0,this.id=void 0,this.mailbox=new kt(this._process.bind(this)),this.delayedEventsMap={},this.observers=new Set,this.logger=void 0,this._processingStatus=m.NotStarted,this._parent=void 0,this._syncSnapshot=void 0,this.ref=void 0,this._actorScope=void 0,this._systemId=void 0,this.sessionId=void 0,this.system=void 0,this._doneEvent=void 0,this.src=void 0,this._deferred=[];const s={...Je,...n},{clock:i,logger:r,parent:o,syncSnapshot:a,id:c,systemId:u,inspect:l}=s;this.system=o?.system??He(this),l&&!o&&this.system.inspect(Mt(l)),this.sessionId=this.system._bookId(),this.id=c??this.sessionId,this.logger=r,this.clock=i,this._parent=o,this._syncSnapshot=a,this.options=s,this.src=s.src??e,this.ref=this,this._actorScope={self:this,id:this.id,sessionId:this.sessionId,logger:this.logger,defer:f=>{this._deferred.push(f)},system:this.system,stopChild:f=>{if(f._parent!==this)throw new Error(`Cannot stop child actor ${f.id} of ${this.id} because it is not a child`);f._stop()}},this.send=this.send.bind(this),this.system._sendInspectionEvent({type:"@xstate.actor",actorRef:this}),u&&(this._systemId=u,this.system._set(u,this)),this._initState(n?.state),u&&this._state.status!=="active"&&this.system._unregister(this)}_initState(e){this._state=e?this.logic.restoreState?this.logic.restoreState(e,this._actorScope):e:this.logic.getInitialState(this._actorScope,this.options?.input)}update(e,n){this._state=e;let s;for(;s=this._deferred.shift();)s();for(const i of this.observers)try{i.next?.(e)}catch(r){x(r)}switch(this._state.status){case"done":this._stopProcedure(),this._complete(),this._doneEvent=je(this.id,this._state.output),this._parent&&this.system._relay(this,this._parent,this._doneEvent);break;case"error":this._stopProcedure(),this._error(this._state.error),this._parent&&this.system._relay(this,this._parent,k(this.id,this._state.error));break}this.system._sendInspectionEvent({type:"@xstate.snapshot",actorRef:this,event:n,snapshot:e})}subscribe(e,n,s){const i=Mt(e,n,s);if(this._processingStatus!==m.Stopped)this.observers.add(i);else try{i.complete?.()}catch(r){x(r)}return{unsubscribe:()=>{this.observers.delete(i)}}}start(){if(this._processingStatus===m.Running)return this;this._syncSnapshot&&this.subscribe({next:s=>{s.status==="active"&&this._parent.send({type:`xstate.snapshot.${this.id}`,snapshot:s})},error:()=>{}}),this.system._register(this.sessionId,this),this._systemId&&this.system._set(this._systemId,this),this._processingStatus=m.Running;const e=Vt(this.options.input);switch(this.system._sendInspectionEvent({type:"@xstate.event",sourceRef:this._parent,actorRef:this,event:e}),this._state.status){case"done":this.update(this._state,e);case"error":return this}if(this.logic.start)try{this.logic.start(this._state,this._actorScope)}catch(s){return this._stopProcedure(),this._error(s),this._parent?.send(k(this.id,s)),this}return this.update(this._state,e),this.options.devTools&&this.attachDevTools(),this.mailbox.start(),this}_process(e){let n,s;try{n=this.logic.transition(this._state,e,this._actorScope)}catch(i){s={err:i}}if(s){const{err:i}=s;this._stopProcedure(),this._error(i),this._parent?.send(k(this.id,i));return}this.update(n,e),e.type===C&&(this._stopProcedure(),this._complete())}_stop(){return this._processingStatus===m.Stopped?this:(this.mailbox.clear(),this._processingStatus===m.NotStarted?(this._processingStatus=m.Stopped,this):(this.mailbox.enqueue({type:C}),this))}stop(){if(this._parent)throw new Error("A non-root actor cannot be stopped directly.");return this._stop()}_complete(){for(const e of this.observers)try{e.complete?.()}catch(n){x(n)}this.observers.clear()}_error(e){if(!this.observers.size){this._parent||x(e);return}let n=!1;for(const s of this.observers){const i=s.error;n||=!i;try{i?.(e)}catch(r){x(r)}}this.observers.clear(),n&&x(e)}_stopProcedure(){if(this._processingStatus!==m.Running)return this;for(const e of Object.keys(this.delayedEventsMap))this.clock.clearTimeout(this.delayedEventsMap[e]);return this.mailbox.clear(),this.mailbox=new kt(this._process.bind(this)),this._processingStatus=m.Stopped,this.system._unregister(this),this}_send(e){this._processingStatus!==m.Stopped&&this.mailbox.enqueue(e)}send(e){this.system._relay(void 0,this,e)}delaySend(e){const{event:n,id:s,delay:i}=e,r=this.clock.setTimeout(()=>{this.system._relay(this,e.to??this,n)},i);s&&(this.delayedEventsMap[s]=r)}cancel(e){this.clock.clearTimeout(this.delayedEventsMap[e]),delete this.delayedEventsMap[e]}attachDevTools(){const{devTools:e}=this.options;e&&(typeof e=="function"?e:$e)(this)}toJSON(){return{xstate$$type:yt,id:this.id}}getPersistedState(e){return this.logic.getPersistedState(this._state,e)}[Pe](){return this}getSnapshot(){return this._state}}function N(t,e){return new Ge(t,e)}function Ke(t,e,n,s,{sendId:i}){const r=typeof i=="function"?i(n,s):i;return[e,r]}function Ve(t,e){t.self.cancel(e)}function qe(t){function e(n,s){}return e.type="xstate.cancel",e.sendId=t,e.resolve=Ke,e.execute=Ve,e}function Ye(t,e,n,s,{id:i,systemId:r,src:o,input:a,syncSnapshot:c}){const u=typeof o=="string"?pt(e.machine,o):o,l=typeof i=="function"?i(n):i;let f;return u&&(f=N(u,{id:l,src:o,parent:t?.self,syncSnapshot:c,systemId:r,input:typeof a=="function"?a({context:e.context,event:n.event,self:t?.self}):a})),[b(e,{children:{...e.children,[l]:f}}),{id:i,actorRef:f}]}function Xe(t,{id:e,actorRef:n}){n&&t.defer(()=>{if(n._processingStatus!==m.Stopped)try{n.start?.()}catch(s){t.self.send(k(e,s));return}})}function Ze(...[t,{id:e,systemId:n,input:s,syncSnapshot:i=!1}={}]){function r(o,a){}return r.type="xstate.spawnChild",r.id=e,r.systemId=n,r.src=t,r.input=s,r.syncSnapshot=i,r.resolve=Ye,r.execute=Xe,r}function Qe(t,e,n,s,{actorRef:i}){const r=typeof i=="function"?i(n,s):i,o=typeof r=="string"?e.children[r]:r;let a=e.children;return o&&(a={...a},delete a[o.id]),[b(e,{children:a}),o]}function tn(t,e){if(e){if(t.system._unregister(e),e._processingStatus!==m.Running){t.stopChild(e);return}t.defer(()=>{t.stopChild(e)})}}function ee(t){function e(n,s){}return e.type="xstate.stopChild",e.actorRef=t,e.resolve=Qe,e.execute=tn,e}function en(t,{context:e,event:n},{guards:s}){return s.some(i=>Y(i,e,n,t))}function Ft(t){function e(n,s){return!1}return e.check=en,e.guards=t,e}function Y(t,e,n,s){const{machine:i}=s,r=typeof t=="function",o=r?t:i.implementations.guards[typeof t=="string"?t:t.type];if(!r&&!o)throw new Error(`Guard '${typeof t=="string"?t:t.type}' is not implemented.'.`);if(typeof o!="function")return Y(o,e,n,s);const a={context:e,event:n},c=r||typeof t=="string"?void 0:"params"in t?typeof t.params=="function"?t.params({context:e,event:n}):t.params:void 0;return"check"in o?o.check(s,a,o):o(a,c)}const gt=t=>t.type==="atomic"||t.type==="final";function O(t){return Object.values(t.states).filter(e=>e.type!=="history")}function P(t,e){const n=[];if(e===t)return n;let s=t.parent;for(;s&&s!==e;)n.push(s),s=s.parent;return n}function J(t){const e=new Set(t),n=se(e);for(const s of e)if(s.type==="compound"&&(!n.get(s)||!n.get(s).length))Ct(s).forEach(i=>e.add(i));else if(s.type==="parallel"){for(const i of O(s))if(i.type!=="history"&&!e.has(i)){const r=Ct(i);for(const o of r)e.add(o)}}for(const s of e){let i=s.parent;for(;i;)e.add(i),i=i.parent}return e}function ne(t,e){const n=e.get(t);if(!n)return{};if(t.type==="compound"){const i=n[0];if(i){if(gt(i))return i.key}else return{}}const s={};for(const i of n)s[i.key]=ne(i,e);return s}function se(t){const e=new Map;for(const n of t)e.has(n)||e.set(n,[]),n.parent&&(e.has(n.parent)||e.set(n.parent,[]),e.get(n.parent).push(n));return e}function ie(t,e){const n=J(e);return ne(t,se(n))}function mt(t,e){return e.type==="compound"?O(e).some(n=>n.type==="final"&&t.has(n)):e.type==="parallel"?O(e).every(n=>mt(t,n)):e.type==="final"}const X=t=>t[0]===Le;function nn(t,e){return t.transitions.get(e)||[...t.transitions.keys()].filter(s=>{if(s===Fe)return!0;if(!s.endsWith(".*"))return!1;const i=s.split("."),r=e.split(".");for(let o=0;o<i.length;o++){const a=i[o],c=r[o];if(a==="*")return o===i.length-1;if(a!==c)return!1}return!0}).sort((s,i)=>i.length-s.length).flatMap(s=>t.transitions.get(s))}function sn(t){const e=t.config.after;if(!e)return[];const n=(i,r)=>{const o=typeof i=="function"?`${t.id}:delay[${r}]`:i,a=Ne(o,t.id),c=a.type;return t.entry.push(kn(a,{id:c,delay:i})),t.exit.push(qe(c)),c};return Object.keys(e).flatMap((i,r)=>{const o=e[i],a=typeof o=="string"?{target:o}:o,c=isNaN(+i)?i:+i,u=n(c,r);return S(a).map(l=>({...l,event:u,delay:c}))}).map(i=>{const{delay:r}=i;return{..._(t,i.event,i),delay:r}})}function _(t,e,n){const s=te(n.target),i=n.reenter??!1,r=an(t,s),o={...n,actions:S(n.actions),guard:n.guard,target:r,source:t,reenter:i,eventType:e,toJSON:()=>({...o,source:`#${t.id}`,target:r?r.map(a=>`#${a.id}`):void 0})};return o}function rn(t){const e=new Map;if(t.config.on)for(const n of Object.keys(t.config.on)){if(n===Gt)throw new Error('Null events ("") cannot be specified as a transition key. Use `always: { ... }` instead.');const s=t.config.on[n];e.set(n,I(s).map(i=>_(t,n,i)))}if(t.config.onDone){const n=`xstate.done.state.${t.id}`;e.set(n,I(t.config.onDone).map(s=>_(t,n,s)))}for(const n of t.invoke){if(n.onDone){const s=`xstate.done.actor.${n.id}`;e.set(s,I(n.onDone).map(i=>_(t,s,i)))}if(n.onError){const s=`xstate.error.actor.${n.id}`;e.set(s,I(n.onError).map(i=>_(t,s,i)))}if(n.onSnapshot){const s=`xstate.snapshot.${n.id}`;e.set(s,I(n.onSnapshot).map(i=>_(t,s,i)))}}for(const n of t.after){let s=e.get(n.eventType);s||(s=[],e.set(n.eventType,s)),s.push(n)}return e}function on(t,e){const n=typeof e=="string"?t.states[e]:e?t.states[e.target]:void 0;if(!n&&e)throw new Error(`Initial state node "${e}" not found on parent state node #${t.id}`);const s={source:t,actions:!e||typeof e=="string"?[]:S(e.actions),eventType:null,reenter:!1,target:n?[n]:[],toJSON:()=>({...s,source:`#${t.id}`,target:n?[`#${n.id}`]:[]})};return s}function an(t,e){if(e!==void 0)return e.map(n=>{if(typeof n!="string")return n;if(X(n))return t.machine.getStateNodeById(n);const s=n[0]===q;if(s&&!t.parent)return G(t,n.slice(1));const i=s?t.key+n:n;if(t.parent)try{return G(t.parent,i)}catch(r){throw new Error(`Invalid transition definition for state node '${t.id}':
|
|
2
|
-
${r.message}`)}else throw new Error(`Invalid target: "${n}" is not a valid target from the root node. Did you mean ".${n}"?`)})}function re(t){const e=te(t.config.target);return e?{target:e.map(n=>typeof n=="string"?G(t.parent,n):n)}:t.parent.initial}function T(t){return t.type==="history"}function Ct(t){const e=oe(t);for(const n of e)for(const s of P(n,t))e.add(s);return e}function oe(t){const e=new Set;function n(s){if(!e.has(s)){if(e.add(s),s.type==="compound")n(s.initial.target[0]);else if(s.type==="parallel")for(const i of O(s))n(i)}}return n(t),e}function $(t,e){if(X(e))return t.machine.getStateNodeById(e);if(!t.states)throw new Error(`Unable to retrieve child state '${e}' from '${t.id}'; no child states exist.`);const n=t.states[e];if(!n)throw new Error(`Child state '${e}' does not exist on '${t.id}'`);return n}function G(t,e){if(typeof e=="string"&&X(e))try{return t.machine.getStateNodeById(e)}catch{}const n=Yt(e).slice();let s=t;for(;n.length;){const i=n.shift();if(!i.length)break;s=$(s,i)}return s}function K(t,e){if(typeof e=="string")return[t,t.states[e]];const n=Object.keys(e),s=n.map(i=>$(t,i)).filter(Boolean);return[t.machine.root,t].concat(s,n.reduce((i,r)=>{const o=$(t,r);if(!o)return i;const a=K(o,e[r]);return i.concat(a)},[]))}function cn(t,e,n,s){const r=$(t,e).next(n,s);return!r||!r.length?t.next(n,s):r}function dn(t,e,n,s){const i=Object.keys(e),r=$(t,i[0]),o=vt(r,e[i[0]],n,s);return!o||!o.length?t.next(n,s):o}function un(t,e,n,s){const i=[];for(const r of Object.keys(e)){const o=e[r];if(!o)continue;const a=$(t,r),c=vt(a,o,n,s);c&&i.push(...c)}return i.length?i:t.next(n,s)}function vt(t,e,n,s){return typeof e=="string"?cn(t,e,n,s):Object.keys(e).length===1?dn(t,e,n,s):un(t,e,n,s)}function fn(t){return Object.keys(t.states).map(e=>t.states[e]).filter(e=>e.type==="history")}function w(t,e){let n=t;for(;n.parent&&n.parent!==e;)n=n.parent;return n.parent===e}function ln(t,e){const n=new Set(t),s=new Set(e);for(const i of n)if(s.has(i))return!0;for(const i of s)if(n.has(i))return!0;return!1}function ae(t,e,n){const s=new Set;for(const i of t){let r=!1;const o=new Set;for(const a of s)if(ln(ct([i],e,n),ct([a],e,n)))if(w(i.source,a.source))o.add(a);else{r=!0;break}if(!r){for(const a of o)s.delete(a);s.add(i)}}return Array.from(s)}function hn(t){const[e,...n]=t;for(const s of P(e,void 0))if(n.every(i=>w(i,s)))return s}function Et(t,e){if(!t.target)return[];const n=new Set;for(const s of t.target)if(T(s))if(e[s.id])for(const i of e[s.id])n.add(i);else for(const i of Et(re(s),e))n.add(i);else n.add(s);return[...n]}function ce(t,e){const n=Et(t,e);if(!n)return;if(!t.reenter&&n.every(i=>i===t.source||w(i,t.source)))return t.source;const s=hn(n.concat(t.source));if(s)return s;if(!t.reenter)return t.source.machine.root}function ct(t,e,n){const s=new Set;for(const i of t)if(i.target?.length){const r=ce(i,n);i.reenter&&i.source===r&&s.add(r);for(const o of e)w(o,r)&&s.add(o)}return[...s]}function pn(t,e){if(t.length!==e.size)return!1;for(const n of t)if(!e.has(n))return!1;return!0}function dt(t,e,n,s,i,r){if(!t.length)return e;const o=new Set(e._nodes);let a=e.historyValue;const c=ae(t,o,a);let u=e;i||([u,a]=vn(u,s,n,c,o,a,r)),u=M(u,s,n,c.flatMap(f=>f.actions),r),u=gn(u,s,n,c,o,r,a,i);const l=[...o];u.status==="done"&&(u=M(u,s,n,l.sort((f,d)=>d.order-f.order).flatMap(f=>f.exit),r));try{return a===e.historyValue&&pn(e._nodes,o)?u:b(u,{_nodes:l,historyValue:a})}catch(f){throw f}}function yn(t,e,n,s,i){if(!s.output)return;const r=ot(i.id,i.output&&i.parent?at(i.output,t.context,e,n.self):void 0);return at(s.output,t.context,r,n.self)}function gn(t,e,n,s,i,r,o,a){let c=t;const u=new Set,l=new Set;mn(s,o,l,u),a&&l.add(t.machine.root);const f=new Set;for(const d of[...u].sort((h,p)=>h.order-p.order)){i.add(d);const h=[];h.push(...d.entry);for(const p of d.invoke)h.push(Ze(p.src,{...p,syncSnapshot:!!p.onSnapshot}));if(l.has(d)){const p=d.initial.actions;h.push(...p)}if(c=M(c,e,n,h,r,d.invoke.map(p=>p.id)),d.type==="final"){const p=d.parent;let g=p?.type==="parallel"?p:p?.parent,v=g||d;for(p?.type==="compound"&&r.push(ot(p.id,d.output?at(d.output,c.context,e,n.self):void 0));g?.type==="parallel"&&!f.has(g)&&mt(i,g);)f.add(g),r.push(ot(g.id)),v=g,g=g.parent;if(g)continue;c=b(c,{status:"done",output:yn(c,e,n,c.machine.root,v)})}}return c}function mn(t,e,n,s){for(const i of t){const r=ce(i,e);for(const a of i.target||[])!T(a)&&(i.source!==a||i.source!==r||i.reenter)&&(s.add(a),n.add(a)),A(a,e,n,s);const o=Et(i,e);for(const a of o){const c=P(a,r);r?.type==="parallel"&&c.push(r),de(s,e,n,c,!i.source.parent&&i.reenter?void 0:r)}}}function A(t,e,n,s){if(T(t))if(e[t.id]){const i=e[t.id];for(const r of i)s.add(r),A(r,e,n,s);for(const r of i)nt(r,t.parent,s,e,n)}else{const i=re(t);for(const r of i.target)s.add(r),i===t.parent?.initial&&n.add(t.parent),A(r,e,n,s);for(const r of i.target)nt(r,t,s,e,n)}else if(t.type==="compound"){const[i]=t.initial.target;T(i)||(s.add(i),n.add(i)),A(i,e,n,s),nt(i,t,s,e,n)}else if(t.type==="parallel")for(const i of O(t).filter(r=>!T(r)))[...s].some(r=>w(r,i))||(T(i)||(s.add(i),n.add(i)),A(i,e,n,s))}function de(t,e,n,s,i){for(const r of s)if((!i||w(r,i))&&t.add(r),r.type==="parallel")for(const o of O(r).filter(a=>!T(a)))[...t].some(a=>w(a,o))||(t.add(o),A(o,e,n,t))}function nt(t,e,n,s,i){de(n,s,i,P(t,e))}function vn(t,e,n,s,i,r,o){let a=t;const c=ct(s,i,r);c.sort((l,f)=>f.order-l.order);let u;for(const l of c)for(const f of fn(l)){let d;f.history==="deep"?d=h=>gt(h)&&w(h,l):d=h=>h.parent===l,u??={...r},u[f.id]=Array.from(i).filter(d)}for(const l of c)a=M(a,e,n,[...l.exit,...l.invoke.map(f=>ee(f.id))],o),i.delete(l);return[a,u||r]}function ue(t,e,n,s,i,r){const{machine:o}=t;let a=t;for(const c of s){const u=typeof c=="function",l=u?c:(o.implementations.actions[typeof c=="string"?c:c.type]);if(!l)continue;const f={context:a.context,event:e,self:n?.self,system:n?.system},d=u||typeof c=="string"?void 0:"params"in c?typeof c.params=="function"?c.params({context:a.context,event:e}):c.params:void 0;if(!("resolve"in l)){n?.self._processingStatus===m.Running?l(f,d):n?.defer(()=>{l(f,d)});continue}const h=l,[p,g,v]=h.resolve(n,a,f,d,l,i);a=p,"retryResolve"in h&&r?.push([h,g]),"execute"in h&&(n?.self._processingStatus===m.Running?h.execute(n,g):n?.defer(h.execute.bind(null,n,g))),v&&(a=ue(a,e,n,v,i,r))}return a}function M(t,e,n,s,i,r){const o=r?[]:void 0,a=ue(t,e,n,s,{internalQueue:i,deferredActorIds:r},o);return o?.forEach(([c,u])=>{c.retryResolve(n,a,u)}),a}function st(t,e,n,s=[]){let i=t;const r=[];if(e.type===C)return i=b(Nt(i,e,n),{status:"stopped"}),r.push(i),{state:i,microstates:r};let o=e;if(o.type!==Kt){const c=jt(o,i);i=dt(c,t,n,o,!1,s),r.push(i)}let a=!0;for(;i.status==="active";){let c=a?En(i,o):[];const u=c.length?i:void 0;if(!c.length){if(!s.length)break;o=s.shift(),c=jt(o,i)}i=dt(c,i,n,o,!1,s),a=i!==u,r.push(i)}return i.status!=="active"&&Nt(i,o,n),{state:i,microstates:r}}function Nt(t,e,n){return M(t,e,n,Object.values(t.children).map(s=>ee(s)),[])}function jt(t,e){return e.machine.getTransitionData(e,t)}function En(t,e){const n=new Set,s=t._nodes.filter(gt);for(const i of s)t:for(const r of[i].concat(P(i,void 0)))if(r.always){for(const o of r.always)if(o.guard===void 0||Y(o.guard,t.context,e,t)){n.add(o);break t}}return ae(Array.from(n),new Set(t._nodes),t.historyValue)}function Sn(t,e){const n=J(K(t,e));return ie(t,[...n])}function wn(t){return!!t&&typeof t=="object"&&"machine"in t&&"value"in t}const _n=function(e){return qt(e,this.value)},Tn=function(e){return this.tags.has(e)},bn=function(e){const n=this.machine.getTransitionData(this,e);return!!n?.length&&n.some(s=>s.target!==void 0||s.actions.length)},Rn=function(){const{_nodes:e,tags:n,machine:s,getMeta:i,toJSON:r,can:o,hasTag:a,matches:c,...u}=this;return{...u,tags:Array.from(n)}},xn=function(){return this._nodes.reduce((e,n)=>(n.meta!==void 0&&(e[n.id]=n.meta),e),{})};function B(t,e){return{status:t.status,output:t.output,error:t.error,machine:e,context:t.context,_nodes:t._nodes,value:ie(e.root,t._nodes),tags:new Set(Xt(t._nodes.map(n=>n.tags))),children:t.children,historyValue:t.historyValue||{},matches:_n,hasTag:Tn,can:bn,getMeta:xn,toJSON:Rn}}function b(t,e={}){return B({...t,...e},t.machine)}function Dn(t,e){const{_nodes:n,tags:s,machine:i,children:r,context:o,can:a,hasTag:c,matches:u,getMeta:l,toJSON:f,...d}=t,h={};for(const g in r){const v=r[g];h[g]={state:v.getPersistedState(e),src:v.src,systemId:v._systemId,syncSnapshot:v._syncSnapshot}}return{...d,context:fe(o),children:h}}function fe(t){let e;for(const n in t){const s=t[n];if(s&&typeof s=="object")if("sessionId"in s&&"send"in s&&"ref"in s)e??=Array.isArray(t)?t.slice():{...t},e[n]={xstate$$type:yt,id:s.id};else{const i=fe(s);i!==s&&(e??=Array.isArray(t)?t.slice():{...t},e[n]=i)}}return e??t}function In(t,e,n,s,{event:i,id:r,delay:o},{internalQueue:a}){const c=e.machine.implementations.delays;if(typeof i=="string")throw new Error(`Only event objects may be used with raise; use raise({ type: "${i}" }) instead`);const u=typeof i=="function"?i(n,s):i;let l;if(typeof o=="string"){const f=c&&c[o];l=typeof f=="function"?f(n,s):f}else l=typeof o=="function"?o(n,s):o;return typeof l!="number"&&a.push(u),[e,{event:u,id:r,delay:l}]}function An(t,e){if(typeof e.delay=="number"){t.self.delaySend(e);return}}function kn(t,e){function n(s,i){}return n.type="xstate.raise",n.event=t,n.id=e?.id,n.delay=e?.delay,n.resolve=In,n.execute=An,n}function j(t){const e="$$xstate.next",n="$$xstate.error",s="$$xstate.complete";return{config:t,transition:(r,o,{self:a,id:c,defer:u,system:l})=>{if(r.status!=="active")return r;switch(o.type){case e:return{...r,context:o.data};case n:return{...r,status:"error",error:o.data,input:void 0,_subscription:void 0};case s:return{...r,status:"done",input:void 0,_subscription:void 0};case C:return r._subscription.unsubscribe(),{...r,status:"stopped",input:void 0,_subscription:void 0};default:return r}},getInitialState:(r,o)=>({status:"active",output:void 0,error:void 0,context:void 0,input:o,_subscription:void 0}),start:(r,{self:o,system:a})=>{r.status!=="done"&&(r._subscription=t({input:r.input,system:a,self:o}).subscribe({next:c=>{a._relay(o,o,{type:e,data:c})},error:c=>{a._relay(o,o,{type:n,data:c})},complete:()=>{a._relay(o,o,{type:s})}}))},getPersistedState:({_subscription:r,...o})=>o,restoreState:r=>({...r,_subscription:void 0})}}const Pt="$$xstate.resolve",Ut="$$xstate.reject";function W(t){return{config:t,transition:(n,s)=>{if(n.status!=="active")return n;switch(s.type){case Pt:{const i=s.data;return{...n,status:"done",output:i,input:void 0}}case Ut:return{...n,status:"error",error:s.data,input:void 0};case C:return{...n,status:"stopped",input:void 0};default:return n}},start:(n,{self:s,system:i})=>{if(n.status!=="active")return;Promise.resolve(t({input:n.input,system:i,self:s})).then(o=>{s.getSnapshot().status==="active"&&i._relay(s,s,{type:Pt,data:o})},o=>{s.getSnapshot().status==="active"&&i._relay(s,s,{type:Ut,data:o})})},getInitialState:(n,s)=>({status:"active",output:void 0,error:void 0,input:s}),getPersistedState:n=>n,restoreState:n=>n}}function On(t,{machine:e,context:n},s,i){const r=(o,a={})=>{const{systemId:c,input:u}=a;if(typeof o=="string"){const l=pt(e,o);if(!l)throw new Error(`Actor logic '${o}' not implemented in machine '${e.id}'`);const f=N(l,{id:a.id,parent:t.self,syncSnapshot:a.syncSnapshot,input:typeof u=="function"?u({context:n,event:s,self:t.self}):u,src:o,systemId:c});return i[f.id]=f,f}else return N(o,{id:a.id,parent:t.self,syncSnapshot:a.syncSnapshot,input:a.input,src:o,systemId:c})};return(o,a)=>{const c=r(o,a);return i[c.id]=c,t.defer(()=>{if(c._processingStatus!==m.Stopped)try{c.start?.()}catch(u){t.self.send(k(c.id,u));return}}),c}}function $n(t,e,n,s,{assignment:i}){if(!e.context)throw new Error("Cannot assign to undefined `context`. Ensure that `context` is defined in the machine config.");const r={},o={context:e.context,event:n.event,spawn:On(t,e,n.event,r),self:t?.self,system:t?.system};let a={};if(typeof i=="function")a=i(o,s);else for(const u of Object.keys(i)){const l=i[u];a[u]=typeof l=="function"?l(o,s):l}const c=Object.assign({},e.context,a);return[b(e,{context:c,children:Object.keys(r).length?{...e.children,...r}:e.children})]}function y(t){function e(n,s){}return e.type="xstate.assign",e.assignment=t,e.resolve=$n,e}let ut=function(t){return t.Parent="#_parent",t.Internal="#_internal",t}({});function Mn(t,e,n,s,{to:i,event:r,id:o,delay:a},c){const u=e.machine.implementations.delays;if(typeof r=="string")throw new Error(`Only event objects may be used with sendTo; use sendTo({ type: "${r}" }) instead`);const l=typeof r=="function"?r(n,s):r;let f;if(typeof a=="string"){const p=u&&u[a];f=typeof p=="function"?p(n,s):p}else f=typeof a=="function"?a(n,s):a;const d=typeof i=="function"?i(n,s):i;let h;if(typeof d=="string"){if(d===ut.Parent?h=t?.self._parent:d===ut.Internal?h=t?.self:d.startsWith("#_")?h=e.children[d.slice(2)]:h=c.deferredActorIds?.includes(d)?d:e.children[d],!h)throw new Error(`Unable to send event to actor '${d}' from machine '${e.machine.id}'.`)}else h=d||t?.self;return[e,{to:h,event:l,id:o,delay:f}]}function Ln(t,e,n){typeof n.to=="string"&&(n.to=e.children[n.to])}function Fn(t,e){if(typeof e.delay=="number"){t.self.delaySend(e);return}t.defer(()=>{const{to:n,event:s}=e;t?.system._relay(t.self,n,s.type===Ce?k(t.self.id,s.data):s)})}function Cn(t,e,n){function s(i,r){}return s.type="xstate.sendTo",s.to=t,s.event=e,s.id=n?.id,s.delay=n?.delay,s.resolve=Mn,s.retryResolve=Ln,s.execute=Fn,s}function F(t,e){return Cn(ut.Parent,t,e)}const Ht=new WeakMap;function D(t,e,n){let s=Ht.get(t);return s?e in s||(s[e]=n()):(s={[e]:n()},Ht.set(t,s)),s[e]}const Nn={},L=t=>typeof t=="string"?{type:t}:typeof t=="function"?"resolve"in t?{type:t.type}:{type:t.name}:t;class St{constructor(e,n){if(this.config=e,this.key=void 0,this.id=void 0,this.type=void 0,this.path=void 0,this.states=void 0,this.history=void 0,this.entry=void 0,this.exit=void 0,this.parent=void 0,this.machine=void 0,this.meta=void 0,this.output=void 0,this.order=-1,this.description=void 0,this.tags=[],this.transitions=void 0,this.always=void 0,this.parent=n._parent,this.key=n._key,this.machine=n._machine,this.path=this.parent?this.parent.path.concat(this.key):[],this.id=this.config.id||[this.machine.id,...this.path].join(q),this.type=this.config.type||(this.config.states&&Object.keys(this.config.states).length?"compound":this.config.history?"history":"atomic"),this.description=this.config.description,this.order=this.machine.idMap.size,this.machine.idMap.set(this.id,this),this.states=this.config.states?$t(this.config.states,(s,i)=>new St(s,{_parent:this,_key:i,_machine:this.machine})):Nn,this.type==="compound"&&!this.config.initial)throw new Error(`No initial state specified for compound state node "#${this.id}". Try adding { initial: "${Object.keys(this.states)[0]}" } to the state config.`);this.history=this.config.history===!0?"shallow":this.config.history||!1,this.entry=S(this.config.entry).slice(),this.exit=S(this.config.exit).slice(),this.meta=this.config.meta,this.output=this.type==="final"||!this.parent?this.config.output:void 0,this.tags=S(e.tags).slice()}_initialize(){this.transitions=rn(this),this.config.always&&(this.always=I(this.config.always).map(e=>_(this,Gt,e))),Object.keys(this.states).forEach(e=>{this.states[e]._initialize()})}get definition(){return{id:this.id,key:this.key,version:this.machine.version,type:this.type,initial:this.initial?{target:this.initial.target,source:this,actions:this.initial.actions.map(L),eventType:null,reenter:!1,toJSON:()=>({target:this.initial.target.map(e=>`#${e.id}`),source:`#${this.id}`,actions:this.initial.actions.map(L),eventType:null})}:void 0,history:this.history,states:$t(this.states,e=>e.definition),on:this.on,transitions:[...this.transitions.values()].flat().map(e=>({...e,actions:e.actions.map(L)})),entry:this.entry.map(L),exit:this.exit.map(L),meta:this.meta,order:this.order||-1,output:this.output,invoke:this.invoke,description:this.description,tags:this.tags}}toJSON(){return this.definition}get invoke(){return D(this,"invoke",()=>S(this.config.invoke).map((e,n)=>{const{src:s,systemId:i}=e,r=e.id||Lt(this.id,n),o=typeof s=="string"?s:`xstate#${Lt(this.id,n)}`;return{...e,src:o,id:r,systemId:i,toJSON(){const{onDone:a,onError:c,...u}=e;return{...u,type:"xstate.invoke",src:o,id:r}}}}))}get on(){return D(this,"on",()=>[...this.transitions].flatMap(([n,s])=>s.map(i=>[n,i])).reduce((n,[s,i])=>(n[s]=n[s]||[],n[s].push(i),n),{}))}get after(){return D(this,"delayedTransitions",()=>sn(this))}get initial(){return D(this,"initial",()=>on(this,this.config.initial))}next(e,n){const s=n.type,i=[];let r;const o=D(this,`candidates-${s}`,()=>nn(this,s));for(const a of o){const{guard:c}=a,u=e.context;let l=!1;try{l=!c||Y(c,u,n,e)}catch(f){const d=typeof c=="string"?c:typeof c=="object"?c.type:void 0;throw new Error(`Unable to evaluate guard ${d?`'${d}' `:""}in transition for event '${s}' in state node '${this.id}':
|
|
3
|
-
${f.message}`)}if(l){i.push(...a.actions),r=a;break}}return r?[r]:void 0}get events(){return D(this,"events",()=>{const{states:e}=this,n=new Set(this.ownEvents);if(e)for(const s of Object.keys(e)){const i=e[s];if(i.states)for(const r of i.events)n.add(`${r}`)}return Array.from(n)})}get ownEvents(){const e=new Set([...this.transitions.keys()].filter(n=>this.transitions.get(n).some(s=>!(!s.target&&!s.actions.length&&!s.reenter))));return Array.from(e)}}const jn="#";class wt{constructor(e,n){this.config=e,this.version=void 0,this.implementations=void 0,this.types=void 0,this.__xstatenode=!0,this.idMap=new Map,this.root=void 0,this.id=void 0,this.states=void 0,this.events=void 0,this.__TResolvedTypesMeta=void 0,this.id=e.id||"(machine)",this.implementations={actors:n?.actors??{},actions:n?.actions??{},delays:n?.delays??{},guards:n?.guards??{}},this.version=this.config.version,this.types=this.config.types??{},this.transition=this.transition.bind(this),this.getInitialState=this.getInitialState.bind(this),this.restoreState=this.restoreState.bind(this),this.start=this.start.bind(this),this.root=new St(e,{_key:this.id,_machine:this}),this.root._initialize(),this.states=this.root.states,this.events=this.root.events}provide(e){const{actions:n,guards:s,actors:i,delays:r}=this.implementations;return new wt(this.config,{actions:{...n,...e.actions},guards:{...s,...e.guards},actors:{...i,...e.actors},delays:{...r,...e.delays}})}resolveState(e){const n=Sn(this.root,e.value),s=J(K(this.root,n));return B({_nodes:[...s],context:e.context||{},children:{},status:mt(s,this.root)?"done":e.status||"active",output:e.output,error:e.error,historyValue:e.historyValue},this)}transition(e,n,s){if(We(n)&&!ze(e).some(r=>r===n.type))return b(e,{status:"error",error:n.data});const{state:i}=st(e,n,s);return i}microstep(e,n,s){return st(e,n,s).microstates}getTransitionData(e,n){return vt(this.root,e.value,e,n)||[]}getPreInitialState(e,n,s){const{context:i}=this.config,r=B({context:typeof i!="function"&&i?i:{},_nodes:[this.root],children:{},status:"active"},this);return typeof i=="function"?M(r,n,e,[y(({spawn:a,event:c})=>i({spawn:a,input:c.input}))],s):r}getInitialState(e,n){const s=Vt(n),i=[],r=this.getPreInitialState(e,s,i),o=dt([{target:[...oe(this.root)],source:this.root,reenter:!0,actions:[],eventType:null,toJSON:null}],r,e,s,!0,i),{state:a}=st(o,s,e,i);return a}start(e){Object.values(e.children).forEach(n=>{n.getSnapshot().status==="active"&&n.start()})}getStateNodeById(e){const n=e.split(q),s=n.slice(1),i=X(n[0])?n[0].slice(jn.length):n[0],r=this.idMap.get(i);if(!r)throw new Error(`Child state node '#${i}' does not exist on machine '${this.id}'`);return G(r,s)}get definition(){return this.root.definition}toJSON(){return this.definition}getPersistedState(e,n){return Dn(e,n)}restoreState(e,n){const s={},i=e.children;Object.keys(i).forEach(c=>{const u=i[c],l=u.state,f=u.src,d=typeof f=="string"?pt(this,f):f;if(!d)return;const h=N(d,{id:c,parent:n?.self,syncSnapshot:u.syncSnapshot,state:l,src:f,systemId:u.systemId});s[c]=h});const r=B({...e,children:s,_nodes:Array.from(J(K(this.root,e.value)))},this);let o=new Set;function a(c,u){if(!o.has(c)){o.add(c);for(let l in c){const f=c[l];if(f&&typeof f=="object"){if("xstate$$type"in f&&f.xstate$$type===yt){c[l]=u[f.id];continue}a(f,u)}}}}return a(r.context,s),r}}function _t(t,e){return new wt(t,e)}const Pn=(t,e)=>new ReadableStream({start(){this.reader=t.getReader()},async pull(n){const s=Date.now(),{done:i,value:r}=await this.reader.read();if(i){n.close();return}n.enqueue(r);const a=Date.now()-s,u=r.length/(e()??Number.MAX_VALUE)*1e3-a;u>0&&await new Promise(l=>setTimeout(l,u))},cancel(){this.reader?.cancel()}}),Un=t=>{if(t.length===0)return[];const e=t.sort((s,i)=>s.start-i.start),n=[e[0]];for(let s=1;s<e.length;s++){const i=e[s],r=n[n.length-1];i.start<=r.end+1?r.end=Math.max(r.end,i.end):n.push(i)}return n},Bt=5e3,Hn=_t({initial:"checkingFile",context:({input:t})=>({settingsDbDocument:t.settingsDbDocument,document:t.document,file:t.file,downloadedRanges:t.file.downloadedRanges??[],downloaded:t.file.downloaded??0,progress:t.file.progress??0,selected:t.file.selected??!1,priority:t.file.priority??0,length:t.file.length??0,offset:t.file.offset??0,path:t.file.path??"",pathArray:t.file.pathArray,name:t.file.name??"",index:t.file.index,status:t.file.status??"checking",streamBandwithLogs:t.file.streamBandwithLogs??[],downloadSpeed:t.file.downloadSpeed??0}),on:{"FILE.PAUSE":{target:".paused"},"FILE.RESUME":{target:".downloading"}},states:{checkingFile:{entry:F({type:"FILE.CHECKING_FILE"}),always:{target:"downloading",guard:({context:t})=>t?.selected===!0}},downloading:{entry:F({type:"FILE.DOWNLOADING"}),invoke:{input:t=>t,src:j(t=>new ve(e=>{const n={input:t.input.context},s=n.input.document;if(n.input.file.selected===!1)return e.complete();const r=n.input.file.downloadedRanges.sort((f,d)=>f.start-d.start).at(0)?.end||0;if(r===n.input.file.length){e.complete();return}let o=[...n.input.streamBandwithLogs],a=[...n.input.file.downloadedRanges.map(f=>({...f}))],c=!1,u,l=new Promise((f,d)=>{u=f});return be({magnet:s.state.magnet,path:n.input.file.pathArray.join("/"),offset:r}).then(async f=>{const d=await n.input.settingsDbDocument.getLatest();let h=d.downloadSpeedLimitEnabled,p=d.downloadSpeedLimit;d.$.subscribe(U=>{h=U.downloadSpeedLimitEnabled,p=U.downloadSpeedLimit});const v=Pn(f.body,()=>h?p:Number.MAX_VALUE).getReader(),{write:he,close:Z}=await z(le(),{key:"io-worker"})("openWriteStream",{filePath:`${n.input.document.infoHash}/${n.input.file.path}`,offset:r,size:n.input.file.length});u(Z);const Tt=async()=>{if(t.self.getSnapshot().status!=="active")return;if(c)return await v.cancel(),await Z(),e.error(err);const{done:U,value:bt}=await v.read();if(U)return await Z(),e.complete();const Q=bt.byteLength;try{await he(bt.buffer)}catch(E){return e.error(E)}const tt=a?.find(E=>E.start<=r&&E.end>=r);tt?tt.end=tt.end+Q:a=[...a,{start:r,end:r+Q}],a=Un(a),o=[...o,{timestamp:Date.now(),byteLength:Q}];const pe=o.filter(E=>E.timestamp>Date.now()-Bt).sort((E,R)=>E.timestamp-R.timestamp),Rt=a.reduce((E,R)=>E+(R.end-R.start),0),ye=pe.reduce((E,R)=>E+R.byteLength,0)/Bt*1e3;e.next({type:"FILE.DOWNLOADING_UPDATE",value:{downloadedRanges:a,downloaded:Rt,progress:Rt/n.input.file.length,status:"downloading",streamBandwithLogs:[...o],downloadSpeed:ye}}),c||Tt()};Tt()}).catch(f=>{u(void 0),console.log("downloadFile err",f),e.error(f)}),()=>{c=!0,l.then(f=>f?.())}})),onSnapshot:{guard:({event:t})=>t.snapshot.context?.type==="FILE.DOWNLOADING_UPDATE",actions:y(({event:t})=>({downloadedRanges:t.snapshot.context.value.downloadedRanges,downloaded:t.snapshot.context.value.downloaded,progress:t.snapshot.context.value.progress,status:t.snapshot.context.value.status,streamBandwithLogs:t.snapshot.context.value.streamBandwithLogs,downloadSpeed:t.snapshot.context.value.downloadSpeed}))},onDone:{target:"finished"}},on:{"FILE.PAUSE":{target:"paused",actions:y({status:"paused"})}}},paused:{entry:[F({type:"FILE.PAUSED"}),y({status:"paused"})],on:{"FILE.RESUME":{target:"downloading",actions:y({status:"downloading"})}}},finished:{entry:[F({type:"FILE.FINISHED"}),y({status:"finished",downloaded:({context:t})=>t.length,progress:1,downloadedRanges:({context:t})=>[{start:0,end:t.length}]})]}}}),Wt=_t({initial:"init",context:({input:t})=>({settingsDbDocument:t.settingsDbDocument,infoHash:t.infoHash,magnet:t.magnet,torrentFile:t.torrentFile,shouldRemoveFiles:!1,lastEvent:null,document:t.document,dbDocument:t.dbDocument,files:[]}),types:{events:{}},always:[{actions:[async({context:t,event:e,self:n})=>{const s=t.files.map(d=>d.getSnapshot().context);if(!t.document||!t.dbDocument||e.type==="TORRENT.REMOVE-AND-KEEP-FILES"||e.type==="TORRENT.REMOVE-AND-DELETE-FILES")return;const i={...t.document,state:{...t.document.state,torrentFile:t.document.state.torrentFile&&Jt(t.document.state.torrentFile)}},r=n.getSnapshot().value,o=s.reduce((d,h)=>d+h.length,0),a=s.reduce((d,h)=>d+h.downloaded,0),c=r==="downloading"?s.reduce((d,h)=>d+h.downloadSpeed,0):0,u=(o-a)/c,{infoHash:l,...f}=xt({state:{name:i.state.name,status:r,progress:s.filter(d=>d.selected).reduce((d,h)=>d+h.progress,0)/s.filter(d=>d.selected).length,size:i.state.size,peers:i.state.peers,proxy:i.state.proxy,p2p:i.state.p2p,addedAt:i.state.addedAt,remainingTime:u,peersCount:i.state.peersCount,seedersCount:i.state.seedersCount,leechersCount:i.state.leechersCount,downloaded:a,uploaded:s.reduce((d,h)=>d+h.uploaded,0),downloadSpeed:c,uploadSpeed:s.reduce((d,h)=>d+h.uploadSpeed,0),ratio:i.state.ratio,files:s.map((d,h)=>({index:h,name:d.name,path:d.path,pathArray:d.pathArray,offset:d.offset,length:d.length,downloaded:d.downloaded,progress:d.progress,selected:d.selected,priority:d.priority,downloadedRanges:d.downloadedRanges.map(p=>({start:p.start,end:p.end})),downloadSpeed:d.downloadSpeed,streamBandwithLogs:d.streamBandwithLogs.map(p=>({byteLength:p.byteLength,timestamp:p.timestamp}))})),streamBandwithLogs:s.reduce((d,h)=>d.concat(h.streamBandwithLogs),[]).sort((d,h)=>d.timestamp-h.timestamp),magnet:i.state.magnet,torrentFile:Ee(i.state.torrentFile)},options:i.options&&{paused:i.options.paused}});await t.dbDocument.incrementalUpdate({$set:{...f}})},y(({event:t})=>({lastEvent:t}))],guard:({context:t,event:e})=>t.lastEvent!==e}],on:{"FILE.CHECKING":".checkingFiles","FILE.FINISHED":{guard:({context:t})=>t.files.every(e=>e.getSnapshot().value==="finished"),target:".finished"},"TORRENT.PAUSE":{actions:y({files:({context:t})=>(t.files.forEach(e=>e.send({type:"FILE.PAUSE"})),t.files)})},"TORRENT.RESUME":{actions:y({files:({context:t})=>(t.files.forEach(e=>e.send({type:"FILE.RESUME"})),t.files)})},"TORRENT.REMOVE-AND-DELETE-FILES":{actions:[y({shouldRemoveFiles:()=>!0})],target:".removing"},"TORRENT.REMOVE-AND-KEEP-FILES":{actions:[y({shouldRemoveFiles:()=>!1})],target:".removing"}},states:{init:{invoke:{input:({context:t,event:e})=>({context:t,data:e}),src:W(async({input:t})=>{const{context:e,data:{input:n}}=t;if(e.dbDocument)return e.dbDocument;const s=await Dt.torrents.findOne(n.infoHash).exec();if(s)return s;const i=n.torrentFile?.infoBuffer?n.torrentFile:await Re({magnet:n.magnet}).then(o=>o.arrayBuffer()).then(o=>Se(we.Buffer.from(o))),r=xt({infoHash:i.infoHash,state:{magnet:n.magnet?n.magnet:_e(n.torrentFile),torrentFile:i}});return Dt.torrents.insert(r)}),onDone:{target:"checkingFiles",actions:[y({document:({event:t})=>t.output.toJSON(),dbDocument:({event:t})=>t.output,files:({spawn:t,event:e,context:n})=>e.output.state.files.filter(s=>s.selected).map(s=>t(Hn,{id:`torrent-${e.output.infoHash}-${s.path}`,input:{settingsDbDocument:n.settingsDbDocument,document:e.output.toJSON(),file:s},syncSnapshot:!0}))})]}}},checkingFiles:{invoke:{src:W(async()=>{}),onDone:[{target:"downloadingMetadata",guard:({context:t})=>!t.torrentFile},{guard:Ft([({context:t})=>t.document.state.stats==="finished",({context:t})=>t.torrent&&t.files.every(e=>e.getSnapshot().value==="finished")]),target:"finished"},{target:"downloading",guard:Ft([({context:t})=>t.document.state.status==="downloading",({context:t})=>t.torrentFile])}]}},downloadingMetadata:{invoke:{input:({context:t})=>t,src:j(t=>t.input.document.$),onSnapshot:{target:"downloading",guard:({event:t})=>t.snapshot.context?.state?.torrentFile!==void 0}}},downloading:{invoke:{input:({context:t})=>t,src:j(({input:t,...e})=>rt([]))},on:{"FILES.FINISHED":"finished","TORRENT.PAUSE":{target:"paused",actions:y({files:({context:t,event:e})=>(t.files.forEach(n=>n.send({type:"FILE.PAUSE"})),t.files)})}}},paused:{on:{"TORRENT.RESUME":{target:"downloading",actions:y({files:({context:t,event:e})=>(t.files.forEach(n=>n.send({type:"FILE.RESUME"})),t.files)})}}},finished:{},removing:{invoke:{input:({context:t,self:e})=>({context:t,self:e}),src:W(async({input:t})=>{if(t.context.dbDocument){const n=async()=>{try{await (await t.context.dbDocument.getLatest()).remove()}catch{await new Promise(i=>setTimeout(i,100)),await n()}};n()}return t.context.files.forEach(n=>t.self._actorScope.stopChild(n)),await (await (await navigator.storage.getDirectory()).getDirectoryHandle("torrents")).removeEntry(t.context.infoHash,{recursive:!0}),t.context.document}),onDone:{actions:[y({document:()=>{},dbDocument:()=>{},files:[]}),F(({context:t})=>({type:"TORRENT.REMOVED",input:{infoHash:t.infoHash}}))]}}}}}),Bn=()=>Te.find().exec(),Wn=_t({id:"torrentManager",initial:"init",context:{settingsDbDocument:void 0,torrents:[],workerReady:!1},types:{events:{}},on:{"WORKER.DISCONNECTED":{actions:y({workerReady:!1})},"WORKER.READY":{actions:y({workerReady:!0})}},states:{init:{invoke:{src:W(async()=>{const[t,e]=await Promise.all([et(),Bn()]);return{settingsDbDocument:t,torrentDbDocuments:e}}),onDone:{target:"waitingForDocuments",actions:y({settingsDbDocument:({event:t})=>t.output.settingsDbDocument,torrents:({spawn:t,event:e})=>e.output.torrentDbDocuments.map(n=>t(Wt,{id:`torrent-${n.infoHash}`,input:{settingsDbDocument:e.output.settingsDbDocument,infoHash:n.infoHash,magnet:n.state.magnet,torrentFile:n.state.torrentFile,document:n.toJSON(),dbDocument:n},syncSnapshot:!0}))})}}},waitingForDocuments:{always:{target:"idle",guard:({context:t})=>t.workerReady}},idle:{invoke:{input:({context:t})=>t,src:j(({input:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.RESUME"})),rt(et()).pipe(It(e=>e?.$),it(e=>e?.paused),At()))),onDone:{target:"paused"}},on:{"TORRENT.ADD":{actions:y({torrents:({spawn:t,context:e,event:n})=>[...e.torrents,t(Wt,{id:`torrent-${n.input.infoHash}`,input:{settingsDbDocument:e.settingsDbDocument,...n.input},syncSnapshot:!0})]})},"TORRENT.PAUSE":{actions:y({torrents:({context:t,event:e})=>(t.torrents.find(s=>s.id===`torrent-${e.output.infoHash}`)?.send({type:"TORRENT.PAUSE"}),t.torrents)})},"TORRENT.RESUME":{actions:y({torrents:({context:t,event:e})=>(t.torrents.find(s=>s.id===`torrent-${e.output.infoHash}`)?.send({type:"TORRENT.RESUME"}),t.torrents)})},"TORRENT.REMOVE-AND-DELETE-FILES":{actions:({context:t,event:e})=>{t.torrents.find(s=>s.id===`torrent-${e.input.infoHash}`)?.send({type:"TORRENT.REMOVE-AND-DELETE-FILES"})}},"TORRENT.REMOVE-AND-KEEP-FILES":{actions:({context:t,event:e})=>{t.torrents.find(s=>s.id===`torrent-${e.input.infoHash}`)?.send({type:"TORRENT.REMOVE-AND-KEEP-FILES"})}},"TORRENT.REMOVED":{actions:y({torrents:({context:t,event:e})=>t.torrents.filter(n=>n.id!==`torrent-${e.input.infoHash}`)})},PAUSE:{actions:y({torrents:({context:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.PAUSE"})),t.torrents)}),target:"paused"}}},paused:{invoke:{id:"paused status watch",input:({context:t})=>t,src:j(({input:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.PAUSE"})),rt(et()).pipe(It(e=>e?.$),it(e=>!e?.paused),At()))),onDone:{target:"idle"}},on:{RESUME:{actions:y({torrents:({context:t})=>(t.torrents.filter(e=>e.getSnapshot().value!=="finished").forEach(e=>e.send({type:"TORRENT.RESUME"})),t.torrents)}),target:"idle"}}}}}),V=N(Wn).start();let ft;le=()=>ft;zn=H(async({workerPort:t})=>{ft&&V.send({type:"WORKER.DISCONNECTED"}),ft=t,await new Promise((e,n)=>{const s=setInterval(()=>{z(t,{key:"torrent-manager"})("ping").then(i=>{clearInterval(s),e(void 0)})},100);z(t,{key:"torrent-manager"})("ping").then(i=>{clearInterval(s),e(void 0)}),setTimeout(()=>{clearInterval(s),n()},1e3)}),V.send({type:"WORKER.READY"})});Vn={newLeader:zn,addTorrent:H(async({infoHash:t,magnet:e,torrentFile:n})=>{V.send({type:"TORRENT.ADD",input:{infoHash:t,magnet:e,torrentFile:n&&Jt(n)}})}),removeTorrent:H(async({infoHash:t,removeFiles:e})=>{V.send({type:e?"TORRENT.REMOVE-AND-DELETE-FILES":"TORRENT.REMOVE-AND-KEEP-FILES",input:{infoHash:t}})}),readTorrentFile:H(({infoHash:t,filePath:e,offset:n,size:s})=>z(le(),{key:"io-worker"})("readTorrentFile",{infoHash:t,filePath:e,offset:n,size:s}))}});export{le as getIoWorkerPort,zn as newLeader,Vn as resolvers,__tla};
|
|
Binary file
|
package/build/jassub-worker.js
DELETED
|
@@ -1,15 +0,0 @@
|
|
|
1
|
-
"use strict";var Module=function(f={}){var f=f,h;f.ready=new Promise(function(t,r){h=t});var C=function(t){return console.log(t)},y=function(t){return console.error(t)};function _(){h(f)}function A(t,r){if(!t)throw r}var w=null;C=function(t){t==="JASSUB: No usable fontconfig configuration file found, using fallback."?console.debug(t):console.log(t)},y=function(t){t==="Fontconfig error: Cannot load default config file: No such file: (null)"?console.debug(t):console.error(t)},Y=function(t){return function(){t(),self.wasmMemory=B,self.HEAPU8C=new Uint8ClampedArray(B.buffer),self.HEAPU8=new Uint8Array(B.buffer)}}(Y);function F(t){throw t}var j,E,M,O,J,k,fe,le,B,ue;function Y(){var t=B.buffer;j=new Int8Array(t),E=new Int16Array(t),M=new Int32Array(t),O=new Uint8Array(t),J=new Uint16Array(t),k=new Uint32Array(t),fe=new Float32Array(t),le=new Float64Array(t)}if(B=new WebAssembly.Memory({initial:256,maximum:32768}),Y(),(!Math.imul||Math.imul(4294967295,5)!==-5)&&(Math.imul=function(t,r){var n=t>>>16,i=t&65535,o=r>>>16,u=r&65535;return i*u+(n*u+i*o<<16)|0}),!Math.fround){var ce=new Float32Array(1);Math.fround=function(t){return ce[0]=t,ce[0]}}Math.clz32||(Math.clz32=function(t){var r=32,n=t>>16;return n&&(r-=16,t=n),n=t>>8,n&&(r-=8,t=n),n=t>>4,n&&(r-=4,t=n),n=t>>2,n&&(r-=2,t=n),n=t>>1,n?r-2:r-t}),Math.trunc||(Math.trunc=function(t){return t<0?Math.ceil(t):Math.floor(t)});var de=typeof TextDecoder<"u"?new TextDecoder("utf8"):void 0;function pe(t,r,n){for(var i=r+n,o=r;t[o]&&!(o>=i);)++o;if(o-r>16&&t.buffer&&de)return de.decode(t.subarray(r,o));for(var u="";r<o;){var p=t[r++];if(!(p&128)){u+=String.fromCharCode(p);continue}var l=t[r++]&63;if((p&224)==192){u+=String.fromCharCode((p&31)<<6|l);continue}var v=t[r++]&63;if((p&240)==224?p=(p&15)<<12|l<<6|v:p=(p&7)<<18|l<<12|v<<6|t[r++]&63,p<65536)u+=String.fromCharCode(p);else{var g=p-65536;u+=String.fromCharCode(55296|g>>10,56320|g&1023)}}return u}function X(t,r){return t?pe(O,t,r):""}function Te(t,r,n,i){F("Assertion failed: "+X(t)+", at: "+[r?X(r):"unknown filename",n,i?X(i):"unknown function"])}function Pe(t,r,n){return 0}function Ae(t,r){}function Fe(t,r,n,i){if(!(i>0))return 0;for(var o=n,u=n+i-1,p=0;p<t.length;++p){var l=t.charCodeAt(p);if(l>=55296&&l<=57343){var v=t.charCodeAt(++p);l=65536+((l&1023)<<10)|v&1023}if(l<=127){if(n>=u)break;r[n++]=l}else if(l<=2047){if(n+1>=u)break;r[n++]=192|l>>6,r[n++]=128|l&63}else if(l<=65535){if(n+2>=u)break;r[n++]=224|l>>12,r[n++]=128|l>>6&63,r[n++]=128|l&63}else{if(n+3>=u)break;r[n++]=240|l>>18,r[n++]=128|l>>12&63,r[n++]=128|l>>6&63,r[n++]=128|l&63}}return r[n]=0,n-o}function at(t,r,n){return Fe(t,O,r,n)}function st(t,r,n){}function ot(t,r,n){return 0}function ft(t,r,n,i){}function lt(t,r,n,i){}function ut(t,r){}function ct(t,r,n,i,o){}function $e(t){switch(t){case 1:return 0;case 2:return 1;case 4:return 2;case 8:return 3;default:throw new TypeError("Unknown type size: "+t)}}function dt(){for(var t=new Array(256),r=0;r<256;++r)t[r]=String.fromCharCode(r);Le=t}var Le=void 0;function D(t){for(var r="",n=t;O[n];)r+=Le[O[n++]];return r}var Q={},Z={},ge={},pt=48,gt=57;function Se(t){if(t===void 0)return"_unknown";t=t.replace(/[^a-zA-Z0-9_]/g,"$");var r=t.charCodeAt(0);return r>=pt&&r<=gt?"_"+t:t}function je(t,r){t=Se(t);var n={};return(n[t]=function(){return r.apply(this,arguments)},n)[t]}function Oe(t,r){var n=je(r,function(i){this.name=r,this.message=i;var o=new Error(i).stack;o!==void 0&&(this.stack=this.toString()+`
|
|
2
|
-
`+o.replace(/^Error(:[^\n]*)?\n/,""))});return n.prototype=Object.create(t.prototype),n.prototype.constructor=n,n.prototype.toString=function(){return this.message===void 0?this.name:this.name+": "+this.message},n}var N=void 0;function T(t){throw new N(t)}var He=void 0;function he(t){throw new He(t)}function K(t,r,n){t.forEach(function(l){ge[l]=r});function i(l){var v=n(l);v.length!==t.length&&he("Mismatched type converter count");for(var g=0;g<t.length;++g)x(t[g],v[g])}var o=new Array(r.length),u=[],p=0;r.forEach(function(l,v){Z.hasOwnProperty(l)?o[v]=Z[l]:(u.push(l),Q.hasOwnProperty(l)||(Q[l]=[]),Q[l].push(function(){o[v]=Z[l],++p,p===u.length&&i(o)}))}),u.length===0&&i(o)}function x(t,r,n){if(n=n===void 0?{}:n,!("argPackAdvance"in r))throw new TypeError("registerType registeredInstance requires argPackAdvance");var i=r.name;if(t||T('type "'+i+'" must have a positive integer typeid pointer'),Z.hasOwnProperty(t)){if(n.ignoreDuplicateRegistrations)return;T("Cannot register type '"+i+"' twice")}if(Z[t]=r,delete ge[t],Q.hasOwnProperty(t)){var o=Q[t];delete Q[t],o.forEach(function(u){return u()})}}function ht(t,r,n,i,o){var u=$e(n);r=D(r),x(t,{name:r,fromWireType:function(p){return!!p},toWireType:function(p,l){return l?i:o},argPackAdvance:8,readValueFromPointer:function(p){var l;if(n===1)l=j;else if(n===2)l=E;else if(n===4)l=M;else throw new TypeError("Unknown boolean type size: "+r);return this.fromWireType(l[p>>u])},destructorFunction:null})}function vt(t){if(!(this instanceof G)||!(t instanceof G))return!1;for(var r=this.$$.ptrType.registeredClass,n=this.$$.ptr,i=t.$$.ptrType.registeredClass,o=t.$$.ptr;r.baseClass;)n=r.upcast(n),r=r.baseClass;for(;i.baseClass;)o=i.upcast(o),i=i.baseClass;return r===i&&n===o}function yt(t){return{count:t.count,deleteScheduled:t.deleteScheduled,preservePointerOnDelete:t.preservePointerOnDelete,ptr:t.ptr,ptrType:t.ptrType,smartPtr:t.smartPtr,smartPtrType:t.smartPtrType}}function Ee(t){function r(n){return n.$$.ptrType.registeredClass.name}T(r(t)+" instance already deleted")}var Me=!1;function Be(t){}function bt(t){t.smartPtr?t.smartPtrType.rawDestructor(t.smartPtr):t.ptrType.registeredClass.rawDestructor(t.ptr)}function xe(t){t.count.value-=1;var r=t.count.value===0;r&&bt(t)}function Ve(t,r,n){if(r===n)return t;if(n.baseClass===void 0)return null;var i=Ve(t,r,n.baseClass);return i===null?null:n.downcast(i)}var ze={};function mt(){return Object.keys(re).length}function wt(){var t=[];for(var r in re)re.hasOwnProperty(r)&&t.push(re[r]);return t}var ee=[];function ke(){for(;ee.length;){var t=ee.pop();t.$$.deleteScheduled=!1,t.delete()}}var te=void 0;function Ct(t){te=t,ee.length&&te&&te(ke)}function _t(){f.getInheritedInstanceCount=mt,f.getLiveInheritedInstances=wt,f.flushPendingDeletes=ke,f.setDelayFunction=Ct}var re={};function Tt(t,r){for(r===void 0&&T("ptr should not be undefined");t.baseClass;)r=t.upcast(r),t=t.baseClass;return r}function Pt(t,r){return r=Tt(t,r),re[r]}function ve(t,r){(!r.ptrType||!r.ptr)&&he("makeClassHandle requires ptr and ptrType");var n=!!r.smartPtrType,i=!!r.smartPtr;return n!==i&&he("Both smartPtrType and smartPtr must be specified"),r.count={value:1},ne(Object.create(t,{$$:{value:r}}))}function At(t){var r=this.getPointee(t);if(!r)return this.destructor(t),null;var n=Pt(this.registeredClass,r);if(n!==void 0){if(n.$$.count.value===0)return n.$$.ptr=r,n.$$.smartPtr=t,n.clone();var i=n.clone();return this.destructor(t),i}function o(){return this.isSmartPointer?ve(this.registeredClass.instancePrototype,{ptrType:this.pointeeType,ptr:r,smartPtrType:this,smartPtr:t}):ve(this.registeredClass.instancePrototype,{ptrType:this,ptr:t})}var u=this.registeredClass.getActualType(r),p=ze[u];if(!p)return o.call(this);var l;this.isConst?l=p.constPointerType:l=p.pointerType;var v=Ve(r,this.registeredClass,l.registeredClass);return v===null?o.call(this):this.isSmartPointer?ve(l.registeredClass.instancePrototype,{ptrType:l,ptr:v,smartPtrType:this,smartPtr:t}):ve(l.registeredClass.instancePrototype,{ptrType:l,ptr:v})}function ne(t){return typeof FinalizationRegistry>"u"?(ne=function(r){return r},t):(Me=new FinalizationRegistry(function(r){xe(r.$$)}),ne=function(r){var n=r.$$,i=!!n.smartPtr;if(i){var o={$$:n};Me.register(r,o,r)}return r},Be=function(r){return Me.unregister(r)},ne(t))}function Ft(){if(this.$$.ptr||Ee(this),this.$$.preservePointerOnDelete)return this.$$.count.value+=1,this;var t=ne(Object.create(Object.getPrototypeOf(this),{$$:{value:yt(this.$$)}}));return t.$$.count.value+=1,t.$$.deleteScheduled=!1,t}function $t(){this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&T("Object already scheduled for deletion"),Be(this),xe(this.$$),this.$$.preservePointerOnDelete||(this.$$.smartPtr=void 0,this.$$.ptr=void 0)}function St(){return!this.$$.ptr}function jt(){return this.$$.ptr||Ee(this),this.$$.deleteScheduled&&!this.$$.preservePointerOnDelete&&T("Object already scheduled for deletion"),ee.push(this),ee.length===1&&te&&te(ke),this.$$.deleteScheduled=!0,this}function Ot(){G.prototype.isAliasOf=vt,G.prototype.clone=Ft,G.prototype.delete=$t,G.prototype.isDeleted=St,G.prototype.deleteLater=jt}function G(){}function Je(t,r,n){if(t[r].overloadTable===void 0){var i=t[r];t[r]=function(){return t[r].overloadTable.hasOwnProperty(arguments.length)||T("Function '"+n+"' called with an invalid number of arguments ("+arguments.length+") - expects one of ("+t[r].overloadTable+")!"),t[r].overloadTable[arguments.length].apply(this,arguments)},t[r].overloadTable=[],t[r].overloadTable[i.argCount]=i}}function Et(t,r,n){f.hasOwnProperty(t)?((n===void 0||f[t].overloadTable!==void 0&&f[t].overloadTable[n]!==void 0)&&T("Cannot register public name '"+t+"' twice"),Je(f,t,t),f.hasOwnProperty(n)&&T("Cannot register multiple overloads of a function with the same number of arguments ("+n+")!"),f[t].overloadTable[n]=r):(f[t]=r,n!==void 0&&(f[t].numArguments=n))}function Mt(t,r,n,i,o,u,p,l){this.name=t,this.constructor=r,this.instancePrototype=n,this.rawDestructor=i,this.baseClass=o,this.getActualType=u,this.upcast=p,this.downcast=l,this.pureVirtualFunctions=[]}function ye(t,r,n){for(;r!==n;)r.upcast||T("Expected null or instance of "+n.name+", got an instance of "+r.name),t=r.upcast(t),r=r.baseClass;return t}function kt(t,r){if(r===null)return this.isReference&&T("null is not a valid "+this.name),0;r.$$||T('Cannot pass "'+Re(r)+'" as a '+this.name),r.$$.ptr||T("Cannot pass deleted object as a pointer of type "+this.name);var n=r.$$.ptrType.registeredClass,i=ye(r.$$.ptr,n,this.registeredClass);return i}function Ut(t,r){var n;if(r===null)return this.isReference&&T("null is not a valid "+this.name),this.isSmartPointer?(n=this.rawConstructor(),t!==null&&t.push(this.rawDestructor,n),n):0;r.$$||T('Cannot pass "'+Re(r)+'" as a '+this.name),r.$$.ptr||T("Cannot pass deleted object as a pointer of type "+this.name),!this.isConst&&r.$$.ptrType.isConst&&T("Cannot convert argument of type "+(r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name)+" to parameter type "+this.name);var i=r.$$.ptrType.registeredClass;if(n=ye(r.$$.ptr,i,this.registeredClass),this.isSmartPointer)switch(r.$$.smartPtr===void 0&&T("Passing raw pointer to smart pointer is illegal"),this.sharingPolicy){case 0:r.$$.smartPtrType===this?n=r.$$.smartPtr:T("Cannot convert argument of type "+(r.$$.smartPtrType?r.$$.smartPtrType.name:r.$$.ptrType.name)+" to parameter type "+this.name);break;case 1:n=r.$$.smartPtr;break;case 2:if(r.$$.smartPtrType===this)n=r.$$.smartPtr;else{var o=r.clone();n=this.rawShare(n,Ue.toHandle(function(){o.delete()})),t!==null&&t.push(this.rawDestructor,n)}break;default:T("Unsupporting sharing policy")}return n}function Rt(t,r){if(r===null)return this.isReference&&T("null is not a valid "+this.name),0;r.$$||T('Cannot pass "'+Re(r)+'" as a '+this.name),r.$$.ptr||T("Cannot pass deleted object as a pointer of type "+this.name),r.$$.ptrType.isConst&&T("Cannot convert argument of type "+r.$$.ptrType.name+" to parameter type "+this.name);var n=r.$$.ptrType.registeredClass,i=ye(r.$$.ptr,n,this.registeredClass);return i}function be(t){return this.fromWireType(M[t>>2])}function Wt(t){return this.rawGetPointee&&(t=this.rawGetPointee(t)),t}function It(t){this.rawDestructor&&this.rawDestructor(t)}function Dt(t){t!==null&&t.delete()}function Lt(){V.prototype.getPointee=Wt,V.prototype.destructor=It,V.prototype.argPackAdvance=8,V.prototype.readValueFromPointer=be,V.prototype.deleteObject=Dt,V.prototype.fromWireType=At}function V(t,r,n,i,o,u,p,l,v,g,m){this.name=t,this.registeredClass=r,this.isReference=n,this.isConst=i,this.isSmartPointer=o,this.pointeeType=u,this.sharingPolicy=p,this.rawGetPointee=l,this.rawConstructor=v,this.rawShare=g,this.rawDestructor=m,!o&&r.baseClass===void 0?i?(this.toWireType=kt,this.destructorFunction=null):(this.toWireType=Rt,this.destructorFunction=null):this.toWireType=Ut}function Ht(t,r,n){f.hasOwnProperty(t)||he("Replacing nonexistant public symbol"),f[t].overloadTable!==void 0&&n!==void 0?f[t].overloadTable[n]=r:(f[t]=r,f[t].argCount=n)}function Bt(t,r,n){var i=dynCalls[t];return n&&n.length?i.apply(null,[r].concat(n)):i.call(null,r)}var me=[];function ie(t){var r=me[t];return r||(t>=me.length&&(me.length=t+1),me[t]=r=ue.get(t)),r}function xt(t,r,n){if(t.includes("j"))return Bt(t,r,n);var i=ie(r).apply(null,n);return i}function Vt(t,r){var n=[];return function(){return n.length=0,Object.assign(n,arguments),xt(t,r,n)}}function q(t,r){t=D(t);function n(){return t.includes("j")?Vt(t,r):ie(r)}var i=n();return typeof i!="function"&&T("unknown function pointer with signature "+t+": "+r),i}var Ge=void 0;function zt(t){var r=Ne(t),n=D(r);return z(r),n}function ae(t,r){var n=[],i={};function o(u){if(!i[u]&&!Z[u]){if(ge[u]){ge[u].forEach(o);return}n.push(u),i[u]=!0}}throw r.forEach(o),new Ge(t+": "+n.map(zt).join([", "]))}function Jt(t,r,n,i,o,u,p,l,v,g,m,P,$){m=D(m),u=q(o,u),l&&(l=q(p,l)),g&&(g=q(v,g)),$=q(P,$);var S=Se(m);Et(S,function(){ae("Cannot construct "+m+" due to unbound types",[i])}),K([t,r,n],i?[i]:[],function(U){U=U[0];var W,R;i?(W=U.registeredClass,R=W.instancePrototype):R=G.prototype;var L=je(S,function(){if(Object.getPrototypeOf(this)!==oe)throw new N("Use 'new' to construct "+m);if(I.constructor_body===void 0)throw new N(m+" has no accessible constructor");var it=I.constructor_body[arguments.length];if(it===void 0)throw new N("Tried to invoke ctor of "+m+" with invalid number of parameters ("+arguments.length+") - expected ("+Object.keys(I.constructor_body).toString()+") parameters instead!");return it.apply(this,arguments)}),oe=Object.create(R,{constructor:{value:L}});L.prototype=oe;var I=new Mt(m,L,oe,$,W,u,l,g);I.baseClass&&(I.baseClass.__derivedClasses===void 0&&(I.baseClass.__derivedClasses=[]),I.baseClass.__derivedClasses.push(I));var Hr=new V(m,I,!0,!1,!1),rt=new V(m+"*",I,!1,!1,!1),nt=new V(m+" const*",I,!1,!0,!1);return ze[t]={pointerType:rt,constPointerType:nt},Ht(S,L),[Hr,rt,nt]})}function qe(t,r){for(var n=[],i=0;i<t;i++)n.push(k[r+i*4>>2]);return n}function Ke(t){for(;t.length;){var r=t.pop(),n=t.pop();n(r)}}function Gt(t,r){if(!(t instanceof Function))throw new TypeError("new_ called with constructor type "+typeof t+" which is not a function");var n=je(t.name||"unknownFunctionName",function(){});n.prototype=t.prototype;var i=new n,o=t.apply(i,r);return o instanceof Object?o:i}function Ye(t,r,n,i,o,u){var p=r.length;p<2&&T("argTypes array size mismatch! Must at least get return value and 'this' types!");for(var l=r[1]!==null&&n!==null,v=!1,g=1;g<r.length;++g)if(r[g]!==null&&r[g].destructorFunction===void 0){v=!0;break}for(var m=r[0].name!=="void",P="",$="",g=0;g<p-2;++g)P+=(g!==0?", ":"")+"arg"+g,$+=(g!==0?", ":"")+"arg"+g+"Wired";var S=`
|
|
3
|
-
return function `+Se(t)+"("+P+`) {
|
|
4
|
-
if (arguments.length !== `+(p-2)+`) {
|
|
5
|
-
throwBindingError('function `+t+" called with "+arguments.length+" arguments, expected "+(p-2)+` args!');
|
|
6
|
-
}`;v&&(S+=`var destructors = [];
|
|
7
|
-
`);var U=v?"destructors":"null",W=["throwBindingError","invoker","fn","runDestructors","retType","classParam"],R=[T,i,o,Ke,r[0],r[1]];l&&(S+="var thisWired = classParam.toWireType("+U+`, this);
|
|
8
|
-
`);for(var g=0;g<p-2;++g)S+="var arg"+g+"Wired = argType"+g+".toWireType("+U+", arg"+g+"); // "+r[g+2].name+`
|
|
9
|
-
`,W.push("argType"+g),R.push(r[g+2]);if(l&&($="thisWired"+($.length>0?", ":"")+$),S+=(m||u?"var rv = ":"")+"invoker(fn"+($.length>0?", ":"")+$+`);
|
|
10
|
-
`,v)S+=`runDestructors(destructors);
|
|
11
|
-
`;else for(var g=l?1:2;g<r.length;++g){var L=g===1?"thisWired":"arg"+(g-2)+"Wired";r[g].destructorFunction!==null&&(S+=L+"_dtor("+L+"); // "+r[g].name+`
|
|
12
|
-
`,W.push(L+"_dtor"),R.push(r[g].destructorFunction))}return m&&(S+=`var ret = retType.fromWireType(rv);
|
|
13
|
-
return ret;
|
|
14
|
-
`),S+=`}
|
|
15
|
-
`,W.push(S),Gt(Function,W).apply(null,R)}function qt(t,r,n,i,o,u){A(r>0);var p=qe(r,n);o=q(i,o),K([],[t],function(l){l=l[0];var v="constructor "+l.name;if(l.registeredClass.constructor_body===void 0&&(l.registeredClass.constructor_body=[]),l.registeredClass.constructor_body[r-1]!==void 0)throw new N("Cannot register multiple constructors with identical number of parameters ("+(r-1)+") for class '"+l.name+"'! Overload resolution is currently only performed using the parameter count, not actual type info!");return l.registeredClass.constructor_body[r-1]=function(){ae("Cannot construct "+l.name+" due to unbound types",p)},K([],p,function(g){return g.splice(1,0,null),l.registeredClass.constructor_body[r-1]=Ye(v,g,null,o,u),[]}),[]})}function Kt(t,r,n,i,o,u,p,l,v){var g=qe(n,i);r=D(r),u=q(o,u),K([],[t],function(m){m=m[0];var P=m.name+"."+r;r.startsWith("@@")&&(r=Symbol[r.substring(2)]),l&&m.registeredClass.pureVirtualFunctions.push(r);function $(){ae("Cannot call "+P+" due to unbound types",g)}var S=m.registeredClass.instancePrototype,U=S[r];return U===void 0||U.overloadTable===void 0&&U.className!==m.name&&U.argCount===n-2?($.argCount=n-2,$.className=m.name,S[r]=$):(Je(S,r,P),S[r].overloadTable[n-2]=$),K([],g,function(W){var R=Ye(P,W,m,u,p,v);return S[r].overloadTable===void 0?(R.argCount=n-2,S[r]=R):S[r].overloadTable[n-2]=R,[]}),[]})}function Xe(t,r,n){return t instanceof Object||T(n+' with invalid "this": '+t),t instanceof r.registeredClass.constructor||T(n+' incompatible with "this" of type '+t.constructor.name),t.$$.ptr||T("cannot call emscripten binding method "+n+" on deleted object"),ye(t.$$.ptr,t.$$.ptrType.registeredClass,r.registeredClass)}function Yt(t,r,n,i,o,u,p,l,v,g){r=D(r),o=q(i,o),K([],[t],function(m){m=m[0];var P=m.name+"."+r,$={get:function(){ae("Cannot access "+P+" due to unbound types",[n,p])},enumerable:!0,configurable:!0};return v?$.set=function(){ae("Cannot access "+P+" due to unbound types",[n,p])}:$.set=function(S){T(P+" is a read-only property")},Object.defineProperty(m.registeredClass.instancePrototype,r,$),K([],v?[n,p]:[n],function(S){var U=S[0],W={get:function(){var L=Xe(this,m,P+" getter");return U.fromWireType(o(u,L))},enumerable:!0};if(v){v=q(l,v);var R=S[1];W.set=function(L){var oe=Xe(this,m,P+" setter"),I=[];v(g,oe,R.toWireType(I,L)),Ke(I)}}return Object.defineProperty(m.registeredClass.instancePrototype,r,W),[]}),[]})}function Xt(){this.allocated=[void 0],this.freelist=[],this.get=function(t){return this.allocated[t]},this.has=function(t){return this.allocated[t]!==void 0},this.allocate=function(t){var r=this.freelist.pop()||this.allocated.length;return this.allocated[r]=t,r},this.free=function(t){this.allocated[t]=void 0,this.freelist.push(t)}}var H=new Xt;function Qt(t){t>=H.reserved&&--H.get(t).refcount===0&&H.free(t)}function Zt(){for(var t=0,r=H.reserved;r<H.allocated.length;++r)H.allocated[r]!==void 0&&++t;return t}function Nt(){H.allocated.push({value:void 0},{value:null},{value:!0},{value:!1}),H.reserved=H.allocated.length,f.count_emval_handles=Zt}var Ue={toValue:function(t){return t||T("Cannot use deleted val. handle = "+t),H.get(t).value},toHandle:function(t){switch(t){case void 0:return 1;case null:return 2;case!0:return 3;case!1:return 4;default:return H.allocate({refcount:1,value:t})}}};function er(t,r){r=D(r),x(t,{name:r,fromWireType:function(n){var i=Ue.toValue(n);return Qt(n),i},toWireType:function(n,i){return Ue.toHandle(i)},argPackAdvance:8,readValueFromPointer:be,destructorFunction:null})}function Re(t){if(t===null)return"null";var r=typeof t;return r==="object"||r==="array"||r==="function"?t.toString():""+t}function tr(t,r){switch(r){case 2:return function(n){return this.fromWireType(fe[n>>2])};case 3:return function(n){return this.fromWireType(le[n>>3])};default:throw new TypeError("Unknown float type: "+t)}}function rr(t,r,n){var i=$e(n);r=D(r),x(t,{name:r,fromWireType:function(o){return o},toWireType:function(o,u){return u},argPackAdvance:8,readValueFromPointer:tr(r,i),destructorFunction:null})}function nr(t,r,n){switch(r){case 0:return n?function(o){return j[o]}:function(o){return O[o]};case 1:return n?function(o){return E[o>>1]}:function(o){return J[o>>1]};case 2:return n?function(o){return M[o>>2]}:function(o){return k[o>>2]};default:throw new TypeError("Unknown integer type: "+t)}}function ir(t,r,n,i,o){r=D(r);var u=$e(n),p=function(P){return P};if(i===0){var l=32-8*n;p=function(P){return P<<l>>>l}}var v=r.includes("unsigned"),g=function(P,$){},m;v?m=function(P,$){return g($,this.name),$>>>0}:m=function(P,$){return g($,this.name),$},x(t,{name:r,fromWireType:p,toWireType:m,argPackAdvance:8,readValueFromPointer:nr(r,u,i!==0),destructorFunction:null})}function ar(t,r,n){var i=[Int8Array,Uint8Array,Int16Array,Uint16Array,Int32Array,Uint32Array,Float32Array,Float64Array],o=i[r];function u(p){p=p>>2;var l=k,v=l[p],g=l[p+1];return new o(l.buffer,g,v)}n=D(n),x(t,{name:n,fromWireType:u,argPackAdvance:8,readValueFromPointer:u},{ignoreDuplicateRegistrations:!0})}function sr(t){for(var r=0,n=0;n<t.length;++n){var i=t.charCodeAt(n);i<=127?r++:i<=2047?r+=2:i>=55296&&i<=57343?(r+=4,++n):r+=3}return r}function or(t,r){r=D(r);var n=r==="std::string";x(t,{name:r,fromWireType:function(i){var o=k[i>>2],u=i+4,p;if(n)for(var l=u,v=0;v<=o;++v){var g=u+v;if(v==o||O[g]==0){var m=g-l,P=X(l,m);p===void 0?p=P:(p+=String.fromCharCode(0),p+=P),l=g+1}}else{for(var $=new Array(o),v=0;v<o;++v)$[v]=String.fromCharCode(O[u+v]);p=$.join("")}return z(i),p},toWireType:function(i,o){o instanceof ArrayBuffer&&(o=new Uint8Array(o));var u,p=typeof o=="string";p||o instanceof Uint8Array||o instanceof Uint8ClampedArray||o instanceof Int8Array||T("Cannot pass non-string to std::string"),n&&p?u=sr(o):u=o.length;var l=De(4+u+1),v=l+4;if(k[l>>2]=u,n&&p)at(o,v,u+1);else if(p)for(var g=0;g<u;++g){var m=o.charCodeAt(g);m>255&&(z(v),T("String has UTF-16 code units that do not fit in 8 bits")),O[v+g]=m}else for(var g=0;g<u;++g)O[v+g]=o[g];return i!==null&&i.push(z,l),l},argPackAdvance:8,readValueFromPointer:be,destructorFunction:function(i){z(i)}})}var Qe=typeof TextDecoder<"u"?new TextDecoder("utf-16le"):void 0;function fr(t,r){for(var n=t,i=n>>1,o=i+r/2;!(i>=o)&&J[i];)++i;if(n=i<<1,n-t>32&&Qe)return Qe.decode(O.subarray(t,n));for(var u="",p=0;!(p>=r/2);++p){var l=E[t+p*2>>1];if(l==0)break;u+=String.fromCharCode(l)}return u}function lr(t,r,n){if(n===void 0&&(n=2147483647),n<2)return 0;n-=2;for(var i=r,o=n<t.length*2?n/2:t.length,u=0;u<o;++u){var p=t.charCodeAt(u);E[r>>1]=p,r+=2}return E[r>>1]=0,r-i}function ur(t){return t.length*2}function cr(t,r){for(var n=0,i="";!(n>=r/4);){var o=M[t+n*4>>2];if(o==0)break;if(++n,o>=65536){var u=o-65536;i+=String.fromCharCode(55296|u>>10,56320|u&1023)}else i+=String.fromCharCode(o)}return i}function dr(t,r,n){if(n===void 0&&(n=2147483647),n<4)return 0;for(var i=r,o=i+n-4,u=0;u<t.length;++u){var p=t.charCodeAt(u);if(p>=55296&&p<=57343){var l=t.charCodeAt(++u);p=65536+((p&1023)<<10)|l&1023}if(M[r>>2]=p,r+=4,r+4>o)break}return M[r>>2]=0,r-i}function pr(t){for(var r=0,n=0;n<t.length;++n){var i=t.charCodeAt(n);i>=55296&&i<=57343&&++n,r+=4}return r}function gr(t,r,n){n=D(n);var i,o,u,p,l;r===2?(i=fr,o=lr,p=ur,u=function(){return J},l=1):r===4&&(i=cr,o=dr,p=pr,u=function(){return k},l=2),x(t,{name:n,fromWireType:function(v){for(var g=k[v>>2],m=u(),P,$=v+4,S=0;S<=g;++S){var U=v+4+S*r;if(S==g||m[U>>l]==0){var W=U-$,R=i($,W);P===void 0?P=R:(P+=String.fromCharCode(0),P+=R),$=U+r}}return z(v),P},toWireType:function(v,g){typeof g!="string"&&T("Cannot pass non-string to C++ string type "+n);var m=p(g),P=De(4+m+r);return k[P>>2]=m>>l,o(g,P+4,m+r),v!==null&&v.push(z,P),P},argPackAdvance:8,readValueFromPointer:be,destructorFunction:function(v){z(v)}})}function hr(t,r){r=D(r),x(t,{isVoid:!0,name:r,argPackAdvance:0,fromWireType:function(){},toWireType:function(n,i){}})}function vr(){throw 1/0}function yr(t,r,n,i,o,u,p){return-52}function br(t,r,n,i,o,u){}function mr(){F("")}var We;typeof performance<"u"&&performance.now?We=function(){return performance.now()}:We=Date.now;function wr(){return 2147483648}function Cr(t){var r=B.buffer;try{return B.grow(t-r.byteLength+65535>>>16),Y(),1}catch{}}function _r(t){var r=O.length;t=t>>>0;var n=wr();if(t>n)return!1;for(var i=function(v,g){return v+(g-v%g)%g},o=1;o<=4;o*=2){var u=r*(1+.2/o);u=Math.min(u,t+100663296);var p=Math.min(n,i(Math.max(t,u),65536)),l=Cr(p);if(l)return!0}return!1}var Ie={};function Tr(){return"./this.program"}function se(){if(!se.strings){var t=(typeof navigator=="object"&&navigator.languages&&navigator.languages[0]||"C").replace("-","_")+".UTF-8",r={USER:"web_user",LOGNAME:"web_user",PATH:"/",PWD:"/",HOME:"/home/web_user",LANG:t,_:Tr()};for(var n in Ie)Ie[n]===void 0?delete r[n]:r[n]=Ie[n];var i=[];for(var n in r)i.push(n+"="+r[n]);se.strings=i}return se.strings}function Pr(t,r){for(var n=0;n<t.length;++n)j[r++>>0]=t.charCodeAt(n);j[r>>0]=0}function Ar(t,r){var n=0;return se().forEach(function(i,o){var u=r+n;k[t+o*4>>2]=u,Pr(i,u),n+=i.length+1}),0}function Fr(t,r){var n=se();k[t>>2]=n.length;var i=0;return n.forEach(function(o){i+=o.length+1}),k[r>>2]=i,0}function $r(t){throw"exit("+t+")"}var Sr=$r;function jr(t){return 52}function Or(t,r,n,i){return 52}function Er(t,r,n,i,o){return 70}var Mr=[null,[],[]];function kr(t,r){var n=Mr[t];r===0||r===10?((t===1?C:y)(pe(n,0)),n.length=0):n.push(r)}function Ur(t,r,n,i){for(var o=0,u=0;u<n;u++){var p=k[r>>2],l=k[r+4>>2];r+=8;for(var v=0;v<l;v++)kr(t,O[p+v]);o+=l}return k[i>>2]=o,0}dt(),N=f.BindingError=Oe(Error,"BindingError"),He=f.InternalError=Oe(Error,"InternalError"),Ot(),_t(),Lt(),Ge=f.UnboundTypeError=Oe(Error,"UnboundTypeError"),Nt();var Rr={b:Te,k:Pe,I:Ae,B:st,K:ot,G:ft,n:lt,H:ut,u:ct,r:ht,j:Jt,A:qt,d:Kt,c:Yt,L:er,p:rr,g:ir,e:ar,q:or,l:gr,s:hr,y:vr,C:yr,D:br,f:mr,m:We,z:_r,E:Ar,F:Fr,h:Sr,i:jr,o:Or,t:Er,J:Ur,x:Wr,v:Dr,w:Ir,a:B};function Wr(t,r,n){var i=Ce();try{return ie(t)(r,n)}catch(o){if(_e(i),o!==o+0)throw o;we(1,0)}}function Ir(t,r,n,i,o){var u=Ce();try{return ie(t)(r,n,i,o)}catch(p){if(_e(u),p!==p+0)throw p;we(1,0)}}function Dr(t,r,n,i){var o=Ce();try{return ie(t)(r,n,i)}catch(u){if(_e(o),u!==u+0)throw u;we(1,0)}}f.getTempRet0=tt,f.setTempRet0=et;function Lr(t){t.M()}var Ze={a:Rr},De,z,Ne,we,et,tt,Ce,_e;return(WebAssembly.instantiateStreaming?WebAssembly.instantiateStreaming(fetch("jassub-worker-modern.wasm"),Ze):WebAssembly.instantiate(f.wasm,Ze)).then(function(t){w=(t.instance||t).exports,f._malloc=De=w.N,z=w.O,Ne=w.P,f.__embind_initialize_bindings=w.Q,we=w.S,et=w.T,tt=w.U,Ce=w.V,_e=w.W,w.X,w.Y,w.Z,w._,ue=w.R,Lr(w),_()}),f.ready};String.prototype.startsWith||(String.prototype.startsWith=function(s,f=0){return this.substring(f,s.length)===s});String.prototype.includes||(String.prototype.includes=function(s,f){return this.indexOf(s,f)!==-1});Uint8Array.prototype.slice||(Uint8Array.prototype.slice=function(s,f){return new Uint8Array(this.subarray(s,f))});function toAbsoluteIndex(s,f){const h=s>>0;return h<0?Math.max(h+f,0):Math.min(h,f)}Uint8Array.prototype.fill||(Int8Array.prototype.fill=Int16Array.prototype.fill=Int32Array.prototype.fill=Uint8Array.prototype.fill=Uint16Array.prototype.fill=Uint32Array.prototype.fill=Float32Array.prototype.fill=Float64Array.prototype.fill=Array.prototype.fill=function(s){if(this==null)throw new TypeError("this is null or not defined");const f=Object(this),h=f.length>>>0,C=arguments.length;let y=toAbsoluteIndex(C>1?arguments[1]:void 0,h);const _=C>2?arguments[2]:void 0,A=_===void 0?h:toAbsoluteIndex(_,h);for(;A>y;)f[y++]=s;return f});Uint8Array.prototype.copyWithin||(Int8Array.prototype.copyWithin=Int16Array.prototype.copyWithin=Int32Array.prototype.copyWithin=Uint8Array.prototype.copyWithin=Uint16Array.prototype.copyWithin=Uint32Array.prototype.copyWithin=Float32Array.prototype.copyWithin=Float64Array.prototype.copyWithin=Array.prototype.copyWithin=function(s,f){const h=Object(this),C=h.length>>>0;let y=toAbsoluteIndex(s,C),_=toAbsoluteIndex(f,C);const A=arguments.length>2?arguments[2]:void 0;let w=Math.min((A===void 0?C:toAbsoluteIndex(A,C))-_,C-y),F=1;for(_<y&&y<_+w&&(F=-1,_+=w-1,y+=w-1);w-- >0;)_ in h?h[y]=h[_]:delete h[y],y+=F,_+=F;return h});Date.now||(Date.now=()=>new Date().getTime());"performance"in self||(self.performance={now:()=>Date.now()});if(typeof console>"u"){const s=(f,h)=>{postMessage({target:"console",command:f,content:JSON.stringify(Array.prototype.slice.call(h))})};self.console={log:function(){s("log",arguments)},debug:function(){s("debug",arguments)},info:function(){s("info",arguments)},warn:function(){s("warn",arguments)},error:function(){s("error",arguments)}},console.log("Detected lack of console, overridden console")}let promiseSupported=typeof Promise<"u";if(promiseSupported)try{let s;new Promise(f=>{s=f}),s()}catch{promiseSupported=!1}promiseSupported||(self.Promise=function(s){let f=()=>{};return s(h=>setTimeout(()=>f(h),0)),{then:h=>f=h}});const read_=(s,f)=>{const h=new XMLHttpRequest;return h.open("GET",s,!1),h.responseType=f?"arraybuffer":"text",h.send(null),h.response},readAsync=(s,f,h)=>{const C=new XMLHttpRequest;C.open("GET",s,!0),C.responseType="arraybuffer",C.onload=()=>{if((C.status===200||C.status===0)&&C.response)return f(C.response)},C.onerror=h,C.send(null)};let lastCurrentTime=0;const rate=1;let rafId=null,nextIsRaf=!1,lastCurrentTimeReceivedAt=Date.now(),targetFps=24,useLocalFonts=!1,blendMode="js",availableFonts={};const fontMap_={};let fontId=0,debug;self.width=0;self.height=0;let asyncRender=!1;self.addFont=({font:s})=>asyncWrite(s);const findAvailableFonts=s=>{s=s.trim().toLowerCase(),s.startsWith("@")&&(s=s.substring(1)),!fontMap_[s]&&(fontMap_[s]=!0,availableFonts[s]?asyncWrite(availableFonts[s]):useLocalFonts&&postMessage({target:"getLocalFont",font:s}))},asyncWrite=s=>{typeof s=="string"?readAsync(s,f=>{allocFont(new Uint8Array(f))},console.error):allocFont(s)},allocFont=s=>{const f=_malloc(s.byteLength);self.HEAPU8.set(s,f),jassubObj.addFont("font-"+fontId++,f,s.byteLength),jassubObj.reloadFonts()},processAvailableFonts=s=>{if(!availableFonts)return;const f=parseAss(s);for(let y=0;y<f.length;y++)for(let _=0;_<f[y].body.length;_++)f[y].body[_].key==="Style"&&findAvailableFonts(f[y].body[_].value.Fontname);const h=/\\fn([^\\}]*?)[\\}]/g;let C;for(;(C=h.exec(s))!==null;)findAvailableFonts(C[1])};self.setTrack=({content:s})=>{processAvailableFonts(s),dropAllBlur&&(s=dropBlur(s)),jassubObj.createTrackMem(s),subtitleColorSpace=libassYCbCrMap[jassubObj.trackColorSpace],postMessage({target:"verifyColorSpace",subtitleColorSpace})};self.getColorSpace=()=>postMessage({target:"verifyColorSpace",subtitleColorSpace});self.freeTrack=()=>{jassubObj.removeTrack()};self.setTrackByUrl=({url:s})=>{self.setTrack({content:read_(s)})};const getCurrentTime=()=>{const s=(Date.now()-lastCurrentTimeReceivedAt)/1e3;return _isPaused?lastCurrentTime:(s>5&&(console.error("Didn't received currentTime > 5 seconds. Assuming video was paused."),setIsPaused(!0)),lastCurrentTime+s*rate)},setCurrentTime=s=>{lastCurrentTime=s,lastCurrentTimeReceivedAt=Date.now(),rafId||(nextIsRaf?rafId=requestAnimationFrame(renderLoop):(renderLoop(),setTimeout(()=>{nextIsRaf=!1},20)))};let _isPaused=!0;const setIsPaused=s=>{s!==_isPaused&&(_isPaused=s,s?rafId&&(clearTimeout(rafId),rafId=null):(lastCurrentTimeReceivedAt=Date.now(),rafId=requestAnimationFrame(renderLoop)))},a="BT601",b="BT709",c="SMPTE240M",d="FCC",libassYCbCrMap=[null,a,null,a,a,b,b,c,c,d,d],render=(s,f)=>{const h={},C=performance.now(),y=blendMode==="wasm"?jassubObj.renderBlend(s,f||0):jassubObj.renderImage(s,f||0);if(debug){const _=performance.now(),A=jassubObj.time;h.WASMRenderTime=A-C,h.WASMBitmapDecodeTime=_-A,h.JSRenderTime=Date.now()}if(jassubObj.changed!==0||f){const _=[],A=[];if(!y)return paintImages({images:_,buffers:A,times:h});if(asyncRender){const w=[];for(let F=y,j=0;j<jassubObj.count;F=F.next,++j){const E={w:F.w,h:F.h,x:F.x,y:F.y},M=F.image,O=hasBitmapBug?self.HEAPU8C.slice(M,M+E.w*E.h*4):self.HEAPU8C.subarray(M,M+E.w*E.h*4);w.push(createImageBitmap(new ImageData(O,E.w,E.h))),_.push(E)}Promise.all(w).then(F=>{for(let j=0;j<_.length;j++)_[j].image=F[j];debug&&(h.JSBitmapGenerationTime=Date.now()-h.JSRenderTime),paintImages({images:_,buffers:F,times:h})})}else{for(let w=y,F=0;F<jassubObj.count;w=w.next,++F){const j={w:w.w,h:w.h,x:w.x,y:w.y,image:w.image};if(!offCanvasCtx){const E=self.wasmMemory.buffer.slice(w.image,w.image+w.w*w.h*4);A.push(E),j.image=E}_.push(j)}paintImages({images:_,buffers:A,times:h})}}else postMessage({target:"unbusy"})};self.demand=({time:s})=>{lastCurrentTime=s,render(s)};const renderLoop=s=>{rafId=0,render(getCurrentTime(),s),_isPaused||(rafId=requestAnimationFrame(renderLoop))},paintImages=({times:s,images:f,buffers:h})=>{const C={target:"render",asyncRender,images:f,times:s,width:self.width,height:self.height,colorSpace:subtitleColorSpace};if(offscreenRender){(offCanvas.height!==self.height||offCanvas.width!==self.width)&&(offCanvas.width=self.width,offCanvas.height=self.height),offCanvasCtx.clearRect(0,0,self.width,self.height);for(const y of f)y.image&&(asyncRender?(offCanvasCtx.drawImage(y.image,y.x,y.y),y.image.close()):(bufferCanvas.width=y.w,bufferCanvas.height=y.h,bufferCtx.putImageData(new ImageData(self.HEAPU8C.subarray(y.image,y.image+y.w*y.h*4),y.w,y.h),0,0),offCanvasCtx.drawImage(bufferCanvas,y.x,y.y)));if(offscreenRender==="hybrid"){if(!f.length)return postMessage(C);debug&&(s.bitmaps=f.length);try{const y=offCanvas.transferToImageBitmap();C.images=[{image:y,x:0,y:0}],C.asyncRender=!0,postMessage(C,[y])}catch{postMessage({target:"unbusy"})}}else{if(debug){s.JSRenderTime=Date.now()-s.JSRenderTime-(s.JSBitmapGenerationTime||0);let y=0;for(const _ in s)y+=s[_];console.log("Bitmaps: "+f.length+" Total: "+(y|0)+"ms",s)}postMessage({target:"unbusy"})}}else postMessage(C,h)},parseAss=s=>{let f,h,C,y,_,A,w,F,j,E;const M=[],O=s.split(/[\r\n]+/g);for(F=0;F<O.length;F++)if(f=O[F].match(/^\[(.*)\]$/),f)h=null,M.push({name:f[1],body:[]});else{if(/^\s*$/.test(O[F])||M.length===0)continue;if(E=M[M.length-1].body,O[F][0]===";")E.push({type:"comment",value:O[F].substring(1)});else{if(y=O[F].split(":"),_=y[0],A=y.slice(1).join(":").trim(),(h||_==="Format")&&(A=A.split(","),h&&A.length>h.length&&(C=A.slice(h.length-1).join(","),A=A.slice(0,h.length-1),A.push(C)),A=A.map(J=>J.trim()),h)){for(w={},j=0;j<A.length;j++)w[h[j]]=A[j];A=w}_==="Format"&&(h=A),E.push({key:_,value:A})}}return M},blurRegex=/\\blur(?:[0-9]+\.)?[0-9]+/gm,dropBlur=s=>s.replace(blurRegex,""),requestAnimationFrame=(()=>{let s=0;return f=>{const h=Date.now();if(s===0)s=h+1e3/targetFps;else for(;h+2>=s;)s+=1e3/targetFps;const C=Math.max(s-h,0);return setTimeout(f,C)}})(),_applyKeys=(s,f)=>{for(const h of Object.keys(s))f[h]=s[h]};let offCanvas,offCanvasCtx,offscreenRender,bufferCanvas,bufferCtx,jassubObj,subtitleColorSpace,dropAllBlur,_malloc,hasBitmapBug;self.init=data=>{hasBitmapBug=data.hasBitmapBug;try{const s=new WebAssembly.Module(Uint8Array.of(0,97,115,109,1,0,0,0));if(!(s instanceof WebAssembly.Module)||!(new WebAssembly.Instance(s)instanceof WebAssembly.Instance))throw new Error("WASM not supported")}catch(e){console.warn(e),eval(read_(data.legacyWasmUrl))}if(WebAssembly.instantiateStreaming){const s=self.fetch;self.fetch=f=>s(data.wasmUrl)}Module({wasm:!WebAssembly.instantiateStreaming&&read_(data.wasmUrl,!0)}).then(s=>{_malloc=s._malloc,self.width=data.width,self.height=data.height,blendMode=data.blendMode,asyncRender=data.asyncRender,asyncRender&&typeof createImageBitmap>"u"&&(asyncRender=!1,console.error("'createImageBitmap' needed for 'asyncRender' unsupported!")),availableFonts=data.availableFonts,debug=data.debug,targetFps=data.targetFps||targetFps,useLocalFonts=data.useLocalFonts,dropAllBlur=data.dropAllBlur;const f=data.fallbackFont.toLowerCase();jassubObj=new s.JASSUB(self.width,self.height,f||null,debug),f&&findAvailableFonts(f);let h=data.subContent;h||(h=read_(data.subUrl)),processAvailableFonts(h),dropAllBlur&&(h=dropBlur(h));for(const C of data.fonts||[])asyncWrite(C);jassubObj.createTrackMem(h),subtitleColorSpace=libassYCbCrMap[jassubObj.trackColorSpace],jassubObj.setDropAnimations(data.dropAllAnimations||0),(data.libassMemoryLimit>0||data.libassGlyphLimit>0)&&jassubObj.setMemoryLimits(data.libassGlyphLimit||0,data.libassMemoryLimit||0),postMessage({target:"ready"}),postMessage({target:"verifyColorSpace",subtitleColorSpace})})};self.offscreenCanvas=({transferable:s})=>{offCanvas=s[0],offCanvasCtx=offCanvas.getContext("2d"),asyncRender||(bufferCanvas=new OffscreenCanvas(self.height,self.width),bufferCtx=bufferCanvas.getContext("2d",{desynchronized:!0})),offscreenRender=!0};self.detachOffscreen=()=>{offCanvas=new OffscreenCanvas(self.height,self.width),offCanvasCtx=offCanvas.getContext("2d",{desynchronized:!0}),offscreenRender="hybrid"};self.canvas=({width:s,height:f,force:h})=>{if(s==null)throw new Error("Invalid canvas size specified");self.width=s,self.height=f,jassubObj&&jassubObj.resizeCanvas(s,f),h&&render(lastCurrentTime,!0)};self.video=({currentTime:s,isPaused:f,rate:h})=>{s!=null&&setCurrentTime(s),f!=null&&setIsPaused(f),h=h||h};self.destroy=()=>{jassubObj.quitLibrary()};self.createEvent=({event:s})=>{_applyKeys(s,jassubObj.getEvent(jassubObj.allocEvent()))};self.getEvents=()=>{const s=[];for(let f=0;f<jassubObj.getEventCount();f++){const{Start:h,Duration:C,ReadOrder:y,Layer:_,Style:A,MarginL:w,MarginR:F,MarginV:j,Name:E,Text:M,Effect:O}=jassubObj.getEvent(f);s.push({Start:h,Duration:C,ReadOrder:y,Layer:_,Style:A,MarginL:w,MarginR:F,MarginV:j,Name:E,Text:M,Effect:O})}postMessage({target:"getEvents",events:s})};self.setEvent=({event:s,index:f})=>{_applyKeys(s,jassubObj.getEvent(f))};self.removeEvent=({index:s})=>{jassubObj.removeEvent(s)};self.createStyle=({style:s})=>{_applyKeys(s,jassubObj.getStyle(jassubObj.allocStyle()))};self.getStyles=()=>{const s=[];for(let f=0;f<jassubObj.getStyleCount();f++){const{Name:h,FontName:C,FontSize:y,PrimaryColour:_,SecondaryColour:A,OutlineColour:w,BackColour:F,Bold:j,Italic:E,Underline:M,StrikeOut:O,ScaleX:J,ScaleY:k,Spacing:fe,Angle:le,BorderStyle:B,Outline:ue,Shadow:Y,Alignment:ce,MarginL:de,MarginR:pe,MarginV:X,Encoding:Te,treat_fontname_as_pattern:Pe,Blur:Ae,Justify:Fe}=jassubObj.getStyle(f);s.push({Name:h,FontName:C,FontSize:y,PrimaryColour:_,SecondaryColour:A,OutlineColour:w,BackColour:F,Bold:j,Italic:E,Underline:M,StrikeOut:O,ScaleX:J,ScaleY:k,Spacing:fe,Angle:le,BorderStyle:B,Outline:ue,Shadow:Y,Alignment:ce,MarginL:de,MarginR:pe,MarginV:X,Encoding:Te,treat_fontname_as_pattern:Pe,Blur:Ae,Justify:Fe})}postMessage({target:"getStyles",time:Date.now(),styles:s})};self.setStyle=({style:s,index:f})=>{_applyKeys(s,jassubObj.getStyle(f))};self.removeStyle=({index:s})=>{jassubObj.removeStyle(s)};onmessage=({data:s})=>{if(self[s.target])self[s.target](s);else throw new Error("Unknown event target "+s.target)};
|