241 lines
287 KiB
JavaScript
241 lines
287 KiB
JavaScript
"use strict";var _f=Object.defineProperty;var dl=n=>{throw TypeError(n)};var yf=(n,e,t)=>e in n?_f(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var Dt=(n,e,t)=>yf(n,typeof e!="symbol"?e+"":e,t),ca=(n,e,t)=>e.has(n)||dl("Cannot "+t);var k=(n,e,t)=>(ca(n,e,"read from private field"),t?t.call(n):e.get(n)),re=(n,e,t)=>e.has(n)?dl("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),X=(n,e,t,s)=>(ca(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),he=(n,e,t)=>(ca(n,e,"access private method"),t);const P=require("obsidian"),fl=globalThis.process?.env?.NODE_ENV,B=fl&&!fl.toLowerCase().startsWith("prod");var Li=Array.isArray,wf=Array.prototype.indexOf,vo=Array.from,gn=Object.defineProperty,is=Object.getOwnPropertyDescriptor,mc=Object.getOwnPropertyDescriptors,bf=Object.prototype,xf=Array.prototype,_o=Object.getPrototypeOf,hl=Object.isExtensible;function kf(n){return typeof n=="function"}const $t=()=>{};function Ef(n){return typeof n?.then=="function"}function Sf(n){return n()}function Ta(n){for(var e=0;e<n.length;e++)n[e]()}function gc(){var n,e,t=new Promise((s,r)=>{n=s,e=r});return{promise:t,resolve:n,reject:e}}const Ve=2,yo=4,Bi=8,en=16,wn=32,hs=64,Ui=128,Ft=512,ze=1024,rt=2048,tn=4096,ft=8192,fn=16384,ji=32768,us=65536,mi=1<<17,vc=1<<18,Vs=1<<19,_c=1<<20,Fn=32768,Ia=1<<21,zi=1<<22,$n=1<<23,Gt=Symbol("$state"),Af=Symbol("legacy props"),Cf=Symbol(""),yc=Symbol("proxy path"),Ts=new class extends Error{constructor(){super(...arguments);Dt(this,"name","StaleReactionError");Dt(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};function wc(n){return n===this.v}function bc(n,e){return n!=n?e==e:n!==e||n!==null&&typeof n=="object"||typeof n=="function"}function xc(n){return!bc(n,this.v)}function qi(n){if(B){const e=new Error(`lifecycle_outside_component
|
||
\`${n}(...)\` can only be used during component initialisation
|
||
https://svelte.dev/e/lifecycle_outside_component`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/lifecycle_outside_component")}function Pf(){if(B){const n=new Error("async_derived_orphan\nCannot create a `$derived(...)` with an `await` expression outside of an effect tree\nhttps://svelte.dev/e/async_derived_orphan");throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/async_derived_orphan")}function Tf(){if(B){const n=new Error(`derived_references_self
|
||
A derived value cannot reference itself recursively
|
||
https://svelte.dev/e/derived_references_self`);throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/derived_references_self")}function If(n){if(B){const e=new Error(`effect_in_teardown
|
||
\`${n}\` cannot be used inside an effect cleanup function
|
||
https://svelte.dev/e/effect_in_teardown`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_in_teardown")}function $f(){if(B){const n=new Error("effect_in_unowned_derived\nEffect cannot be created inside a `$derived` value that was not itself created inside an effect\nhttps://svelte.dev/e/effect_in_unowned_derived");throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function Rf(n){if(B){const e=new Error(`effect_orphan
|
||
\`${n}\` can only be used inside an effect (e.g. during component initialisation)
|
||
https://svelte.dev/e/effect_orphan`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/effect_orphan")}function Mf(){if(B){const n=new Error(`effect_update_depth_exceeded
|
||
Maximum update depth exceeded. This typically indicates that an effect reads and writes the same piece of state
|
||
https://svelte.dev/e/effect_update_depth_exceeded`);throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function Ff(n){if(B){const e=new Error(`lifecycle_legacy_only
|
||
\`${n}(...)\` cannot be used in runes mode
|
||
https://svelte.dev/e/lifecycle_legacy_only`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/lifecycle_legacy_only")}function Nf(n){if(B){const e=new Error(`props_invalid_value
|
||
Cannot do \`bind:${n}={undefined}\` when \`${n}\` has a fallback value
|
||
https://svelte.dev/e/props_invalid_value`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/props_invalid_value")}function Of(n){if(B){const e=new Error(`rune_outside_svelte
|
||
The \`${n}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files
|
||
https://svelte.dev/e/rune_outside_svelte`);throw e.name="Svelte error",e}else throw new Error("https://svelte.dev/e/rune_outside_svelte")}function Df(){if(B){const n=new Error("state_descriptors_fixed\nProperty descriptors defined on `$state` objects must contain `value` and always be `enumerable`, `configurable` and `writable`.\nhttps://svelte.dev/e/state_descriptors_fixed");throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function Lf(){if(B){const n=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/state_prototype_fixed")}function Bf(){if(B){const n=new Error("state_unsafe_mutation\nUpdating state inside `$derived(...)`, `$inspect(...)` or a template expression is forbidden. If the value should not be reactive, declare it without `$state`\nhttps://svelte.dev/e/state_unsafe_mutation");throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function Uf(){if(B){const n=new Error("svelte_boundary_reset_onerror\nA `<svelte:boundary>` `reset` function cannot be called while an error is still being handled\nhttps://svelte.dev/e/svelte_boundary_reset_onerror");throw n.name="Svelte error",n}else throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}let Ys=!1,jf=!1;function zf(){Ys=!0}const kc=1,Ec=2,Sc=4,qf=8,Wf=16,Hf=1,Vf=2,Yf=4,Kf=8,Jf=16,Xf=4,Gf=1,Qf=2,Ne=Symbol(),Zf=Symbol("filename"),eh="http://www.w3.org/1999/xhtml";function th(n){const e=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let t=Error();Error.stackTraceLimit=e;const s=t.stack;if(!s)return null;const r=s.split(`
|
||
`),i=[`
|
||
`];for(let a=0;a<r.length;a++){const o=r[a],l=o.replaceAll("\\","/");if(o!=="Error"){if(o.includes("validate_each_keys"))return null;l.includes("svelte/src/internal")||l.includes("node_modules/.vite")||i.push(o)}}return i.length===1?null:(gn(t,"stack",{value:i.join(`
|
||
`)}),gn(t,"name",{value:n}),t)}function Bt(n,e){return n.label=e,Ac(n.v,e),n}function Ac(n,e){return n?.[yc]?.(e),n}let oe=null;function Us(n){oe=n}let br=null;function gi(n){br=n}let Rr=null;function pl(n){Rr=n}function ge(n,e=!1,t){oe={p:oe,i:!1,c:null,e:null,s:n,x:null,l:Ys&&!e?{s:null,u:null,$:[]}:null},B&&(oe.function=t,Rr=t)}function ve(n){var e=oe,t=e.e;if(t!==null){e.e=null;for(var s of t)Xc(s)}return e.i=!0,oe=e.p,B&&(Rr=oe?.function??null),{}}function Ks(){return!Ys||oe!==null&&oe.l===null}let Kn=[];function Cc(){var n=Kn;Kn=[],Ta(n)}function Dn(n){if(Kn.length===0&&!Ms){var e=Kn;queueMicrotask(()=>{e===Kn&&Cc()})}Kn.push(n)}function nh(){for(;Kn.length>0;)Cc()}const sh=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function Is(n){if(typeof n!="object"||n===null||Gt in n)return n;const e=_o(n);if(e!==bf&&e!==xf)return n;var t=new Map,s=Li(n),r=An(0),i=as,a=d=>{if(as===i)return d();var u=se,h=as;tt(null),yl(i);var f=d();return tt(u),yl(h),f};s&&(t.set("length",An(n.length)),B&&(n=ih(n)));var o="";let l=!1;function c(d){if(!l){l=!0,o=d,Bt(r,`${o} version`);for(const[u,h]of t)Bt(h,jn(o,u));l=!1}}return new Proxy(n,{defineProperty(d,u,h){(!("value"in h)||h.configurable===!1||h.enumerable===!1||h.writable===!1)&&Df();var f=t.get(u);return f===void 0?f=a(()=>{var p=An(h.value);return t.set(u,p),B&&typeof u=="string"&&Bt(p,jn(o,u)),p}):T(f,h.value,!0),!0},deleteProperty(d,u){var h=t.get(u);if(h===void 0){if(u in d){const f=a(()=>An(Ne));t.set(u,f),mr(r),B&&Bt(f,jn(o,u))}}else T(h,Ne),mr(r);return!0},get(d,u,h){if(u===Gt)return n;if(B&&u===yc)return c;var f=t.get(u),p=u in d;if(f===void 0&&(!p||is(d,u)?.writable)&&(f=a(()=>{var v=Is(p?d[u]:Ne),_=An(v);return B&&Bt(_,jn(o,u)),_}),t.set(u,f)),f!==void 0){var m=g(f);return m===Ne?void 0:m}return Reflect.get(d,u,h)},getOwnPropertyDescriptor(d,u){var h=Reflect.getOwnPropertyDescriptor(d,u);if(h&&"value"in h){var f=t.get(u);f&&(h.value=g(f))}else if(h===void 0){var p=t.get(u),m=p?.v;if(p!==void 0&&m!==Ne)return{enumerable:!0,configurable:!0,value:m,writable:!0}}return h},has(d,u){if(u===Gt)return!0;var h=t.get(u),f=h!==void 0&&h.v!==Ne||Reflect.has(d,u);if(h!==void 0||ie!==null&&(!f||is(d,u)?.writable)){h===void 0&&(h=a(()=>{var m=f?Is(d[u]):Ne,v=An(m);return B&&Bt(v,jn(o,u)),v}),t.set(u,h));var p=g(h);if(p===Ne)return!1}return f},set(d,u,h,f){var p=t.get(u),m=u in d;if(s&&u==="length")for(var v=h;v<p.v;v+=1){var _=t.get(v+"");_!==void 0?T(_,Ne):v in d&&(_=a(()=>An(Ne)),t.set(v+"",_),B&&Bt(_,jn(o,v)))}if(p===void 0)(!m||is(d,u)?.writable)&&(p=a(()=>An(void 0)),B&&Bt(p,jn(o,u)),T(p,Is(h)),t.set(u,p));else{m=p.v!==Ne;var y=a(()=>Is(h));T(p,y)}var b=Reflect.getOwnPropertyDescriptor(d,u);if(b?.set&&b.set.call(f,h),!m){if(s&&typeof u=="string"){var E=t.get("length"),C=Number(u);Number.isInteger(C)&&C>=E.v&&T(E,C+1)}mr(r)}return!0},ownKeys(d){g(r);var u=Reflect.ownKeys(d).filter(p=>{var m=t.get(p);return m===void 0||m.v!==Ne});for(var[h,f]of t)f.v!==Ne&&!(h in d)&&u.push(h);return u},setPrototypeOf(){Lf()}})}function jn(n,e){return typeof e=="symbol"?`${n}[Symbol(${e.description??""})]`:sh.test(e)?`${n}.${e}`:/^\d+$/.test(e)?`${n}[${e}]`:`${n}['${e}']`}function ua(n){try{if(n!==null&&typeof n=="object"&&Gt in n)return n[Gt]}catch{}return n}const rh=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function ih(n){return new Proxy(n,{get(e,t,s){var r=Reflect.get(e,t,s);return rh.has(t)?function(...i){Sh();var a=r.apply(this,i);return jc(),a}:r}})}function ah(){const n=Array.prototype,e=Array.__svelte_cleanup;e&&e();const{indexOf:t,lastIndexOf:s,includes:r}=n;n.indexOf=function(i,a){const o=t.call(this,i,a);if(o===-1){for(let l=a??0;l<this.length;l+=1)if(ua(this[l])===i){break}}return o},n.lastIndexOf=function(i,a){const o=s.call(this,i,a??this.length-1);if(o===-1){for(let l=0;l<=(a??this.length-1);l+=1)if(ua(this[l])===i){break}}return o},n.includes=function(i,a){const o=r.call(this,i,a);if(!o){for(let l=0;l<this.length;l+=1)if(ua(this[l])===i){break}}return o},Array.__svelte_cleanup=()=>{n.indexOf=t,n.lastIndexOf=s,n.includes=r}}var ml,wo,Pc,Tc;function oh(){if(ml===void 0){ml=window,wo=/Firefox/.test(navigator.userAgent);var n=Element.prototype,e=Node.prototype,t=Text.prototype;Pc=is(e,"firstChild").get,Tc=is(e,"nextSibling").get,hl(n)&&(n.__click=void 0,n.__className=void 0,n.__attributes=null,n.__style=void 0,n.__e=void 0),hl(t)&&(t.__t=void 0),B&&(n.__svelte_meta=null,ah())}}function vn(n=""){return document.createTextNode(n)}function vi(n){return Pc.call(n)}function Mr(n){return Tc.call(n)}function R(n,e){return vi(n)}function Be(n,e=!1){{var t=vi(n);return t instanceof Comment&&t.data===""?Mr(t):t}}function H(n,e=1,t=!1){let s=n;for(;e--;)s=Mr(s);return s}function lh(n){n.textContent=""}function Ic(){return!1}const $a=new WeakMap;function $c(n){var e=ie;if(e===null)return se.f|=$n,n;if(B&&n instanceof Error&&!$a.has(n)&&$a.set(n,ch(n,e)),(e.f&ji)===0){if((e.f&Ui)===0)throw B&&!e.parent&&n instanceof Error&&Rc(n),n;e.b.error(n)}else js(n,e)}function js(n,e){for(;e!==null;){if((e.f&Ui)!==0)try{e.b.error(n);return}catch(t){n=t}e=e.parent}throw B&&n instanceof Error&&Rc(n),n}function ch(n,e){const t=is(n,"message");if(!(t&&!t.configurable)){for(var s=wo?" ":" ",r=`
|
||
${s}in ${e.fn?.name||"<unknown>"}`,i=e.ctx;i!==null;)r+=`
|
||
${s}in ${i.function?.[Zf].split("/").pop()}`,i=i.p;return{message:n.message+`
|
||
${r}
|
||
`,stack:n.stack?.split(`
|
||
`).filter(a=>!a.includes("svelte/src/internal")).join(`
|
||
`)}}}function Rc(n){const e=$a.get(n);e&&(gn(n,"message",{value:e.message}),gn(n,"stack",{value:e.stack}))}const Yr=new Set;let pe=null,xt=null,wt=[],Wi=null,Ra=!1,Ms=!1;var Os,Ds,Zn,es,Tr,Ls,Bs,Ce,Ma,qn,Fa,Mc,Fc;const Ni=class Ni{constructor(){re(this,Ce);Dt(this,"committed",!1);Dt(this,"current",new Map);Dt(this,"previous",new Map);re(this,Os,new Set);re(this,Ds,new Set);re(this,Zn,0);re(this,es,0);re(this,Tr,null);re(this,Ls,[]);re(this,Bs,[]);Dt(this,"skipped_effects",new Set);Dt(this,"is_fork",!1)}is_deferred(){return this.is_fork||k(this,es)>0}process(e){wt=[],this.apply();var t={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const s of e)he(this,Ce,Ma).call(this,s,t);this.is_fork||he(this,Ce,Mc).call(this),this.is_deferred()?(he(this,Ce,qn).call(this,t.effects),he(this,Ce,qn).call(this,t.render_effects),he(this,Ce,qn).call(this,t.block_effects)):(pe=null,gl(t.render_effects),gl(t.effects),k(this,Tr)?.resolve()),xt=null}capture(e,t){this.previous.has(e)||this.previous.set(e,t),(e.f&$n)===0&&(this.current.set(e,e.v),xt?.set(e,e.v))}activate(){pe=this,this.apply()}deactivate(){pe===this&&(pe=null,xt=null)}flush(){if(this.activate(),wt.length>0){if(Nc(),pe!==null&&pe!==this)return}else k(this,Zn)===0&&this.process([]);this.deactivate()}discard(){for(const e of k(this,Ds))e(this);k(this,Ds).clear()}increment(e){X(this,Zn,k(this,Zn)+1),e&&X(this,es,k(this,es)+1)}decrement(e){X(this,Zn,k(this,Zn)-1),e&&X(this,es,k(this,es)-1),this.revive()}revive(){for(const e of k(this,Ls))We(e,rt),ds(e);for(const e of k(this,Bs))We(e,tn),ds(e);X(this,Ls,[]),X(this,Bs,[]),this.flush()}oncommit(e){k(this,Os).add(e)}ondiscard(e){k(this,Ds).add(e)}settled(){return(k(this,Tr)??X(this,Tr,gc())).promise}static ensure(){if(pe===null){const e=pe=new Ni;Yr.add(pe),Ms||Ni.enqueue(()=>{pe===e&&e.flush()})}return pe}static enqueue(e){Dn(e)}apply(){}};Os=new WeakMap,Ds=new WeakMap,Zn=new WeakMap,es=new WeakMap,Tr=new WeakMap,Ls=new WeakMap,Bs=new WeakMap,Ce=new WeakSet,Ma=function(e,t){e.f^=ze;for(var s=e.first;s!==null;){var r=s.f,i=(r&(wn|hs))!==0,a=i&&(r&ze)!==0,o=a||(r&ft)!==0||this.skipped_effects.has(s);if((s.f&Ui)!==0&&s.b?.is_pending()&&(t={parent:t,effect:s,effects:[],render_effects:[],block_effects:[]}),!o&&s.fn!==null){i?s.f^=ze:(r&yo)!==0?t.effects.push(s):Js(s)&&((s.f&en)!==0&&t.block_effects.push(s),Ws(s));var l=s.first;if(l!==null){s=l;continue}}var c=s.parent;for(s=s.next;s===null&&c!==null;)c===t.effect&&(he(this,Ce,qn).call(this,t.effects),he(this,Ce,qn).call(this,t.render_effects),he(this,Ce,qn).call(this,t.block_effects),t=t.parent),s=c.next,c=c.parent}},qn=function(e){for(const t of e)((t.f&rt)!==0?k(this,Ls):k(this,Bs)).push(t),he(this,Ce,Fa).call(this,t.deps),We(t,ze)},Fa=function(e){if(e!==null)for(const t of e)(t.f&Ve)===0||(t.f&Fn)===0||(t.f^=Fn,he(this,Ce,Fa).call(this,t.deps))},Mc=function(){if(k(this,es)===0){for(const e of k(this,Os))e();k(this,Os).clear()}k(this,Zn)===0&&he(this,Ce,Fc).call(this)},Fc=function(){var i;if(Yr.size>1){this.previous.clear();var e=xt,t=!0,s={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const a of Yr){if(a===this){t=!1;continue}const o=[];for(const[c,d]of this.current){if(a.current.has(c))if(t&&d!==a.current.get(c))a.current.set(c,d);else continue;o.push(c)}if(o.length===0)continue;const l=[...a.current.keys()].filter(c=>!this.current.has(c));if(l.length>0){var r=wt;wt=[];const c=new Set,d=new Map;for(const u of o)Oc(u,l,c,d);if(wt.length>0){pe=a,a.apply();for(const u of wt)he(i=a,Ce,Ma).call(i,u,s);a.deactivate()}wt=r}}pe=null,xt=e}this.committed=!0,Yr.delete(this)};let Yt=Ni;function uh(n){var e=Ms;Ms=!0;try{for(var t;;){if(nh(),wt.length===0&&(pe?.flush(),wt.length===0))return Wi=null,t;Nc()}}finally{Ms=e}}function Nc(){var n=Mn;Ra=!0;var e=B?new Set:null;try{var t=0;for(_i(!0);wt.length>0;){var s=Yt.ensure();if(t++>1e3){if(B){var r=new Map;for(const a of s.current.keys())for(const[o,l]of a.updated??[]){var i=r.get(o);i||(i={error:l.error,count:0},r.set(o,i)),i.count+=l.count}for(const a of r.values())a.error}dh()}if(s.process(wt),Rn.clear(),B)for(const a of s.current.keys())e.add(a)}}finally{if(Ra=!1,_i(n),Wi=null,B)for(const a of e)a.updated=null}}function dh(){try{Mf()}catch(n){B&&gn(n,"stack",{value:""}),js(n,Wi)}}let ln=null;function gl(n){var e=n.length;if(e!==0){for(var t=0;t<e;){var s=n[t++];if((s.f&(fn|ft))===0&&Js(s)&&(ln=new Set,Ws(s),s.deps===null&&s.first===null&&s.nodes_start===null&&(s.teardown===null&&s.ac===null?Zc(s):s.fn=null),ln?.size>0)){Rn.clear();for(const r of ln){if((r.f&(fn|ft))!==0)continue;const i=[r];let a=r.parent;for(;a!==null;)ln.has(a)&&(ln.delete(a),i.push(a)),a=a.parent;for(let o=i.length-1;o>=0;o--){const l=i[o];(l.f&(fn|ft))===0&&Ws(l)}}ln.clear()}}ln=null}}function Oc(n,e,t,s){if(!t.has(n)&&(t.add(n),n.reactions!==null))for(const r of n.reactions){const i=r.f;(i&Ve)!==0?Oc(r,e,t,s):(i&(zi|en))!==0&&(i&rt)===0&&Dc(r,e,s)&&(We(r,rt),ds(r))}}function Dc(n,e,t){const s=t.get(n);if(s!==void 0)return s;if(n.deps!==null)for(const r of n.deps){if(e.includes(r))return!0;if((r.f&Ve)!==0&&Dc(r,e,t))return t.set(r,!0),!0}return t.set(n,!1),!1}function ds(n){for(var e=Wi=n;e.parent!==null;){e=e.parent;var t=e.f;if(Ra&&e===ie&&(t&en)!==0&&(t&vc)===0)return;if((t&(hs|wn))!==0){if((t&ze)===0)return;e.f^=ze}}wt.push(e)}function fh(n){let e=0,t=_n(0),s;return B&&Bt(t,"createSubscriber version"),()=>{Hi()&&(g(t),Gs(()=>(e===0&&(s=z(()=>n(()=>mr(t)))),e+=1,()=>{Dn(()=>{e-=1,e===0&&(s?.(),s=void 0,mr(t))})})))}}var hh=us|Vs|Ui;function ph(n,e,t){new mh(n,e,t)}var vt,_t,go,zt,ts,qt,yt,Ze,Wt,cn,Tn,ns,In,ss,un,Oi,Re,gh,vh,Na,si,ri,Oa;class mh{constructor(e,t,s){re(this,Re);Dt(this,"parent");re(this,vt,!1);re(this,_t);re(this,go,null);re(this,zt);re(this,ts);re(this,qt);re(this,yt,null);re(this,Ze,null);re(this,Wt,null);re(this,cn,null);re(this,Tn,null);re(this,ns,0);re(this,In,0);re(this,ss,!1);re(this,un,null);re(this,Oi,fh(()=>(X(this,un,_n(k(this,ns))),B&&Bt(k(this,un),"$effect.pending()"),()=>{X(this,un,null)})));X(this,_t,e),X(this,zt,t),X(this,ts,s),this.parent=ie.b,X(this,vt,!!k(this,zt).pending),X(this,qt,Vi(()=>{ie.b=this;{var r=he(this,Re,Na).call(this);try{X(this,yt,bt(()=>s(r)))}catch(i){this.error(i)}k(this,In)>0?he(this,Re,ri).call(this):X(this,vt,!1)}return()=>{k(this,Tn)?.remove()}},hh))}is_pending(){return k(this,vt)||!!this.parent&&this.parent.is_pending()}has_pending_snippet(){return!!k(this,zt).pending}update_pending_count(e){he(this,Re,Oa).call(this,e),X(this,ns,k(this,ns)+e),k(this,un)&&hn(k(this,un),k(this,ns))}get_effect_pending(){return k(this,Oi).call(this),g(k(this,un))}error(e){var t=k(this,zt).onerror;let s=k(this,zt).failed;if(k(this,ss)||!t&&!s)throw e;k(this,yt)&&(st(k(this,yt)),X(this,yt,null)),k(this,Ze)&&(st(k(this,Ze)),X(this,Ze,null)),k(this,Wt)&&(st(k(this,Wt)),X(this,Wt,null));var r=!1,i=!1;const a=()=>{if(r){return}r=!0,i&&Uf(),Yt.ensure(),X(this,ns,0),k(this,Wt)!==null&&Ns(k(this,Wt),()=>{X(this,Wt,null)}),X(this,vt,this.has_pending_snippet()),X(this,yt,he(this,Re,si).call(this,()=>(X(this,ss,!1),bt(()=>k(this,ts).call(this,k(this,_t)))))),k(this,In)>0?he(this,Re,ri).call(this):X(this,vt,!1)};var o=se;try{tt(null),i=!0,t?.(e,a),i=!1}catch(l){js(l,k(this,qt)&&k(this,qt).parent)}finally{tt(o)}s&&Dn(()=>{X(this,Wt,he(this,Re,si).call(this,()=>{Yt.ensure(),X(this,ss,!0);try{return bt(()=>{s(k(this,_t),()=>e,()=>a)})}catch(l){return js(l,k(this,qt).parent),null}finally{X(this,ss,!1)}}))})}}vt=new WeakMap,_t=new WeakMap,go=new WeakMap,zt=new WeakMap,ts=new WeakMap,qt=new WeakMap,yt=new WeakMap,Ze=new WeakMap,Wt=new WeakMap,cn=new WeakMap,Tn=new WeakMap,ns=new WeakMap,In=new WeakMap,ss=new WeakMap,un=new WeakMap,Oi=new WeakMap,Re=new WeakSet,gh=function(){try{X(this,yt,bt(()=>k(this,ts).call(this,k(this,_t))))}catch(e){this.error(e)}X(this,vt,!1)},vh=function(){const e=k(this,zt).pending;e&&(X(this,Ze,bt(()=>e(k(this,_t)))),Yt.enqueue(()=>{var t=he(this,Re,Na).call(this);X(this,yt,he(this,Re,si).call(this,()=>(Yt.ensure(),bt(()=>k(this,ts).call(this,t))))),k(this,In)>0?he(this,Re,ri).call(this):(Ns(k(this,Ze),()=>{X(this,Ze,null)}),X(this,vt,!1))}))},Na=function(){var e=k(this,_t);return k(this,vt)&&(X(this,Tn,vn()),k(this,_t).before(k(this,Tn)),e=k(this,Tn)),e},si=function(e){var t=ie,s=se,r=oe;Mt(k(this,qt)),tt(k(this,qt)),Us(k(this,qt).ctx);try{return e()}catch(i){return $c(i),null}finally{Mt(t),tt(s),Us(r)}},ri=function(){const e=k(this,zt).pending;k(this,yt)!==null&&(X(this,cn,document.createDocumentFragment()),k(this,cn).append(k(this,Tn)),nu(k(this,yt),k(this,cn))),k(this,Ze)===null&&X(this,Ze,bt(()=>e(k(this,_t))))},Oa=function(e){var t;if(!this.has_pending_snippet()){this.parent&&he(t=this.parent,Re,Oa).call(t,e);return}X(this,In,k(this,In)+e),k(this,In)===0&&(X(this,vt,!1),k(this,Ze)&&Ns(k(this,Ze),()=>{X(this,Ze,null)}),k(this,cn)&&(k(this,_t).before(k(this,cn)),X(this,cn,null)))};function Lc(n,e){return e}function _h(n,e,t){for(var s=[],r=e.length,i=0;i<r;i++)Eo(e[i].e,s,!0);eu(s,()=>{var a=s.length===0&&t!==null;if(a){var o=t,l=o.parentNode;lh(l),l.append(o),n.items.clear(),Ut(n,e[0].prev,e[r-1].next)}for(var c=0;c<r;c++){var d=e[c];a||(n.items.delete(d.k),Ut(n,d.prev,d.next)),st(d.e,!a)}n.first===e[0]&&(n.first=e[0].prev)})}function zs(n,e,t,s,r,i=null){var a=n,o=new Map,l=null,c=(e&Sc)!==0,d=(e&kc)!==0,u=(e&Ec)!==0;if(c){var h=n;a=h.appendChild(vn())}var f=null,p=qe(()=>{var E=t();return Li(E)?E:E==null?[]:vo(E)}),m,v=!0;function _(){yh(b,m,a,e,s),f!==null&&(m.length===0?(f.fragment?(a.before(f.fragment),f.fragment=null):So(f.effect),y.first=f.effect):Ns(f.effect,()=>{f=null}))}var y=Vi(()=>{m=g(p);for(var E=m.length,C=new Set,F=pe,x=null,A=Ic(),I=0;I<E;I+=1){var $=m[I],D=s($,I),G=v?null:o.get(D);G?(d&&hn(G.v,$),u?hn(G.i,I):G.i=I,A&&F.skipped_effects.delete(G.e)):(G=wh(v?a:null,x,$,D,I,r,e,t),v&&(G.o=!0,x===null?l=G:x.next=G,x=G),o.set(D,G)),C.add(D)}if(E===0&&i&&!f)if(v)f={fragment:null,effect:bt(()=>i(a))};else{var ye=document.createDocumentFragment(),ce=vn();ye.append(ce),f={fragment:ye,effect:bt(()=>i(ce))}}if(!v)if(A){for(const[Ee,we]of o)C.has(Ee)||F.skipped_effects.add(we.e);F.oncommit(_),F.ondiscard(()=>{})}else _();g(p)}),b={effect:y,items:o,first:l};v=!1}function yh(n,e,t,s,r){var i=(s&qf)!==0,a=e.length,o=n.items,l=n.first,c,d=null,u,h=[],f=[],p,m,v,_;if(i)for(_=0;_<a;_+=1)p=e[_],m=r(p,_),v=o.get(m),v.a?.measure(),(u??(u=new Set)).add(v);for(_=0;_<a;_+=1){if(p=e[_],m=r(p,_),v=o.get(m),n.first??(n.first=v),!v.o){v.o=!0;var y=d?d.next:l;Ut(n,d,v),Ut(n,v,y),da(v,y,t),d=v,h=[],f=[],l=d.next;continue}if((v.e.f&ft)!==0&&(So(v.e),i&&(v.a?.unfix(),(u??(u=new Set)).delete(v))),v!==l){if(c!==void 0&&c.has(v)){if(h.length<f.length){var b=f[0],E;d=b.prev;var C=h[0],F=h[h.length-1];for(E=0;E<h.length;E+=1)da(h[E],b,t);for(E=0;E<f.length;E+=1)c.delete(f[E]);Ut(n,C.prev,F.next),Ut(n,d,C),Ut(n,F,b),l=b,d=F,_-=1,h=[],f=[]}else c.delete(v),da(v,l,t),Ut(n,v.prev,v.next),Ut(n,v,d===null?n.first:d.next),Ut(n,d,v),d=v;continue}for(h=[],f=[];l!==null&&l.k!==m;)(l.e.f&ft)===0&&(c??(c=new Set)).add(l),f.push(l),l=l.next;if(l===null)continue;v=l}h.push(v),d=v,l=v.next}if(l!==null||c!==void 0){for(var x=c===void 0?[]:vo(c);l!==null;)(l.e.f&ft)===0&&x.push(l),l=l.next;var A=x.length;if(A>0){var I=(s&Sc)!==0&&a===0?t:null;if(i){for(_=0;_<A;_+=1)x[_].a?.measure();for(_=0;_<A;_+=1)x[_].a?.fix()}_h(n,x,I)}}i&&Dn(()=>{if(u!==void 0)for(v of u)v.a?.apply()})}function wh(n,e,t,s,r,i,a,o){var l=(a&kc)!==0,c=(a&Wf)===0,d=l?c?q(t,!1,!1):_n(t):t,u=(a&Ec)===0?r:_n(r);B&&l&&(d.trace=()=>{var p=typeof u=="number"?r:u.v;o()[p]});var h={i:u,v:d,k:s,a:null,e:null,o:!1,prev:e,next:null};try{if(n===null){var f=document.createDocumentFragment();f.append(n=vn())}return h.e=bt(()=>i(n,d,u,o)),e!==null&&(e.next=h),h}finally{}}function da(n,e,t){for(var s=n.next?n.next.e.nodes_start:t,r=e?e.e.nodes_start:t,i=n.e.nodes_start;i!==null&&i!==s;){var a=Mr(i);r.before(i),i=a}}function Ut(n,e,t){e===null?(n.first=t,n.effect.first=t&&t.e):(e.e.next&&(e.e.next.prev=null),e.next=t,e.e.next=t&&t.e),t===null?n.effect.last=e&&e.e:(t.e.prev&&(t.e.prev.next=null),t.prev=e,t.e.prev=e&&e.e)}function bh(n,e,t,s){const r=Ks()?Fr:qe;if(t.length===0&&n.length===0){s(e.map(r));return}var i=pe,a=ie,o=Bc();function l(){Promise.all(t.map(c=>kh(c))).then(c=>{o();try{s([...e.map(r),...c])}catch(d){(a.f&fn)===0&&js(d,a)}i?.deactivate(),xr()}).catch(c=>{js(c,a)})}n.length>0?Promise.all(n).then(()=>{o();try{return l()}finally{i?.deactivate(),xr()}}):l()}function Bc(){var n=ie,e=se,t=oe,s=pe;if(B)var r=br;return function(a=!0){Mt(n),tt(e),Us(t),a&&s?.activate(),B&&gi(r)}}function xr(){Mt(null),tt(null),Us(null),B&&gi(null)}const xh=new Set;function Fr(n){var e=Ve|rt,t=se!==null&&(se.f&Ve)!==0?se:null;return ie!==null&&(ie.f|=Vs),{ctx:oe,deps:null,effects:null,equals:wc,f:e,fn:n,reactions:null,rv:0,v:Ne,wv:0,parent:t??ie,ac:null}}function kh(n,e){let t=ie;t===null&&Pf();var s=t.b,r=void 0,i=_n(Ne),a=!se,o=new Map;return Rh(()=>{var l=gc();r=l.promise;try{Promise.resolve(n()).then(l.resolve,l.reject).then(()=>{c===pe&&c.committed&&c.deactivate(),xr()})}catch(h){l.reject(h),xr()}var c=pe;if(a){var d=!s.is_pending();s.update_pending_count(1),c.increment(d),o.get(c)?.reject(Ts),o.delete(c),o.set(c,l)}const u=(h,f=void 0)=>{if(c.activate(),f)f!==Ts&&(i.f|=$n,hn(i,f));else{(i.f&$n)!==0&&(i.f^=$n),hn(i,h);for(const[p,m]of o){if(o.delete(p),p===c)break;m.reject(Ts)}}a&&(s.update_pending_count(-1),c.decrement(d))};l.promise.then(u,h=>u(null,h||"unknown"))}),Xs(()=>{for(const l of o.values())l.reject(Ts)}),B&&(i.f|=zi),new Promise(l=>{function c(d){function u(){d===r?l(i):c(r)}d.then(u,u)}c(r)})}function Fs(n){const e=Fr(n);return qc(e),e}function qe(n){const e=Fr(n);return e.equals=xc,e}function Da(n){var e=n.effects;if(e!==null){n.effects=null;for(var t=0;t<e.length;t+=1)st(e[t])}}let fa=[];function Eh(n){for(var e=n.parent;e!==null;){if((e.f&Ve)===0)return(e.f&fn)===0?e:null;e=e.parent}return null}function bo(n){var e,t=ie;if(Mt(Eh(n)),B){let s=qs;vl(new Set);try{fa.includes(n)&&Tf(),fa.push(n),n.f&=~Fn,Da(n),e=La(n)}finally{Mt(t),vl(s),fa.pop()}}else try{n.f&=~Fn,Da(n),e=La(n)}finally{Mt(t)}return e}function Uc(n){var e=bo(n);if(n.equals(e)||(pe?.is_fork||(n.v=e),n.wv=Hc()),!ps)if(xt!==null)Hi()&&xt.set(n,e);else{var t=(n.f&Ft)===0?tn:ze;We(n,t)}}let qs=new Set;const Rn=new Map;function vl(n){qs=n}let xo=!1;function Sh(){xo=!0}function _n(n,e){var t={f:0,v:n,reactions:null,equals:wc,rv:0,wv:0};return t}function An(n,e){const t=_n(n);return qc(t),t}function q(n,e=!1,t=!0){var r;const s=_n(n);return e||(s.equals=xc),Ys&&t&&oe!==null&&oe.l!==null&&((r=oe.l).s??(r.s=[])).push(s),s}function pr(n,e){return T(n,z(()=>g(n))),e}function T(n,e,t=!1){se!==null&&(!Kt||(se.f&mi)!==0)&&Ks()&&(se.f&(Ve|en|zi|mi))!==0&&!pn?.includes(n)&&Bf();let s=t?Is(e):e;return B&&Ac(s,n.label),hn(n,s)}function hn(n,e){if(!n.equals(e)){var t=n.v;ps?Rn.set(n,e):Rn.set(n,t),n.v=e;var s=Yt.ensure();if(s.capture(n,t),B){if(ie!==null){n.updated??(n.updated=new Map);const r=(n.updated.get("")?.count??0)+1;if(n.updated.set("",{error:null,count:r}),r>5){const i=th("updated at");if(i!==null){let a=n.updated.get(i.stack);a||(a={error:i,count:0},n.updated.set(i.stack,a)),a.count++}}}ie!==null&&(n.set_during_effect=!0)}(n.f&Ve)!==0&&((n.f&rt)!==0&&bo(n),We(n,(n.f&Ft)!==0?ze:tn)),n.wv=Hc(),zc(n,rt),Ks()&&ie!==null&&(ie.f&ze)!==0&&(ie.f&(wn|hs))===0&&(gt===null?Ah([n]):gt.push(n)),!s.is_fork&&qs.size>0&&!xo&&jc()}return e}function jc(){xo=!1;var n=Mn;_i(!0);const e=Array.from(qs);try{for(const t of e)(t.f&ze)!==0&&We(t,tn),Js(t)&&Ws(t)}finally{_i(n)}qs.clear()}function mr(n){T(n,n.v+1)}function zc(n,e){var t=n.reactions;if(t!==null)for(var s=Ks(),r=t.length,i=0;i<r;i++){var a=t[i],o=a.f;if(!(!s&&a===ie)){if(B&&(o&mi)!==0){qs.add(a);continue}var l=(o&rt)===0;if(l&&We(a,e),(o&Ve)!==0){var c=a;xt?.delete(c),(o&Fn)===0&&(o&Ft&&(a.f|=Fn),zc(c,tn))}else l&&((o&en)!==0&&ln!==null&&ln.add(a),ds(a))}}}function ko(n,e,t,s=!0){s&&t();for(var r of e)n.addEventListener(r,t);Xs(()=>{for(var i of e)n.removeEventListener(i,t)})}function Nr(n){var e=se,t=ie;tt(null),Mt(null);try{return n()}finally{tt(e),Mt(t)}}let Mn=!1;function _i(n){Mn=n}let ps=!1;function _l(n){ps=n}let se=null,Kt=!1;function tt(n){se=n}let ie=null;function Mt(n){ie=n}let pn=null;function qc(n){se!==null&&(pn===null?pn=[n]:pn.push(n))}let Xe=null,ot=0,gt=null;function Ah(n){gt=n}let Wc=1,kr=0,as=kr;function yl(n){as=n}function Hc(){return++Wc}function Js(n){var e=n.f;if((e&rt)!==0)return!0;if(e&Ve&&(n.f&=~Fn),(e&tn)!==0){var t=n.deps;if(t!==null)for(var s=t.length,r=0;r<s;r++){var i=t[r];if(Js(i)&&Uc(i),i.wv>n.wv)return!0}(e&Ft)!==0&&xt===null&&We(n,ze)}return!1}function Vc(n,e,t=!0){var s=n.reactions;if(s!==null&&!pn?.includes(n))for(var r=0;r<s.length;r++){var i=s[r];(i.f&Ve)!==0?Vc(i,e,!1):e===i&&(t?We(i,rt):(i.f&ze)!==0&&We(i,tn),ds(i))}}function La(n){var p;var e=Xe,t=ot,s=gt,r=se,i=pn,a=oe,o=Kt,l=as,c=n.f;Xe=null,ot=0,gt=null,se=(c&(wn|hs))===0?n:null,pn=null,Us(n.ctx),Kt=!1,as=++kr,n.ac!==null&&(Nr(()=>{n.ac.abort(Ts)}),n.ac=null);try{n.f|=Ia;var d=n.fn,u=d(),h=n.deps;if(Xe!==null){var f;if(yi(n,ot),h!==null&&ot>0)for(h.length=ot+Xe.length,f=0;f<Xe.length;f++)h[ot+f]=Xe[f];else n.deps=h=Xe;if(Mn&&Hi()&&(n.f&Ft)!==0)for(f=ot;f<h.length;f++)((p=h[f]).reactions??(p.reactions=[])).push(n)}else h!==null&&ot<h.length&&(yi(n,ot),h.length=ot);if(Ks()&>!==null&&!Kt&&h!==null&&(n.f&(Ve|tn|rt))===0)for(f=0;f<gt.length;f++)Vc(gt[f],n);return r!==null&&r!==n&&(kr++,gt!==null&&(s===null?s=gt:s.push(...gt))),(n.f&$n)!==0&&(n.f^=$n),u}catch(m){return $c(m)}finally{n.f^=Ia,Xe=e,ot=t,gt=s,se=r,pn=i,Us(a),Kt=o,as=l}}function Ch(n,e){let t=e.reactions;if(t!==null){var s=wf.call(t,n);if(s!==-1){var r=t.length-1;r===0?t=e.reactions=null:(t[s]=t[r],t.pop())}}t===null&&(e.f&Ve)!==0&&(Xe===null||!Xe.includes(e))&&(We(e,tn),(e.f&Ft)!==0&&(e.f^=Ft,e.f&=~Fn),Da(e),yi(e,0))}function yi(n,e){var t=n.deps;if(t!==null)for(var s=e;s<t.length;s++)Ch(n,t[s])}function Ws(n){var e=n.f;if((e&fn)===0){We(n,ze);var t=ie,s=Mn;if(ie=n,Mn=!0,B){var r=Rr;pl(n.component_function);var i=br;gi(n.dev_stack??br)}try{(e&en)!==0?Mh(n):Qc(n),Gc(n);var a=La(n);n.teardown=typeof a=="function"?a:null,n.wv=Wc;var o;B&&jf&&(n.f&rt)!==0&&n.deps}finally{Mn=s,ie=t,B&&(pl(r),gi(i))}}}function g(n){var e=n.f,t=(e&Ve)!==0;if(se!==null&&!Kt){var s=ie!==null&&(ie.f&fn)!==0;if(!s&&!pn?.includes(n)){var r=se.deps;if((se.f&Ia)!==0)n.rv<kr&&(n.rv=kr,Xe===null&&r!==null&&r[ot]===n?ot++:Xe===null?Xe=[n]:Xe.includes(n)||Xe.push(n));else{(se.deps??(se.deps=[])).push(n);var i=n.reactions;i===null?n.reactions=[se]:i.includes(se)||i.push(se)}}}if(B&&xh.delete(n),ps){if(Rn.has(n))return Rn.get(n);if(t){var a=n,o=a.v;return((a.f&ze)===0&&a.reactions!==null||Kc(a))&&(o=bo(a)),Rn.set(a,o),o}}else t&&!xt?.has(n)&&(a=n,Js(a)&&Uc(a),Mn&&Hi()&&(a.f&Ft)===0&&Yc(a));if(xt?.has(n))return xt.get(n);if((n.f&$n)!==0)throw n.v;return n.v}function Yc(n){if(n.deps!==null){n.f^=Ft;for(const e of n.deps)(e.reactions??(e.reactions=[])).push(n),(e.f&Ve)!==0&&(e.f&Ft)===0&&Yc(e)}}function Kc(n){if(n.v===Ne)return!0;if(n.deps===null)return!1;for(const e of n.deps)if(Rn.has(e)||(e.f&Ve)!==0&&Kc(e))return!0;return!1}function z(n){var e=Kt;try{return Kt=!0,n()}finally{Kt=e}}const Ph=-7169;function We(n,e){n.f=n.f&Ph|e}function O(n){if(!(typeof n!="object"||!n||n instanceof EventTarget)){if(Gt in n)Ba(n);else if(!Array.isArray(n))for(let e in n){const t=n[e];typeof t=="object"&&t&&Gt in t&&Ba(t)}}}function Ba(n,e=new Set){if(typeof n=="object"&&n!==null&&!(n instanceof EventTarget)&&!e.has(n)){e.add(n),n instanceof Date&&n.getTime();for(let s in n)try{Ba(n[s],e)}catch{}const t=_o(n);if(t!==Object.prototype&&t!==Array.prototype&&t!==Map.prototype&&t!==Set.prototype&&t!==Date.prototype){const s=mc(t);for(let r in s){const i=s[r].get;if(i)try{i.call(n)}catch{}}}}}function Jc(n){ie===null&&(se===null&&Rf(n),$f()),ps&&If(n)}function Th(n,e){var t=e.last;t===null?e.last=e.first=n:(t.next=n,n.prev=t,e.last=n)}function nn(n,e,t){var s=ie;if(B)for(;s!==null&&(s.f&mi)!==0;)s=s.parent;s!==null&&(s.f&ft)!==0&&(n|=ft);var r={ctx:oe,deps:null,nodes_start:null,nodes_end:null,f:n|rt|Ft,first:null,fn:e,last:null,next:null,parent:s,b:s&&s.b,prev:null,teardown:null,transitions:null,wv:0,ac:null};if(B&&(r.component_function=Rr),t)try{Ws(r),r.f|=ji}catch(o){throw st(r),o}else e!==null&&ds(r);var i=r;if(t&&i.deps===null&&i.teardown===null&&i.nodes_start===null&&i.first===i.last&&(i.f&Vs)===0&&(i=i.first,(n&en)!==0&&(n&us)!==0&&i!==null&&(i.f|=us)),i!==null&&(i.parent=s,s!==null&&Th(i,s),se!==null&&(se.f&Ve)!==0&&(n&hs)===0)){var a=se;(a.effects??(a.effects=[])).push(i)}return r}function Hi(){return se!==null&&!Kt}function Xs(n){const e=nn(Bi,null,!1);return We(e,ze),e.teardown=n,e}function Ua(n){Jc("$effect"),B&&gn(n,"name",{value:"$effect"});var e=ie.f,t=!se&&(e&wn)!==0&&(e&ji)===0;if(t){var s=oe;(s.e??(s.e=[])).push(n)}else return Xc(n)}function Xc(n){return nn(yo|_c,n,!1)}function Ih(n){return Jc("$effect.pre"),B&&gn(n,"name",{value:"$effect.pre"}),nn(Bi|_c,n,!0)}function $h(n){Yt.ensure();const e=nn(hs|Vs,n,!0);return(t={})=>new Promise(s=>{t.outro?Ns(e,()=>{st(e),s(void 0)}):(st(e),s(void 0))})}function Hs(n){return nn(yo,n,!1)}function He(n,e){var t=oe,s={effect:null,ran:!1,deps:n};t.l.$.push(s),s.effect=Gs(()=>{n(),!s.ran&&(s.ran=!0,z(e))})}function sn(){var n=oe;Gs(()=>{for(var e of n.l.$){e.deps();var t=e.effect;(t.f&ze)!==0&&We(t,tn),Js(t)&&Ws(t),e.ran=!1}})}function Rh(n){return nn(zi|Vs,n,!0)}function Gs(n,e=0){return nn(Bi|e,n,!0)}function me(n,e=[],t=[],s=[]){bh(s,e,t,r=>{nn(Bi,()=>n(...r.map(g)),!0)})}function Vi(n,e=0){var t=nn(en|e,n,!0);return B&&(t.dev_stack=br),t}function bt(n){return nn(wn|Vs,n,!0)}function Gc(n){var e=n.teardown;if(e!==null){const t=ps,s=se;_l(!0),tt(null);try{e.call(null)}finally{_l(t),tt(s)}}}function Qc(n,e=!1){var t=n.first;for(n.first=n.last=null;t!==null;){const r=t.ac;r!==null&&Nr(()=>{r.abort(Ts)});var s=t.next;(t.f&hs)!==0?t.parent=null:st(t,e),t=s}}function Mh(n){for(var e=n.first;e!==null;){var t=e.next;(e.f&wn)===0&&st(e),e=t}}function st(n,e=!0){var t=!1;(e||(n.f&vc)!==0)&&n.nodes_start!==null&&n.nodes_end!==null&&(Fh(n.nodes_start,n.nodes_end),t=!0),Qc(n,e&&!t),yi(n,0),We(n,fn);var s=n.transitions;if(s!==null)for(const i of s)i.stop();Gc(n);var r=n.parent;r!==null&&r.first!==null&&Zc(n),B&&(n.component_function=null),n.next=n.prev=n.teardown=n.ctx=n.deps=n.fn=n.nodes_start=n.nodes_end=n.ac=null}function Fh(n,e){for(;n!==null;){var t=n===e?null:Mr(n);n.remove(),n=t}}function Zc(n){var e=n.parent,t=n.prev,s=n.next;t!==null&&(t.next=s),s!==null&&(s.prev=t),e!==null&&(e.first===n&&(e.first=s),e.last===n&&(e.last=t))}function Ns(n,e,t=!0){var s=[];Eo(n,s,!0),eu(s,()=>{t&&st(n),e&&e()})}function eu(n,e){var t=n.length;if(t>0){var s=()=>--t||e();for(var r of n)r.out(s)}else e()}function Eo(n,e,t){if((n.f&ft)===0){if(n.f^=ft,n.transitions!==null)for(const a of n.transitions)(a.is_global||t)&&e.push(a);for(var s=n.first;s!==null;){var r=s.next,i=(s.f&us)!==0||(s.f&wn)!==0&&(n.f&en)!==0;Eo(s,e,i?t:!1),s=r}}}function So(n){tu(n,!0)}function tu(n,e){if((n.f&ft)!==0){n.f^=ft,(n.f&ze)===0&&(We(n,rt),ds(n));for(var t=n.first;t!==null;){var s=t.next,r=(t.f&us)!==0||(t.f&wn)!==0;tu(t,r?e:!1),t=s}if(n.transitions!==null)for(const i of n.transitions)(i.is_global||e)&&i.in()}}function nu(n,e){for(var t=n.nodes_start,s=n.nodes_end;t!==null;){var r=t===s?null:Mr(t);e.append(t),t=r}}const Nh=["touchstart","touchmove"];function Oh(n){return Nh.includes(n)}var wl=new Map;function Dh(n,e){var t=wl.get(n);t||(t=new Set,wl.set(n,t)),t.add(e)}const Lh=new Set,bl=new Set;function Bh(n,e,t,s={}){function r(i){if(s.capture||rr.call(e,i),!i.cancelBubble)return Nr(()=>t?.call(this,i))}return n.startsWith("pointer")||n.startsWith("touch")||n==="wheel"?Dn(()=>{e.addEventListener(n,r,s)}):e.addEventListener(n,r,s),r}function le(n,e,t,s,r){var i={capture:s,passive:r},a=Bh(n,e,t,i);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&Xs(()=>{e.removeEventListener(n,a,i)})}let xl=null;function rr(n){var e=this,t=e.ownerDocument,s=n.type,r=n.composedPath?.()||[],i=r[0]||n.target;xl=n;var a=0,o=xl===n&&n.__root;if(o){var l=r.indexOf(o);if(l!==-1&&(e===document||e===window)){n.__root=e;return}var c=r.indexOf(e);if(c===-1)return;l<=c&&(a=l)}if(i=r[a]||n.target,i!==e){gn(n,"currentTarget",{configurable:!0,get(){return i||t}});var d=se,u=ie;tt(null),Mt(null);try{for(var h,f=[];i!==null;){var p=i.assignedSlot||i.parentNode||i.host||null;try{var m=i["__"+s];m!=null&&(!i.disabled||n.target===i)&&m.call(i,n)}catch(v){h?f.push(v):h=v}if(n.cancelBubble||p===e||p===null)break;i=p}if(h){for(let v of f)queueMicrotask(()=>{throw v});throw h}}finally{n.__root=e,delete n.currentTarget,tt(d),Mt(u)}}}function Uh(n){var e=document.createElement("template");return e.innerHTML=n.replaceAll("<!>","<!---->"),e.content}function wi(n,e){var t=ie;t.nodes_start===null&&(t.nodes_start=n,t.nodes_end=e)}function J(n,e){var t=(e&Gf)!==0,s=(e&Qf)!==0,r,i=!n.startsWith("<!>");return()=>{r===void 0&&(r=Uh(i?n:"<!>"+n),t||(r=vi(r)));var a=s||wo?document.importNode(r,!0):r.cloneNode(!0);if(t){var o=vi(a),l=a.lastChild;wi(o,l)}else wi(a,a);return a}}function jh(n=""){{var e=vn(n+"");return wi(e,e),e}}function nt(){var n=document.createDocumentFragment(),e=document.createComment(""),t=vn();return n.append(e,t),wi(e,t),n}function L(n,e){n!==null&&n.before(e)}let ja=!0;function je(n,e){var t=e==null?"":typeof e=="object"?e+"":e;t!==(n.__t??(n.__t=n.nodeValue))&&(n.__t=t,n.nodeValue=t+"")}function za(n,e){return zh(n,e)}const bs=new Map;function zh(n,{target:e,anchor:t,props:s={},events:r,context:i,intro:a=!0}){oh();var o=new Set,l=u=>{for(var h=0;h<u.length;h++){var f=u[h];if(!o.has(f)){o.add(f);var p=Oh(f);e.addEventListener(f,rr,{passive:p});var m=bs.get(f);m===void 0?(document.addEventListener(f,rr,{passive:p}),bs.set(f,1)):bs.set(f,m+1)}}};l(vo(Lh)),bl.add(l);var c=void 0,d=$h(()=>{var u=t??e.appendChild(vn());return ph(u,{pending:()=>{}},h=>{if(i){ge({});var f=oe;f.c=i}r&&(s.$$events=r),ja=a,c=n(h,s)||{},ja=!0,i&&ve()}),()=>{for(var h of o){e.removeEventListener(h,rr);var f=bs.get(h);--f===0?(document.removeEventListener(h,rr),bs.delete(h)):bs.set(h,f)}bl.delete(l),u!==t&&u.parentNode?.removeChild(u)}});return qa.set(c,d),c}let qa=new WeakMap;function Wa(n,e){const t=qa.get(n);return t?(qa.delete(n),t(e)):(B&&(Gt in n?void 0:void 0),Promise.resolve())}var It,Ht,ct,rs,Ir,$r,Di;class su{constructor(e,t=!0){Dt(this,"anchor");re(this,It,new Map);re(this,Ht,new Map);re(this,ct,new Map);re(this,rs,new Set);re(this,Ir,!0);re(this,$r,()=>{var e=pe;if(k(this,It).has(e)){var t=k(this,It).get(e),s=k(this,Ht).get(t);if(s)So(s),k(this,rs).delete(t);else{var r=k(this,ct).get(t);r&&(k(this,Ht).set(t,r.effect),k(this,ct).delete(t),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),s=r.effect)}for(const[i,a]of k(this,It)){if(k(this,It).delete(i),i===e)break;const o=k(this,ct).get(a);o&&(st(o.effect),k(this,ct).delete(a))}for(const[i,a]of k(this,Ht)){if(i===t||k(this,rs).has(i))continue;const o=()=>{if(Array.from(k(this,It).values()).includes(i)){var c=document.createDocumentFragment();nu(a,c),c.append(vn()),k(this,ct).set(i,{effect:a,fragment:c})}else st(a);k(this,rs).delete(i),k(this,Ht).delete(i)};k(this,Ir)||!s?(k(this,rs).add(i),Ns(a,o,!1)):o()}}});re(this,Di,e=>{k(this,It).delete(e);const t=Array.from(k(this,It).values());for(const[s,r]of k(this,ct))t.includes(s)||(st(r.effect),k(this,ct).delete(s))});this.anchor=e,X(this,Ir,t)}ensure(e,t){var s=pe,r=Ic();if(t&&!k(this,Ht).has(e)&&!k(this,ct).has(e))if(r){var i=document.createDocumentFragment(),a=vn();i.append(a),k(this,ct).set(e,{effect:bt(()=>t(a)),fragment:i})}else k(this,Ht).set(e,bt(()=>t(this.anchor)));if(k(this,It).set(s,e),r){for(const[o,l]of k(this,Ht))o===e?s.skipped_effects.delete(l):s.skipped_effects.add(l);for(const[o,l]of k(this,ct))o===e?s.skipped_effects.delete(l.effect):s.skipped_effects.add(l.effect);s.oncommit(k(this,$r)),s.ondiscard(k(this,Di))}else k(this,$r).call(this)}}It=new WeakMap,Ht=new WeakMap,ct=new WeakMap,rs=new WeakMap,Ir=new WeakMap,$r=new WeakMap,Di=new WeakMap;const qh=0,ha=1;function Wh(n,e,t,s,r){var i=Ks(),a=Ne,o=i?_n(a):q(a,!1,!1),l=i?_n(a):q(a,!1,!1),c=new su(n);Vi(()=>{var d=e(),u=!1;if(Ef(d)){var h=Bc(),f=!1;const p=m=>{if(!u){f=!0,h(!1),Yt.ensure();try{m()}finally{xr(),Ms||uh()}}};d.then(m=>{p(()=>{hn(o,m),c.ensure(ha,s&&(v=>s(v,o)))})},m=>{p(()=>{if(hn(l,m),c.ensure(ha,r&&(v=>r(v,l))),!r)throw l.v})}),Dn(()=>{f||p(()=>{c.ensure(qh,t)})})}else hn(o,d),c.ensure(ha,s&&(p=>s(p,o)));return()=>{u=!0}})}function de(n,e,t=!1){var s=new su(n),r=t?us:0;function i(a,o){s.ensure(a,o)}Vi(()=>{var a=!1;e((o,l=!0)=>{a=!0,i(l,o)}),a||i(!1,null)},r)}function ru(n,e,t,s,r){var i=e.$$slots?.[t],a=!1;i===!0&&(i=e[t==="default"?"children":t],a=!0),i===void 0?r!==null&&r(n):i(n,a?()=>s:s)}function Pe(n,e){Hs(()=>{var t=n.getRootNode(),s=t.host?t:t.head??t.ownerDocument.head;if(!s.querySelector("#"+e.hash)){const r=document.createElement("style");r.id=e.hash,r.textContent=e.code,s.appendChild(r),B&&Dh(e.hash,r)}})}function iu(n){var e,t,s="";if(typeof n=="string"||typeof n=="number")s+=n;else if(typeof n=="object")if(Array.isArray(n)){var r=n.length;for(e=0;e<r;e++)n[e]&&(t=iu(n[e]))&&(s&&(s+=" "),s+=t)}else for(t in n)n[t]&&(s&&(s+=" "),s+=t);return s}function Hh(){for(var n,e,t=0,s="",r=arguments.length;t<r;t++)(n=arguments[t])&&(e=iu(n))&&(s&&(s+=" "),s+=e);return s}function kl(n){return typeof n=="object"?Hh(n):n??""}const El=[...`
|
||
\r\f \v\uFEFF`];function Vh(n,e,t){var s=n==null?"":""+n;if(e&&(s=s?s+" "+e:e),t){for(var r in t)if(t[r])s=s?s+" "+r:r;else if(s.length)for(var i=r.length,a=0;(a=s.indexOf(r,a))>=0;){var o=a+i;(a===0||El.includes(s[a-1]))&&(o===s.length||El.includes(s[o]))?s=(a===0?"":s.substring(0,a))+s.substring(o+1):a=o}}return s===""?null:s}function Sl(n,e=!1){var t=e?" !important;":";",s="";for(var r in n){var i=n[r];i!=null&&i!==""&&(s+=" "+r+": "+i+t)}return s}function pa(n){return n[0]!=="-"||n[1]!=="-"?n.toLowerCase():n}function Yh(n,e){if(e){var t="",s,r;if(Array.isArray(e)?(s=e[0],r=e[1]):s=e,n){n=String(n).replaceAll(/\s*\/\*.*?\*\/\s*/g,"").trim();var i=!1,a=0,o=!1,l=[];s&&l.push(...Object.keys(s).map(pa)),r&&l.push(...Object.keys(r).map(pa));var c=0,d=-1;const m=n.length;for(var u=0;u<m;u++){var h=n[u];if(o?h==="/"&&n[u-1]==="*"&&(o=!1):i?i===h&&(i=!1):h==="/"&&n[u+1]==="*"?o=!0:h==='"'||h==="'"?i=h:h==="("?a++:h===")"&&a--,!o&&i===!1&&a===0){if(h===":"&&d===-1)d=u;else if(h===";"||u===m-1){if(d!==-1){var f=pa(n.substring(c,d).trim());if(!l.includes(f)){h!==";"&&u++;var p=n.substring(c,u).trim();t+=" "+p+";"}}c=u+1,d=-1}}}}return s&&(t+=Sl(s)),r&&(t+=Sl(r,!0)),t=t.trim(),t===""?null:t}return n==null?null:String(n)}function Qt(n,e,t,s,r,i){var a=n.__className;if(a!==t||a===void 0){var o=Vh(t,s,i);o==null?n.removeAttribute("class"):n.className=o,n.__className=t}else if(i&&r!==i)for(var l in i){var c=!!i[l];(r==null||c!==!!r[l])&&n.classList.toggle(l,c)}return i}function ma(n,e={},t,s){for(var r in t){var i=t[r];e[r]!==i&&(t[r]==null?n.style.removeProperty(r):n.style.setProperty(r,i,s))}}function Er(n,e,t,s){var r=n.__style;if(r!==e){var i=Yh(e,s);i==null?n.removeAttribute("style"):n.style.cssText=i,n.__style=e}else s&&(Array.isArray(s)?(ma(n,t?.[0],s[0]),ma(n,t?.[1],s[1],"important")):ma(n,t,s));return s}const Kh=Symbol("is custom element"),Jh=Symbol("is html");function ue(n,e,t,s){var r=Xh(n);r[e]!==(r[e]=t)&&(e==="loading"&&(n[Cf]=t),t==null?n.removeAttribute(e):typeof t!="string"&&Gh(n).includes(e)?n[e]=t:n.setAttribute(e,t))}function Xh(n){return n.__attributes??(n.__attributes={[Kh]:n.nodeName.includes("-"),[Jh]:n.namespaceURI===eh})}var Al=new Map;function Gh(n){var e=n.getAttribute("is")||n.nodeName,t=Al.get(e);if(t)return t;Al.set(e,t=[]);for(var s,r=n,i=Element.prototype;i!==r;){s=mc(r);for(var a in s)s[a].set&&t.push(a);r=_o(r)}return t}const Qh=()=>performance.now(),dn={tick:n=>requestAnimationFrame(n),now:()=>Qh(),tasks:new Set};function au(){const n=dn.now();dn.tasks.forEach(e=>{e.c(n)||(dn.tasks.delete(e),e.f())}),dn.tasks.size!==0&&dn.tick(au)}function Zh(n){let e;return dn.tasks.size===0&&dn.tick(au),{promise:new Promise(t=>{dn.tasks.add(e={c:n,f:t})}),abort(){dn.tasks.delete(e)}}}function Kr(n,e){Nr(()=>{n.dispatchEvent(new CustomEvent(e))})}function ep(n){if(n==="float")return"cssFloat";if(n==="offset")return"cssOffset";if(n.startsWith("--"))return n;const e=n.split("-");return e.length===1?e[0]:e[0]+e.slice(1).map(t=>t[0].toUpperCase()+t.slice(1)).join("")}function Cl(n){const e={},t=n.split(";");for(const s of t){const[r,i]=s.split(":");if(!r||i===void 0)break;const a=ep(r.trim());e[a]=i.trim()}return e}const tp=n=>n;function ou(n,e,t,s){var r=(n&Xf)!==0,i="both",a,o=e.inert,l=e.style.overflow,c,d;function u(){return Nr(()=>a??(a=t()(e,s?.()??{},{direction:i})))}var h={is_global:r,in(){e.inert=o,Kr(e,"introstart"),c=Ha(e,u(),d,1,()=>{Kr(e,"introend"),c?.abort(),c=a=void 0,e.style.overflow=l})},out(v){e.inert=!0,Kr(e,"outrostart"),d=Ha(e,u(),c,0,()=>{Kr(e,"outroend"),v?.()})},stop:()=>{c?.abort(),d?.abort()}},f=ie;if((f.transitions??(f.transitions=[])).push(h),ja){var p=r;if(!p){for(var m=f.parent;m&&(m.f&us)!==0;)for(;(m=m.parent)&&(m.f&en)===0;);p=!m||(m.f&ji)!==0}p&&Hs(()=>{z(()=>h.in())})}}function Ha(n,e,t,s,r){var i=s===1;if(kf(e)){var a,o=!1;return Dn(()=>{if(!o){var v=e({direction:i?"in":"out"});a=Ha(n,v,t,s,r)}}),{abort:()=>{o=!0,a?.abort()},deactivate:()=>a.deactivate(),reset:()=>a.reset(),t:()=>a.t()}}if(t?.deactivate(),!e?.duration)return r(),{abort:$t,deactivate:$t,reset:$t,t:()=>s};const{delay:l=0,css:c,tick:d,easing:u=tp}=e;var h=[];if(i&&t===void 0&&(d&&d(0,1),c)){var f=Cl(c(0,1));h.push(f,f)}var p=()=>1-s,m=n.animate(h,{duration:l,fill:"forwards"});return m.onfinish=()=>{m.cancel();var v=t?.t()??1-s;t?.abort();var _=s-v,y=e.duration*Math.abs(_),b=[];if(y>0){var E=!1;if(c)for(var C=Math.ceil(y/16.666666666666668),F=0;F<=C;F+=1){var x=v+_*u(F/C),A=Cl(c(x,1-x));b.push(A),E||(E=A.overflow==="hidden")}E&&(n.style.overflow="hidden"),p=()=>{var I=m.currentTime;return v+_*u(I/y)},d&&Zh(()=>{if(m.playState!=="running")return!1;var I=p();return d(I,1-I),!0})}m=n.animate(b,{duration:y,fill:"forwards"}),m.onfinish=()=>{p=()=>s,d?.(s,1-s),r()}},{abort:()=>{m&&(m.cancel(),m.effect=null,m.onfinish=$t)},deactivate:()=>{r=$t},reset:()=>{s===0&&d?.(1,0)},t:()=>p()}}function np(n,e,t=e){var s,r,i=()=>{cancelAnimationFrame(s),n.paused||(s=requestAnimationFrame(i));var a=n.currentTime;r!==a&&t(r=a)};s=requestAnimationFrame(i),n.addEventListener("timeupdate",i),Gs(()=>{var a=Number(e());r!==a&&!isNaN(a)&&(n.currentTime=r=a)}),Xs(()=>{cancelAnimationFrame(s),n.removeEventListener("timeupdate",i)})}function sp(n,e,t=e){Hs(()=>{var s=Number(e());s!==n.playbackRate&&!isNaN(s)&&(n.playbackRate=s)}),Hs(()=>{ko(n,["ratechange"],()=>{t(n.playbackRate)})})}function rp(n,e,t=e){var s=e(),r=()=>{s!==n.paused&&t(s=n.paused)};ko(n,["play","pause","canplay"],r,s==null),Hs(()=>{(s=!!e())!==n.paused&&(s?n.pause():n.play().catch(()=>{t(s=!0)}))})}function ip(n,e,t=e){var s=()=>{t(n.volume)};e()==null&&s(),ko(n,["volumechange"],s,!1),Gs(()=>{var r=Number(e());r!==n.volume&&!isNaN(r)&&(n.volume=r)})}function Pl(n,e){return n===e||n?.[Gt]===e}function Nn(n={},e,t,s){return Hs(()=>{var r,i;return Gs(()=>{r=i,i=[],z(()=>{n!==t(...i)&&(e(n,...i),r&&Pl(t(...r),n)&&e(null,...r))})}),()=>{Dn(()=>{i&&Pl(t(...i),n)&&e(null,...i)})}}),n}function ap(n,e,t,s,r){var i=()=>{s(t[n])};t.addEventListener(e,i),i(),(t===document.body||t===window||t===document)&&Xs(()=>{t.removeEventListener(e,i)})}function op(n){return function(...e){var t=e[0];return t.preventDefault(),n?.apply(this,e)}}function _e(n=!1){const e=oe,t=e.l.u;if(!t)return;let s=()=>O(e.s);if(n){let r=0,i={};const a=Fr(()=>{let o=!1;const l=e.s;for(const c in l)l[c]!==i[c]&&(i[c]=l[c],o=!0);return o&&r++,r});s=()=>g(a)}t.b.length&&Ih(()=>{Tl(e,s),Ta(t.b)}),Ua(()=>{const r=z(()=>t.m.map(Sf));return()=>{for(const i of r)typeof i=="function"&&i()}}),t.a.length&&Ua(()=>{Tl(e,s),Ta(t.a)})}function Tl(n,e){if(n.l.s)for(const t of n.l.s)g(t);e()}function lu(n,e){var t=n.$$events?.[e.type],s=Li(t)?t.slice():t==null?[]:[t];for(var r of s)r.call(this,e)}let ir=!1,Va=Symbol();function Ue(n,e,t){const s=t[e]??(t[e]={store:null,source:q(void 0),unsubscribe:$t});if(B&&(s.source.label=e),s.store!==n&&!(Va in t))if(s.unsubscribe(),s.store=n??null,n==null)s.source.v=void 0,s.unsubscribe=$t;else{var r=!0;s.unsubscribe=du(n,i=>{r?s.source.v=i:T(s.source,i)}),r=!1}return n&&Va in t?ee(n):g(s.source)}function gr(n,e){return n.set(e),e}function Or(){const n={};function e(){Xs(()=>{for(var t in n)n[t].unsubscribe();gn(n,Va,{enumerable:!1,value:!0})})}return[n,e]}function lp(){ir=!0}function cp(n){var e=ir;try{return ir=!1,[n(),ir]}finally{ir=e}}function M(n,e,t,s){var r=!Ys||(t&Vf)!==0,i=(t&Kf)!==0,a=(t&Jf)!==0,o=s,l=!0,c=()=>(l&&(l=!1,o=a?z(s):s),o),d;if(i){var u=Gt in n||Af in n;d=is(n,e)?.set??(u&&e in n?b=>n[e]=b:void 0)}var h,f=!1;i?[h,f]=cp(()=>n[e]):h=n[e],h===void 0&&s!==void 0&&(h=c(),d&&(r&&Nf(e),d(h)));var p;if(r?p=()=>{var b=n[e];return b===void 0?c():(l=!0,b)}:p=()=>{var b=n[e];return b!==void 0&&(o=void 0),b===void 0?o:b},r&&(t&Yf)===0)return p;if(d){var m=n.$$legacy;return(function(b,E){return arguments.length>0?((!r||!E||m||f)&&d(E?p():b),b):p()})}var v=!1,_=((t&Hf)!==0?Fr:qe)(()=>(v=!1,p()));B&&(_.label=e),i&&g(_);var y=ie;return(function(b,E){if(arguments.length>0){const C=E?g(_):r&&i?Is(b):b;return T(_,C),v=!0,o!==void 0&&(o=C),b}return ps&&v||(y.f&fn)!==0?_.v:g(_)})}if(B){let n=function(e){if(!(e in globalThis)){let t;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(t!==void 0)return t;Of(e)},set:s=>{t=s}})}};n("$state"),n("$effect"),n("$derived"),n("$inspect"),n("$props"),n("$bindable")}function rn(n){oe===null&&qi("onMount"),Ys&&oe.l!==null?uu(oe).m.push(n):Ua(()=>{const e=z(n);if(typeof e=="function")return e})}function Yi(n){oe===null&&qi("onDestroy"),rn(()=>()=>z(n))}function up(n,e,{bubbles:t=!1,cancelable:s=!1}={}){return new CustomEvent(n,{detail:e,bubbles:t,cancelable:s})}function Ye(){const n=oe;return n===null&&qi("createEventDispatcher"),(e,t,s)=>{const r=n.s.$$events?.[e];if(r){const i=Li(r)?r.slice():[r],a=up(e,t,s);for(const o of i)o.call(n.x,a);return!a.defaultPrevented}return!0}}function cu(n){oe===null&&qi("afterUpdate"),oe.l===null&&Ff("afterUpdate"),uu(oe).a.push(n)}function uu(n){var e=n.l;return e.u??(e.u={a:[],b:[],m:[]})}function du(n,e,t){if(n==null)return e(void 0),$t;const s=z(()=>n.subscribe(e,t));return s.unsubscribe?()=>s.unsubscribe():s}const xs=[];function dp(n,e){return{subscribe:Te(n,e).subscribe}}function Te(n,e=$t){let t=null;const s=new Set;function r(o){if(bc(n,o)&&(n=o,t)){const l=!xs.length;for(const c of s)c[1](),xs.push(c,n);if(l){for(let c=0;c<xs.length;c+=2)xs[c][0](xs[c+1]);xs.length=0}}}function i(o){r(o(n))}function a(o,l=$t){const c=[o,l];return s.add(c),s.size===1&&(t=e(r,i)||$t),o(n),()=>{s.delete(c),s.size===0&&t&&(t(),t=null)}}return{set:r,update:i,subscribe:a}}function ee(n){let e;return du(n,t=>e=t)(),e}var Z=(n=>(n[n.PodcastGrid=0]="PodcastGrid",n[n.EpisodeList=1]="EpisodeList",n[n.Player=2]="Player",n))(Z||{});function Jn(n){return!n||!n.title?"":n.podcastName?`${n.podcastName}::${n.title}`:n.title}const Zt=Te(),Pt=Te(0),bi=Te(0),os=Te(1),xi=Te(!1),Qe=(()=>{const n=Te(),{subscribe:e,update:t}=n;return{subscribe:e,update:t,set:(s,r=!0)=>{t(i=>{if(i){r&&_p(i);const a=ee(Pt),o=ee(bi),l=a===o;kt.setEpisodeTime(i,a,o,l)}return s})}}})(),Vt=Te(!0),kt=(()=>{const n=Te({}),{subscribe:e,update:t,set:s}=n;function r(i,a){if(!a)return;const o=Jn(a);if(o&&i[o])return i[o];if(a.title&&i[a.title])return i[a.title]}return{subscribe:e,set:s,update:t,get:i=>r(ee(n),i),setEpisodeTime:(i,a,o,l)=>{i&&t(c=>{const d=Jn(i);return d&&(c[d]={title:i.title,podcastName:i.podcastName,time:a,duration:o,finished:l}),c})},markAsPlayed:i=>{i&&t(a=>{const o=Jn(i);if(!o)return a;const l=r(a,i)||{title:i.title,podcastName:i.podcastName,time:0,duration:0,finished:!1};return l.time=l.duration,l.finished=!0,a[o]=l,a})},markAsUnplayed:i=>{i&&t(a=>{const o=Jn(i);if(!o)return a;const l=r(a,i)||{title:i.title,podcastName:i.podcastName,time:0,duration:0,finished:!1};return l.time=0,l.finished=!1,a[o]=l,a})}}})(),fp=Te(0),mn=Te({}),Xn=Te({}),fu=10;function ki(n){return n?.episodeDate?Number(n.episodeDate):0}function hp(n){return n?.length?n.slice(0,fu).sort((e,t)=>ki(t)-ki(e)):[]}function pp(n,e){if(!n||!e||n.length!==e.length)return!1;for(let t=0;t<n.length;t+=1)if(n[t]!==e[t])return!1;return!0}const Il=n=>`${n.podcastName}::${n.title}`;function mp(n,e,t){const s=[...n],r=ki(e);let i=0,a=s.length;for(;i<a;){const o=i+a>>1,l=ki(s[o]);r>l?a=o:i=o+1}return s.splice(i,0,e),s.length>t&&(s.length=t),s}function hu(n,e=[]){if(!e?.length)return n;const t=new Set(e.map(Il));return n.filter(s=>!t.has(Il(s)))}function gp(n,e,t,s){let r=hu(n,e);if(!t?.length)return r;for(const i of t)r=mp(r,i,s);return r}const vp=dp([],n=>{let e=new Map,t=new Map,s=[];const r=Xn.subscribe(i=>{const a=Object.entries(i),o=a.length,l=Math.max(1,fu*Math.max(o,1));let c=!1,d=s;const u=new Map,h=new Map;for(const[f,p]of a){u.set(f,p);const m=t.get(f),v=e.get(f)||[],_=m===p&&v?v:hp(p);h.set(f,_),pp(v,_)||(c=!0,d=gp(d,v,_,l))}for(const f of e.keys())u.has(f)||(c=!0,d=hu(d,e.get(f)));t=u,e=h,c&&(s=d,n(s))});return()=>{e.clear(),t.clear(),s=[],r()}}),ht=(()=>{const n=Te({}),{subscribe:e,update:t,set:s}=n;function r(i){return ee(n)[i.podcastName]?.some(a=>a.title===i.title)}return{subscribe:e,set:s,update:t,isEpisodeDownloaded:r,addEpisode:(i,a,o)=>{t(l=>{const c=l[i.podcastName]||[],d=c.findIndex(u=>u.title===i.title);return d!==-1?c[d]={...i,filePath:a,size:o}:c.push({...i,filePath:a,size:o}),l[i.podcastName]=c,l})},removeEpisode:(i,a)=>{t(o=>{const l=o[i.podcastName]||[],c=l.findIndex(u=>u.title===i.title);if(c===-1)return o;const d=l[c].filePath;if(l.splice(c,1),a&&d)try{const u=app.vault.getAbstractFileByPath(d);u instanceof P.TFile&&app.vault.delete(u)}catch{}return o[i.podcastName]=l,o})},getEpisode:i=>ee(n)[i.podcastName]?.find(a=>a.title===i.title)}})(),Et=(()=>{const n=Te({icon:"list-ordered",name:"Queue",episodes:[],shouldEpisodeRemoveAfterPlay:!0,shouldRepeat:!1}),{subscribe:e,update:t,set:s}=n;return{subscribe:e,update:t,set:s,add:r=>{t(i=>(i.episodes.push(r),i))},remove:r=>{t(i=>(i.episodes=i.episodes.filter(a=>a.title!==r.title),i))},playNext:()=>{t(r=>{const i=r.episodes.shift();return i&&Qe.set(i,!1),r})}}})(),ls=Te({icon:"lucide-star",name:"Favorites",episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1}),Sr=(()=>{const n=Te({icon:"folder",name:"Local Files",episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1}),{subscribe:e,update:t,set:s}=n;return{subscribe:e,update:t,set:s,getLocalEpisode:r=>ee(n).episodes.find(a=>a.title===r),updateStreamUrl:(r,i)=>{n.update(a=>{const o=a.episodes.findIndex(l=>l.title===r);return o!==-1&&(a.episodes[o].streamUrl=i),a})},addEpisode:r=>{n.update(i=>{const a=i.episodes.findIndex(o=>o.title===r.title);return a!==-1?i.episodes[a]=r:i.episodes.push(r),i})}}})(),Rt=Te({}),Ya=Te(),Je=(()=>{const n=Te(Z.PodcastGrid),{subscribe:e,set:t}=n;return{subscribe:e,set:s=>{t(s),ee(Ya)?.scrollIntoView()}}})();function _p(n){Et.update(e=>{const t=[n,...e.episodes];return e.episodes=t,e})}class yp{constructor(){this.activeUrls=new Map}async createUrl(e){this.revokeUrl(e);const t=app.vault.getAbstractFileByPath(e);if(!t||!(t instanceof P.TFile))return"";const s=await app.vault.readBinary(t),r=URL.createObjectURL(new Blob([s],{type:"audio/mpeg"}));return this.activeUrls.set(e,r),r}revokeUrl(e){const t=this.activeUrls.get(e);t&&(URL.revokeObjectURL(t),this.activeUrls.delete(e))}revokeAll(){for(const e of this.activeUrls.values())URL.revokeObjectURL(e);this.activeUrls.clear()}get activeCount(){return this.activeUrls.size}}const pu=new yp;async function mu(n){return pu.createUrl(n)}function Ar(n,e){const t=Math.floor(n/3600),s=Math.floor(n%3600/60),r=Math.floor(n%60),i=t%12||12,a=t>=12,o=l=>l.toString().padStart(2,"0");return e.replace(/HH/g,o(t)).replace(/H/g,t.toString()).replace(/hh/g,o(i)).replace(/h/g,i.toString()).replace(/mm/g,o(s)).replace(/m/g,s.toString()).replace(/ss/g,o(r)).replace(/s/g,r.toString()).replace(/A/g,a?"PM":"AM").replace(/a/g,a?"pm":"am")}function wp(n,e,t){const s=new URL("obsidian://podnotes");return s.searchParams.set("episodeName",n),s.searchParams.set("url",e),t&&s.searchParams.set("time",t.toString()),s}function gu(n){return n.podcastName==="local file"}const bp=n=>Math.min(1,Math.max(0,n));class xp{get podcast(){return ee(Qe)}get length(){return ee(bi)}get currentTime(){return ee(Pt)}set currentTime(e){Pt.update(t=>e)}get isPlaying(){return!ee(Vt)}get volume(){return ee(os)}set volume(e){os.set(bp(e))}getPodcastTimeFormatted(e,t=!1,s=0){if(!this.podcast)throw new Error("No podcast loaded");const r=Math.max(0,this.currentTime-s),i=Ar(r,e);if(!t)return i;const o=gu(this.podcast)?ht.getEpisode(this.podcast)?.filePath:this.podcast.feedUrl;if(!o||o==="")return i;const l=wp(this.podcast.title,o,r);return`[${i}](${l.href})`}start(){Vt.update(e=>!1)}stop(){Vt.update(e=>!0)}togglePlayback(){Vt.update(e=>!e)}skipBackward(){const e=ee(Zt).settings.skipBackwardLength;this.currentTime-=e}skipForward(){const e=ee(Zt).settings.skipForwardLength;this.currentTime+=e}}const Wn="podcast_player_view",vu={icon:"lucide-star",name:"Favorites",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},_u={icon:"list-ordered",name:"Queue",shouldEpisodeRemoveAfterPlay:!0,shouldRepeat:!1},yu={icon:"folder",name:"Local Files",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},$l={savedFeeds:{},podNotes:{},defaultPlaybackRate:1,defaultVolume:1,hidePlayedEpisodes:!1,playedEpisodes:{},favorites:{...vu,episodes:[]},queue:{..._u,episodes:[]},playlists:{},skipBackwardLength:15,skipForwardLength:15,currentEpisode:void 0,timestamp:{template:"- {{time}} ",offset:0},note:{path:"",template:""},download:{path:""},downloadedEpisodes:{},localFiles:{...yu,episodes:[]},openAIApiKey:"",transcript:{path:"transcripts/{{podcast}}/{{title}}.md",template:`# {{title}}
|
||
|
||
Podcast: {{podcast}}
|
||
Date: {{date}}
|
||
|
||
{{transcript}}`},feedCache:{enabled:!0,ttlHours:6}},kp="5";var pc;typeof window<"u"&&((pc=window.__svelte??(window.__svelte={})).v??(pc.v=new Set)).add(kp);zf();const Ep=3e4;class ii extends Error{constructor(e,t,s){super(e),this.url=t,this.cause=s,this.name="NetworkError"}}class Sp extends ii{constructor(e,t){super(`Request timed out after ${t}ms`,e),this.name="TimeoutError"}}async function Ao(n,e={}){const{timeoutMs:t=Ep,method:s,headers:r,body:i}=e;let a;const o=new Promise((l,c)=>{a=setTimeout(()=>{c(new Sp(n,t))},t)});try{const l=await Promise.race([P.requestUrl({url:n,method:s,headers:r,body:i,throw:!1}),o]);if(l.status>=400)throw new ii(`HTTP ${l.status}: ${l.text?.slice(0,100)||"Unknown error"}`,n);return l}catch(l){throw l instanceof ii?l:new ii(l instanceof Error?l.message:String(l),n,l)}finally{a&&clearTimeout(a)}}async function wu(n){const e=new URL("https://itunes.apple.com/search?");e.searchParams.append("term",n),e.searchParams.append("media","podcast"),e.searchParams.append("limit","3"),e.searchParams.append("kind","podcast");try{return((await Ao(e.href,{timeoutMs:15e3})).json.results||[]).map(r=>({title:r.collectionName,url:r.feedUrl,artworkUrl:r.artworkUrl100,collectionId:r.collectionId}))}catch{return[]}}class Ki{constructor(e){this.feed=e}async findItemByTitle(e,t){(!this.feed||this.feed.url!==t)&&await this.getFeed(t);const r=(await this.parseFeed(t)).querySelectorAll("item"),i=e.trim().toLowerCase(),o=Array.from(r).map(l=>this.parseItem(l)).filter(l=>!!l).find(l=>l.title.trim().toLowerCase()===i);if(!o)throw new Error("Could not find episode");return!o.artworkUrl&&this.feed&&(o.artworkUrl=this.feed.artworkUrl),!o.podcastName&&this.feed&&(o.podcastName=this.feed.title),!o.feedUrl&&this.feed&&(o.feedUrl=this.feed.url),o}async getEpisodes(e){(!this.feed||this.feed.url!==e)&&await this.getFeed(e);const t=await this.parseFeed(e);return this.parsePage(t)}async getFeed(e){const t=await this.parseFeed(e),s=t.querySelector("title"),r=t.querySelector("link"),i=this.findImageElement(t);if(!s||!r)throw new Error("Invalid RSS feed");const a=s.textContent||"",o=i?.getAttribute("href")||i?.querySelector("url")?.textContent||"",l={title:a,url:e,artworkUrl:o};return this.feed=l,l}findImageElement(e){const t=e.getElementsByTagName("itunes:image")[0];return t||e.querySelector("image")}parsePage(e){const t=e.querySelectorAll("item");function s(r){return!!r}return Array.from(t).map(this.parseItem.bind(this)).filter(s)}parseItem(e){const t=e.querySelector("title"),s=e.querySelector("enclosure"),r=e.querySelector("link"),i=e.querySelector("description"),a=e.querySelector("*|encoded"),o=e.querySelector("pubDate"),l=this.findImageElement(e),c=e.getElementsByTagName("itunes:title")[0],d=e.getElementsByTagName("podcast:chapters")[0];if(!t||!s||!o)return null;const u=t.textContent||"",h=s.getAttribute("url")||"",f=r?.textContent||"",p=i?.textContent||"",m=a?.textContent||"",v=new Date(o.textContent),_=l?.getAttribute("href")||this.feed?.artworkUrl,y=c?.textContent,b=d?.getAttribute("url")||void 0;return{title:u,streamUrl:h,url:f||this.feed?.url||"",description:p,content:m,podcastName:this.feed?.title||"",artworkUrl:_,episodeDate:v,feedUrl:this.feed?.url||"",itunesTitle:y||"",chaptersUrl:b}}async parseFeed(e){const t=await Ao(e,{timeoutMs:3e4});return new DOMParser().parseFromString(t.text,"text/xml")}}function Ap(n){try{return new URL(n)}catch{return null}}function Qs(n){return Object.entries(n).map(([e,t])=>`${e}: ${t}`).join("; ")}var Cp=J("<span></span>");function Co(n,e){ge(e,!1);let t=M(e,"value",12,""),s=M(e,"disabled",8,!1),r=M(e,"placeholder",8,""),i=M(e,"type",8,"text"),a=M(e,"el",12,null),o=q();const l=Ye();let c=q(),d=M(e,"style",24,()=>({})),u=null,h=null,f=!1;rn(()=>{T(c,new P.TextComponent(g(o)))}),Yi(()=>{g(c)?.inputEl&&u&&g(c).inputEl.removeEventListener("input",u)});function p(b){if(f)return;const C=b.target?.value??"";t(C),l("input",{value:C})}function m(b){f||(t(b),l("change",{value:b}))}function v(b){!b?.inputEl||u||(h=m,b.onChange(h),u=p,b.inputEl.addEventListener("input",u))}function _(b,E,C,F,x,A){const I=typeof b.getValue=="function"?b.getValue():b.inputEl?.value;E!==void 0&&I!==E&&(f=!0,b.setValue(E),f=!1),b?.inputEl&&(b.inputEl.disabled!==C&&b.setDisabled(C),F&&b.inputEl.placeholder!==F&&b.setPlaceholder(F),b.inputEl.type!==x&&(b.inputEl.type=x),A&&b.inputEl.setAttr("style",Qs(A)),a(b.inputEl))}He(()=>(g(c),O(t()),O(s()),O(r()),O(i()),O(d())),()=>{g(c)&&(v(g(c)),_(g(c),t(),s(),r(),i(),d()))}),sn(),_e();var y=Cp();Nn(y,b=>T(o,b),()=>g(o)),L(n,y),ve()}var Pp=J("<span></span>");function Cr(n,e){ge(e,!1);let t=M(e,"text",8,""),s=M(e,"tooltip",8,""),r=M(e,"ariaLabel",8,""),i=M(e,"icon",8,void 0),a=M(e,"disabled",8,!1),o=M(e,"warning",8,!1),l=M(e,"cta",8,!1),c=q(),d=M(e,"class",8),u=M(e,"style",8),h;const f=Ye();rn(()=>p(g(c))),cu(()=>m(h));function p(_){h=new P.ButtonComponent(_),m(h)}function m(_){t()&&_.setButtonText(t()),s()&&_.setTooltip(s()),i()&&_.setIcon(i()),a()&&_.setDisabled(a()),o()?_.setWarning():_.buttonEl.classList.remove("mod-warning"),d()&&_.setClass(d()),l()?_.setCta():_.removeCta(),_.onClick(y=>{f("click",{event:y})}),u()&&_.buttonEl.setAttr("style",Qs(u())),r()?_.buttonEl.setAttr("aria-label",r()):_.buttonEl.removeAttribute("aria-label")}_e();var v=Pp();Nn(v,_=>T(c,_),()=>g(c)),L(n,v),ve()}const Tp=n=>n;function bu(n,{delay:e=0,duration:t=400,easing:s=Tp}={}){const r=+getComputedStyle(n).opacity;return{delay:e,duration:t,easing:s,css:i=>`opacity: ${i*r}`}}var Ip=J('<div class="podcast-result-card svelte-bw0itx"><div class="podcast-artwork-container svelte-bw0itx"><img class="podcast-artwork svelte-bw0itx"/></div> <div class="podcast-info svelte-bw0itx"><h3 class="podcast-title svelte-bw0itx"> </h3></div> <div class="podcast-actions svelte-bw0itx"><!></div></div>');const $p={hash:"svelte-bw0itx",code:".podcast-result-card.svelte-bw0itx {display:flex;align-items:center;gap:0.875rem;padding:0.875rem;border:1px solid var(--background-modifier-border);border-radius:0.5rem;background-color:var(--background-secondary);max-width:100%;transition:transform 150ms ease, box-shadow 150ms ease, border-color 150ms ease;}.podcast-result-card.svelte-bw0itx:hover {border-color:var(--interactive-accent);box-shadow:0 4px 12px rgba(0, 0, 0, 0.1);transform:translateY(-1px);}.podcast-artwork-container.svelte-bw0itx {width:4rem;height:4rem;flex-shrink:0;overflow:hidden;border-radius:0.375rem;position:relative;background:var(--background-modifier-border);}.podcast-artwork.svelte-bw0itx {width:100%;height:100%;object-fit:cover;position:absolute;top:0;left:0;}.podcast-info.svelte-bw0itx {flex:1 1 auto;min-width:0;}.podcast-title.svelte-bw0itx {margin:0;font-size:0.9rem;font-weight:600;line-height:1.4;color:var(--text-normal);overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;}.podcast-actions.svelte-bw0itx {display:flex;align-items:center;flex-shrink:0;}.podcast-actions button {padding:0.375rem;border-radius:0.25rem;transition:background-color 120ms ease;}.podcast-actions button:hover {background-color:var(--background-modifier-hover);}"};function Rp(n,e){ge(e,!1),Pe(n,$p);let t=M(e,"podcast",8),s=M(e,"isSaved",8,!1);const r=Ye();_e();var i=Ip(),a=R(i),o=R(a),l=H(a,2),c=R(l),d=R(c),u=H(l,2),h=R(u);{var f=m=>{{let v=qe(()=>(O(t()),z(()=>`Remove ${t().title} podcast`)));Cr(m,{icon:"trash",get ariaLabel(){return g(v)},$$events:{click:()=>r("removePodcast",{podcast:t()})}})}},p=m=>{{let v=qe(()=>(O(t()),z(()=>`Add ${t().title} podcast`)));Cr(m,{icon:"plus",get ariaLabel(){return g(v)},$$events:{click:()=>r("addPodcast",{podcast:t()})}})}};de(h,m=>{s()?m(f):m(p,!1)})}me(()=>{ue(o,"src",(O(t()),z(()=>t().artworkUrl))),ue(o,"alt",(O(t()),z(()=>`Artwork for ${t().title}`))),je(d,(O(t()),z(()=>t().title)))}),ou(3,i,()=>bu,()=>({duration:300})),L(n,i),ve()}var Mp=J('<div role="listitem"><!></div>'),Fp=J('<div class="podcast-query-container svelte-8ek8i8"><!> <div class="podcast-query-results svelte-8ek8i8" role="list" aria-label="Podcast search results"></div></div>');const Np={hash:"svelte-8ek8i8",code:`.podcast-query-container.svelte-8ek8i8 {margin-bottom:1.5rem;}.podcast-query-results.svelte-8ek8i8 {display:grid;gap:0.75rem;grid-template-columns:1fr;}
|
||
|
||
@media (min-width: 500px) {.podcast-query-results.svelte-8ek8i8 {grid-template-columns:repeat(auto-fill, minmax(18rem, 1fr));}
|
||
}`};function Op(n,e){ge(e,!1),Pe(n,Np);const t=()=>Ue(mn,"$savedFeeds",r),s=()=>Ue(fp,"$podcastsUpdated",r),[r,i]=Or();let a=q([]),o=q("grid-3"),l=q(""),c=q();rn(()=>{d(),g(c)&&g(c).focus()});function d(){g(l).trim()===""&&T(a,Object.values(t()))}const u=P.debounce(async({detail:{value:_}})=>{T(l,_);const y=Ap(_);if(y){const b=await new Ki().getFeed(y.href);T(a,[b])}else _.trim()===""?d():T(a,await wu(_))},300,!0);function h(_){const{podcast:y}=_.detail;mn.update(b=>({...b,[y.title]:y})),d()}function f(_){const{podcast:y}=_.detail;mn.update(b=>{const E={...b};return delete E[y.title],E}),d()}He(()=>(g(l),t(),s()),()=>{g(l).trim()===""&&T(a,Object.values(t())),s()}),He(()=>g(a),()=>{g(a).length%3===0||g(a).length>3?T(o,"grid-3"):g(a).length%2===0?T(o,"grid-2"):g(a).length%1===0&&T(o,"grid-1")}),sn(),_e();var p=Fp(),m=R(p);Co(m,{placeholder:"Search or enter feed URL...",style:{width:"100%","margin-bottom":"1rem"},get el(){return g(c)},set el(_){T(c,_)},$$events:{change:u},$$legacy:!0});var v=H(m,2);zs(v,5,()=>g(a),_=>_.url,(_,y)=>{var b=Mp(),E=R(b);{let C=qe(()=>(g(y),t(),z(()=>typeof g(y).url=="string"&&t()[g(y).title]?.url===g(y).url)));Rp(E,{get podcast(){return g(y)},get isSaved(){return g(C)},$$events:{addPodcast:h,removePodcast:f}})}L(_,b)}),ou(3,p,()=>bu,()=>({duration:300})),L(n,p),ve(),i()}var Dp=J('<button type="button" class="icon-button svelte-11mdast"><span></span></button>'),Lp=J('<span class="icon-static svelte-11mdast"></span>');const Bp={hash:"svelte-11mdast",code:".icon-button.svelte-11mdast {border:none;background:none;padding:0;cursor:pointer;display:inline-flex;align-items:center;justify-content:center;}.icon-button.svelte-11mdast:disabled {cursor:not-allowed;opacity:0.4;}.icon-static.svelte-11mdast {display:inline-flex;align-items:center;justify-content:center;}"};function Ge(n,e){ge(e,!1),Pe(n,Bp);let t=M(e,"size",8,16),s=M(e,"icon",8),r=M(e,"clickable",8,!0),i=M(e,"label",8,""),a=M(e,"pressed",8,void 0),o=M(e,"disabled",8,!1),l=q(),c=M(e,"style",24,()=>({})),d=q(),u=q();const h=Ye();rn(()=>{P.setIcon(g(l),s()),f()}),cu(()=>{P.setIcon(g(l),s()),f()});function f(){g(l)&&(pr(l,g(l).style.cssText=g(d)),t()&&(pr(l,g(l).style.width=`${t()}px`),pr(l,g(l).style.height=`${t()}px`)))}function p(b){!r()||o()||h("click",{event:b})}He(()=>O(c()),()=>{T(d,Qs(c()))}),He(()=>O(a()),()=>{T(u,a()===void 0?void 0:a()?"true":"false")}),sn(),_e();var m=nt(),v=Be(m);{var _=b=>{var E=Dp(),C=R(E);Nn(C,F=>T(l,F),()=>g(l)),me(()=>{ue(E,"aria-label",i()),ue(E,"aria-pressed",g(u)),E.disabled=o()}),le("click",E,p),L(b,E)},y=b=>{var E=Lp();Nn(E,C=>T(l,C),()=>g(l)),me(()=>{ue(E,"aria-label",i()||void 0),ue(E,"aria-hidden",i()?void 0:"true")}),L(b,E)};de(v,b=>{r()?b(_):b(y,!1)})}L(n,m),ve()}var Up=J('<button type="button"><!></button>'),jp=J('<div class="playlist-item svelte-jzsw7l"><div class="playlist-item-left svelte-jzsw7l"><!> <span class="playlist-name svelte-jzsw7l"> </span> <span class="playlist-count svelte-jzsw7l"> </span></div> <div class="playlist-item-controls svelte-jzsw7l"><!></div></div>');const zp={hash:"svelte-jzsw7l",code:".playlist-item.svelte-jzsw7l {display:flex;align-items:center;justify-content:space-between;gap:0.75rem;padding:0.625rem 0.75rem;width:100%;background:var(--background-secondary);transition:background-color 120ms ease;}.playlist-item.svelte-jzsw7l:not(:last-child) {border-bottom:1px solid var(--background-modifier-border);}.playlist-item.svelte-jzsw7l:hover {background:var(--background-secondary-alt);}.playlist-item-left.svelte-jzsw7l {display:flex;align-items:center;gap:0.5rem;min-width:0;}.playlist-name.svelte-jzsw7l {font-weight:500;font-size:0.9rem;color:var(--text-normal);}.playlist-count.svelte-jzsw7l {font-size:0.8rem;color:var(--text-muted);}.playlist-item-controls.svelte-jzsw7l {display:flex;align-items:center;gap:0.25rem;}.delete-button.svelte-jzsw7l {display:flex;align-items:center;justify-content:center;padding:0.375rem;border:none;border-radius:0.25rem;background:transparent;color:var(--text-muted);cursor:pointer;transition:background-color 120ms ease, color 120ms ease;}.delete-button.svelte-jzsw7l:hover {background:var(--background-modifier-hover);color:var(--text-error);}.delete-button.confirm.svelte-jzsw7l {color:var(--text-success);}.delete-button.confirm.svelte-jzsw7l:hover {color:var(--text-success);}"};function ga(n,e){ge(e,!1),Pe(n,zp);let t=M(e,"playlist",8),s=M(e,"showDeleteButton",8,!0),r=q(!1);const i=Ye();function a(){if(g(r)){i("delete",{value:t()});return}T(r,!0),setTimeout(()=>{T(r,!1)},2e3)}_e();var o=jp(),l=R(o),c=R(l);Ge(c,{get icon(){return O(t()),z(()=>t().icon)},clickable:!1,size:18});var d=H(c,2),u=R(d),h=H(d,2),f=R(h),p=H(l,2),m=R(p);{var v=_=>{var y=Up();let b;var E=R(y);{let C=qe(()=>g(r)?"check":"trash");Ge(E,{get icon(){return g(C)},clickable:!1,size:16})}me(()=>{b=Qt(y,1,"delete-button svelte-jzsw7l",null,b,{confirm:g(r)}),ue(y,"aria-label",g(r)?"Confirm deletion":"Delete playlist")}),le("click",y,a),L(_,y)};de(m,_=>{s()&&_(v)})}me(()=>{je(u,(O(t()),z(()=>t().name))),je(f,`(${O(t()),z(()=>t().episodes.length)??""})`)}),L(n,o),ve()}var qp=J("<span></span>");function Wp(n,e){ge(e,!1);let t=M(e,"value",8,""),s=M(e,"options",24,()=>({})),r=M(e,"disabled",8,!1),i=q(),a,o=M(e,"style",8);const l=Ye();rn(()=>{a=new P.DropdownComponent(g(i)),c(a)});function c(u){s()&&u.addOptions(s()),t()&&u.setValue(t()),r()&&u.setDisabled(r()),u.onChange(h=>{l("change",{value:h})}),o()&&u.selectEl.setAttr("style",Qs(o()))}_e();var d=qp();Nn(d,u=>T(i,u),()=>g(i)),L(n,d),ve()}const Hp=new Set(["activity","airplay","alarm-check","alarm-clock-off","alarm-clock","alarm-minus","alarm-plus","album","alert-circle","alert-octagon","alert-triangle","align-center-horizontal","align-center-vertical","align-center","align-end-horizontal","align-end-vertical","align-horizontal-distribute-center","align-horizontal-distribute-end","align-horizontal-distribute-start","align-horizontal-justify-center","align-horizontal-justify-end","align-horizontal-justify-start","align-horizontal-space-around","align-horizontal-space-between","align-justify","align-left","align-right","align-start-horizontal","align-start-vertical","align-vertical-distribute-center","align-vertical-distribute-end","align-vertical-distribute-start","align-vertical-justify-center","align-vertical-justify-end","align-vertical-justify-start","align-vertical-space-around","align-vertical-space-between","anchor","aperture","archive","arrow-big-down","arrow-big-left","arrow-big-right","arrow-big-up","arrow-down-circle","arrow-down-left","arrow-down-right","arrow-down","arrow-left-circle","arrow-left-right","arrow-left","arrow-right-circle","arrow-right","arrow-up-circle","arrow-up-left","arrow-up-right","arrow-up","asterisk","at-sign","award","axe","banknote","bar-chart-2","bar-chart","baseline","battery-charging","battery-full","battery-low","battery-medium","battery","beaker","bell-minus","bell-off","bell-plus","bell-ring","bell","bike","binary","bitcoin","bluetooth-connected","bluetooth-off","bluetooth-searching","bluetooth","bold","book-open","book","bookmark-minus","bookmark-plus","bookmark","bot","box-select","box","briefcase","brush","bug","building-2","building","bus","calculator","calendar","camera-off","camera","car","carrot","cast","check-circle-2","check-circle","check-square","check","chevron-down","chevron-first","chevron-last","chevron-left","chevron-right","chevron-up","chevrons-down-up","chevrons-down","chevrons-left","chevrons-right","chevrons-up-down","chevrons-up","chrome","circle-slashed","circle","clipboard-check","clipboard-copy","clipboard-list","clipboard-x","clipboard","clock-1","clock-10","clock-11","clock-12","clock-2","clock-3","clock-4","clock-5","clock-6","clock-7","clock-8","clock-9","clock","cloud-drizzle","cloud-fog","cloud-hail","cloud-lightning","cloud-moon","cloud-off","cloud-rain-wind","cloud-rain","cloud-snow","cloud-sun","cloud","cloudy","clover","code-2","code","codepen","codesandbox","coffee","coins","columns","command","compass","contact","contrast","cookie","copy","copyleft","copyright","corner-down-left","corner-down-right","corner-left-down","corner-left-up","corner-right-down","corner-right-up","corner-up-left","corner-up-right","cpu","credit-card","crop","cross","crosshair","crown","currency","database","delete","dice-1","dice-2","dice-3","dice-4","dice-5","dice-6","disc","divide-circle","divide-square","divide","dollar-sign","download-cloud","download","dribbble","droplet","droplets","drumstick","edit-2","edit-3","edit","egg","equal-not","equal","eraser","euro","expand","external-link","eye-off","eye","facebook","fast-forward","feather","figma","file-check-2","file-check","file-code","file-digit","file-input","file-minus-2","file-minus","file-output","file-plus-2","file-plus","file-search","file-text","file-x-2","file-x","file","files","film","filter","flag-off","flag-triangle-left","flag-triangle-right","flag","flame","flashlight-off","flashlight","flask-conical","flask-round","folder-minus","folder-open","folder-plus","folder","form-input","forward","frame","framer","frown","function-square","gamepad-2","gamepad","gauge","gavel","gem","ghost","gift","git-branch-plus","git-branch","git-commit","git-fork","git-merge","git-pull-request","github","gitlab","glasses","globe-2","globe","grab","graduation-cap","grid","grip-horizontal","grip-vertical","hammer","hand-metal","hand","hard-drive","hard-hat","hash","haze","headphones","heart","help-circle","hexagon","highlighter","history","home","image-minus","image-off","image-plus","image","import","inbox","indent","indian-rupee","infinity","info","inspect","instagram","italic","japanese-yen","key","keyboard","landmark","languages","laptop-2","laptop","lasso-select","lasso","layers","layout-dashboard","layout-grid","layout-list","layout-template","layout","library","life-buoy","lightbulb-off","lightbulb","link-2-off","link-2","link","linkedin","list-checks","list-minus","list-ordered","list-plus","list-x","list","loader-2","loader","locate-fixed","locate-off","locate","lock","log-in","log-out","mail","map-pin","map","maximize-2","maximize","megaphone","meh","menu","message-circle","message-square","mic-off","mic","minimize-2","minimize","minus-circle","minus-square","minus","monitor-off","monitor-speaker","monitor","moon","more-horizontal","more-vertical","mountain-snow","mountain","mouse-pointer-2","mouse-pointer-click","mouse-pointer","mouse","move-diagonal-2","move-diagonal","move-horizontal","move-vertical","move","music","navigation-2","navigation","network","octagon","option","outdent","package-check","package-minus","package-plus","package-search","package-x","package","palette","palmtree","paperclip","pause-circle","pause-octagon","pause","pen-tool","pencil","percent","person-standing","phone-call","phone-forwarded","phone-incoming","phone-missed","phone-off","phone-outgoing","phone","pie-chart","piggy-bank","pin","pipette","plane","play-circle","play","plug-zap","plus-circle","plus-square","plus","pocket","podcast","pointer","pound-sterling","power-off","power","printer","qr-code","quote","radio-receiver","radio","redo","refresh-ccw","refresh-cw","regex","repeat-1","repeat","reply-all","reply","rewind","rocket","rocking-chair","rotate-ccw","rotate-cw","rss","ruler","russian-ruble","save","scale","scan-line","scan","scissors","screen-share-off","screen-share","search","send","separator-horizontal","separator-vertical","server-crash","server-off","server","settings-2","settings","share-2","share","sheet","shield-alert","shield-check","shield-close","shield-off","shield","shirt","shopping-bag","shopping-cart","shovel","shrink","shuffle","sidebar-close","sidebar-open","sidebar","sigma","signal-high","signal-low","signal-medium","signal-zero","signal","skip-back","skip-forward","skull","slack","slash","sliders","smartphone-charging","smartphone","smile","snowflake","sort-asc","sort-desc","speaker","sprout","square","star-half","star","stop-circle","stretch-horizontal","stretch-vertical","strikethrough","subscript","sun","sunrise","sunset","superscript","swiss-franc","switch-camera","table","tablet","tag","target","tent","terminal-square","terminal","text-cursor-input","text-cursor","thermometer-snowflake","thermometer-sun","thermometer","thumbs-down","thumbs-up","ticket","timer-off","timer-reset","timer","toggle-left","toggle-right","tornado","trash-2","trash","trello","trending-down","trending-up","triangle","truck","tv-2","tv","twitch","twitter","type","umbrella","underline","undo","unlink-2","unlink","unlock","upload-cloud","upload","user-check","user-minus","user-plus","user-x","user","users","verified","vibrate","video-off","video","view","voicemail","volume-1","volume-2","volume-x","volume","wallet","wand","watch","waves","webcam","wifi-off","wifi","wind","wrap-text","wrench","x-circle","x-octagon","x-square","x","youtube","zap-off","zap","zoom-in","zoom-out","search-large","search","activity","airplay","alarm-check","alarm-clock-off","alarm-clock","alarm-minus","alarm-plus","album","alert-circle","alert-octagon","alert-triangle","align-center-horizontal","align-center-vertical","align-center","align-end-horizontal","align-end-vertical","align-horizontal-distribute-center","align-horizontal-distribute-end","align-horizontal-distribute-start","align-horizontal-justify-center","align-horizontal-justify-end","align-horizontal-justify-start","align-horizontal-space-around","align-horizontal-space-between","align-justify","align-left","align-right","align-start-horizontal","align-start-vertical","align-vertical-distribute-center","align-vertical-distribute-end","align-vertical-distribute-start","align-vertical-justify-center","align-vertical-justify-end","align-vertical-justify-start","align-vertical-space-around","align-vertical-space-between","anchor","aperture","archive","arrow-big-down","arrow-big-left","arrow-big-right","arrow-big-up","arrow-down-circle","arrow-down-left","arrow-down-right","arrow-down","arrow-left-circle","arrow-left-right","arrow-left","arrow-right-circle","arrow-right","arrow-up-circle","arrow-up-left","arrow-up-right","arrow-up","asterisk","at-sign","award","axe","banknote","bar-chart-2","bar-chart","baseline","battery-charging","battery-full","battery-low","battery-medium","battery","beaker","bell-minus","bell-off","bell-plus","bell-ring","bell","bike","binary","bitcoin","bluetooth-connected","bluetooth-off","bluetooth-searching","bluetooth","bold","book-open","book","bookmark-minus","bookmark-plus","bookmark","bot","box-select","box","briefcase","brush","bug","building-2","building","bus","calculator","calendar","camera-off","camera","car","carrot","cast","check-circle-2","check-circle","check-square","check","chevron-down","chevron-first","chevron-last","chevron-left","chevron-right","chevron-up","chevrons-down-up","chevrons-down","chevrons-left","chevrons-right","chevrons-up-down","chevrons-up","chrome","circle-slashed","circle","clipboard-check","clipboard-copy","clipboard-list","clipboard-x","clipboard","clock-1","clock-10","clock-11","clock-12","clock-2","clock-3","clock-4","clock-5","clock-6","clock-7","clock-8","clock-9","lucide-clock","cloud-drizzle","cloud-fog","cloud-hail","cloud-lightning","cloud-moon","cloud-off","cloud-rain-wind","cloud-rain","cloud-snow","cloud-sun","lucide-cloud","cloudy","clover","code-2","code","codepen","codesandbox","coffee","coins","columns","command","compass","contact","contrast","cookie","copy","copyleft","copyright","corner-down-left","corner-down-right","corner-left-down","corner-left-up","corner-right-down","corner-right-up","corner-up-left","corner-up-right","cpu","credit-card","crop","lucide-cross","crosshair","crown","currency","database","delete","dice-1","dice-2","dice-3","dice-4","dice-5","dice-6","disc","divide-circle","divide-square","divide","dollar-sign","download-cloud","download","dribbble","droplet","droplets","drumstick","edit-2","edit-3","edit","egg","equal-not","equal","eraser","euro","expand","external-link","eye-off","eye","facebook","fast-forward","feather","figma","file-check-2","file-check","file-code","file-digit","file-input","file-minus-2","file-minus","file-output","file-plus-2","file-plus","file-search","file-text","file-x-2","file-x","file","files","film","filter","flag-off","flag-triangle-left","flag-triangle-right","flag","flame","flashlight-off","flashlight","flask-conical","flask-round","folder-minus","folder-open","folder-plus","lucide-folder","form-input","forward","frame","framer","frown","function-square","gamepad-2","gamepad","gauge","gavel","gem","ghost","gift","git-branch-plus","git-branch","git-commit","git-fork","git-merge","git-pull-request","github","gitlab","glasses","globe-2","globe","grab","graduation-cap","grid","grip-horizontal","grip-vertical","hammer","hand-metal","hand","hard-drive","hard-hat","hash","haze","headphones","heart","help-circle","hexagon","highlighter","history","home","image-minus","image-off","image-plus","image","import","inbox","indent","indian-rupee","infinity","lucide-info","inspect","instagram","italic","japanese-yen","key","keyboard","landmark","lucide-languages","laptop-2","laptop","lasso-select","lasso","layers","layout-dashboard","layout-grid","layout-list","layout-template","layout","library","life-buoy","lightbulb-off","lightbulb","link-2-off","link-2","lucide-link","linkedin","list-checks","list-minus","list-ordered","list-plus","list-x","list","loader-2","loader","locate-fixed","locate-off","locate","lock","log-in","log-out","mail","map-pin","map","maximize-2","maximize","megaphone","meh","menu","message-circle","message-square","mic-off","mic","minimize-2","minimize","minus-circle","minus-square","minus","monitor-off","monitor-speaker","monitor","moon","more-horizontal","more-vertical","mountain-snow","mountain","mouse-pointer-2","mouse-pointer-click","mouse-pointer","mouse","move-diagonal-2","move-diagonal","move-horizontal","move-vertical","move","music","navigation-2","navigation","network","octagon","option","outdent","package-check","package-minus","package-plus","package-search","package-x","package","palette","palmtree","paperclip","pause-circle","pause-octagon","pause","pen-tool","lucide-pencil","percent","person-standing","phone-call","phone-forwarded","phone-incoming","phone-missed","phone-off","phone-outgoing","phone","pie-chart","piggy-bank","lucide-pin","pipette","plane","play-circle","play","plug-zap","plus-circle","plus-square","plus","pocket","podcast","pointer","pound-sterling","power-off","power","printer","qr-code","quote","radio-receiver","radio","redo","refresh-ccw","refresh-cw","regex","repeat-1","repeat","reply-all","reply","rewind","rocket","rocking-chair","rotate-ccw","rotate-cw","rss","ruler","russian-ruble","save","scale","scan-line","scan","scissors","screen-share-off","screen-share","lucide-search","send","separator-horizontal","separator-vertical","server-crash","server-off","server","settings-2","settings","share-2","share","sheet","shield-alert","shield-check","shield-close","shield-off","shield","shirt","shopping-bag","shopping-cart","shovel","shrink","shuffle","sidebar-close","sidebar-open","sidebar","sigma","signal-high","signal-low","signal-medium","signal-zero","signal","skip-back","skip-forward","skull","slack","slash","sliders","smartphone-charging","smartphone","smile","snowflake","sort-asc","sort-desc","speaker","sprout","square","star-half","lucide-star","stop-circle","stretch-horizontal","stretch-vertical","strikethrough","subscript","sun","sunrise","sunset","superscript","swiss-franc","switch-camera","table","tablet","tag","target","tent","terminal-square","terminal","text-cursor-input","text-cursor","thermometer-snowflake","thermometer-sun","thermometer","thumbs-down","thumbs-up","ticket","timer-off","timer-reset","timer","toggle-left","toggle-right","tornado","trash-2","lucide-trash","trello","trending-down","trending-up","triangle","truck","tv-2","tv","twitch","twitter","type","umbrella","underline","undo","unlink-2","unlink","unlock","upload-cloud","upload","user-check","user-minus","user-plus","user-x","user","users","verified","vibrate","video-off","video","view","voicemail","volume-1","volume-2","volume-x","volume","wallet","wand","watch","waves","webcam","wifi-off","wifi","wind","wrap-text","wrench","x-circle","x-octagon","x-square","x","youtube","zap-off","zap","zoom-in","zoom-out","search-large","lucide-search"]),va=Array.from(Hp);var Vp=J('<div class="playlist-manager-container svelte-w5in4v"><div class="playlist-list svelte-w5in4v"><!> <!> <!></div> <div class="add-playlist-container svelte-w5in4v"><!> <!> <!></div></div>');const Yp={hash:"svelte-w5in4v",code:".playlist-manager-container.svelte-w5in4v {display:flex;flex-direction:column;width:100%;margin-bottom:1.5rem;}.playlist-list.svelte-w5in4v {display:flex;flex-direction:column;width:100%;border:1px solid var(--background-modifier-border);border-radius:0.5rem;overflow:hidden;}.add-playlist-container.svelte-w5in4v {display:flex;align-items:center;gap:0.5rem;margin-top:1rem;}"};function Kp(n,e){ge(e,!1),Pe(n,Yp);const t=()=>Ue(Et,"$queue",r),s=()=>Ue(ls,"$favorites",r),[r,i]=Or();let a=q([]),o=q(""),l=va.reduce((x,A)=>(x[A]=A,x),{}),c=q(va[0]);rn(()=>{const x=Rt.subscribe(A=>{T(a,Object.values(A))});return()=>{x()}});function d(){Rt.update(x=>(x[g(o)]={name:g(o),icon:g(c),episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},x)),T(o,""),T(c,va[0])}function u(x){T(c,x.detail.value)}function h(x){Rt.update(A=>(delete A[x.detail.value.name],A))}function f(x){Rt.update(A=>(A[x.detail.value.name].shouldRepeat=!A[x.detail.value.name].shouldRepeat,A))}_e();var p=Vp(),m=R(p),v=R(m);ga(v,{get playlist(){return t()},showDeleteButton:!1});var _=H(v,2);ga(_,{get playlist(){return s()},showDeleteButton:!1});var y=H(_,2);zs(y,1,()=>g(a),Lc,(x,A)=>{ga(x,{get playlist(){return g(A)},$$events:{delete:h,toggleRepeat:f}})});var b=H(m,2),E=R(b);Wp(E,{get options(){return l},get value(){return g(c)},set value(x){T(c,x)},$$events:{change:u},$$legacy:!0});var C=H(E,2);Co(C,{placeholder:"Playlist name",get value(){return g(o)},set value(x){T(o,x)},$$legacy:!0});var F=H(C,2);Cr(F,{icon:"plus",cta:!0,$$events:{click:d}}),L(n,p),ve(),i()}function yn(n){return Array.isArray?Array.isArray(n):Eu(n)==="[object Array]"}function Jp(n){if(typeof n=="string")return n;let e=n+"";return e=="0"&&1/n==-1/0?"-0":e}function Xp(n){return n==null?"":Jp(n)}function Jt(n){return typeof n=="string"}function xu(n){return typeof n=="number"}function Gp(n){return n===!0||n===!1||Qp(n)&&Eu(n)=="[object Boolean]"}function ku(n){return typeof n=="object"}function Qp(n){return ku(n)&&n!==null}function ut(n){return n!=null}function _a(n){return!n.trim().length}function Eu(n){return n==null?n===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(n)}const Zp="Incorrect 'index' type",em=n=>`Invalid value for key ${n}`,tm=n=>`Pattern length exceeds max of ${n}.`,nm=n=>`Missing ${n} property in key`,sm=n=>`Property 'weight' in key '${n}' must be a positive integer`,Rl=Object.prototype.hasOwnProperty;class rm{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(s=>{let r=Su(s);this._keys.push(r),this._keyMap[r.id]=r,t+=r.weight}),this._keys.forEach(s=>{s.weight/=t})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function Su(n){let e=null,t=null,s=null,r=1,i=null;if(Jt(n)||yn(n))s=n,e=Ml(n),t=Ka(n);else{if(!Rl.call(n,"name"))throw new Error(nm("name"));const a=n.name;if(s=a,Rl.call(n,"weight")&&(r=n.weight,r<=0))throw new Error(sm(a));e=Ml(a),t=Ka(a),i=n.getFn}return{path:e,id:t,weight:r,src:s,getFn:i}}function Ml(n){return yn(n)?n:n.split(".")}function Ka(n){return yn(n)?n.join("."):n}function im(n,e){let t=[],s=!1;const r=(i,a,o)=>{if(ut(i))if(!a[o])t.push(i);else{let l=a[o];const c=i[l];if(!ut(c))return;if(o===a.length-1&&(Jt(c)||xu(c)||Gp(c)))t.push(Xp(c));else if(yn(c)){s=!0;for(let d=0,u=c.length;d<u;d+=1)r(c[d],a,o+1)}else a.length&&r(c,a,o+1)}};return r(n,Jt(e)?e.split("."):e,0),s?t:t[0]}const am={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},om={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(n,e)=>n.score===e.score?n.idx<e.idx?-1:1:n.score<e.score?-1:1},lm={location:0,threshold:.6,distance:100},cm={useExtendedSearch:!1,getFn:im,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1};var Y={...om,...am,...lm,...cm};const um=/[^ ]+/g;function dm(n=1,e=3){const t=new Map,s=Math.pow(10,e);return{get(r){const i=r.match(um).length;if(t.has(i))return t.get(i);const a=1/Math.pow(i,.5*n),o=parseFloat(Math.round(a*s)/s);return t.set(i,o),o},clear(){t.clear()}}}class Po{constructor({getFn:e=Y.getFn,fieldNormWeight:t=Y.fieldNormWeight}={}){this.norm=dm(t,3),this.getFn=e,this.isCreated=!1,this.setIndexRecords()}setSources(e=[]){this.docs=e}setIndexRecords(e=[]){this.records=e}setKeys(e=[]){this.keys=e,this._keysMap={},e.forEach((t,s)=>{this._keysMap[t.id]=s})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,Jt(this.docs[0])?this.docs.forEach((e,t)=>{this._addString(e,t)}):this.docs.forEach((e,t)=>{this._addObject(e,t)}),this.norm.clear())}add(e){const t=this.size();Jt(e)?this._addString(e,t):this._addObject(e,t)}removeAt(e){this.records.splice(e,1);for(let t=e,s=this.size();t<s;t+=1)this.records[t].i-=1}getValueForItemAtKeyId(e,t){return e[this._keysMap[t]]}size(){return this.records.length}_addString(e,t){if(!ut(e)||_a(e))return;let s={v:e,i:t,n:this.norm.get(e)};this.records.push(s)}_addObject(e,t){let s={i:t,$:{}};this.keys.forEach((r,i)=>{let a=r.getFn?r.getFn(e):this.getFn(e,r.path);if(ut(a)){if(yn(a)){let o=[];const l=[{nestedArrIndex:-1,value:a}];for(;l.length;){const{nestedArrIndex:c,value:d}=l.pop();if(ut(d))if(Jt(d)&&!_a(d)){let u={v:d,i:c,n:this.norm.get(d)};o.push(u)}else yn(d)&&d.forEach((u,h)=>{l.push({nestedArrIndex:h,value:u})})}s.$[i]=o}else if(Jt(a)&&!_a(a)){let o={v:a,n:this.norm.get(a)};s.$[i]=o}}}),this.records.push(s)}toJSON(){return{keys:this.keys,records:this.records}}}function Au(n,e,{getFn:t=Y.getFn,fieldNormWeight:s=Y.fieldNormWeight}={}){const r=new Po({getFn:t,fieldNormWeight:s});return r.setKeys(n.map(Su)),r.setSources(e),r.create(),r}function fm(n,{getFn:e=Y.getFn,fieldNormWeight:t=Y.fieldNormWeight}={}){const{keys:s,records:r}=n,i=new Po({getFn:e,fieldNormWeight:t});return i.setKeys(s),i.setIndexRecords(r),i}function Jr(n,{errors:e=0,currentLocation:t=0,expectedLocation:s=0,distance:r=Y.distance,ignoreLocation:i=Y.ignoreLocation}={}){const a=e/n.length;if(i)return a;const o=Math.abs(s-t);return r?a+o/r:o?1:a}function hm(n=[],e=Y.minMatchCharLength){let t=[],s=-1,r=-1,i=0;for(let a=n.length;i<a;i+=1){let o=n[i];o&&s===-1?s=i:!o&&s!==-1&&(r=i-1,r-s+1>=e&&t.push([s,r]),s=-1)}return n[i-1]&&i-s>=e&&t.push([s,i-1]),t}const Vn=32;function pm(n,e,t,{location:s=Y.location,distance:r=Y.distance,threshold:i=Y.threshold,findAllMatches:a=Y.findAllMatches,minMatchCharLength:o=Y.minMatchCharLength,includeMatches:l=Y.includeMatches,ignoreLocation:c=Y.ignoreLocation}={}){if(e.length>Vn)throw new Error(tm(Vn));const d=e.length,u=n.length,h=Math.max(0,Math.min(s,u));let f=i,p=h;const m=o>1||l,v=m?Array(u):[];let _;for(;(_=n.indexOf(e,p))>-1;){let x=Jr(e,{currentLocation:_,expectedLocation:h,distance:r,ignoreLocation:c});if(f=Math.min(x,f),p=_+d,m){let A=0;for(;A<d;)v[_+A]=1,A+=1}}p=-1;let y=[],b=1,E=d+u;const C=1<<d-1;for(let x=0;x<d;x+=1){let A=0,I=E;for(;A<I;)Jr(e,{errors:x,currentLocation:h+I,expectedLocation:h,distance:r,ignoreLocation:c})<=f?A=I:E=I,I=Math.floor((E-A)/2+A);E=I;let $=Math.max(1,h-I+1),D=a?u:Math.min(h+I,u)+d,G=Array(D+2);G[D+1]=(1<<x)-1;for(let ce=D;ce>=$;ce-=1){let Ee=ce-1,we=t[n.charAt(Ee)];if(m&&(v[Ee]=+!!we),G[ce]=(G[ce+1]<<1|1)&we,x&&(G[ce]|=(y[ce+1]|y[ce])<<1|1|y[ce+1]),G[ce]&C&&(b=Jr(e,{errors:x,currentLocation:Ee,expectedLocation:h,distance:r,ignoreLocation:c}),b<=f)){if(f=b,p=Ee,p<=h)break;$=Math.max(1,2*h-p)}}if(Jr(e,{errors:x+1,currentLocation:h,expectedLocation:h,distance:r,ignoreLocation:c})>f)break;y=G}const F={isMatch:p>=0,score:Math.max(.001,b)};if(m){const x=hm(v,o);x.length?l&&(F.indices=x):F.isMatch=!1}return F}function mm(n){let e={};for(let t=0,s=n.length;t<s;t+=1){const r=n.charAt(t);e[r]=(e[r]||0)|1<<s-t-1}return e}const Ei=String.prototype.normalize?(n=>n.normalize("NFD").replace(/[\u0300-\u036F\u0483-\u0489\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u0610-\u061A\u064B-\u065F\u0670\u06D6-\u06DC\u06DF-\u06E4\u06E7\u06E8\u06EA-\u06ED\u0711\u0730-\u074A\u07A6-\u07B0\u07EB-\u07F3\u07FD\u0816-\u0819\u081B-\u0823\u0825-\u0827\u0829-\u082D\u0859-\u085B\u08D3-\u08E1\u08E3-\u0903\u093A-\u093C\u093E-\u094F\u0951-\u0957\u0962\u0963\u0981-\u0983\u09BC\u09BE-\u09C4\u09C7\u09C8\u09CB-\u09CD\u09D7\u09E2\u09E3\u09FE\u0A01-\u0A03\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A70\u0A71\u0A75\u0A81-\u0A83\u0ABC\u0ABE-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AE2\u0AE3\u0AFA-\u0AFF\u0B01-\u0B03\u0B3C\u0B3E-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B62\u0B63\u0B82\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD7\u0C00-\u0C04\u0C3E-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C62\u0C63\u0C81-\u0C83\u0CBC\u0CBE-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CE2\u0CE3\u0D00-\u0D03\u0D3B\u0D3C\u0D3E-\u0D44\u0D46-\u0D48\u0D4A-\u0D4D\u0D57\u0D62\u0D63\u0D82\u0D83\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DF2\u0DF3\u0E31\u0E34-\u0E3A\u0E47-\u0E4E\u0EB1\u0EB4-\u0EB9\u0EBB\u0EBC\u0EC8-\u0ECD\u0F18\u0F19\u0F35\u0F37\u0F39\u0F3E\u0F3F\u0F71-\u0F84\u0F86\u0F87\u0F8D-\u0F97\u0F99-\u0FBC\u0FC6\u102B-\u103E\u1056-\u1059\u105E-\u1060\u1062-\u1064\u1067-\u106D\u1071-\u1074\u1082-\u108D\u108F\u109A-\u109D\u135D-\u135F\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17B4-\u17D3\u17DD\u180B-\u180D\u1885\u1886\u18A9\u1920-\u192B\u1930-\u193B\u1A17-\u1A1B\u1A55-\u1A5E\u1A60-\u1A7C\u1A7F\u1AB0-\u1ABE\u1B00-\u1B04\u1B34-\u1B44\u1B6B-\u1B73\u1B80-\u1B82\u1BA1-\u1BAD\u1BE6-\u1BF3\u1C24-\u1C37\u1CD0-\u1CD2\u1CD4-\u1CE8\u1CED\u1CF2-\u1CF4\u1CF7-\u1CF9\u1DC0-\u1DF9\u1DFB-\u1DFF\u20D0-\u20F0\u2CEF-\u2CF1\u2D7F\u2DE0-\u2DFF\u302A-\u302F\u3099\u309A\uA66F-\uA672\uA674-\uA67D\uA69E\uA69F\uA6F0\uA6F1\uA802\uA806\uA80B\uA823-\uA827\uA880\uA881\uA8B4-\uA8C5\uA8E0-\uA8F1\uA8FF\uA926-\uA92D\uA947-\uA953\uA980-\uA983\uA9B3-\uA9C0\uA9E5\uAA29-\uAA36\uAA43\uAA4C\uAA4D\uAA7B-\uAA7D\uAAB0\uAAB2-\uAAB4\uAAB7\uAAB8\uAABE\uAABF\uAAC1\uAAEB-\uAAEF\uAAF5\uAAF6\uABE3-\uABEA\uABEC\uABED\uFB1E\uFE00-\uFE0F\uFE20-\uFE2F]/g,"")):(n=>n);class Cu{constructor(e,{location:t=Y.location,threshold:s=Y.threshold,distance:r=Y.distance,includeMatches:i=Y.includeMatches,findAllMatches:a=Y.findAllMatches,minMatchCharLength:o=Y.minMatchCharLength,isCaseSensitive:l=Y.isCaseSensitive,ignoreDiacritics:c=Y.ignoreDiacritics,ignoreLocation:d=Y.ignoreLocation}={}){if(this.options={location:t,threshold:s,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:l,ignoreDiacritics:c,ignoreLocation:d},e=l?e:e.toLowerCase(),e=c?Ei(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;const u=(f,p)=>{this.chunks.push({pattern:f,alphabet:mm(f),startIndex:p})},h=this.pattern.length;if(h>Vn){let f=0;const p=h%Vn,m=h-p;for(;f<m;)u(this.pattern.substr(f,Vn),f),f+=Vn;if(p){const v=h-Vn;u(this.pattern.substr(v),v)}}else u(this.pattern,0)}searchIn(e){const{isCaseSensitive:t,ignoreDiacritics:s,includeMatches:r}=this.options;if(e=t?e:e.toLowerCase(),e=s?Ei(e):e,this.pattern===e){let m={isMatch:!0,score:0};return r&&(m.indices=[[0,e.length-1]]),m}const{location:i,distance:a,threshold:o,findAllMatches:l,minMatchCharLength:c,ignoreLocation:d}=this.options;let u=[],h=0,f=!1;this.chunks.forEach(({pattern:m,alphabet:v,startIndex:_})=>{const{isMatch:y,score:b,indices:E}=pm(e,m,v,{location:i+_,distance:a,threshold:o,findAllMatches:l,minMatchCharLength:c,includeMatches:r,ignoreLocation:d});y&&(f=!0),h+=b,y&&E&&(u=[...u,...E])});let p={isMatch:f,score:f?h/this.chunks.length:1};return f&&r&&(p.indices=u),p}}class Ln{constructor(e){this.pattern=e}static isMultiMatch(e){return Fl(e,this.multiRegex)}static isSingleMatch(e){return Fl(e,this.singleRegex)}search(){}}function Fl(n,e){const t=n.match(e);return t?t[1]:null}class gm extends Ln{constructor(e){super(e)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(e){const t=e===this.pattern;return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}}class vm extends Ln{constructor(e){super(e)}static get type(){return"inverse-exact"}static get multiRegex(){return/^!"(.*)"$/}static get singleRegex(){return/^!(.*)$/}search(e){const s=e.indexOf(this.pattern)===-1;return{isMatch:s,score:s?0:1,indices:[0,e.length-1]}}}class _m extends Ln{constructor(e){super(e)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(e){const t=e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,this.pattern.length-1]}}}class ym extends Ln{constructor(e){super(e)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(e){const t=!e.startsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}}class wm extends Ln{constructor(e){super(e)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(e){const t=e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[e.length-this.pattern.length,e.length-1]}}}class bm extends Ln{constructor(e){super(e)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(e){const t=!e.endsWith(this.pattern);return{isMatch:t,score:t?0:1,indices:[0,e.length-1]}}}class Pu extends Ln{constructor(e,{location:t=Y.location,threshold:s=Y.threshold,distance:r=Y.distance,includeMatches:i=Y.includeMatches,findAllMatches:a=Y.findAllMatches,minMatchCharLength:o=Y.minMatchCharLength,isCaseSensitive:l=Y.isCaseSensitive,ignoreDiacritics:c=Y.ignoreDiacritics,ignoreLocation:d=Y.ignoreLocation}={}){super(e),this._bitapSearch=new Cu(e,{location:t,threshold:s,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:l,ignoreDiacritics:c,ignoreLocation:d})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(e){return this._bitapSearch.searchIn(e)}}class Tu extends Ln{constructor(e){super(e)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(e){let t=0,s;const r=[],i=this.pattern.length;for(;(s=e.indexOf(this.pattern,t))>-1;)t=s+i,r.push([s,t-1]);const a=!!r.length;return{isMatch:a,score:a?0:1,indices:r}}}const Ja=[gm,Tu,_m,ym,bm,wm,vm,Pu],Nl=Ja.length,xm=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,km="|";function Em(n,e={}){return n.split(km).map(t=>{let s=t.trim().split(xm).filter(i=>i&&!!i.trim()),r=[];for(let i=0,a=s.length;i<a;i+=1){const o=s[i];let l=!1,c=-1;for(;!l&&++c<Nl;){const d=Ja[c];let u=d.isMultiMatch(o);u&&(r.push(new d(u,e)),l=!0)}if(!l)for(c=-1;++c<Nl;){const d=Ja[c];let u=d.isSingleMatch(o);if(u){r.push(new d(u,e));break}}}return r})}const Sm=new Set([Pu.type,Tu.type]);class Am{constructor(e,{isCaseSensitive:t=Y.isCaseSensitive,ignoreDiacritics:s=Y.ignoreDiacritics,includeMatches:r=Y.includeMatches,minMatchCharLength:i=Y.minMatchCharLength,ignoreLocation:a=Y.ignoreLocation,findAllMatches:o=Y.findAllMatches,location:l=Y.location,threshold:c=Y.threshold,distance:d=Y.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:s,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:a,location:l,threshold:c,distance:d},e=t?e:e.toLowerCase(),e=s?Ei(e):e,this.pattern=e,this.query=Em(this.pattern,this.options)}static condition(e,t){return t.useExtendedSearch}searchIn(e){const t=this.query;if(!t)return{isMatch:!1,score:1};const{includeMatches:s,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?Ei(e):e;let a=0,o=[],l=0;for(let c=0,d=t.length;c<d;c+=1){const u=t[c];o.length=0,a=0;for(let h=0,f=u.length;h<f;h+=1){const p=u[h],{isMatch:m,indices:v,score:_}=p.search(e);if(m){if(a+=1,l+=_,s){const y=p.constructor.type;Sm.has(y)?o=[...o,...v]:o.push(v)}}else{l=0,a=0,o.length=0;break}}if(a){let h={isMatch:!0,score:l/a};return s&&(h.indices=o),h}}return{isMatch:!1,score:1}}}const Xa=[];function Cm(...n){Xa.push(...n)}function Ga(n,e){for(let t=0,s=Xa.length;t<s;t+=1){let r=Xa[t];if(r.condition(n,e))return new r(n,e)}return new Cu(n,e)}const Si={AND:"$and",OR:"$or"},Qa={PATH:"$path",PATTERN:"$val"},Za=n=>!!(n[Si.AND]||n[Si.OR]),Pm=n=>!!n[Qa.PATH],Tm=n=>!yn(n)&&ku(n)&&!Za(n),Ol=n=>({[Si.AND]:Object.keys(n).map(e=>({[e]:n[e]}))});function Iu(n,e,{auto:t=!0}={}){const s=r=>{let i=Object.keys(r);const a=Pm(r);if(!a&&i.length>1&&!Za(r))return s(Ol(r));if(Tm(r)){const l=a?r[Qa.PATH]:i[0],c=a?r[Qa.PATTERN]:r[l];if(!Jt(c))throw new Error(em(l));const d={keyId:Ka(l),pattern:c};return t&&(d.searcher=Ga(c,e)),d}let o={children:[],operator:i[0]};return i.forEach(l=>{const c=r[l];yn(c)&&c.forEach(d=>{o.children.push(s(d))})}),o};return Za(n)||(n=Ol(n)),s(n)}function Im(n,{ignoreFieldNorm:e=Y.ignoreFieldNorm}){n.forEach(t=>{let s=1;t.matches.forEach(({key:r,norm:i,score:a})=>{const o=r?r.weight:null;s*=Math.pow(a===0&&o?Number.EPSILON:a,(o||1)*(e?1:i))}),t.score=s})}function $m(n,e){const t=n.matches;e.matches=[],ut(t)&&t.forEach(s=>{if(!ut(s.indices)||!s.indices.length)return;const{indices:r,value:i}=s;let a={indices:r,value:i};s.key&&(a.key=s.key.src),s.idx>-1&&(a.refIndex=s.idx),e.matches.push(a)})}function Rm(n,e){e.score=n.score}function Mm(n,e,{includeMatches:t=Y.includeMatches,includeScore:s=Y.includeScore}={}){const r=[];return t&&r.push($m),s&&r.push(Rm),n.map(i=>{const{idx:a}=i,o={item:e[a],refIndex:a};return r.length&&r.forEach(l=>{l(i,o)}),o})}class ms{constructor(e,t={},s){this.options={...Y,...t},this.options.useExtendedSearch,this._keyStore=new rm(this.options.keys),this.setCollection(e,s)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof Po))throw new Error(Zp);this._myIndex=t||Au(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){ut(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=()=>!1){const t=[];for(let s=0,r=this._docs.length;s<r;s+=1){const i=this._docs[s];e(i,s)&&(this.removeAt(s),s-=1,r-=1,t.push(i))}return t}removeAt(e){this._docs.splice(e,1),this._myIndex.removeAt(e)}getIndex(){return this._myIndex}search(e,{limit:t=-1}={}){const{includeMatches:s,includeScore:r,shouldSort:i,sortFn:a,ignoreFieldNorm:o}=this.options;let l=Jt(e)?Jt(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e);return Im(l,{ignoreFieldNorm:o}),i&&l.sort(a),xu(t)&&t>-1&&(l=l.slice(0,t)),Mm(l,this._docs,{includeMatches:s,includeScore:r})}_searchStringList(e){const t=Ga(e,this.options),{records:s}=this._myIndex,r=[];return s.forEach(({v:i,i:a,n:o})=>{if(!ut(i))return;const{isMatch:l,score:c,indices:d}=t.searchIn(i);l&&r.push({item:i,idx:a,matches:[{score:c,value:i,norm:o,indices:d}]})}),r}_searchLogical(e){const t=Iu(e,this.options),s=(o,l,c)=>{if(!o.children){const{keyId:u,searcher:h}=o,f=this._findMatches({key:this._keyStore.get(u),value:this._myIndex.getValueForItemAtKeyId(l,u),searcher:h});return f&&f.length?[{idx:c,item:l,matches:f}]:[]}const d=[];for(let u=0,h=o.children.length;u<h;u+=1){const f=o.children[u],p=s(f,l,c);if(p.length)d.push(...p);else if(o.operator===Si.AND)return[]}return d},r=this._myIndex.records,i={},a=[];return r.forEach(({$:o,i:l})=>{if(ut(o)){let c=s(t,o,l);c.length&&(i[l]||(i[l]={idx:l,item:o,matches:[]},a.push(i[l])),c.forEach(({matches:d})=>{i[l].matches.push(...d)}))}}),a}_searchObjectList(e){const t=Ga(e,this.options),{keys:s,records:r}=this._myIndex,i=[];return r.forEach(({$:a,i:o})=>{if(!ut(a))return;let l=[];s.forEach((c,d)=>{l.push(...this._findMatches({key:c,value:a[d],searcher:t}))}),l.length&&i.push({idx:o,item:a,matches:l})}),i}_findMatches({key:e,value:t,searcher:s}){if(!ut(t))return[];let r=[];if(yn(t))t.forEach(({v:i,i:a,n:o})=>{if(!ut(i))return;const{isMatch:l,score:c,indices:d}=s.searchIn(i);l&&r.push({score:c,key:e,value:i,idx:a,norm:o,indices:d})});else{const{v:i,n:a}=t,{isMatch:o,score:l,indices:c}=s.searchIn(i);o&&r.push({score:l,key:e,value:i,norm:a,indices:c})}return r}}ms.version="7.1.0";ms.createIndex=Au;ms.parseIndex=fm;ms.config=Y;ms.parseQuery=Iu;Cm(Am);function To(n){const t=new RegExp(/\.([0-9a-z]+)(?:[?#]|$)/i).exec(n);if(!t)return"";const[,s]=t;return s}function Ji(n,e){const t=n.getFullYear(),s=n.getMonth(),r=n.getDate(),i=n.getDay(),a=n.getHours(),o=n.getMinutes(),l=n.getSeconds(),c=F=>F.toString().padStart(2,"0"),d=["January","February","March","April","May","June","July","August","September","October","November","December"],u=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],h=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],f=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],p=F=>{const x=["th","st","nd","rd"],A=F%100;return F+(x[(A-20)%10]||x[A]||x[0])},m=a%12||12,v=a>=12,_={YYYY:t.toString(),YY:t.toString().slice(-2),MMMM:d[s],MMM:u[s],MM:c(s+1),Mo:p(s+1),M:(s+1).toString(),dddd:h[i],ddd:f[i],Do:p(r),DD:c(r),D:r.toString(),HH:c(a),H:a.toString(),hh:c(m),h:m.toString(),mm:c(o),m:o.toString(),ss:c(l),s:l.toString(),A:v?"PM":"AM",a:v?"pm":"am"},y=Object.keys(_).sort((F,x)=>x.length-F.length).map(F=>F.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),b=new RegExp(`\\[([^\\]]*)]|(${y})|.`,"g");let E="",C;for(;(C=b.exec(e))!==null;)C[1]!==void 0?E+=C[1]:C[2]!==void 0?E+=_[C[2]]:E+=C[0];return E}function Dr(){const n={};function e(s,r){n[s]=r}function t(s){return s.replace(/\{\{(.*?)(:\s*?.+?)?\}\}/g,(r,i,a)=>{const o=n[i.toLowerCase()];if(o==null){const c=new ms(Object.keys(n),{shouldSort:!0,findAllMatches:!1,threshold:.4,isCaseSensitive:!1}).search(i);return new P.Notice(`Tag ${i} is invalid.${c.length>0?` Did you mean ${c[0].item}?`:""}`),r}if(typeof o=="function"){if(a){const l=a.slice(1).split(","),c=Array.isArray(l)?l:[a];return o(...c)}return o()}return o})}return[t,e]}function Fm(n,e){const[t,s]=Dr();return s("title",e.title),s("description",r=>{const i=P.htmlToMarkdown(e.description).replace(/\n{3,}/g,`
|
||
|
||
`);return r?i.split(`
|
||
`).map(a=>`${r}${a}`).join(`
|
||
`):i}),s("content",r=>r?P.htmlToMarkdown(e.content).split(`
|
||
`).map(i=>`${r}${i}`).join(`
|
||
`):P.htmlToMarkdown(e.content)),s("safetitle",On(e.title)),s("stream",e.streamUrl),s("url",e.url),s("date",r=>e.episodeDate?Ji(e.episodeDate,r??"YYYY-MM-DD"):""),s("podcast",On(e.podcastName)),s("artwork",e.artworkUrl??""),t(n)}function $u(n){const[e,t]=Dr(),{api:s,settings:r}=ee(Zt),i=r.timestamp.offset??0;return t("time",a=>s.getPodcastTimeFormatted(a??"HH:mm:ss",!1,i)),t("linktime",a=>s.getPodcastTimeFormatted(a??"HH:mm:ss",!0,i)),e(n)}function cs(n,e){const[t,s]=Dr();return s("title",r=>{const i=On(e.title);return r?i.replace(/\s+/g,r):i}),s("podcast",r=>{const i=On(e.podcastName);return r?i.replace(/\s+/g,r):i}),s("date",r=>e.episodeDate?Ji(e.episodeDate,r??"YYYY-MM-DD"):""),t(n)}function Io(n,e){const t=To(n),s=t?n.replace(t,""):n,[r,i]=Dr();return i("title",a=>{const o=On(e.title);return a?o.replace(/\s+/g,a):o}),i("podcast",a=>{const o=On(e.podcastName);return a?o.replace(/\s+/g,a):o}),i("date",a=>e.episodeDate?Ji(e.episodeDate,a??"YYYY-MM-DD"):""),r(s)}function Nm(n,e,t){const[s,r]=Dr();return r("title",i=>{const a=On(e.title);return i?a.replace(/\s+/g,i):a}),r("podcast",i=>{const a=On(e.podcastName);return i?a.replace(/\s+/g,i):a}),r("date",i=>e.episodeDate?Ji(e.episodeDate,i??"YYYY-MM-DD"):""),r("transcript",t),r("description",i=>i?P.htmlToMarkdown(e.description).split(`
|
||
`).map(a=>`${i}${a}`).join(`
|
||
`):P.htmlToMarkdown(e.description)),r("url",e.url),r("artwork",e.artworkUrl??""),s(n)}function On(n){return n.replace(/[\\,#%&{}/*<>$'":@\u2023|\\.?]/g,"").replace(/\n/," ").replace(" "," ")}function Om(n,e){let t=e;const s=Date.now();let r,i;const a=new P.Notice(e,0);function o(u){return`${n} (${c()}):
|
||
|
||
${u}`}function l(u){t=u,a.setMessage(o(t))}function c(){return Dm(r?r-s:Date.now()-s)}function d(){i!==void 0&&(clearInterval(i),i=void 0)}return i=setInterval(()=>{a.setMessage(o(t))},1e3),{update:l,hide:()=>{d(),a.hide()},stop:()=>{r=Date.now(),d()}}}function Dm(n){const e=Math.floor(n/1e3),t=Math.floor(e/60);return`${Math.floor(t/60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`}async function Lm(n){try{const t=new DOMParser().parseFromString(n,"application/xml");if(t.documentElement.nodeName==="parsererror")throw new Error("Invalid XML format");const s=t.querySelectorAll("outline[text][xmlUrl]"),r=[];for(let f=0;f<s.length;f++){const p=s.item(f),m=p.getAttribute("text"),v=p.getAttribute("xmlUrl");!m||!v||r.push({title:m,url:v})}if(r.length===0)throw new Error("No valid podcast entries found in OPML");const i=ee(mn),a=r.filter(f=>!Object.values(i).some(p=>p.url===f.url)),o=Om("Importing podcasts","Preparing to import...");let l=0;const c=()=>{const f=(l/a.length*100).toFixed(1);o.update(`Importing... ${l}/${a.length} podcasts completed (${f}%)`)};c();const d=await Promise.all(a.map(async f=>{try{const p=await new Ki().getFeed(f.url);return l++,c(),p}catch{return l++,c(),null}}));o.stop();const u=d.filter(f=>f!==null);mn.update(f=>{for(const p of u)f[p.title]||(f[p.title]=structuredClone(p));return f});const h=r.length-a.length;if(o.update(`OPML import complete. Saved ${u.length} new podcasts. Skipped ${h} existing podcasts.`),u.length!==a.length){const f=a.length-u.length;new P.Notice(`Failed to import ${f} podcasts. Check console for details.`,1e4)}setTimeout(()=>o.hide(),5e3)}catch(e){new P.Notice(`Error importing OPML: ${e instanceof Error?e.message:"Unknown error"}`,1e4)}}async function Bm(n,e,t="PodNotes_Export.opml"){const s='<?xml version="1.0" encoding="utf=8" standalone="no"?>',r=u=>`<opml version="1.0">${u}</opml>`,i=u=>`<head>${u}</head>`,a="<title>PodNotes Feeds</title>",o=u=>`<body>${u}</body>`,l=u=>`<outline text="${u.title}" type="rss" xmlUrl="${u.url}" />`,c=u=>`<outline text="feeds">${e.map(l).join("")}</outline>`,d=s+r(`${i(a)}
|
||
${o(c())}`);try{await n.vault.create(t,d),new P.Notice(`Exported ${e.length} podcast feeds to file "${t}".`)}catch(u){u instanceof Error?u.message.includes("Folder does not exist")?new P.Notice("Unable to create export file: Folder does not exist."):new P.Notice(`Unable to create podcast export file:
|
||
|
||
${u.message}`):new P.Notice("An unexpected error occurred during export.")}}const vr="podnotes:feed-cache:v1",Um=1e3*60*60*6,jm=75,Dl=4*1024*1024;let De=null;function $o(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function Ru(){if(De)return De;const n=$o();if(!n)return De={},De;try{const e=n.getItem(vr);return e?(De=JSON.parse(e),De):(De={},De)}catch{return De={},De}}function zm(n,e){const t=Object.entries(n);t.sort((i,a)=>i[1].updatedAt-a[1].updatedAt);const s={};let r=0;for(let i=t.length-1;i>=0;i--){const[a,o]=t[i],l=JSON.stringify({[a]:o}).length;r+l<=e&&(s[a]=o,r+=l)}return s}function Mu(){const n=$o();if(!(!n||!De))try{let e=JSON.stringify(De);e.length>Dl&&(De=zm(De,Dl*.8),e=JSON.stringify(De)),n.setItem(vr,e)}catch(e){if(e instanceof DOMException&&(e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"))try{De={},n.setItem(vr,"{}")}catch{n.removeItem(vr)}}}function qm(n){return{...n,episodeDate:n.episodeDate?.toISOString()}}function Wm(n){return{...n,episodeDate:n.episodeDate?new Date(n.episodeDate):void 0}}function Fu(n){return n.url??n.title}function Hm(n,e=Um){const t=Ru(),s=Fu(n),r=t[s];return r?Date.now()-r.updatedAt>e?(delete t[s],Mu(),null):r.episodes.map(Wm):null}function Vm(n,e){if(!e.length)return;const t=Ru(),s=Fu(n);t[s]={updatedAt:Date.now(),episodes:e.slice(0,jm).map(qm)},Mu()}function Ym(){De={};const n=$o();try{n?.removeItem(vr)}catch{}}class Km extends P.PluginSettingTab{constructor(e,t){super(e,t),this.podcastQueryGrid=null,this.playlistManager=null,this.plugin=t,this.settingsTab=this}display(){const{containerEl:e}=this;e.empty();const t=e.createEl("h2",{text:"PodNotes"});t.style.textAlign="center";const s=e.createDiv();s.classList.add("settings-container"),new P.Setting(s).setName("Search Podcasts").setHeading().setDesc("Search for podcasts by name or custom feed URL.");const r=s.createDiv();this.podcastQueryGrid=za(Op,{target:r}),new P.Setting(s).setName("Playlists").setHeading().setDesc("Add playlists to gather podcast episodes.");const i=s.createDiv();this.playlistManager=za(Kp,{target:i}),this.addDefaultPlaybackRateSetting(s),this.addDefaultVolumeSetting(s),this.addSkipLengthSettings(s),this.addNoteSettings(s),this.addDownloadSettings(s),this.addPerformanceSettings(s),this.addImportExportSettings(s),this.addTranscriptSettings(s)}hide(){this.podcastQueryGrid&&(Wa(this.podcastQueryGrid),this.podcastQueryGrid=null),this.playlistManager&&(Wa(this.playlistManager),this.playlistManager=null)}addDefaultPlaybackRateSetting(e){new P.Setting(e).setName("Default Playback Rate").addSlider(t=>t.setLimits(.5,4,.1).setValue(this.plugin.settings.defaultPlaybackRate).onChange(s=>{this.plugin.settings.defaultPlaybackRate=s,this.plugin.saveSettings()}).setDynamicTooltip())}addDefaultVolumeSetting(e){new P.Setting(e).setName("Default Volume").setDesc("Set the default playback volume.").addSlider(t=>t.setLimits(0,1,.05).setValue(this.plugin.settings.defaultVolume).onChange(s=>{this.plugin.settings.defaultVolume=s,this.plugin.saveSettings()}).setDynamicTooltip())}addSkipLengthSettings(e){new P.Setting(e).setName("Skip backward length (s)").addText(t=>{t.inputEl.type="number",t.setValue(`${this.plugin.settings.skipBackwardLength}`).onChange(s=>{this.plugin.settings.skipBackwardLength=Number.parseInt(s),this.plugin.saveSettings()}).setPlaceholder("seconds")}),new P.Setting(e).setName("Skip forward length (s)").addText(t=>{t.inputEl.type="number",t.setValue(`${this.plugin.settings.skipForwardLength}`).onChange(s=>{this.plugin.settings.skipForwardLength=Number.parseInt(s),this.plugin.saveSettings()}).setPlaceholder("seconds")})}addNoteSettings(e){const t=e.createDiv();t.createEl("h4",{text:"Note settings"});const s=new P.Setting(t).setName("Capture timestamp format").setHeading().addTextArea(d=>{d.setValue(this.plugin.settings.timestamp.template),d.setPlaceholder("- {{linktime}} "),d.onChange(u=>{this.plugin.settings.timestamp.template=u,this.plugin.saveSettings(),i(u)}),d.inputEl.style.width="100%"});s.settingEl.style.flexDirection="column",s.settingEl.style.alignItems="unset",s.settingEl.style.gap="10px";const r=t.createDiv(),i=d=>{if(!this.plugin.api.podcast)return;const u=$u(d);r.empty(),P.MarkdownRenderer.renderMarkdown(u,r,"",new P.Component)};new P.Setting(t).setName("Timestamp offset (s)").setDesc("Subtract this many seconds when capturing a timestamp to compensate for reaction time.").addText(d=>{d.inputEl.type="number",d.setValue(`${this.plugin.settings.timestamp.offset}`).onChange(u=>{const h=Number.parseInt(u,10);this.plugin.settings.timestamp.offset=Number.isNaN(h)?0:Math.max(0,h),this.plugin.saveSettings(),i(this.plugin.settings.timestamp.template)}).setPlaceholder("e.g. 5")}),i(this.plugin.settings.timestamp.template);const a=ya(),o=new P.Setting(t).setName("Note creation file path").setHeading().addText(d=>{d.setValue(this.plugin.settings.note.path),d.setPlaceholder("inputs/podcasts/{{podcast}} - {{title}}.md"),d.onChange(u=>{this.plugin.settings.note.path=u,this.plugin.saveSettings();const h=cs(u,a);l.empty(),P.MarkdownRenderer.renderMarkdown(h,l,"",new P.Component)}),d.inputEl.style.width="100%"});o.settingEl.style.flexDirection="column",o.settingEl.style.alignItems="unset",o.settingEl.style.gap="10px";const l=t.createDiv(),c=new P.Setting(t).setName("Note creation template").setHeading().addTextArea(d=>{d.setValue(this.plugin.settings.note.template),d.onChange(u=>{this.plugin.settings.note.template=u,this.plugin.saveSettings()}),d.inputEl.style.width="100%",d.inputEl.style.height="25vh",d.setPlaceholder(`## {{title}}
|
||

|
||
### Metadata
|
||
Podcast:: {{podcast}}
|
||
Episode:: {{title}}
|
||
PublishDate:: {{date:YYYY-MM-DD}}
|
||
### Description
|
||
> {{description}}`)});c.settingEl.style.flexDirection="column",c.settingEl.style.alignItems="unset",c.settingEl.style.gap="10px"}addDownloadSettings(e){e.createEl("h4",{text:"Download settings"});const t=ya(),s=new P.Setting(e).setName("Episode download path").setDesc("The path where the episode will be downloaded to. Avoid setting an extension, as it will be added automatically.").setHeading().addText(i=>{i.setValue(this.plugin.settings.download.path),i.setPlaceholder("inputs/podcasts/{{podcast}} - {{title}}"),i.onChange(a=>{this.plugin.settings.download.path=a,this.plugin.saveSettings();const o=Io(a,t);r.empty(),P.MarkdownRenderer.renderMarkdown(`${o}.mp3`,r,"",new P.Component)}),i.inputEl.style.width="100%"});s.settingEl.style.flexDirection="column",s.settingEl.style.alignItems="unset",s.settingEl.style.gap="10px";const r=e.createDiv()}addPerformanceSettings(e){e.createEl("h4",{text:"Performance"}),new P.Setting(e).setName("Cache podcast feeds").setDesc("Store recently downloaded feeds locally for faster startup.").addToggle(t=>t.setValue(this.plugin.settings.feedCache.enabled).onChange(async s=>{this.plugin.settings.feedCache.enabled=s,await this.plugin.saveSettings()})),new P.Setting(e).setName("Cache duration (hours)").setDesc("Choose how long to reuse cached feeds before fetching again.").addSlider(t=>t.setLimits(1,24,1).setValue(this.plugin.settings.feedCache.ttlHours).setDynamicTooltip().onChange(async s=>{this.plugin.settings.feedCache.ttlHours=s,await this.plugin.saveSettings()})),new P.Setting(e).setName("Clear cached feeds").setDesc("Remove stored feed data. PodNotes will refetch feeds as needed.").addButton(t=>t.setButtonText("Clear cache").onClick(()=>{Ym(),Xn.set({}),new P.Notice("Cleared cached podcast feeds.")}))}addImportExportSettings(e){e.createEl("h3",{text:"Import/Export"}),new P.Setting(e).setName("Import OPML").setDesc("Import podcasts from an OPML file.").addButton(s=>s.setButtonText("Import").onClick(()=>{const r=document.createElement("input");r.type="file",r.accept=".opml",r.style.display="none",document.body.appendChild(r),r.click(),r.onchange=async i=>{const o=i.target.files?.[0];if(o){const l=new FileReader;l.onload=async c=>{const d=c.target?.result;if(d)try{await Lm(d)}catch(u){new P.Notice(`Error importing OPML: ${u instanceof Error?u.message:"Unknown error"}`,1e4)}},l.readAsText(o)}else new P.Notice("No file selected")}}));let t="PodNotes_Export.opml";new P.Setting(e).setName("Export OPML").setDesc("Export saved podcast feeds to an OPML file.").addText(s=>s.setPlaceholder("Export file name").setValue(t).onChange(r=>{t=r})).addButton(s=>s.setButtonText("Export").onClick(()=>{const r=Object.values(ee(mn));if(r.length===0){new P.Notice("No podcasts to export.");return}Bm(this.app,r,t.endsWith(".opml")?t:`${t}.opml`)}))}addTranscriptSettings(e){e.createEl("h4",{text:"Transcript settings"});const t=ya();new P.Setting(e).setName("OpenAI API Key").setDesc("Enter your OpenAI API key for transcription functionality.").addText(a=>{a.setPlaceholder("Enter your OpenAI API key").setValue(this.plugin.settings.openAIApiKey).onChange(async o=>{this.plugin.settings.openAIApiKey=o,await this.plugin.saveSettings()}),a.inputEl.type="password"}),new P.Setting(e).setName("Transcript file path").setDesc("The path where transcripts will be saved. Use {{}} for dynamic values.").addText(a=>{a.setPlaceholder("transcripts/{{podcast}}/{{title}}.md").setValue(this.plugin.settings.transcript.path).onChange(async o=>{this.plugin.settings.transcript.path=o,await this.plugin.saveSettings(),r(o)})});const s=e.createDiv(),r=a=>{const o=cs(a,t);s.empty(),s.createEl("p",{text:`Example: ${o}`})};r(this.plugin.settings.transcript.path);const i=new P.Setting(e).setName("Transcript template").setDesc("The template for the transcript file content.").setHeading().addTextArea(a=>{a.setPlaceholder(`# {{title}}
|
||
|
||
Podcast: {{podcast}}
|
||
Date: {{date}}
|
||
URL: {{url}}
|
||
|
||
## Description
|
||
|
||
{{description}}
|
||
|
||
## Transcript
|
||
|
||
{{transcript}}`).setValue(this.plugin.settings.transcript.template).onChange(async o=>{this.plugin.settings.transcript.template=o,await this.plugin.saveSettings()}),a.inputEl.style.width="100%",a.inputEl.style.height="25vh"});i.settingEl.style.flexDirection="column",i.settingEl.style.alignItems="unset",i.settingEl.style.gap="10px"}}function ya(){const n={description:"demo",content:"demo",podcastName:"demo",title:"demo",url:"demo",artworkUrl:"demo",streamUrl:"demo",episodeDate:new Date,feedUrl:"demo"},e=Object.values(ee(Xn));if(!e.length)return n;const t=e[Math.floor(Math.random()*e.length)];return t.length?t[Math.floor(Math.random()*t.length)]:n}var Jm=J('<button type="button" class="playlist-card svelte-5dhk44"><!> <span class="svelte-5dhk44"> </span></button>');const Xm={hash:"svelte-5dhk44",code:".playlist-card.svelte-5dhk44 {display:flex;flex-direction:column;align-items:center;justify-content:center;gap:0.25rem;width:100%;min-height:5rem;padding:0.75rem 0.5rem;border:1px solid var(--background-modifier-border);border-radius:0.5rem;text-align:center;background:var(--background-secondary);cursor:pointer;transition:transform 150ms ease, box-shadow 150ms ease, border-color 150ms ease, background-color 150ms ease;}.playlist-card.svelte-5dhk44:hover {transform:scale(1.02);border-color:var(--interactive-accent);background-color:var(--background-secondary-alt);box-shadow:0 4px 12px rgba(0, 0, 0, 0.15);}.playlist-card.svelte-5dhk44:active {transform:scale(0.98);}.playlist-card.svelte-5dhk44 span:where(.svelte-5dhk44) {font-size:0.8rem;color:var(--text-muted);}"};function Gm(n,e){ge(e,!1),Pe(n,Xm);let t=M(e,"playlist",8);const s=Ye();function r(c){s("clickPlaylist",{playlist:t(),event:c})}_e();var i=Jm(),a=R(i);Ge(a,{get icon(){return O(t()),z(()=>t().icon)},size:40,clickable:!1});var o=H(a,2),l=R(o);me(()=>{ue(i,"aria-label",(O(t()),z(()=>t().name))),je(l,`(${O(t()),z(()=>t().episodes.length)??""})`)}),le("click",i,r),L(n,i),ve()}var Qm=J('<button type="button" class="pn_image_container svelte-ds4mor"><img draggable="false"/></button>'),Zm=J('<div class="pn_image_container pn_image_container--static svelte-ds4mor"><img draggable="false"/></div>');const eg={hash:"svelte-ds4mor",code:".pn_image_container.svelte-ds4mor {width:100%;height:100%;display:block;position:relative;overflow:hidden;border:none;padding:0;background:var(--background-secondary);}.pn_image_container--static.svelte-ds4mor {cursor:default;}.pn_image_container.svelte-ds4mor:not(.pn_image_container--static) {cursor:pointer;}.pn_image_container.svelte-ds4mor img:where(.svelte-ds4mor) {display:block;width:100%;height:100%;object-fit:cover;}"};function Ro(n,e){ge(e,!1),Pe(n,eg);let t=M(e,"src",8),s=M(e,"alt",8),r=M(e,"fadeIn",8,!1),i=M(e,"opacity",8,0),a=M(e,"interactive",8,!1),o=M(e,"loading",8,"lazy"),l=M(e,"class",8,""),c=q(!1),d=q(!0),u=q(!1);const h=Ye();function f(y){h("click",{event:y})}_e();var p=nt(),m=Be(p);{var v=y=>{var b=nt(),E=Be(b);{var C=x=>{var A=Qm(),I=R(A);let $;me(()=>{ue(I,"src",t()),ue(I,"alt",s()),ue(I,"loading",o()),Qt(I,1,kl(l()),"svelte-ds4mor"),$=Er(I,"",$,{opacity:i()?i():r()?g(c)?1:0:1,transition:r()?"opacity 0.5s ease-out":""})}),le("load",I,()=>{T(c,!0),T(d,!1)}),le("error",I,()=>{T(u,!0),T(d,!1)}),le("click",A,f),L(x,A)},F=x=>{var A=Zm(),I=R(A);let $;me(()=>{ue(I,"src",t()),ue(I,"alt",s()),ue(I,"loading",o()),Qt(I,1,kl(l()),"svelte-ds4mor"),$=Er(I,"",$,{opacity:i()?i():r()?g(c)?1:0:1,transition:r()?"opacity 0.5s ease-out":""})}),le("load",I,()=>{T(c,!0),T(d,!1)}),le("error",I,()=>{T(u,!0),T(d,!1)}),L(x,A)};de(E,x=>{a()?x(C):x(F,!1)})}L(y,b)},_=y=>{var b=nt(),E=Be(b);{var C=F=>{var x=nt(),A=Be(x);ru(A,e,"fallback",{},null),L(F,x)};de(E,F=>{g(u)&&F(C)},!0)}L(y,b)};de(m,y=>{g(d)||g(c)?y(v):y(_,!1)})}L(n,p),ve()}const tg={hash:"svelte-o3c98i",code:".podcast-image {width:100%;height:100%;aspect-ratio:1;cursor:pointer !important;object-fit:cover;background-size:cover;background-position:center;background-repeat:no-repeat;border:1px solid var(--background-modifier-border);border-radius:0.5rem;transition:transform 150ms ease, box-shadow 150ms ease, border-color 150ms ease;}.podcast-image:hover {transform:scale(1.02);border-color:var(--interactive-accent);box-shadow:0 4px 12px rgba(0, 0, 0, 0.15);}.podcast-image:active {transform:scale(0.98);}"};function ng(n,e){ge(e,!1),Pe(n,tg);let t=M(e,"feed",8);const s=Ye();function r(a){s("clickPodcast",{feed:a})}_e();var i=Fs(()=>r.bind(null,t()));Ro(n,{get src(){return O(t()),z(()=>t().artworkUrl)},get alt(){return O(t()),z(()=>t().title)},interactive:!0,class:"podcast-image",$$events:{click(...a){g(i)?.apply(this,a)}}}),ve()}var sg=J("<div><p>No saved podcasts.</p></div>"),rg=J('<div class="podcast-grid svelte-1x0bcng"><!> <!></div>');const ig={hash:"svelte-1x0bcng",code:`.podcast-grid.svelte-1x0bcng {display:grid;grid-template-columns:repeat(auto-fill, minmax(6rem, 1fr));grid-auto-rows:min-content;gap:0.5rem;padding:0.5rem;flex:1;min-height:0;overflow-y:auto;}
|
||
|
||
@media (min-width: 400px) {.podcast-grid.svelte-1x0bcng {grid-template-columns:repeat(auto-fill, minmax(7rem, 1fr));gap:0.75rem;padding:0.75rem;}
|
||
}
|
||
|
||
@media (min-width: 600px) {.podcast-grid.svelte-1x0bcng {grid-template-columns:repeat(auto-fill, minmax(8rem, 1fr));}
|
||
}`};function ag(n,e){ge(e,!1),Pe(n,ig);let t=M(e,"feeds",24,()=>[]),s=M(e,"playlists",24,()=>[]);const r=Ye();function i({detail:{playlist:h,event:f}}){r("clickPlaylist",{playlist:h,event:f})}_e();var a=rg(),o=R(a);{var l=h=>{var f=nt(),p=Be(f);zs(p,1,s,m=>m.name,(m,v)=>{Gm(m,{get playlist(){return g(v)},$$events:{clickPlaylist:i}})}),L(h,f)};de(o,h=>{O(s()),z(()=>s().length>0)&&h(l)})}var c=H(o,2);{var d=h=>{var f=nt(),p=Be(f);zs(p,1,t,m=>m.url,(m,v)=>{ng(m,{get feed(){return g(v)},$$events:{clickPodcast(_){lu.call(this,e,_)}}})}),L(h,f)},u=h=>{var f=sg();L(h,f)};de(c,h=>{O(t()),z(()=>t().length>0)?h(d):h(u,!1)})}L(n,a),ve()}async function og(n){if(!n)return[];try{const e=await Ao(n,{timeoutMs:1e4}),t=JSON.parse(e.text);return!t.chapters||!Array.isArray(t.chapters)?[]:t.chapters.filter(s=>s.toc!==!1).sort((s,r)=>s.startTime-r.startTime)}catch{return[]}}var lg=J("<span></span>");function Ll(n,e){ge(e,!1);let t=M(e,"value",8),s=M(e,"limits",8),r=q();const i=Ye();let a=q(),o=M(e,"style",24,()=>({})),l=null,c=!1;rn(()=>{T(a,new P.SliderComponent(g(r))),l=h=>{if(c)return;const f=Number(h.target.value);i("change",{value:f})},g(a).sliderEl.addEventListener("input",l)}),Yi(()=>{g(a)?.sliderEl&&l&&g(a).sliderEl.removeEventListener("input",l)});function d(h,f,p,m){const v=typeof h.getValue=="function"?h.getValue():Number(h.sliderEl?.value);f!==void 0&&v!==f&&(c=!0,h.setValue(f),c=!1),p&&(p.length===2?h.setLimits(p[0],p[1],1):h.setLimits(p[0],p[1],p[2])),m&&h.sliderEl.setAttr("style",Qs(m))}He(()=>(g(a),O(t()),O(s()),O(o())),()=>{g(a)&&d(g(a),t(),s(),o())}),sn(),_e();var u=lg();Nn(u,h=>T(r,h),()=>g(r)),L(n,u),ve()}var cg=J('<div class="la-line-scale svelte-k6ycv0"><div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div></div>');const ug={hash:"svelte-k6ycv0",code:`
|
||
/*!
|
||
* Load Awesome v1.1.0 (http://github.danielcardoso.net/load-awesome/)
|
||
* Copyright 2015 Daniel Cardoso <@DanielCardoso>
|
||
* Licensed under MIT
|
||
*/.la-line-scale.svelte-k6ycv0,
|
||
.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0) {position:relative;-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;}.la-line-scale.svelte-k6ycv0 {display:block;font-size:0;color:#fff;}
|
||
/* .la-line-scale.la-dark {
|
||
color: #333;
|
||
} */.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0) {display:inline-block;float:none;background-color:currentColor;border:0 solid currentColor;}.la-line-scale.svelte-k6ycv0 {width:40px;height:32px;}.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0) {width:4px;height:32px;margin:2px;margin-top:0;margin-bottom:0;border-radius:0;
|
||
-webkit-animation: svelte-k6ycv0-line-scale 1.2s infinite ease;
|
||
-moz-animation: svelte-k6ycv0-line-scale 1.2s infinite ease;
|
||
-o-animation: svelte-k6ycv0-line-scale 1.2s infinite ease;
|
||
animation: svelte-k6ycv0-line-scale 1.2s infinite ease;}.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0):nth-child(1) {-webkit-animation-delay:-1.2s;-moz-animation-delay:-1.2s;-o-animation-delay:-1.2s;animation-delay:-1.2s;}.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0):nth-child(2) {-webkit-animation-delay:-1.1s;-moz-animation-delay:-1.1s;-o-animation-delay:-1.1s;animation-delay:-1.1s;}.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0):nth-child(3) {-webkit-animation-delay:-1s;-moz-animation-delay:-1s;-o-animation-delay:-1s;animation-delay:-1s;}.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0):nth-child(4) {-webkit-animation-delay:-.9s;-moz-animation-delay:-.9s;-o-animation-delay:-.9s;animation-delay:-.9s;}.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0):nth-child(5) {-webkit-animation-delay:-.8s;-moz-animation-delay:-.8s;-o-animation-delay:-.8s;animation-delay:-.8s;}
|
||
/* .la-line-scale.la-sm {
|
||
width: 20px;
|
||
height: 16px;
|
||
}
|
||
.la-line-scale.la-sm > div {
|
||
width: 2px;
|
||
height: 16px;
|
||
margin: 1px;
|
||
margin-top: 0;
|
||
margin-bottom: 0;
|
||
}
|
||
.la-line-scale.la-2x {
|
||
width: 80px;
|
||
height: 64px;
|
||
}
|
||
.la-line-scale.la-2x > div {
|
||
width: 8px;
|
||
height: 64px;
|
||
margin: 4px;
|
||
margin-top: 0;
|
||
margin-bottom: 0;
|
||
}
|
||
.la-line-scale.la-3x {
|
||
width: 120px;
|
||
height: 96px;
|
||
}
|
||
.la-line-scale.la-3x > div {
|
||
width: 12px;
|
||
height: 96px;
|
||
margin: 6px;
|
||
margin-top: 0;
|
||
margin-bottom: 0;
|
||
}*/
|
||
/*
|
||
* Animation
|
||
*/
|
||
@-webkit-keyframes svelte-k6ycv0-line-scale {
|
||
0%,
|
||
40%,
|
||
100% {
|
||
-webkit-transform: scaleY(.4);
|
||
transform: scaleY(.4);
|
||
}
|
||
20% {
|
||
-webkit-transform: scaleY(1);
|
||
transform: scaleY(1);
|
||
}
|
||
}
|
||
@-moz-keyframes svelte-k6ycv0-line-scale {
|
||
0%,
|
||
40%,
|
||
100% {
|
||
-webkit-transform: scaleY(.4);
|
||
-moz-transform: scaleY(.4);
|
||
transform: scaleY(.4);
|
||
}
|
||
20% {
|
||
-webkit-transform: scaleY(1);
|
||
-moz-transform: scaleY(1);
|
||
transform: scaleY(1);
|
||
}
|
||
}
|
||
@-o-keyframes svelte-k6ycv0-line-scale {
|
||
0%,
|
||
40%,
|
||
100% {
|
||
-webkit-transform: scaleY(.4);
|
||
-o-transform: scaleY(.4);
|
||
transform: scaleY(.4);
|
||
}
|
||
20% {
|
||
-webkit-transform: scaleY(1);
|
||
-o-transform: scaleY(1);
|
||
transform: scaleY(1);
|
||
}
|
||
}
|
||
@keyframes svelte-k6ycv0-line-scale {
|
||
0%,
|
||
40%,
|
||
100% {
|
||
-webkit-transform: scaleY(.4);
|
||
-moz-transform: scaleY(.4);
|
||
-o-transform: scaleY(.4);
|
||
transform: scaleY(.4);
|
||
}
|
||
20% {
|
||
-webkit-transform: scaleY(1);
|
||
-moz-transform: scaleY(1);
|
||
-o-transform: scaleY(1);
|
||
transform: scaleY(1);
|
||
}
|
||
}`};function Nu(n){Pe(n,ug);var e=cg();L(n,e)}var dg=J('<div class="image-loader svelte-jp8vu"><!></div>');const fg={hash:"svelte-jp8vu",code:".image-loader.svelte-jp8vu {position:relative;width:100%;}"};function hg(n,e){ge(e,!1),Pe(n,fg);const t=q(),s=q(),r=q();let i=M(e,"src",8),a=M(e,"alt",8),o=M(e,"fadeIn",8,!1),l=M(e,"interactive",8,!1),c=M(e,"width",8),d=M(e,"height",8),u=M(e,"aspectRatio",8,"1 / 1"),h=M(e,"loading",8,"lazy"),f=M(e,"class",8,"");const p=Ye(),m=b=>typeof b=="number"?`${b}px`:b;He(()=>O(c()),()=>{T(t,m(c()))}),He(()=>O(d()),()=>{T(s,m(d()))}),He(()=>(g(s),O(u())),()=>{T(r,g(s)?void 0:u())}),sn(),_e();var v=dg();let _;var y=R(v);Ro(y,{get alt(){return a()},get src(){return i()},get fadeIn(){return o()},get interactive(){return l()},get loading(){return h()},get class(){return f()},$$events:{click:b=>p("click",{event:b})}}),me(()=>_=Er(v,"",_,{width:g(t),height:g(s),"aspect-ratio":g(r)})),L(n,v),ve()}var pg=J('<div class="podcast-episode-thumbnail-container svelte-dmhmse"><!></div>'),mg=J('<div class="podcast-episode-thumbnail-container svelte-dmhmse"></div>'),gg=J('<button type="button" class="podcast-episode-item svelte-dmhmse"><!> <div class="podcast-episode-information svelte-dmhmse"><span class="episode-item-date svelte-dmhmse"> </span> <span> </span></div></button>');const vg={hash:"svelte-dmhmse",code:`.podcast-episode-item.svelte-dmhmse {display:flex;flex-direction:row;justify-content:flex-start;align-items:center;padding:0.625rem 0.75rem;min-height:4.5rem;width:100%;border:none;border-bottom:1px solid var(--background-modifier-border);gap:0.75rem;background:transparent;text-align:left;cursor:pointer;transition:background-color 120ms ease;}.podcast-episode-item.svelte-dmhmse:last-child {border-bottom:none;}.podcast-episode-item.svelte-dmhmse:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:-2px;border-radius:0.25rem;}.podcast-episode-item.svelte-dmhmse:hover {background-color:var(--background-secondary-alt);}.podcast-episode-item.svelte-dmhmse:active {background-color:var(--background-modifier-border);}.strikeout.svelte-dmhmse {text-decoration:line-through;opacity:0.6;}.podcast-episode-information.svelte-dmhmse {display:flex;flex-direction:column;justify-content:center;align-items:flex-start;gap:0.25rem;flex:1 1 auto;min-width:0;}.episode-item-date.svelte-dmhmse {font-size:0.75rem;font-weight:500;letter-spacing:0.025em;color:var(--text-muted);}.episode-item-title.svelte-dmhmse {font-size:0.9rem;line-height:1.4;color:var(--text-normal);overflow:hidden;text-overflow:ellipsis;display:-webkit-box;-webkit-line-clamp:2;line-clamp:2;-webkit-box-orient:vertical;}.podcast-episode-thumbnail-container.svelte-dmhmse {flex:0 0 3.5rem;width:3.5rem;height:3.5rem;display:flex;align-items:center;justify-content:center;background:var(--background-secondary);border-radius:0.375rem;overflow:hidden;}
|
||
|
||
@media (min-width: 400px) {.podcast-episode-thumbnail-container.svelte-dmhmse {flex:0 0 4rem;width:4rem;height:4rem;}
|
||
}.podcast-episode-thumbnail {width:100%;height:100%;object-fit:cover;border-radius:0.375rem;}`};function _g(n,e){ge(e,!1),Pe(n,vg);let t=M(e,"episode",8),s=M(e,"episodeFinished",8,!1),r=M(e,"showEpisodeImage",8,!1);const i=Ye(),a=new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"long",year:"numeric"}),o=new Map;function l(){i("clickEpisode",{episode:t()})}function c(x){i("contextMenu",{episode:t(),event:x})}function d(x){if(!x)return null;const A=new Date(x);return Number.isNaN(A.getTime())?null:A}function u(x,A){return`${x.url??x.streamUrl??x.title??"episode"}|${A.getTime()}`}function h(x){const A=d(x?.episodeDate);if(!A)return"";const I=u(x,A),$=o.get(I);if($)return $;const D=a.format(A).toUpperCase();return o.set(I,D),D}let f=q("");He(()=>O(t()),()=>{T(f,h(t()))}),sn(),_e();var p=gg(),m=R(p);{var v=x=>{var A=pg(),I=R(A);hg(I,{get src(){return O(t()),z(()=>t().artworkUrl)},get alt(){return O(t()),z(()=>t().title)},fadeIn:!0,width:"100%",height:"100%",class:"podcast-episode-thumbnail"}),L(x,A)},_=x=>{var A=nt(),I=Be(A);{var $=D=>{var G=mg();L(D,G)};de(I,D=>{r()&&D($)},!0)}L(x,A)};de(m,x=>{O(r()),O(t()),z(()=>r()&&t()?.artworkUrl)?x(v):x(_,!1)})}var y=H(m,2),b=R(y),E=R(b),C=H(b,2),F=R(C);me(()=>{je(E,g(f)),Qt(C,1,`episode-item-title ${s()&&"strikeout"}`,"svelte-dmhmse"),je(F,(O(t()),z(()=>t().title)))}),le("click",p,l),le("contextmenu",p,c),L(n,p),ve()}var yg=J('<div class="episode-list-menu svelte-ozfrsd"><div class="episode-list-search svelte-ozfrsd"><!></div> <!> <!></div>'),wg=J('<div class="episode-list-loading svelte-ozfrsd" role="status" aria-live="polite"><!> <span>Fetching episodes...</span></div>'),bg=J('<p class="svelte-ozfrsd">No episodes found.</p>'),xg=J('<div class="episode-list-view-container svelte-ozfrsd"><!> <!> <div class="podcast-episode-list svelte-ozfrsd"><!> <!> <!></div></div>');const kg={hash:"svelte-ozfrsd",code:".episode-list-view-container.svelte-ozfrsd {display:flex;flex-direction:column;align-items:stretch;justify-content:flex-start;width:100%;height:100%;overflow:hidden;}.podcast-episode-list.svelte-ozfrsd {display:flex;flex-direction:column;align-items:stretch;justify-content:flex-start;width:100%;flex:1 1 auto;overflow-y:auto;overflow-x:hidden;}.podcast-episode-list.svelte-ozfrsd p:where(.svelte-ozfrsd) {padding:1.5rem;text-align:center;color:var(--text-muted);}.episode-list-menu.svelte-ozfrsd {display:flex;flex-direction:row;justify-content:flex-end;align-items:center;gap:0.5rem;width:100%;padding:0.5rem 0.75rem;border-bottom:1px solid var(--background-modifier-border);background:var(--background-secondary);}.episode-list-search.svelte-ozfrsd {flex:1 1 auto;min-width:0;}.episode-list-loading.svelte-ozfrsd {display:flex;align-items:center;justify-content:center;gap:0.75rem;padding:2rem 1rem;color:var(--text-muted);font-size:0.9rem;}"};function Ou(n,e){ge(e,!1),Pe(n,kg);const t=()=>Ue(xi,"$hidePlayedEpisodes",r),s=()=>Ue(kt,"$playedEpisodes",r),[r,i]=Or();let a=M(e,"episodes",24,()=>[]),o=M(e,"showThumbnails",8,!1),l=M(e,"showListMenu",8,!0),c=M(e,"isLoading",8,!1),d=q("");function u($,D){if(!$)return!1;const G=Jn($);return G&&D[G]?.finished||D[$.title]?.finished||!1}const h=Ye();function f($){h("clickEpisode",{episode:$.detail.episode})}function p($){h("contextMenuEpisode",{episode:$.detail.episode,event:$.detail.event})}function m($){h("search",{query:$.detail.value})}_e();var v=xg(),_=R(v);ru(_,e,"header",{},$=>{var D=jh("Fallback");L($,D)});var y=H(_,2);{var b=$=>{var D=yg(),G=R(D),ye=R(G);Co(ye,{placeholder:"Search episodes",style:{width:"100%"},get value(){return g(d)},set value(we){T(d,we)},$$events:{input:m},$$legacy:!0});var ce=H(G,2);{let we=qe(()=>t()?"eye-off":"eye"),gs=qe(()=>t()?"Show played episodes":"Hide played episodes");Ge(ce,{get icon(){return g(we)},size:25,get label(){return g(gs)},get pressed(){return t()},$$events:{click:()=>xi.update(K=>!K)}})}var Ee=H(ce,2);Ge(Ee,{icon:"refresh-cw",size:25,label:"Refresh episodes",$$events:{click:()=>h("clickRefresh")}}),L($,D)};de(y,$=>{l()&&$(b)})}var E=H(y,2),C=R(E);{var F=$=>{var D=wg(),G=R(D);Nu(G),L($,D)};de(C,$=>{c()&&$(F)})}var x=H(C,2);{var A=$=>{var D=bg();L($,D)};de(x,$=>{O(a()),O(c()),z(()=>a().length===0&&!c())&&$(A)})}var I=H(x,2);zs(I,3,a,($,D)=>Jn($)??`${$.title}-${$.episodeDate??""}-${D}`,($,D)=>{const G=qe(()=>(g(D),s(),z(()=>u(g(D),s()))));var ye=nt(),ce=Be(ye);{var Ee=we=>{_g(we,{get episode(){return g(D)},get episodeFinished(){return g(G)},get showEpisodeImage(){return o()},$$events:{clickEpisode:f,contextMenu:p}})};de(ce,we=>{(!t()||!g(G))&&we(Ee)})}L($,ye)}),L(n,v),ve(),i()}var Eg=J('<li><button type="button" class="chapter-item svelte-1vxfdxx"><span class="chapter-time svelte-1vxfdxx"> </span> <span class="chapter-title svelte-1vxfdxx"> </span></button></li>'),Sg=J('<ul class="chapters svelte-1vxfdxx"></ul>'),Ag=J('<div class="chapter-list svelte-1vxfdxx"><button type="button" class="chapter-header svelte-1vxfdxx"><!> <h3 class="svelte-1vxfdxx"> </h3></button> <!></div>');const Cg={hash:"svelte-1vxfdxx",code:".chapter-list.svelte-1vxfdxx {margin:1rem 0;}.chapter-header.svelte-1vxfdxx {display:flex;align-items:center;gap:0.25rem;background:none;border:none;padding:0.25rem 0;cursor:pointer;width:100%;text-align:left;color:var(--text-normal);}.chapter-header.svelte-1vxfdxx:hover {color:var(--text-accent);}.chapter-header.svelte-1vxfdxx h3:where(.svelte-1vxfdxx) {margin:0;font-size:0.875rem;font-weight:600;}.chapters.svelte-1vxfdxx {list-style:none;padding:0;margin:0.5rem 0 0 0;display:flex;flex-direction:column;gap:0.125rem;}.chapters.svelte-1vxfdxx li:where(.svelte-1vxfdxx) {border-radius:0.375rem;}.chapters.svelte-1vxfdxx li.active:where(.svelte-1vxfdxx) {background:var(--background-modifier-hover);}.chapter-item.svelte-1vxfdxx {display:flex;align-items:center;gap:0.75rem;width:100%;padding:0.5rem 0.625rem;background:none;border:none;cursor:pointer;text-align:left;color:var(--text-normal);border-radius:0.375rem;transition:background 100ms ease;}.chapter-item.svelte-1vxfdxx:hover {background:var(--background-modifier-hover);}.chapter-time.svelte-1vxfdxx {font-size:0.75rem;font-family:var(--font-monospace);color:var(--text-muted);min-width:4rem;}.chapter-title.svelte-1vxfdxx {font-size:0.875rem;flex:1;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.chapters.svelte-1vxfdxx li.active:where(.svelte-1vxfdxx) .chapter-title:where(.svelte-1vxfdxx) {font-weight:500;color:var(--text-accent);}"};function Pg(n,e){ge(e,!1),Pe(n,Cg);const t=q();let s=M(e,"chapters",24,()=>[]),r=M(e,"currentTime",8,0);const i=Ye();let a=q(!0);function o(){for(let h=s().length-1;h>=0;h--)if(r()>=s()[h].startTime)return h;return-1}function l(h){i("seek",{time:h.startTime})}He(()=>{},()=>{T(t,o())}),sn(),_e();var c=nt(),d=Be(c);{var u=h=>{var f=Ag(),p=R(f),m=R(p);{let E=qe(()=>g(a)?"chevron-down":"chevron-right");Ge(m,{get icon(){return g(E)},size:16})}var v=H(m,2),_=R(v),y=H(p,2);{var b=E=>{var C=Sg();zs(C,5,s,Lc,(F,x,A)=>{var I=Eg();let $;var D=R(I),G=R(D),ye=R(G),ce=H(G,2),Ee=R(ce);me(we=>{$=Qt(I,1,"svelte-1vxfdxx",null,$,{active:A===g(t)}),je(ye,we),je(Ee,(g(x),z(()=>g(x).title)))},[()=>(O(Ar),g(x),z(()=>Ar(g(x).startTime,"H:mm:ss")))]),le("click",D,()=>l(g(x))),L(F,I)}),L(E,C)};de(y,E=>{g(a)&&E(b)})}me(()=>{ue(p,"aria-expanded",g(a)),je(_,`Chapters (${O(s()),z(()=>s().length)??""})`)}),le("click",p,()=>T(a,!g(a))),L(h,f)};de(d,h=>{O(s()),z(()=>s().length>0)&&h(u)})}L(n,c),ve()}var Tg=J('<div class="progress svelte-aac6sw" role="slider" tabindex="0" aria-valuemin="0"><div class="progress__bar svelte-aac6sw"></div></div>');const Ig={hash:"svelte-aac6sw",code:`.progress.svelte-aac6sw {position:relative;width:100%;height:0.5rem;background:var(--background-modifier-border);border-radius:9999px;overflow:hidden;cursor:pointer;transition:height 120ms ease;}.progress.svelte-aac6sw:hover,
|
||
.progress.svelte-aac6sw:focus-visible {height:0.625rem;}.progress.svelte-aac6sw:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:2px;}.progress__bar.svelte-aac6sw {position:absolute;top:0;left:0;height:100%;background:var(--interactive-accent);border-radius:9999px;transition:width 50ms linear;}`};function $g(n,e){ge(e,!1),Pe(n,Ig);let t=M(e,"max",8),s=M(e,"value",8),r=!1,i=M(e,"style",24,()=>({})),a=q(),o=q();const l=Ye();function c(v,_){l("click",{event:v,percent:_})}function d(){r=!0}function u(){r=!1}function h(v){r&&c(v)}function f(v){if(!g(a)||!t())return;const _=t()*.05;let y=s();switch(v.key){case"ArrowRight":case"ArrowUp":y=Math.min(t(),s()+_);break;case"ArrowLeft":case"ArrowDown":y=Math.max(0,s()-_);break;case"Home":y=0;break;case"End":y=t();break;case"Enter":case" ":y=s();break;default:return}v.preventDefault();const b=t()?y/t():0;c(v,b)}He(()=>O(i()),()=>{T(o,Qs(i()))}),sn(),_e();var p=Tg(),m=R(p);Nn(p,v=>T(a,v),()=>g(a)),me(v=>{ue(p,"aria-valuemax",t()),ue(p,"aria-valuenow",s()),Er(p,g(o)),Er(m,v)},[()=>(O(t()),O(s()),z(()=>`width: ${t()?Math.min(100,s()/t()*100):0}%;`))]),le("click",p,c),le("mousedown",p,d),le("mouseup",p,u),le("mousemove",p,h),le("keydown",p,f),L(n,p),ve()}function Du(n,e){const t=e.startsWith(".")?e:`.${e}`;return n.endsWith(t)?n:`${n}${t}`}async function Lu(n){const e=ee(Zt),t=cs(e.settings.note.path,n),s=Du(t,"md"),r=Fm(e.settings.note.template,n);try{const i=await Mg(s,r,n);app.workspace.getLeaf().openFile(i)}catch{new P.Notice(`Failed to create note: "${s}"`)}}function Mo(n){const e=ee(Zt),t=cs(e.settings.note.path,n),s=Du(t,"md"),r=app.vault.getAbstractFileByPath(s);return!r||!(r instanceof P.TFile)?null:r}function Rg(n){const e=Mo(n);if(!e){new P.Notice(`Note for "${n.title}" does not exist`);return}app.workspace.getLeaf().openFile(e)}async function Mg(n,e,t,s=!0){const r=Mo(t);if(r)return new P.Notice(`Note for "${t.title}" already exists`),r;const i=n.split("/").slice(0,-1);for(let a=0;a<i.length;a++){const o=i.slice(0,a+1).join("/");!app.vault.getAbstractFileByPath(o)&&s&&await app.vault.createFolder(o)}return await app.vault.create(n,e)}const Fg=/[()]/g,Ng={"(":"%28",")":"%29"};function Bu(n){const e=n.trim();if(!e)return e;let t;try{t=new URL(e).toString()}catch{t=Og(e)}return t.replace(Fg,r=>Ng[r]??r)}function Og(n){return n.replace(/\s/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)}const Dg=[{pattern:/audio\/mpeg/i,extension:"mp3"},{pattern:/audio\/mp3/i,extension:"mp3"},{pattern:/audio\/mp4/i,extension:"m4a"},{pattern:/audio\/x-m4a/i,extension:"m4a"},{pattern:/audio\/aac/i,extension:"aac"},{pattern:/audio\/ogg/i,extension:"ogg"},{pattern:/audio\/wav/i,extension:"wav"},{pattern:/audio\/x-wav/i,extension:"wav"},{pattern:/audio\/flac/i,extension:"flac"},{pattern:/audio\/x-flac/i,extension:"flac"},{pattern:/audio\/x-ms-wma/i,extension:"wma"},{pattern:/audio\/wma/i,extension:"wma"},{pattern:/audio\/amr/i,extension:"amr"}];function Uu(n){if(!n)return null;for(const{pattern:e,extension:t}of Dg)if(e.test(n))return t;return null}function Xi(n){return n instanceof Error?n.message:String(n)}async function ju(n,e){const t=Bu(n);try{const s=await P.requestUrl({url:t,method:"GET"});if(s.status!==200)throw new Error("Could not download episode.");const r=s.arrayBuffer.byteLength;return e?.onFinished?.(),{blob:new Blob([s.arrayBuffer],{type:s.headers["content-type"]??s.headers["Content-Type"]??""}),contentLength:r,receivedLength:r,responseUrl:t}}catch(s){const r=new Error(`Failed to download ${n}:
|
||
|
||
${Xi(s)}`);throw e?.onError?.(r),r}}async function zu(n,e){const{doc:t,update:s}=Lg(`Download "${n.title}"`),r=999999999,i=new P.Notice(t,r);s(u=>u.createEl("p",{text:"Starting download..."})),s(u=>{u.createEl("p",{text:"Downloading..."})});const{blob:a}=await ju(n.streamUrl,{onFinished:()=>{s(u=>u.createEl("p",{text:"Download complete!"}))},onError:u=>{s(h=>h.createEl("p",{text:`Download failed: ${u.message}`}))}}),o=await jg(n,a),l=(a.type??"").toLowerCase();if(!(l===""||l.includes("audio"))&&!o)throw s(u=>{u.createEl("p",{text:`Downloaded file is not an audio file. It is of type "${a.type}". Blob: ${a.size} bytes.`})}),new Error("Not an audio file");const d=o??"mp3";try{s(u=>u.createEl("p",{text:"Creating file..."})),await qu({episode:n,downloadPathTemplate:e,blob:a,extension:d}),s(u=>u.createEl("p",{text:`Successfully downloaded "${n.title}" from ${n.podcastName}.`}))}catch(u){s(h=>{h.createEl("p",{text:`Failed to create file for downloaded episode "${n.title}" from ${n.podcastName}.`});const f=h.createEl("p",{text:Xi(u)});f.style.fontStyle="italic"})}setTimeout(()=>i.hide(),1e4)}function Lg(n){const e=new DocumentFragment,t=e.createDiv();t.style.width="100%",t.style.display="flex";const s=t.createEl("span",{text:n});s.style.textAlign="center",s.style.fontWeight="bold",s.style.marginBottom="0.5em";const r=e.createDiv();return r.style.display="flex",r.style.flexDirection="column",r.style.alignItems="center",r.style.justifyContent="center",{doc:e,update:(i,a=!0)=>{a&&r.empty(),i(r)}}}async function qu({episode:n,downloadPathTemplate:e,blob:t,extension:s}){const i=`${Io(e,n)}.${s}`,a=await t.arrayBuffer();try{await app.vault.createBinary(i,a)}catch(o){throw new Error(`Failed to write file "${i}": ${Xi(o)}`)}ht.addEpisode(n,i,t.size)}function Bg(n){const e=ht.getEpisode(n),t=[n.filePath,e?.filePath,Ug(n.url)];for(const s of t){if(!s)continue;const r=app.vault.getAbstractFileByPath(s);if(r instanceof P.TFile)return r.path}return null}function Ug(n){if(!n)return null;const e=n.trim();if(!e)return null;const t=e.match(/^\[\[(.*)\]\]$/)?.[1]??e,[s]=t.split("|"),r=s?.trim();if(!r)return null;const i=app.vault.getAbstractFileByPath(r);if(i instanceof P.TFile)return i.path;const a=app.metadataCache?.getFirstLinkpathDest(r,"");return a instanceof P.TFile?a.path:null}async function jg(n,e){const t=await Wg(e);if(t)return t;const s=To(n.streamUrl);return s||Uu(e.type)}async function zg(n,e){if(gu(n)){const a=Bg(n);if(!a)throw new Error(`Unable to locate the local audio file for "${n.title}". Try playing the file again.`);return a}const t=Io(e,n),s=await qg(n.streamUrl),r=`${t}.${s}`;if(app.vault.getAbstractFileByPath(r)instanceof P.TFile)return r;try{const{blob:a}=await ju(n.streamUrl);if(!a.type.includes("audio")&&!s)throw new Error("Not an audio file.");return await qu({episode:n,downloadPathTemplate:e,blob:a,extension:s}),r}catch(a){throw new Error(`Failed to download ${n.title}: ${Xi(a)}`)}}async function qg(n){const e=Bu(n),t=To(e);if(t)return t;try{const r=(await fetch(e,{method:"HEAD"})).headers.get("content-type"),i=Uu(r);if(i)return i}catch{}return"mp3"}async function Wg(n){const e=[{signature:[255,224],mask:[255,224],fileExtension:"mp3"},{signature:[73,68,51],fileExtension:"mp3"},{signature:[82,73,70,70],fileExtension:"wav"},{signature:[79,103,103,83],fileExtension:"ogg"},{signature:[102,76,97,67],fileExtension:"flac"},{signature:[77,52,65,32],fileExtension:"m4a"},{signature:[48,38,178,117,142,102,207,17],fileExtension:"wma"},{signature:[35,33,65,77,82,10],fileExtension:"amr"}];return new Promise((t,s)=>{const r=new FileReader;r.onloadend=i=>{if(!i.target?.result){s(new Error("No result from file reader"));return}const a=new Uint8Array(i.target.result);for(const{signature:o,mask:l,fileExtension:c}of e){let d=!0;for(let u=0;u<o.length;u++)if(l){if((a[u]&l[u])!==(o[u]&l[u])){d=!1;break}}else if(a[u]!==o[u]){d=!1;break}if(d){t(c);return}}t(null)},r.onerror=()=>{s(r.error)},r.readAsArrayBuffer(n.slice(0,Math.max(...e.map(i=>i.signature.length))))})}function eo(n,e,t){const s=new P.Menu;if(t?.play||s.addItem(r=>r.setIcon("play").setTitle("Play").onClick(()=>{Qe.set(n),Je.set(Z.Player)})),!t?.markPlayed){const r=Object.values(ee(kt)).find(i=>i.title===n.title&&i.finished);s.addItem(i=>i.setIcon(r?"cross":"check").setTitle(`Mark as ${r?"Unplayed":"Played"}`).onClick(()=>{r?kt.markAsUnplayed(n):kt.markAsPlayed(n)}))}if(!t?.download){const r=ht.isEpisodeDownloaded(n);s.addItem(i=>i.setIcon(r?"cross":"download").setTitle(r?"Remove file":"Download").onClick(()=>{if(r)ht.removeEpisode(n,!0);else{const a=ee(Zt).settings.download.path;if(!a){new P.Notice("Please set a download path in the settings.");return}zu(n,a)}}))}if(!t?.createNote){const r=!!Mo(n);s.addItem(i=>i.setIcon("pencil").setTitle(`${r?"Open":"Create"} Note`).onClick(async()=>{if(r)Rg(n);else{const{path:a,template:o}=ee(Zt).settings.note;if(!!!(a&&o)){new P.Notice("Please set a note path and template in the settings.");return}await Lu(n)}}))}if(!t?.favorite){const r=ee(ls).episodes.find(i=>i.title===n.title);s.addItem(i=>i.setIcon("lucide-star").setTitle(`${r?"Remove from":"Add to"} Favorites`).onClick(()=>{r?ls.update(a=>(a.episodes=a.episodes.filter(o=>o.title!==n.title),a)):ls.update(a=>{const o=[...a.episodes,n];return a.episodes=o,a})}))}if(!t?.queue){const r=ee(Et).episodes.find(i=>i.title===n.title);s.addItem(i=>i.setIcon("list-ordered").setTitle(`${r?"Remove from":"Add to"} Queue`).onClick(()=>{r?Et.update(a=>(a.episodes=a.episodes.filter(o=>o.title!==n.title),a)):Et.update(a=>{const o=[...a.episodes,n];return a.episodes=o,a})}))}if(!t?.playlists){s.addSeparator();const r=ee(Rt);for(const i of Object.values(r)){const a=i.episodes.find(o=>o.title===n.title);s.addItem(o=>o.setIcon(i.icon).setTitle(`${a?"Remove from":"Add to"} ${i.name}`).onClick(()=>{a?Rt.update(l=>(l[i.name].episodes=l[i.name].episodes.filter(c=>c.title!==n.title),l)):Rt.update(l=>{const c=[...l[i.name].episodes,n];return l[i.name].episodes=c,l})}))}}s.showAtMouseEvent(e)}var Hg=J("<div><!></div>"),Vg=J('<div class="podcast-artwork-isloading-overlay svelte-vlhi04"><!></div>'),Yg=J("<div><!></div>"),Kg=J("<audio></audio>"),Jg=J("<h3>Queue</h3>"),Xg=J('<div class="episode-player svelte-vlhi04"><div class="episode-image-container svelte-vlhi04"><button type="button" class="hover-container svelte-vlhi04" aria-label="Toggle playback"><!> <!></button></div> <h2 class="podcast-title svelte-vlhi04"> </h2> <!> <div class="status-container svelte-vlhi04"><span class="svelte-vlhi04"> </span> <!> <span class="svelte-vlhi04"> </span></div> <div class="controls-container svelte-vlhi04"><!> <!></div> <div class="slider-stack svelte-vlhi04"><div class="volume-container svelte-vlhi04"><span class="svelte-vlhi04"> </span> <!></div> <div class="playbackrate-container svelte-vlhi04"><span class="svelte-vlhi04"> </span> <!></div></div> <div class="lists-container svelte-vlhi04"><!> <!></div></div>');const Gg={hash:"svelte-vlhi04",code:`.episode-player.svelte-vlhi04 {display:flex;flex-direction:column;flex:1 1 auto;min-height:0;padding:0 1rem;overflow-y:auto;gap:0.35rem;}.episode-image-container.svelte-vlhi04 {width:100%;max-width:20rem;margin:0 auto 0.5rem;padding:1rem 0 0.5rem;}.hover-container.svelte-vlhi04 {width:100%;height:0;padding-bottom:100%;display:block;position:relative;border:none;background:transparent;cursor:pointer;border-radius:0.75rem;overflow:hidden;box-shadow:0 4px 20px rgba(0, 0, 0, 0.2);transition:box-shadow 200ms ease, transform 200ms ease;}.hover-container.svelte-vlhi04:hover {box-shadow:0 6px 24px rgba(0, 0, 0, 0.25);}.hover-container.svelte-vlhi04:active {transform:scale(0.98);}.hover-container.svelte-vlhi04 .pn_image_container {position:absolute;inset:0;}.podcast-artwork {width:100%;height:100%;object-fit:cover;transition:opacity 200ms ease;}.podcast-artwork-placeholder {width:100%;height:100%;position:absolute;display:flex;align-items:center;justify-content:center;background:var(--background-secondary);transition:opacity 200ms ease;}.podcast-artwork-overlay.svelte-vlhi04 {position:absolute;inset:0;display:flex;align-items:center;justify-content:center;opacity:0;background:rgba(0, 0, 0, 0.1);transition:opacity 200ms ease;}.podcast-artwork-overlay.visible.svelte-vlhi04 {opacity:1;}.podcast-artwork-isloading-overlay.svelte-vlhi04 {position:absolute;inset:0;display:flex;align-items:center;justify-content:center;background:rgba(0, 0, 0, 0.3);}.opacity-50 {opacity:0.5;}.podcast-title.svelte-vlhi04 {font-size:1.125rem;font-weight:600;line-height:1.4;margin:0 0 0.75rem;text-align:center;color:var(--text-normal);white-space:normal;word-break:break-word;}.status-container.svelte-vlhi04 {display:flex;align-items:center;gap:0.75rem;padding:0 0.25rem;}.status-container.svelte-vlhi04 span:where(.svelte-vlhi04) {font-size:0.8rem;font-variant-numeric:tabular-nums;color:var(--text-muted);min-width:4rem;text-align:center;}.status-container.svelte-vlhi04 span:where(.svelte-vlhi04):first-child {text-align:right;}.status-container.svelte-vlhi04 span:where(.svelte-vlhi04):last-child {text-align:left;}.episode-player .status-container .progress {height:var(--episode-player-progress-height, 0.5rem);flex:1 1 auto;}.controls-container.svelte-vlhi04 {display:flex;align-items:center;justify-content:center;gap:2rem;margin:1.25rem 0;}.player-control-button {margin:0;cursor:pointer;padding:0.5rem;border-radius:50%;transition:background-color 120ms ease;}.player-control-button:hover {background-color:var(--background-modifier-hover);}.slider-stack.svelte-vlhi04 {display:flex;flex-direction:column;gap:1rem;padding:1rem 0 0.75rem;border-top:1px solid var(--background-modifier-border);}.playbackrate-container.svelte-vlhi04,
|
||
.volume-container.svelte-vlhi04 {display:flex;align-items:center;gap:1rem;padding:0 0.5rem;}.playbackrate-container.svelte-vlhi04 span:where(.svelte-vlhi04),
|
||
.volume-container.svelte-vlhi04 span:where(.svelte-vlhi04) {font-size:0.8rem;color:var(--text-muted);min-width:5rem;}.episode-player h3 {font-size:0.875rem;font-weight:600;color:var(--text-muted);text-transform:uppercase;letter-spacing:0.05em;margin:1rem 0 0.5rem;padding:0 0.5rem;}.episode-player .episode-list-view-container {height:auto;overflow:visible;}.episode-player .podcast-episode-list {flex:0 0 auto;overflow:visible;}.lists-container.svelte-vlhi04 {display:flex;flex-direction:column;gap:0.25rem;padding-bottom:0.5rem;}.lists-container .episode-list-view-container {height:auto;}`};function Qg(n,e){ge(e,!1),Pe(n,Gg);const t=()=>Ue(Zt,"$plugin",c),s=()=>Ue(bi,"$duration",c),r=()=>Ue(Qe,"$currentEpisode",c),i=()=>Ue(kt,"$playedEpisodes",c),a=()=>Ue(Pt,"$currentTime",c),o=()=>Ue(Vt,"$isPaused",c),l=()=>Ue(Et,"$queue",c),[c,d]=Or();class u{constructor(){this.playbackRate=t().settings.defaultPlaybackRate||1}get _playbackRate(){return this.playbackRate}set _playbackRate(ne){}}const h=q(new u),f=W=>Math.min(1,Math.max(0,W));let p=q(!1),m=q(!0),v=q(1),_=q([]),y;function b(){Vt.update(W=>!W)}function E({detail:{event:W,percent:ne}}){if(typeof ne=="number"){Pt.set(ne*s());return}if(W instanceof MouseEvent){const ae=W.currentTarget,fe=ae.offsetWidth?W.offsetX/ae.offsetWidth:0;Pt.set(fe*s())}}function C(){Rt.update(W=>(Object.values(W).forEach(ne=>{ne.episodes=ne.episodes.filter(ae=>ae.title!==r().title)}),W)),Et.remove(r())}function F(){kt.markAsPlayed(r()),C(),Et.playNext()}function x(W){pr(h,g(h).playbackRate=W.detail.value)}function A(W){const ne=f(W.detail.value);os.set(ne)}function I(W){Pt.set(W.detail.time)}function $(){T(m,!1),D()}function D(){const W=i(),ne=r();if(!ne){Pt.set(0),Vt.set(!1);return}const ae=Jn(ne),fe=ae&&W[ae]||W[ne.title];fe?.time?Pt.set(fe.time):Pt.set(0),Vt.set(!1)}let G=q(we(r()));rn(()=>{const W=ht.subscribe(fe=>{T(G,we(r()))}),ne=Qe.subscribe(fe=>{T(G,we(r()));const Ct=fe?.chaptersUrl;Ct&&Ct!==y?(y=Ct,og(Ct).then(la=>{T(_,la)})):Ct||(y=void 0,T(_,[]))}),ae=os.subscribe(fe=>{T(v,f(fe))});return()=>{W(),ne(),ae()}}),Yi(()=>{kt.setEpisodeTime(r(),a(),s(),a()===s()),Vt.set(!0)});function ye({detail:{event:W,episode:ne}}){eo(ne,W)}function ce(W){eo(r(),W,{play:!0,markPlayed:!0})}function Ee(W){const{episode:ne}=W.detail;Qe.set(ne),Je.set(Z.Player)}async function we(W){if(ht.isEpisodeDownloaded(W)){const ne=ht.getEpisode(W);return ne?mu(ne.filePath):""}return W.streamUrl}_e();var gs=Xg(),K=R(gs),te=R(K),be=R(te);{let W=qe(()=>r().artworkUrl??""),ne=qe(()=>g(p)||o()?.5:1);Ro(be,{class:"podcast-artwork",get src(){return g(W)},get alt(){return r().title},get opacity(){return g(ne)},$$slots:{fallback:(ae,fe)=>{var Ct=Hg(),la=R(Ct);Ge(la,{icon:"image",size:150,clickable:!1}),me(()=>Qt(Ct,1,"podcast-artwork-placeholder"+(g(p)||o()?" opacity-50":""),"svelte-vlhi04")),L(ae,Ct)}}})}var Nt=H(be,2);{var xn=W=>{var ne=Vg(),ae=R(ne);Nu(ae),L(W,ne)},xe=W=>{var ne=Yg();let ae;var fe=R(ne);{let Ct=qe(()=>o()?"play":"pause");Ge(fe,{get icon(){return g(Ct)},clickable:!1})}me(()=>ae=Qt(ne,1,"podcast-artwork-overlay svelte-vlhi04",null,ae,{visible:g(p)||o()})),L(W,ne)};de(Nt,W=>{g(m)?W(xn):W(xe,!1)})}var pt=H(K,2),mt=R(pt),Ie=H(pt,2);Wh(Ie,()=>g(G),null,(W,ne)=>{var ae=Kg();ae.autoplay=!0,me(()=>ue(ae,"src",g(ne))),ap("duration","durationchange",ae,fe=>gr(bi,fe)),np(ae,a,fe=>gr(Pt,fe)),rp(ae,o,fe=>gr(Vt,fe)),sp(ae,()=>g(h)._playbackRate,fe=>pr(h,g(h)._playbackRate=fe)),ip(ae,()=>g(v),fe=>T(v,fe)),le("ended",ae,F),le("loadedmetadata",ae,$),le("play",ae,op(function(fe){lu.call(this,e,fe)})),L(W,ae)});var Fe=H(Ie,2),kn=R(Fe),vs=R(kn),Bn=H(kn,2);$g(Bn,{get value(){return a()},get max(){return s()},$$events:{click:E}});var qr=H(Bn,2),_s=R(qr),Un=H(Fe,2),ys=R(Un),tr=Fs(()=>t().api.skipBackward.bind(t().api));Cr(ys,{icon:"skip-back",tooltip:"Skip backward",class:"player-control-button",$$events:{click(...W){g(tr)?.apply(this,W)}}});var Ot=H(ys,2),St=Fs(()=>t().api.skipForward.bind(t().api));Cr(Ot,{icon:"skip-forward",tooltip:"Skip forward",class:"player-control-button",$$events:{click(...W){g(St)?.apply(this,W)}}});var At=H(Un,2),En=R(At),ws=R(En),Sn=R(ws),Wr=H(ws,2);Ll(Wr,{get value(){return g(v)},limits:[0,1,.05],$$events:{change:A}});var nr=H(En,2),Hr=R(nr),Vr=R(Hr),aa=H(Hr,2);Ll(aa,{get value(){return g(h).playbackRate},limits:[.5,3.5,.1],$$events:{change:x}});var oa=H(At,2),ul=R(oa);Pg(ul,{get chapters(){return g(_)},get currentTime(){return a()},$$events:{seek:I}});var vf=H(ul,2);Ou(vf,{get episodes(){return l().episodes},showListMenu:!1,showThumbnails:!0,$$events:{contextMenuEpisode:ye,clickEpisode:Ee},$$slots:{header:(W,ne)=>{var ae=Jg();L(W,ae)}}}),me((W,ne,ae)=>{je(mt,r().title),je(vs,W),je(_s,ne),je(Sn,`Volume: ${ae??""}%`),je(Vr,`${g(h).playbackRate??""}x`)},[()=>Ar(a(),"HH:mm:ss"),()=>Ar(s()-a(),"HH:mm:ss"),()=>Math.round(g(v)*100)]),le("click",te,b),le("contextmenu",te,ce),le("mouseenter",te,()=>T(p,!0)),le("mouseleave",te,()=>T(p,!1)),L(n,gs),ve(),d()}var Zg=J('<div class="topbar-container svelte-1uvslqs"><button type="button" aria-label="Podcast grid"><!></button> <button type="button"><!></button> <button type="button"><!></button></div>');const ev={hash:"svelte-1uvslqs",code:`.topbar-container.svelte-1uvslqs {display:flex;flex-direction:row;align-items:center;justify-content:stretch;gap:0.375rem;padding:0.5rem;min-height:3rem;border-bottom:1px solid var(--background-modifier-border);background:var(--background-secondary);box-sizing:border-box;}.topbar-menu-button.svelte-1uvslqs {display:flex;align-items:center;justify-content:center;height:2rem;padding:0 0.75rem;flex:1 1 0;border:1px solid transparent;border-radius:0.375rem;background:transparent;color:var(--text-muted);transition:background-color 120ms ease,
|
||
border-color 120ms ease,
|
||
color 120ms ease;}.topbar-menu-button.svelte-1uvslqs:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:1px;}.topbar-selectable.svelte-1uvslqs {cursor:pointer;color:var(--text-normal);}.topbar-selectable.svelte-1uvslqs:hover:not(.topbar-selected) {background:var(--background-modifier-hover);}.topbar-selectable.svelte-1uvslqs:active:not(.topbar-selected) {background:var(--background-modifier-border);}.topbar-selected.svelte-1uvslqs,
|
||
.topbar-selected.svelte-1uvslqs:hover {color:var(--text-on-accent);background:var(--interactive-accent);}.topbar-disabled.svelte-1uvslqs,
|
||
.topbar-menu-button.svelte-1uvslqs:disabled {cursor:not-allowed;color:var(--text-faint);opacity:0.5;}`};function tv(n,e){ge(e,!1),Pe(n,ev);const t=q(),s=q();let r=M(e,"viewState",28,()=>Z.PodcastGrid),i=M(e,"canShowEpisodeList",8,!1),a=M(e,"canShowPlayer",8,!1);const o="Browse podcast grid",l="Select a podcast or playlist to view its episodes.",c="Start playing an episode to open the player.";function d(C){r()!==C&&(C===Z.EpisodeList&&!i()||C===Z.Player&&!a()||r(C))}He(()=>O(i()),()=>{T(t,i()?"View episode list":l)}),He(()=>O(a()),()=>{T(s,a()?"Open player":c)}),sn(),_e();var u=Zg(),h=R(u),f=Fs(()=>d.bind(null,Z.PodcastGrid));ue(h,"title",o);var p=R(h);Ge(p,{icon:"grid",size:20,clickable:!1});var m=H(h,2),v=Fs(()=>d.bind(null,Z.EpisodeList)),_=R(m);Ge(_,{icon:"list-minus",size:20,clickable:!1});var y=H(m,2),b=Fs(()=>d.bind(null,Z.Player)),E=R(y);Ge(E,{icon:"play",size:20,clickable:!1}),me(()=>{Qt(h,1,(O(r()),O(Z),z(()=>`
|
||
topbar-menu-button
|
||
topbar-selectable
|
||
${r()===Z.PodcastGrid?"topbar-selected":""}
|
||
`)),"svelte-1uvslqs"),ue(h,"aria-pressed",(O(r()),O(Z),z(()=>r()===Z.PodcastGrid))),Qt(m,1,(O(r()),O(Z),O(i()),z(()=>`
|
||
topbar-menu-button
|
||
${r()===Z.EpisodeList?"topbar-selected":""}
|
||
${i()?"topbar-selectable":"topbar-disabled"}
|
||
`)),"svelte-1uvslqs"),ue(m,"aria-label",i()?"Episode list":"Episode list (select a podcast or playlist first)"),ue(m,"aria-pressed",(O(r()),O(Z),z(()=>r()===Z.EpisodeList))),m.disabled=!i(),ue(m,"title",g(t)),Qt(y,1,(O(r()),O(Z),O(a()),z(()=>`
|
||
topbar-menu-button
|
||
${r()===Z.Player?"topbar-selected":""}
|
||
${a()?"topbar-selectable":"topbar-disabled"}
|
||
`)),"svelte-1uvslqs"),ue(y,"aria-label",a()?"Player":"Player (start playing an episode to open the player)"),ue(y,"aria-pressed",(O(r()),O(Z),z(()=>r()===Z.Player))),y.disabled=!a(),ue(y,"title",g(s))}),le("click",h,function(...C){g(f)?.apply(this,C)}),le("click",m,function(...C){g(v)?.apply(this,C)}),le("click",y,function(...C){g(b)?.apply(this,C)}),L(n,u),ve()}var nv=J('<img id="podcast-artwork" class="svelte-4w31cc"/>'),sv=J('<div class="podcast-header svelte-4w31cc"><!> <h2 class="podcast-heading svelte-4w31cc"> </h2></div>');const rv={hash:"svelte-4w31cc",code:".podcast-header.svelte-4w31cc {display:flex;flex-direction:column;justify-content:center;align-items:center;gap:0.75rem;padding:1rem;}#podcast-artwork.svelte-4w31cc {width:5rem;height:5rem;border-radius:0.5rem;object-fit:cover;box-shadow:0 2px 8px rgba(0, 0, 0, 0.15);}.podcast-heading.svelte-4w31cc {margin:0;font-size:1.125rem;font-weight:600;text-align:center;color:var(--text-normal);}"};function wa(n,e){Pe(n,rv);let t=M(e,"text",8,""),s=M(e,"artworkUrl",8,"");var r=sv(),i=R(r);{var a=c=>{var d=nv();me(()=>{ue(d,"src",s()),ue(d,"alt",t())}),L(c,d)};de(i,c=>{s()&&c(a)})}var o=H(i,2),l=R(o);me(()=>je(l,t())),L(n,r)}const iv={shouldSort:!0,findAllMatches:!0,threshold:.4,isCaseSensitive:!1,keys:["title"]},Bl=new WeakMap;function av(n){const e=Bl.get(n);if(e&&e.size===n.length)return e.fuse;const t=new ms(n,iv);return Bl.set(n,{fuse:t,size:n.length}),t}function zn(n,e){return e.length===0?[]:n.length===0?e:av(e).search(n).map(r=>r.item)}var ov=J('<span class="feed-loading-names svelte-14kt8yt"> </span>'),lv=J('<div class="feed-loading-banner svelte-14kt8yt"><div class="feed-loading-spinner svelte-14kt8yt"><!></div> <div class="feed-loading-text svelte-14kt8yt"><span> </span> <!></div></div>'),cv=J('<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <!>',1),uv=J('<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <div class="playlist-header-icon svelte-14kt8yt"><!></div> <!>',1),dv=J("<!> <!>",1),fv=J('<div class="podcast-view svelte-14kt8yt"><!> <!></div>');const hv={hash:"svelte-14kt8yt",code:`.podcast-view.svelte-14kt8yt {display:flex;flex-direction:column;height:100%;overflow:hidden;}.feed-loading-banner.svelte-14kt8yt {display:flex;align-items:center;gap:0.625rem;width:100%;padding:0.625rem 0.75rem;background:var(--background-secondary);border-bottom:1px solid var(--background-modifier-border);box-sizing:border-box;}.feed-loading-spinner.svelte-14kt8yt {display:inline-flex;color:var(--interactive-accent);
|
||
animation: svelte-14kt8yt-spin 1s linear infinite;}.feed-loading-text.svelte-14kt8yt {display:flex;flex-direction:column;gap:0.125rem;font-size:0.85rem;color:var(--text-normal);}.feed-loading-names.svelte-14kt8yt {font-size:0.75rem;color:var(--text-muted);}
|
||
|
||
@keyframes svelte-14kt8yt-spin {
|
||
from {
|
||
transform: rotate(0deg);
|
||
}
|
||
|
||
to {
|
||
transform: rotate(360deg);
|
||
}
|
||
}.go-back.svelte-14kt8yt {display:inline-flex;align-items:center;gap:0.375rem;padding:0.375rem 0.625rem;margin:0.5rem 0.5rem 0;font-size:0.85rem;color:var(--text-muted);cursor:pointer;background:none;border:none;border-radius:0.25rem;transition:color 120ms ease, background-color 120ms ease;}.go-back.svelte-14kt8yt:hover {color:var(--text-normal);background:var(--background-modifier-hover);}.go-back.svelte-14kt8yt:active {background:var(--background-modifier-border);}.playlist-header-icon.svelte-14kt8yt {display:flex;align-items:center;justify-content:center;padding:0.5rem;color:var(--text-muted);}`};function pv(n,e){ge(e,!1),Pe(n,hv);const t=()=>Ue(Et,"$queue",a),s=()=>Ue(Qe,"$currentEpisode",a),r=()=>Ue(Ya,"$podcastView",a),i=()=>Ue(Je,"$viewState",a),[a,o]=Or();let l=q([]),c=q(null),d=q(null),u=q([]),h=q([]),f=q([]),p=q(!1),m=q(new Set),v=q(""),_=q([]),y=q(""),b=!0;Yi(()=>{b=!1}),rn(()=>{const K=Rt.subscribe(xe=>{T(h,[ee(Et),ee(ls),ee(Sr),...Object.values(xe)])}),te=mn.subscribe(xe=>{const pt=Object.values(xe),mt=new Set(g(l).map(Fe=>Fe.title));T(l,pt);const Ie=pt.filter(Fe=>!mt.has(Fe.title));Ie.length>0&&F(Ie)});let be=ee(Je);const Nt=Je.subscribe(xe=>{be=xe}),xn=vp.subscribe(xe=>{T(f,xe),be===Z.EpisodeList&&!g(c)&&!g(d)&&T(u,g(v)?zn(g(v),xe):xe)});return()=>{xn(),Nt(),te(),K()}});async function E(K,te=!0){const Nt=ee(Zt)?.settings?.feedCache,xn=Nt?.enabled!==!1,xe=Math.max(1,Nt?.ttlHours??6)*60*60*1e3,mt=ee(Xn)[K.title];if(te&&mt&&mt.length>0)return mt;if(te&&xn){const Ie=Hm(K,xe);if(Ie?.length)return Xn.update(Fe=>({...Fe,[K.title]:Ie})),Ie}try{const Ie=await new Ki(K).getEpisodes(K.url);return Xn.update(Fe=>({...Fe,[K.title]:Ie})),xn&&Vm(K,Ie),Ie}catch{return ee(ht)[K.title]||[]}}function C(K,te){if(!b)return;const be=new Set(g(m));te?be.add(K):be.delete(K),T(m,be)}function F(K){return K.length?Promise.all(K.map(async te=>{C(te.title,!0);try{await E(te)}finally{C(te.title,!1)}})).then(()=>{}):Promise.resolve()}async function x(K){const{feed:te}=K.detail;T(c,te),T(u,[]),Je.set(Z.EpisodeList),C(te.title,!0);try{const be=await E(te);T(u,g(v)?zn(g(v),be):be)}finally{C(te.title,!1)}}function A(K){const{episode:te}=K.detail;Qe.set(te),Je.set(Z.Player)}function I({detail:{event:K,episode:te}}){eo(te,K)}async function $(){if(g(c)){C(g(c).title,!0);try{const K=await E(g(c),!1);T(u,g(v)?zn(g(v),K):K)}finally{C(g(c).title,!1)}}}const D=P.debounce(K=>{const{query:te}=K.detail;if(T(v,te),g(c)){const Nt=ee(Xn)[g(c).title]??[];T(u,zn(te,Nt));return}T(u,zn(te,g(f)))},250);function G(K){const{event:te,playlist:be}=K.detail;be.name===t().name&&t().episodes.length>0?(s()||Qe.set(t().episodes[0]),Je.set(Z.Player)):(T(d,be),T(u,be.episodes),Je.set(Z.EpisodeList))}He(()=>g(m),()=>{T(_,Array.from(g(m)))}),He(()=>g(_),()=>{T(y,g(_).length>3?`${g(_).slice(0,3).join(", ")} +${g(_).length-3} more`:g(_).join(", "))}),He(()=>g(_),()=>{T(p,g(_).length>0)}),sn(),_e();var ye=fv(),ce=R(ye);{let K=qe(()=>!!s());tv(ce,{canShowEpisodeList:!0,get canShowPlayer(){return g(K)},get viewState(){return lp(),i()},set viewState(te){gr(Je,te)},$$legacy:!0})}var Ee=H(ce,2);{var we=K=>{Qg(K,{})},gs=K=>{var te=nt(),be=Be(te);{var Nt=xe=>{var pt=dv(),mt=Be(pt);{var Ie=kn=>{var vs=lv(),Bn=R(vs),qr=R(Bn);Ge(qr,{icon:"loader-2",size:18,clickable:!1});var _s=H(Bn,2),Un=R(_s),ys=R(Un),tr=H(Un,2);{var Ot=St=>{var At=ov(),En=R(At);me(()=>je(En,g(y))),L(St,At)};de(tr,St=>{g(y)&&St(Ot)})}me(()=>je(ys,`Updating ${g(_),z(()=>g(_).length)??""} feed${g(_),z(()=>g(_).length===1?"":"s")??""}`)),L(kn,vs)};de(mt,kn=>{g(_),z(()=>g(_).length>0)&&kn(Ie)})}var Fe=H(mt,2);{let kn=qe(()=>!g(c)||!g(d)),vs=qe(()=>(g(c),g(m),g(p),z(()=>g(c)?g(m).has(g(c).title):g(p))));Ou(Fe,{get episodes(){return g(u)},get showThumbnails(){return g(kn)},get isLoading(){return g(vs)},$$events:{clickEpisode:A,contextMenuEpisode:I,clickRefresh:$,search:D},$$slots:{header:(Bn,qr)=>{var _s=nt(),Un=Be(_s);{var ys=Ot=>{var St=cv(),At=Be(St),En=R(At);Ge(En,{icon:"arrow-left",size:20,clickable:!1});var ws=H(At,2);wa(ws,{get text(){return g(c),z(()=>g(c).title)},get artworkUrl(){return g(c),z(()=>g(c).artworkUrl)}}),le("click",At,()=>{T(c,null),T(u,g(v)?zn(g(v),g(f)):g(f)),Je.set(Z.EpisodeList)}),L(Ot,St)},tr=Ot=>{var St=nt(),At=Be(St);{var En=Sn=>{var Wr=uv(),nr=Be(Wr),Hr=R(nr);Ge(Hr,{icon:"arrow-left",size:20,clickable:!1});var Vr=H(nr,2),aa=R(Vr);Ge(aa,{get icon(){return g(d),z(()=>g(d).icon)},size:40,clickable:!1});var oa=H(Vr,2);wa(oa,{get text(){return g(d),z(()=>g(d).name)}}),le("click",nr,()=>{T(d,null),T(u,g(v)?zn(g(v),g(f)):g(f)),Je.set(Z.EpisodeList)}),L(Sn,Wr)},ws=Sn=>{wa(Sn,{text:"Latest Episodes"})};de(At,Sn=>{g(d)?Sn(En):Sn(ws,!1)},!0)}L(Ot,St)};de(Un,Ot=>{g(c)?Ot(ys):Ot(tr,!1)})}L(Bn,_s)}}})}L(xe,pt)},xn=xe=>{var pt=nt(),mt=Be(pt);{var Ie=Fe=>{ag(Fe,{get feeds(){return g(l)},get playlists(){return g(h)},$$events:{clickPodcast:x,clickPlaylist:G}})};de(mt,Fe=>{i(),O(Z),z(()=>i()===Z.PodcastGrid)&&Fe(Ie)},!0)}L(xe,pt)};de(be,xe=>{i(),O(Z),z(()=>i()===Z.EpisodeList)?xe(Nt):xe(xn,!1)},!0)}L(K,te)};de(Ee,K=>{i(),O(Z),z(()=>i()===Z.Player)?K(we):K(gs,!1)})}Nn(ye,K=>gr(Ya,K),()=>r()),L(n,ye),ve(),o()}class mv extends P.ItemView{constructor(e,t){super(e),this.plugin=t,this.podcastView=null}getViewType(){return Wn}getDisplayText(){return"Podcast Player"}getIcon(){return"play-circle"}async onOpen(){this.podcastView=za(pv,{target:this.contentEl})}async onClose(){this.podcastView&&(await Wa(this.podcastView),this.podcastView=null),this.contentEl.empty()}}class bn{constructor(e){this.unsubscribe=null,this.store=e}on(){return this.unsubscribe=this.store.subscribe(this.onChange.bind(this)),this}off(){return this.unsubscribe?.(),this}}class gv extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.playedEpisodes=e,this.plugin.saveSettings()}}class vv extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.savedFeeds=e,this.plugin.saveSettings()}}class _v extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.playlists=e,this.plugin.saveSettings()}}class yv extends bn{constructor(e,t){super(e),this.unsubscribeCurrentEpisode=null,this.plugin=t}onChange(e){this.plugin.settings.queue={...e,..._u},this.plugin.saveSettings()}on(){return this.removeCurrentEpisodeFromQueue(),super.on()}off(){return this.unsubscribeCurrentEpisode?.(),super.off()}removeCurrentEpisodeFromQueue(){this.unsubscribeCurrentEpisode=Qe.subscribe(e=>{if(!e)return;const s=ee(this.store).episodes.find(r=>r.title===e.title);this.store.update(r=>(s&&(r.episodes=r.episodes.filter(i=>i.title!==e.title)),r))})}}class wv extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.favorites={...e,...vu},this.plugin.saveSettings()}}class bv extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.currentEpisode=e,this.plugin.saveSettings()}}class xv extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.hidePlayedEpisodes!==e&&(this.plugin.settings.hidePlayedEpisodes=e,this.plugin.saveSettings())}}class kv extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.downloadedEpisodes=e,this.plugin.saveSettings()}}class Ev extends bn{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.localFiles={...e,...yu},this.plugin.saveSettings()}}async function Sv({url:n,episodeName:e,time:t},s){if(!n||!e||!t){new P.Notice("URL, episode name, and timestamp are required to play an episode");return}const r=e.replace(/\+/g," ");if(ee(Qe)?.title===r){Je.set(Z.Player),s.currentTime=parseFloat(t);return}const o=n.replace(/\+/g," "),l=app.vault.getAbstractFileByPath(o);let c;if(l?c=Sr.getLocalEpisode(r):c=await new Ki().findItemByTitle(r,n),!c){new P.Notice("Episode not found");return}Qe.set(c),Je.set(Z.Player),new P.Notice("Episode found, playing now. Please click timestamp again to play at specific time.")}function Av(n){return n.workspace.on("file-menu",(e,t)=>{t instanceof P.TFile&&t.extension.match(/mp3|mp4|wma|aac|wav|webm|aac|flac|m4a|/)&&e.addItem(s=>s.setIcon("play").setTitle("Play with PodNotes").onClick(async()=>{const r={title:t.basename,description:"",content:"",podcastName:"local file",url:n.fileManager.generateMarkdownLink(t,""),streamUrl:await mu(t.path),filePath:t.path,episodeDate:new Date(t.stat.ctime)};ht.isEpisodeDownloaded(r)||(ht.addEpisode(r,t.path,t.stat.size),Sr.addEpisode(r)),ee(kt)[t.basename]?.finished&&kt.markAsUnplayed(r),Qe.set(r),Je.set(Z.Player)}))})}async function Cv(n){const{title:e,itunesTitle:t,podcastName:s,feedUrl:r}=n.podcast;try{const a=(await wu(n.podcast.podcastName)).find(u=>u.title===s&&u.url===r);if(!a||!a.collectionId)throw new Error("Failed to get podcast from iTunes.");const o=`https://pod.link/${a.collectionId}.json?limit=1000`,l=await P.requestUrl({url:o});if(l.status!==200)throw new Error(`Failed to get response from pod.link: ${o}`);const c=t??e,d=l.json.episodes.find(u=>u.title===c);if(!d)throw new Error(`Failed to find episode "${c}" on pod.link. URL: ${o}`);window.navigator.clipboard.writeText(`https://pod.link/${a.collectionId}/episode/${d.episodeId}`),new P.Notice("Universal episode link copied to clipboard.")}catch{new P.Notice("Could not get podcast link.");return}}function Pv(n,e){let t=e;const s=Date.now();let r;const i=new P.Notice(e,0);function a(d){return`${n} (${c()}):
|
||
|
||
${d}`}function o(d){t=d,i.setMessage(a(t))}const l=setInterval(()=>{i.setMessage(a(t))},1e3);function c(){return Tv(r?r-s:Date.now()-s)}return{update:o,hide:()=>i.hide(),stop:()=>{r=Date.now(),clearInterval(l)}}}function Tv(n){const e=Math.floor(n/1e3),t=Math.floor(e/60);return`${Math.floor(t/60).toString().padStart(2,"0")}:${(t%60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`}class Iv{constructor(e){this.client=null,this.cachedApiKey=null,this.MAX_RETRIES=3,this.CHUNK_SIZE_BYTES=20*1024*1024,this.WAV_HEADER_SIZE=44,this.PCM_BYTES_PER_SAMPLE=2,this.MAX_CONCURRENT_TRANSCRIPTIONS=2,this.MAX_CONCURRENT_CHUNK_TRANSCRIPTIONS=3,this.pendingEpisodes=[],this.activeTranscriptions=new Set,this.plugin=e}async transcribeCurrentEpisode(){if(!this.plugin.settings.openAIApiKey?.trim()){new P.Notice("Please add your OpenAI API key in the transcript settings first.");return}const e=this.plugin.api.podcast;if(!e){new P.Notice("No episode is currently playing.");return}const t=cs(this.plugin.settings.transcript.path,e);if(this.plugin.app.vault.getAbstractFileByPath(t)instanceof P.TFile){new P.Notice(`You've already transcribed this episode - found ${t}.`);return}const r=this.getEpisodeKey(e);if(this.pendingEpisodes.some(a=>this.getEpisodeKey(a)===r)||this.activeTranscriptions.has(r)){new P.Notice("This episode is already queued or transcribing.");return}this.pendingEpisodes.push(e),new P.Notice(`Queued "${e.title}" for transcription. It will start automatically.`),this.drainQueue()}drainQueue(){for(;this.activeTranscriptions.size<this.MAX_CONCURRENT_TRANSCRIPTIONS&&this.pendingEpisodes.length>0;){const e=this.pendingEpisodes.shift();if(!e)return;const t=this.getEpisodeKey(e);this.activeTranscriptions.add(t),this.transcribeEpisode(e).finally(()=>{this.activeTranscriptions.delete(t),this.drainQueue()})}}getEpisodeKey(e){return`${e.podcastName}:${e.title}`}async transcribeEpisode(e){const t=Pv(`Transcription: ${e.title}`,"Preparing to transcribe...");try{const s=cs(this.plugin.settings.transcript.path,e);if(this.plugin.app.vault.getAbstractFileByPath(s)instanceof P.TFile){t.stop(),t.update(`Transcript already exists - skipped (${s}).`);return}t.update("Downloading episode...");const i=await zg(e,this.plugin.settings.download.path),a=this.plugin.app.vault.getAbstractFileByPath(i);if(!a||!(a instanceof P.TFile))throw new Error("Failed to download or locate the episode.");t.update("Preparing audio for transcription...");const o=await this.plugin.app.vault.readBinary(a),l=a.extension,c=this.getMimeType(l);t.update("Creating audio chunks...");const d=await this.createChunkFiles({buffer:o,basename:a.basename,extension:l,mimeType:c});t.update("Starting transcription...");const u=await this.transcribeChunks(d,t.update);t.update("Saving transcription..."),await this.saveTranscription(e,u),t.stop(),t.update("Transcription completed and saved.")}catch(s){const r=s instanceof Error?s.message:String(s);t.stop(),t.update(`Transcription failed: ${r}`)}finally{t.stop(),setTimeout(()=>t.hide(),5e3)}}async createChunkFiles({buffer:e,basename:t,extension:s,mimeType:r}){if(this.shouldConvertToWav(s,r)){const i=await this.convertToWavChunks(e,t);if(i.length>0)return i}return this.createBinaryChunkFiles(e,t,s,r)}shouldConvertToWav(e,t){return e.toLowerCase()==="m4a"||t==="audio/mp4"}createBinaryChunkFiles(e,t,s,r){if(e.byteLength<=this.CHUNK_SIZE_BYTES)return[new File([e],`${t}.${s}`,{type:r})];const i=[];for(let a=0,o=0;a<e.byteLength;a+=this.CHUNK_SIZE_BYTES,o++){const l=e.slice(a,a+this.CHUNK_SIZE_BYTES);i.push(new File([l],`${t}.part${o}.${s}`,{type:r}))}return i}async convertToWavChunks(e,t){const s=this.createAudioContext();if(!s)return[];try{const r=await s.decodeAudioData(e.slice(0));return this.renderWavChunks(r,t)}catch{return[]}finally{try{await s.close()}catch{}}}createAudioContext(){if(typeof window>"u")return null;const e=window.AudioContext||window.webkitAudioContext;return e?new e:null}renderWavChunks(e,t){const s=e.numberOfChannels,r=s*this.PCM_BYTES_PER_SAMPLE,i=this.CHUNK_SIZE_BYTES-this.WAV_HEADER_SIZE,a=Math.max(1,Math.floor(i/r)),o=Array.from({length:s},(d,u)=>e.getChannelData(u)),l=[];let c=0;for(let d=0;d<e.length;d+=a){const u=Math.min(e.length,d+a),h=this.renderWavBuffer(o,e.sampleRate,d,u);l.push(new File([h],`${t}.part${c}.wav`,{type:"audio/wav"})),c++}return l}renderWavBuffer(e,t,s,r){const i=e.length,a=Math.max(0,r-s),o=i*this.PCM_BYTES_PER_SAMPLE,l=new ArrayBuffer(this.WAV_HEADER_SIZE+a*o),c=new DataView(l);this.writeWavHeader(c,t,i,a);let d=this.WAV_HEADER_SIZE;for(let u=0;u<a;u++)for(let h=0;h<i;h++){const f=e[h][s+u]??0,p=Math.max(-1,Math.min(1,f)),m=p<0?p*32768:p*32767;c.setInt16(d,Math.round(m),!0),d+=this.PCM_BYTES_PER_SAMPLE}return l}writeWavHeader(e,t,s,r){const i=s*this.PCM_BYTES_PER_SAMPLE,a=t*i,o=r*i;this.writeString(e,0,"RIFF"),e.setUint32(4,36+o,!0),this.writeString(e,8,"WAVE"),this.writeString(e,12,"fmt "),e.setUint32(16,16,!0),e.setUint16(20,1,!0),e.setUint16(22,s,!0),e.setUint32(24,t,!0),e.setUint32(28,a,!0),e.setUint16(32,i,!0),e.setUint16(34,this.PCM_BYTES_PER_SAMPLE*8,!0),this.writeString(e,36,"data"),e.setUint32(40,o,!0)}writeString(e,t,s){for(let r=0;r<s.length;r++)e.setUint8(t+r,s.charCodeAt(r))}getMimeType(e){switch(e.toLowerCase()){case"mp3":return"audio/mp3";case"m4a":return"audio/mp4";case"ogg":return"audio/ogg";case"wav":return"audio/wav";case"flac":return"audio/flac";default:return"audio/mpeg"}}async transcribeChunks(e,t){const s=await this.getClient(),r=new Array(e.length);let i=0,a=0;const o=()=>{const u=(i/e.length*100).toFixed(1);t(`Transcribing... ${i}/${e.length} chunks completed (${u}%)`)};o();const l=async()=>{for(;;){const u=a++;if(u>=e.length)return;const h=e[u];let f=0;for(;f<this.MAX_RETRIES;)try{const p=await s.audio.transcriptions.create({model:"whisper-1",file:h});r[u]=p.text,i++,o();break}catch{f++,f>=this.MAX_RETRIES?(r[u]=`[Error transcribing chunk ${u}]`,i++,o()):await new Promise(m=>setTimeout(m,1e3*f))}}},c=Math.min(this.MAX_CONCURRENT_CHUNK_TRANSCRIPTIONS,e.length),d=Array.from({length:c},()=>l());return await Promise.all(d),r.join(" ")}async saveTranscription(e,t){const s=cs(this.plugin.settings.transcript.path,e),r=t.replace(/\.\s+/g,`.
|
||
|
||
`),i=Nm(this.plugin.settings.transcript.template,e,r),a=this.plugin.app.vault,o=s.substring(0,s.lastIndexOf("/"));if(o){const c=o.split("/");let d="";for(const u of c)d=d?`${d}/${u}`:u,a.getAbstractFileByPath(d)||await a.createFolder(d)}const l=a.getAbstractFileByPath(s);if(l)if(l instanceof P.TFile)await this.plugin.app.workspace.getLeaf().openFile(l);else throw new Error("Expected a file but found a folder at transcript path.");else{const c=await a.create(s,i);await this.plugin.app.workspace.getLeaf().openFile(c)}}async getClient(){const e=this.plugin.settings.openAIApiKey?.trim();if(!e)throw new Error("Missing OpenAI API key");if(this.client&&this.cachedApiKey===e)return this.client;const{OpenAI:t}=await Promise.resolve().then(()=>N_);return this.client=new t({apiKey:e,dangerouslyAllowBrowser:!0}),this.cachedApiKey=e,this.client}}class $v extends P.Plugin{constructor(){super(...arguments),this.view=null,this.maxLayoutReadyAttempts=10,this.layoutReadyAttempts=0,this.isReady=!1,this.pendingSave=null,this.saveScheduled=!1,this.saveChain=Promise.resolve()}async onload(){Zt.set(this),await this.loadSettings(),kt.set(this.settings.playedEpisodes),mn.set(this.settings.savedFeeds),Rt.set(this.settings.playlists),Et.set(this.settings.queue),ls.set(this.settings.favorites),Sr.set(this.settings.localFiles),ht.set(this.settings.downloadedEpisodes),this.settings.currentEpisode&&Qe.set(this.settings.currentEpisode),xi.set(this.settings.hidePlayedEpisodes),os.set(Math.min(1,Math.max(0,this.settings.defaultVolume??1))),this.playedEpisodeController=new gv(kt,this).on(),this.savedFeedsController=new vv(mn,this).on(),this.playlistController=new _v(Rt,this).on(),this.queueController=new yv(Et,this).on(),this.favoritesController=new wv(ls,this).on(),this.localFilesController=new Ev(Sr,this).on(),this.downloadedEpisodesController=new kv(ht,this).on(),this.currentEpisodeController=new bv(Qe,this).on(),this.hidePlayedEpisodesController=new xv(xi,this).on(),this.api=new xp,this.volumeUnsubscribe=os.subscribe(e=>{const t=Math.min(1,Math.max(0,e));if(t!==e){os.set(t);return}t!==this.settings.defaultVolume&&(this.settings.defaultVolume=t,this.saveSettings())}),this.addCommand({id:"podnotes-show-leaf",name:"Show PodNotes",icon:"podcast",checkCallback:e=>{if(e)return!this.app.workspace.getLeavesOfType(Wn).length;this.app.workspace.getRightLeaf(!1)?.setViewState({type:Wn})}}),this.addCommand({id:"start-playing",name:"Play Podcast",icon:"play-circle",checkCallback:e=>{if(e)return!this.api.isPlaying&&!!this.api.podcast;this.api.start()}}),this.addCommand({id:"stop-playing",name:"Stop Podcast",icon:"stop-circle",checkCallback:e=>{if(e)return this.api.isPlaying&&!!this.api.podcast;this.api.stop()}}),this.addCommand({id:"skip-backward",name:"Skip Backward",icon:"skip-back",checkCallback:e=>{if(e)return this.api.isPlaying&&!!this.api.podcast;this.api.skipBackward()}}),this.addCommand({id:"skip-forward",name:"Skip Forward",icon:"skip-forward",checkCallback:e=>{if(e)return this.api.isPlaying&&!!this.api.podcast;this.api.skipForward()}}),this.addCommand({id:"download-playing-episode",name:"Download Playing Episode",icon:"download",checkCallback:e=>{if(e)return!!this.api.podcast;const t=this.api.podcast;zu(t,this.settings.download.path)}}),this.addCommand({id:"hrpn",name:"Reload PodNotes",callback:()=>{const e=this.manifest.id;this.app.plugins.disablePlugin(e).then(()=>this.app.plugins.enablePlugin(e))}}),this.addCommand({id:"capture-timestamp",name:"Capture Timestamp",icon:"clock",editorCheckCallback:(e,t,s)=>{if(e)return!!this.api.podcast&&!!this.settings.timestamp.template;const r=t.getCursor(),i=$u(this.settings.timestamp.template);t.replaceRange(i,r),t.setCursor(r.line,r.ch+i.length)}}),this.addCommand({id:"create-podcast-note",name:"Create Podcast Note",icon:"file-plus",checkCallback:e=>{if(e)return!!this.api.podcast&&!!this.settings.note.path&&!!this.settings.note.template;Lu(this.api.podcast)}}),this.addCommand({id:"get-share-link-episode",name:"Copy universal episode link to clipboard",icon:"share",checkCallback:e=>{if(e)return!!this.api.podcast;Cv(this.api)}}),this.addCommand({id:"podnotes-toggle-playback",name:"Toggle playback",icon:"play",checkCallback:e=>{if(e)return!!this.api.podcast;this.api.togglePlayback()}}),this.addCommand({id:"podnotes-transcribe",name:"Transcribe current episode",checkCallback:e=>{const t=!!this.api.podcast&&!!this.settings.openAIApiKey?.trim();if(e)return t;t&&this.getTranscriptionService().transcribeCurrentEpisode()}}),this.addSettingTab(new Km(this.app,this)),this.registerView(Wn,e=>(this.view=new mv(e,this),this.view)),this.app.workspace.onLayoutReady(this.onLayoutReady.bind(this)),this.registerObsidianProtocolHandler("podnotes",e=>Sv(e,this.api)),this.registerEvent(Av(this.app)),this.isReady=!0}onLayoutReady(){if(!this.app.workspace||!this.app.workspace.layoutReady){this.layoutReadyAttempts++,this.layoutReadyAttempts<this.maxLayoutReadyAttempts&&setTimeout(()=>this.onLayoutReady(),100);return}if(this.app.workspace.getLeavesOfType(Wn).length)return;const e=this.app.workspace.getRightLeaf(!1);e&&e.setViewState({type:Wn})}getTranscriptionService(){return this.transcriptionService||(this.transcriptionService=new Iv(this)),this.transcriptionService}onunload(){this.playedEpisodeController?.off(),this.savedFeedsController?.off(),this.playlistController?.off(),this.queueController?.off(),this.favoritesController?.off(),this.localFilesController?.off(),this.downloadedEpisodesController?.off(),this.currentEpisodeController?.off(),this.hidePlayedEpisodesController?.off(),this.volumeUnsubscribe?.(),pu.revokeAll(),this.app.workspace.detachLeavesOfType(Wn)}async loadSettings(){const e=await this.loadData();this.settings=Object.assign({},$l,e),this.settings.timestamp={...$l.timestamp,...e?.timestamp??{}}}async saveSettings(){if(this.isReady)return this.pendingSave=this.cloneSettings(),this.saveScheduled?this.saveChain:(this.saveScheduled=!0,this.saveChain=this.saveChain.then(async()=>{for(;this.pendingSave;){const e=this.pendingSave;this.pendingSave=null,await this.saveData(e)}}).catch(e=>{}).finally(()=>{this.saveScheduled=!1,this.pendingSave&&this.saveSettings()}),this.saveChain)}cloneSettings(){return typeof structuredClone=="function"?structuredClone(this.settings):JSON.parse(JSON.stringify(this.settings))}}function V(n,e,t,s,r){if(typeof e=="function"?n!==e||!0:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(n,t),t}function w(n,e,t,s){if(t==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!s:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?s:t==="a"?s.call(n):s?s.value:e.get(n)}let Wu=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return Wu=n.randomUUID.bind(n),n.randomUUID();const e=new Uint8Array(1),t=n?()=>n.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^t()&15>>+s/4).toString(16))};function to(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const no=n=>{if(n instanceof Error)return n;if(typeof n=="object"&&n!==null){try{if(Object.prototype.toString.call(n)==="[object Error]"){const e=new Error(n.message,n.cause?{cause:n.cause}:{});return n.stack&&(e.stack=n.stack),n.cause&&!e.cause&&(e.cause=n.cause),n.name&&(e.name=n.name),e}}catch{}try{return new Error(JSON.stringify(n))}catch{}}return new Error(n)};class j extends Error{}class Me extends j{constructor(e,t,s,r){super(`${Me.makeMessage(e,t,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=t;const i=t;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,t,s){const r=t?.message?typeof t.message=="string"?t.message:JSON.stringify(t.message):t?JSON.stringify(t):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,t,s,r){if(!e||!r)return new Lr({message:s,cause:no(t)});const i=t?.error;return e===400?new Fo(e,i,s,r):e===401?new No(e,i,s,r):e===403?new Oo(e,i,s,r):e===404?new Do(e,i,s,r):e===409?new Lo(e,i,s,r):e===422?new Bo(e,i,s,r):e===429?new Uo(e,i,s,r):e>=500?new jo(e,i,s,r):new Me(e,i,s,r)}}class dt extends Me{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Lr extends Me{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class Gi extends Lr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class Fo extends Me{}class No extends Me{}class Oo extends Me{}class Do extends Me{}class Lo extends Me{}class Bo extends Me{}class Uo extends Me{}class jo extends Me{}class Hu extends j{constructor(){super("Could not parse response content as the length limit was reached")}}class Vu extends j{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class $s extends Error{constructor(e){super(e)}}const Rv=/^[a-z][a-z0-9+.-]*:/i,Mv=n=>Rv.test(n);let et=n=>(et=Array.isArray,et(n)),Ul=et;function Yu(n){return typeof n!="object"?{}:n??{}}function Fv(n){if(!n)return!0;for(const e in n)return!1;return!0}function Nv(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function ba(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const Ov=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new j(`${n} must be an integer`);if(e<0)throw new j(`${n} must be a positive integer`);return e},Dv=n=>{try{return JSON.parse(n)}catch{return}},Br=n=>new Promise(e=>setTimeout(e,n)),As="6.9.1",Lv=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function Bv(){return typeof Deno<"u"&&Deno.build!=null?"deno":typeof EdgeRuntime<"u"?"edge":Object.prototype.toString.call(typeof globalThis.process<"u"?globalThis.process:0)==="[object process]"?"node":"unknown"}const Uv=()=>{const n=Bv();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":As,"X-Stainless-OS":zl(Deno.build.os),"X-Stainless-Arch":jl(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:Deno.version?.deno??"unknown"};if(typeof EdgeRuntime<"u")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":As,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(n==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":As,"X-Stainless-OS":zl(globalThis.process.platform??"unknown"),"X-Stainless-Arch":jl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=jv();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":As,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":As,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function jv(){if(typeof navigator>"u"||!navigator)return null;const n=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(const{key:e,pattern:t}of n){const s=t.exec(navigator.userAgent);if(s){const r=s[1]||0,i=s[2]||0,a=s[3]||0;return{browser:e,version:`${r}.${i}.${a}`}}}return null}const jl=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",zl=n=>(n=n.toLowerCase(),n.includes("ios")?"iOS":n==="android"?"Android":n==="darwin"?"MacOS":n==="win32"?"Windows":n==="freebsd"?"FreeBSD":n==="openbsd"?"OpenBSD":n==="linux"?"Linux":n?`Other:${n}`:"Unknown");let ql;const zv=()=>ql??(ql=Uv());function qv(){if(typeof fetch<"u")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ku(...n){const e=globalThis.ReadableStream;if(typeof e>"u")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...n)}function Ju(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return Ku({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function Xu(n){if(n[Symbol.asyncIterator])return n;const e=n.getReader();return{async next(){try{const t=await e.read();return t?.done&&e.releaseLock(),t}catch(t){throw e.releaseLock(),t}},async return(){const t=e.cancel();return e.releaseLock(),await t,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function Wv(n){if(n===null||typeof n!="object")return;if(n[Symbol.asyncIterator]){await n[Symbol.asyncIterator]().return?.();return}const e=n.getReader(),t=e.cancel();e.releaseLock(),await t}const Hv=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Gu="RFC3986",Qu=n=>String(n),Wl={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:Qu},Vv="RFC1738";let so=(n,e)=>(so=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),so(n,e));const Lt=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),xa=1024,Yv=(n,e,t,s,r)=>{if(n.length===0)return n;let i=n;if(typeof n=="symbol"?i=Symbol.prototype.toString.call(n):typeof n!="string"&&(i=String(n)),t==="iso-8859-1")return escape(i).replace(/%u[0-9a-f]{4}/gi,function(o){return"%26%23"+parseInt(o.slice(2),16)+"%3B"});let a="";for(let o=0;o<i.length;o+=xa){const l=i.length>=xa?i.slice(o,o+xa):i,c=[];for(let d=0;d<l.length;++d){let u=l.charCodeAt(d);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||r===Vv&&(u===40||u===41)){c[c.length]=l.charAt(d);continue}if(u<128){c[c.length]=Lt[u];continue}if(u<2048){c[c.length]=Lt[192|u>>6]+Lt[128|u&63];continue}if(u<55296||u>=57344){c[c.length]=Lt[224|u>>12]+Lt[128|u>>6&63]+Lt[128|u&63];continue}d+=1,u=65536+((u&1023)<<10|l.charCodeAt(d)&1023),c[c.length]=Lt[240|u>>18]+Lt[128|u>>12&63]+Lt[128|u>>6&63]+Lt[128|u&63]}a+=c.join("")}return a};function Kv(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function Hl(n,e){if(et(n)){const t=[];for(let s=0;s<n.length;s+=1)t.push(e(n[s]));return t}return e(n)}const Zu={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},ed=function(n,e){Array.prototype.push.apply(n,et(e)?e:[e])};let Vl;const Ae={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Yv,encodeValuesOnly:!1,format:Gu,formatter:Qu,indices:!1,serializeDate(n){return(Vl??(Vl=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function Jv(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const ka={};function td(n,e,t,s,r,i,a,o,l,c,d,u,h,f,p,m,v,_){let y=n,b=_,E=0,C=!1;for(;(b=b.get(ka))!==void 0&&!C;){const $=b.get(n);if(E+=1,typeof $<"u"){if($===E)throw new RangeError("Cyclic object value");C=!0}typeof b.get(ka)>"u"&&(E=0)}if(typeof c=="function"?y=c(e,y):y instanceof Date?y=h?.(y):t==="comma"&&et(y)&&(y=Hl(y,function($){return $ instanceof Date?h?.($):$})),y===null){if(i)return l&&!m?l(e,Ae.encoder,v,"key",f):e;y=""}if(Jv(y)||Kv(y)){if(l){const $=m?e:l(e,Ae.encoder,v,"key",f);return[p?.($)+"="+p?.(l(y,Ae.encoder,v,"value",f))]}return[p?.(e)+"="+p?.(String(y))]}const F=[];if(typeof y>"u")return F;let x;if(t==="comma"&&et(y))m&&l&&(y=Hl(y,l)),x=[{value:y.length>0?y.join(",")||null:void 0}];else if(et(c))x=c;else{const $=Object.keys(y);x=d?$.sort(d):$}const A=o?String(e).replace(/\./g,"%2E"):String(e),I=s&&et(y)&&y.length===1?A+"[]":A;if(r&&et(y)&&y.length===0)return I+"[]";for(let $=0;$<x.length;++$){const D=x[$],G=typeof D=="object"&&typeof D.value<"u"?D.value:y[D];if(a&&G===null)continue;const ye=u&&o?D.replace(/\./g,"%2E"):D,ce=et(y)?typeof t=="function"?t(I,ye):I:I+(u?"."+ye:"["+ye+"]");_.set(n,E);const Ee=new WeakMap;Ee.set(ka,_),ed(F,td(G,ce,t,s,r,i,a,o,t==="comma"&&m&&et(y)?null:l,c,d,u,h,f,p,m,v,Ee))}return F}function Xv(n=Ae){if(typeof n.allowEmptyArrays<"u"&&typeof n.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof n.encodeDotInKeys<"u"&&typeof n.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(n.encoder!==null&&typeof n.encoder<"u"&&typeof n.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=n.charset||Ae.charset;if(typeof n.charset<"u"&&n.charset!=="utf-8"&&n.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let t=Gu;if(typeof n.format<"u"){if(!so(Wl,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const s=Wl[t];let r=Ae.filter;(typeof n.filter=="function"||et(n.filter))&&(r=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in Zu?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=Ae.arrayFormat,"commaRoundTrip"in n&&typeof n.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof n.allowDots>"u"?n.encodeDotInKeys?!0:Ae.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:Ae.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:Ae.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:Ae.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?Ae.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:Ae.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:Ae.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:Ae.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:Ae.encodeValuesOnly,filter:r,format:t,formatter:s,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:Ae.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:Ae.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:Ae.strictNullHandling}}function Gv(n,e={}){let t=n;const s=Xv(e);let r,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):et(s.filter)&&(i=s.filter,r=i);const a=[];if(typeof t!="object"||t===null)return"";const o=Zu[s.arrayFormat],l=o==="comma"&&s.commaRoundTrip;r||(r=Object.keys(t)),s.sort&&r.sort(s.sort);const c=new WeakMap;for(let h=0;h<r.length;++h){const f=r[h];s.skipNulls&&t[f]===null||ed(a,td(t[f],f,o,l,s.allowEmptyArrays,s.strictNullHandling,s.skipNulls,s.encodeDotInKeys,s.encode?s.encoder:null,s.filter,s.sort,s.allowDots,s.serializeDate,s.format,s.formatter,s.encodeValuesOnly,s.charset,c))}const d=a.join(s.delimiter);let u=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),d.length>0?u+d:""}function Qv(n){let e=0;for(const r of n)e+=r.length;const t=new Uint8Array(e);let s=0;for(const r of n)t.set(r,s),s+=r.length;return t}let Yl;function zo(n){let e;return(Yl??(e=new globalThis.TextEncoder,Yl=e.encode.bind(e)))(n)}let Kl;function Jl(n){let e;return(Kl??(e=new globalThis.TextDecoder,Kl=e.decode.bind(e)))(n)}var it,at;class Qi{constructor(){it.set(this,void 0),at.set(this,void 0),V(this,it,new Uint8Array),V(this,at,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?zo(e):e;V(this,it,Qv([w(this,it,"f"),t]));const s=[];let r;for(;(r=Zv(w(this,it,"f"),w(this,at,"f")))!=null;){if(r.carriage&&w(this,at,"f")==null){V(this,at,r.index);continue}if(w(this,at,"f")!=null&&(r.index!==w(this,at,"f")+1||r.carriage)){s.push(Jl(w(this,it,"f").subarray(0,w(this,at,"f")-1))),V(this,it,w(this,it,"f").subarray(w(this,at,"f"))),V(this,at,null);continue}const i=w(this,at,"f")!==null?r.preceding-1:r.preceding,a=Jl(w(this,it,"f").subarray(0,i));s.push(a),V(this,it,w(this,it,"f").subarray(r.index)),V(this,at,null)}return s}flush(){return w(this,it,"f").length?this.decode(`
|
||
`):[]}}it=new WeakMap,at=new WeakMap;Qi.NEWLINE_CHARS=new Set([`
|
||
`,"\r"]);Qi.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Zv(n,e){for(let r=e??0;r<n.length;r++){if(n[r]===10)return{preceding:r,index:r+1,carriage:!1};if(n[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function e_(n){for(let s=0;s<n.length-1;s++){if(n[s]===10&&n[s+1]===10||n[s]===13&&n[s+1]===13)return s+2;if(n[s]===13&&n[s+1]===10&&s+3<n.length&&n[s+2]===13&&n[s+3]===10)return s+4}return-1}const Ai={off:0,error:200,warn:300,info:400,debug:500},Xl=(n,e,t)=>{if(n){if(Nv(Ai,n))return n;Oe(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Ai))}`)}};function ar(){}function Xr(n,e,t){return!e||Ai[n]>Ai[t]?ar:e[n].bind(e)}const t_={error:ar,warn:ar,info:ar,debug:ar};let Gl=new WeakMap;function Oe(n){const e=n.logger,t=n.logLevel??"off";if(!e)return t_;const s=Gl.get(e);if(s&&s[0]===t)return s[1];const r={error:Xr("error",e,t),warn:Xr("warn",e,t),info:Xr("info",e,t),debug:Xr("debug",e,t)};return Gl.set(e,[t,r]),r}const Hn=n=>(n.options&&(n.options={...n.options},delete n.options.headers),n.headers&&(n.headers=Object.fromEntries((n.headers instanceof Headers?[...n.headers]:Object.entries(n.headers)).map(([e,t])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":t]))),"retryOfRequestLogID"in n&&(n.retryOfRequestLogID&&(n.retryOf=n.retryOfRequestLogID),delete n.retryOfRequestLogID),n);var sr;class Xt{constructor(e,t,s){this.iterator=e,sr.set(this,void 0),this.controller=t,V(this,sr,s)}static fromSSEResponse(e,t,s){let r=!1;const i=s?Oe(s):console;async function*a(){if(r)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of n_(e,t))if(!o){if(l.data.startsWith("[DONE]")){o=!0;continue}if(l.event===null||!l.event.startsWith("thread.")){let c;try{c=JSON.parse(l.data)}catch(d){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),d}if(c&&c.error)throw new Me(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(l.data)}catch(d){throw d}if(l.event=="error")throw new Me(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}o=!0}catch(l){if(to(l))return;throw l}finally{o||t.abort()}}return new Xt(a,t,s)}static fromReadableStream(e,t,s){let r=!1;async function*i(){const o=new Qi,l=Xu(e);for await(const c of l)for(const d of o.decode(c))yield d;for(const c of o.flush())yield c}async function*a(){if(r)throw new j("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of i())o||l&&(yield JSON.parse(l));o=!0}catch(l){if(to(l))return;throw l}finally{o||t.abort()}}return new Xt(a,t,s)}[(sr=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],t=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const a=s.next();e.push(a),t.push(a)}return i.shift()}});return[new Xt(()=>r(e),this.controller,w(this,sr,"f")),new Xt(()=>r(t),this.controller,w(this,sr,"f"))]}toReadableStream(){const e=this;let t;return Ku({async start(){t=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await t.next();if(i)return s.close();const a=zo(JSON.stringify(r)+`
|
||
`);s.enqueue(a)}catch(r){s.error(r)}},async cancel(){await t.return?.()}})}}async function*n_(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new j("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new j("Attempted to iterate over a response with no body");const t=new r_,s=new Qi,r=Xu(n.body);for await(const i of s_(r))for(const a of s.decode(i)){const o=t.decode(a);o&&(yield o)}for(const i of s.flush()){const a=t.decode(i);a&&(yield a)}}async function*s_(n){let e=new Uint8Array;for await(const t of n){if(t==null)continue;const s=t instanceof ArrayBuffer?new Uint8Array(t):typeof t=="string"?zo(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=e_(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class r_{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;const i={event:this.event,data:this.data.join(`
|
||
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],i}if(this.chunks.push(e),e.startsWith(":"))return null;let[t,s,r]=i_(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function i_(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function nd(n,e){const{response:t,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Oe(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):Xt.fromSSEResponse(t,e.controller,n);if(t.status===204)return null;if(e.options.__binaryResponse)return t;const l=t.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const u=await t.json();return sd(u,t)}return await t.text()})();return Oe(n).debug(`[${s}] response parsed`,Hn({retryOfRequestLogID:r,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function sd(n,e){return!n||typeof n!="object"||Array.isArray(n)?n:Object.defineProperty(n,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var or;class Ur extends Promise{constructor(e,t,s=nd){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=s,or.set(this,void 0),V(this,or,e)}_thenUnwrap(e){return new Ur(w(this,or,"f"),this.responsePromise,async(t,s)=>sd(e(await this.parseResponse(t,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(w(this,or,"f"),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}or=new WeakMap;var Gr;class qo{constructor(e,t,s,r){Gr.set(this,void 0),V(this,Gr,e),this.options=r,this.response=t,this.body=s}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){const e=this.nextPageRequestOptions();if(!e)throw new j("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,Gr,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Gr=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class rd extends Ur{constructor(e,t,s){super(e,t,async(r,i)=>new s(r,i.response,await nd(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class Zi extends qo{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class ke extends qo{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Yu(this.options.query),after:t}}:null}}class Ci extends qo{constructor(e,t,s,r){super(e,t,s,r),this.data=s.data||[],this.has_more=s.has_more||!1,this.last_id=s.last_id||""}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){const e=this.last_id;return e?{...this.options,query:{...Yu(this.options.query),after:e}}:null}}const id=()=>{if(typeof File>"u"){const{process:n}=globalThis,e=typeof n?.versions?.node=="string"&&parseInt(n.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(e?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function _r(n,e,t){return id(),new File(n,e??"unknown_file",t)}function ai(n){return(typeof n=="object"&&n!==null&&("name"in n&&n.name&&String(n.name)||"url"in n&&n.url&&String(n.url)||"filename"in n&&n.filename&&String(n.filename)||"path"in n&&n.path&&String(n.path))||"").split(/[\\/]/).pop()||void 0}const Wo=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",Ql=async(n,e)=>ro(n.body)?{...n,body:await ad(n.body,e)}:n,fs=async(n,e)=>({...n,body:await ad(n.body,e)}),Zl=new WeakMap;function a_(n){const e=typeof n=="function"?n:n.fetch,t=Zl.get(e);if(t)return t;const s=(async()=>{try{const r="Response"in e?e.Response:(await e("data:,")).constructor,i=new FormData;return i.toString()!==await new r(i).text()}catch{return!0}})();return Zl.set(e,s),s}const ad=async(n,e)=>{if(!await a_(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const t=new FormData;return await Promise.all(Object.entries(n||{}).map(([s,r])=>io(t,s,r))),t},od=n=>n instanceof Blob&&"name"in n,o_=n=>typeof n=="object"&&n!==null&&(n instanceof Response||Wo(n)||od(n)),ro=n=>{if(o_(n))return!0;if(Array.isArray(n))return n.some(ro);if(n&&typeof n=="object"){for(const e in n)if(ro(n[e]))return!0}return!1},io=async(n,e,t)=>{if(t!==void 0){if(t==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t=="string"||typeof t=="number"||typeof t=="boolean")n.append(e,String(t));else if(t instanceof Response)n.append(e,_r([await t.blob()],ai(t)));else if(Wo(t))n.append(e,_r([await new Response(Ju(t)).blob()],ai(t)));else if(od(t))n.append(e,t,ai(t));else if(Array.isArray(t))await Promise.all(t.map(s=>io(n,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,r])=>io(n,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}},ld=n=>n!=null&&typeof n=="object"&&typeof n.size=="number"&&typeof n.type=="string"&&typeof n.text=="function"&&typeof n.slice=="function"&&typeof n.arrayBuffer=="function",l_=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&ld(n),c_=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function cd(n,e,t){if(id(),n=await n,l_(n))return n instanceof File?n:_r([await n.arrayBuffer()],n.name);if(c_(n)){const r=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),_r(await ao(r),e,t)}const s=await ao(n);if(e||(e=ai(n)),!t?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return _r(s,e,t)}async function ao(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(ld(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(Wo(n))for await(const t of n)e.push(...await ao(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${u_(n)}`)}return e}function u_(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class U{constructor(e){this._client=e}}function ud(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const ec=Object.freeze(Object.create(null)),d_=(n=ud)=>function(t,...s){if(t.length===1)return t[0];let r=!1;const i=[],a=t.reduce((d,u,h)=>{/[?#]/.test(u)&&(r=!0);const f=s[h];let p=(r?encodeURIComponent:n)(""+f);return h!==s.length&&(f==null||typeof f=="object"&&f.toString===Object.getPrototypeOf(Object.getPrototypeOf(f.hasOwnProperty??ec)??ec)?.toString)&&(p=f+"",i.push({start:d.length+u.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(f).slice(8,-1)} is not a valid path parameter`})),d+u+(h===s.length?"":p)},""),o=a.split(/[?#]/,1)[0],l=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi;let c;for(;(c=l.exec(o))!==null;)i.push({start:c.index,length:c[0].length,error:`Value "${c[0]}" can't be safely passed as a path parameter`});if(i.sort((d,u)=>d.start-u.start),i.length>0){let d=0;const u=i.reduce((h,f)=>{const p=" ".repeat(f.start-d),m="^".repeat(f.length);return d=f.start+f.length,h+p+m},"");throw new j(`Path parameters result in path with invalid segments:
|
||
${i.map(h=>h.error).join(`
|
||
`)}
|
||
${a}
|
||
${u}`)}return a},S=d_(ud);let dd=class extends U{list(e,t={},s){return this._client.getAPIList(S`/chat/completions/${e}/messages`,ke,{query:t,...s})}};function Pi(n){return n!==void 0&&"function"in n&&n.function!==void 0}function Ho(n){return n?.$brand==="auto-parseable-response-format"}function jr(n){return n?.$brand==="auto-parseable-tool"}function f_(n,e){return!e||!fd(e)?{...n,choices:n.choices.map(t=>(hd(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:Vo(n,e)}function Vo(n,e){const t=n.choices.map(s=>{if(s.finish_reason==="length")throw new Hu;if(s.finish_reason==="content_filter")throw new Vu;return hd(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>p_(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?h_(e,s.message.content):null}}});return{...n,choices:t}}function h_(n,e){return n.response_format?.type!=="json_schema"?null:n.response_format?.type==="json_schema"?"$parseRaw"in n.response_format?n.response_format.$parseRaw(e):JSON.parse(e):null}function p_(n,e){const t=n.tools?.find(s=>Pi(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:jr(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function m_(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(s=>Pi(s)&&s.function?.name===e.function.name);return Pi(t)&&(jr(t)||t?.function.strict||!1)}function fd(n){return Ho(n.response_format)?!0:n.tools?.some(e=>jr(e)||e.type==="function"&&e.function.strict===!0)??!1}function hd(n){for(const e of n||[])if(e.type!=="function")throw new j(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function g_(n){for(const e of n??[]){if(e.type!=="function")throw new j(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new j(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Ti=n=>n?.role==="assistant",pd=n=>n?.role==="tool";var oo,oi,li,lr,cr,ci,ur,on,dr,Ii,$i,Cs,md;class Yo{constructor(){oo.add(this),this.controller=new AbortController,oi.set(this,void 0),li.set(this,()=>{}),lr.set(this,()=>{}),cr.set(this,void 0),ci.set(this,()=>{}),ur.set(this,()=>{}),on.set(this,{}),dr.set(this,!1),Ii.set(this,!1),$i.set(this,!1),Cs.set(this,!1),V(this,oi,new Promise((e,t)=>{V(this,li,e,"f"),V(this,lr,t,"f")})),V(this,cr,new Promise((e,t)=>{V(this,ci,e,"f"),V(this,ur,t,"f")})),w(this,oi,"f").catch(()=>{}),w(this,cr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,oo,"m",md).bind(this))},0)}_connected(){this.ended||(w(this,li,"f").call(this),this._emit("connect"))}get ended(){return w(this,dr,"f")}get errored(){return w(this,Ii,"f")}get aborted(){return w(this,$i,"f")}abort(){this.controller.abort()}on(e,t){return(w(this,on,"f")[e]||(w(this,on,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=w(this,on,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===t);return r>=0&&s.splice(r,1),this}once(e,t){return(w(this,on,"f")[e]||(w(this,on,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{V(this,Cs,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){V(this,Cs,!0),await w(this,cr,"f")}_emit(e,...t){if(w(this,dr,"f"))return;e==="end"&&(V(this,dr,!0),w(this,ci,"f").call(this));const s=w(this,on,"f")[e];if(s&&(w(this,on,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!w(this,Cs,"f")&&!s?.length&&Promise.reject(r),w(this,lr,"f").call(this,r),w(this,ur,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!w(this,Cs,"f")&&!s?.length&&Promise.reject(r),w(this,lr,"f").call(this,r),w(this,ur,"f").call(this,r),this._emit("end")}}_emitFinal(){}}oi=new WeakMap,li=new WeakMap,lr=new WeakMap,cr=new WeakMap,ci=new WeakMap,ur=new WeakMap,on=new WeakMap,dr=new WeakMap,Ii=new WeakMap,$i=new WeakMap,Cs=new WeakMap,oo=new WeakSet,md=function(e){if(V(this,Ii,!0),e instanceof Error&&e.name==="AbortError"&&(e=new dt),e instanceof dt)return V(this,$i,!0),this._emit("abort",e);if(e instanceof j)return this._emit("error",e);if(e instanceof Error){const t=new j(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new j(String(e)))};function v_(n){return typeof n.parse=="function"}var Ke,lo,Ri,co,uo,fo,gd,vd;const __=10;class _d extends Yo{constructor(){super(...arguments),Ke.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if("content"in e||(e.content=null),this.messages.push(e),t){if(this._emit("message",e),pd(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Ti(e)&&e.tool_calls)for(const s of e.tool_calls)s.type==="function"&&this._emit("functionToolCall",s.function)}}async finalChatCompletion(){await this.done();const e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new j("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),w(this,Ke,"m",lo).call(this)}async finalMessage(){return await this.done(),w(this,Ke,"m",Ri).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,Ke,"m",co).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,Ke,"m",uo).call(this)}async totalUsage(){return await this.done(),w(this,Ke,"m",fo).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=w(this,Ke,"m",Ri).call(this);t&&this._emit("finalMessage",t);const s=w(this,Ke,"m",lo).call(this);s&&this._emit("finalContent",s);const r=w(this,Ke,"m",co).call(this);r&&this._emit("finalFunctionToolCall",r);const i=w(this,Ke,"m",uo).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",w(this,Ke,"m",fo).call(this))}async _createChatCompletion(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),w(this,Ke,"m",gd).call(this,t);const i=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Vo(i,t))}async _runChatCompletion(e,t,s){for(const r of t.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,t,s)}async _runTools(e,t,s){const r="tool",{tool_choice:i="auto",stream:a,...o}=t,l=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:c=__}=s||{},d=t.tools.map(f=>{if(jr(f)){if(!f.$callback)throw new j("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:f.$callback,name:f.function.name,description:f.function.description||"",parameters:f.function.parameters,parse:f.$parseRaw,strict:!0}}}return f}),u={};for(const f of d)f.type==="function"&&(u[f.function.name||f.function.function.name]=f.function);const h="tools"in t?d.map(f=>f.type==="function"?{type:"function",function:{name:f.function.name||f.function.function.name,parameters:f.function.parameters,description:f.function.description,strict:f.function.strict}}:f):void 0;for(const f of t.messages)this._addMessage(f,!1);for(let f=0;f<c;++f){const m=(await this._createChatCompletion(e,{...o,tool_choice:i,tools:h,messages:[...this.messages]},s)).choices[0]?.message;if(!m)throw new j("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const v of m.tool_calls){if(v.type!=="function")continue;const _=v.id,{name:y,arguments:b}=v.function,E=u[y];if(E){if(l&&l!==y){const A=`Invalid tool_call: ${JSON.stringify(y)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:_,content:A});continue}}else{const A=`Invalid tool_call: ${JSON.stringify(y)}. Available options are: ${Object.keys(u).map(I=>JSON.stringify(I)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:_,content:A});continue}let C;try{C=v_(E)?await E.parse(b):b}catch(A){const I=A instanceof Error?A.message:String(A);this._addMessage({role:r,tool_call_id:_,content:I});continue}const F=await E.function(C,this),x=w(this,Ke,"m",vd).call(this,F);if(this._addMessage({role:r,tool_call_id:_,content:x}),l)return}}}}Ke=new WeakSet,lo=function(){return w(this,Ke,"m",Ri).call(this).content??null},Ri=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Ti(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new j("stream ended without producing a ChatCompletionMessage with role=assistant")},co=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ti(t)&&t?.tool_calls?.length)return t.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},uo=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(pd(t)&&t.content!=null&&typeof t.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===t.tool_call_id)))return t.content}},fo=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},gd=function(e){if(e.n!=null&&e.n>1)throw new j("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},vd=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Ko extends _d{static runTools(e,t,s){const r=new Ko,i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}_addMessage(e,t=!0){super._addMessage(e,t),Ti(e)&&e.content&&this._emit("content",e.content)}}const yd=1,wd=2,bd=4,xd=8,kd=16,Ed=32,Sd=64,Ad=128,Cd=256,Pd=Ad|Cd,Td=kd|Ed|Pd|Sd,Id=yd|wd|Td,$d=bd|xd,y_=Id|$d,$e={STR:yd,NUM:wd,ARR:bd,OBJ:xd,NULL:kd,BOOL:Ed,NAN:Sd,INFINITY:Ad,MINUS_INFINITY:Cd,INF:Pd,SPECIAL:Td,ATOM:Id,COLLECTION:$d,ALL:y_};class w_ extends Error{}class b_ extends Error{}function x_(n,e=$e.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return k_(n.trim(),e)}const k_=(n,e)=>{const t=n.length;let s=0;const r=h=>{throw new w_(`${h} at position ${s}`)},i=h=>{throw new b_(`${h} at position ${s}`)},a=()=>(u(),s>=t&&r("Unexpected end of input"),n[s]==='"'?o():n[s]==="{"?l():n[s]==="["?c():n.substring(s,s+4)==="null"||$e.NULL&e&&t-s<4&&"null".startsWith(n.substring(s))?(s+=4,null):n.substring(s,s+4)==="true"||$e.BOOL&e&&t-s<4&&"true".startsWith(n.substring(s))?(s+=4,!0):n.substring(s,s+5)==="false"||$e.BOOL&e&&t-s<5&&"false".startsWith(n.substring(s))?(s+=5,!1):n.substring(s,s+8)==="Infinity"||$e.INFINITY&e&&t-s<8&&"Infinity".startsWith(n.substring(s))?(s+=8,1/0):n.substring(s,s+9)==="-Infinity"||$e.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(n.substring(s))?(s+=9,-1/0):n.substring(s,s+3)==="NaN"||$e.NAN&e&&t-s<3&&"NaN".startsWith(n.substring(s))?(s+=3,NaN):d()),o=()=>{const h=s;let f=!1;for(s++;s<t&&(n[s]!=='"'||f&&n[s-1]==="\\");)f=n[s]==="\\"?!f:!1,s++;if(n.charAt(s)=='"')try{return JSON.parse(n.substring(h,++s-Number(f)))}catch(p){i(String(p))}else if($e.STR&e)try{return JSON.parse(n.substring(h,s-Number(f))+'"')}catch{return JSON.parse(n.substring(h,n.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{s++,u();const h={};try{for(;n[s]!=="}";){if(u(),s>=t&&$e.OBJ&e)return h;const f=o();u(),s++;try{const p=a();Object.defineProperty(h,f,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if($e.OBJ&e)return h;throw p}u(),n[s]===","&&s++}}catch{if($e.OBJ&e)return h;r("Expected '}' at end of object")}return s++,h},c=()=>{s++;const h=[];try{for(;n[s]!=="]";)h.push(a()),u(),n[s]===","&&s++}catch{if($e.ARR&e)return h;r("Expected ']' at end of array")}return s++,h},d=()=>{if(s===0){n==="-"&&$e.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if($e.NUM&e)try{return n[n.length-1]==="."?JSON.parse(n.substring(0,n.lastIndexOf("."))):JSON.parse(n.substring(0,n.lastIndexOf("e")))}catch{}i(String(f))}}const h=s;for(n[s]==="-"&&s++;n[s]&&!",]}".includes(n[s]);)s++;s==t&&!($e.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(n.substring(h,s))}catch{n.substring(h,s)==="-"&&$e.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n.substring(h,n.lastIndexOf("e")))}catch(p){i(String(p))}}},u=()=>{for(;s<t&&`
|
||
\r `.includes(n[s]);)s++};return a()},tc=n=>x_(n,$e.ALL^$e.NUM);var Se,an,ks,Cn,Ea,Qr,Sa,Aa,Ca,Zr,Pa,nc;class Pr extends _d{constructor(e){super(),Se.add(this),an.set(this,void 0),ks.set(this,void 0),Cn.set(this,void 0),V(this,an,e),V(this,ks,[])}get currentChatCompletionSnapshot(){return w(this,Cn,"f")}static fromReadableStream(e){const t=new Pr(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const r=new Pr(t);return r._run(()=>r._runChatCompletion(e,{...t,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,t,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),w(this,Se,"m",Ea).call(this);const i=await e.chat.completions.create({...t,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const a of i)w(this,Se,"m",Sa).call(this,a);if(i.controller.signal?.aborted)throw new dt;return this._addChatCompletion(w(this,Se,"m",Zr).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,Se,"m",Ea).call(this),this._connected();const r=Xt.fromReadableStream(e,this.controller);let i;for await(const a of r)i&&i!==a.id&&this._addChatCompletion(w(this,Se,"m",Zr).call(this)),w(this,Se,"m",Sa).call(this,a),i=a.id;if(r.controller.signal?.aborted)throw new dt;return this._addChatCompletion(w(this,Se,"m",Zr).call(this))}[(an=new WeakMap,ks=new WeakMap,Cn=new WeakMap,Se=new WeakSet,Ea=function(){this.ended||V(this,Cn,void 0)},Qr=function(t){let s=w(this,ks,"f")[t.index];return s||(s={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},w(this,ks,"f")[t.index]=s,s)},Sa=function(t){if(this.ended)return;const s=w(this,Se,"m",nc).call(this,t);this._emit("chunk",t,s);for(const r of t.choices){const i=s.choices[r.index];r.delta.content!=null&&i.message?.role==="assistant"&&i.message?.content&&(this._emit("content",r.delta.content,i.message.content),this._emit("content.delta",{delta:r.delta.content,snapshot:i.message.content,parsed:i.message.parsed})),r.delta.refusal!=null&&i.message?.role==="assistant"&&i.message?.refusal&&this._emit("refusal.delta",{delta:r.delta.refusal,snapshot:i.message.refusal}),r.logprobs?.content!=null&&i.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:r.logprobs?.content,snapshot:i.logprobs?.content??[]}),r.logprobs?.refusal!=null&&i.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:r.logprobs?.refusal,snapshot:i.logprobs?.refusal??[]});const a=w(this,Se,"m",Qr).call(this,i);i.finish_reason&&(w(this,Se,"m",Ca).call(this,i),a.current_tool_call_index!=null&&w(this,Se,"m",Aa).call(this,i,a.current_tool_call_index));for(const o of r.delta.tool_calls??[])a.current_tool_call_index!==o.index&&(w(this,Se,"m",Ca).call(this,i),a.current_tool_call_index!=null&&w(this,Se,"m",Aa).call(this,i,a.current_tool_call_index)),a.current_tool_call_index=o.index;for(const o of r.delta.tool_calls??[]){const l=i.message.tool_calls?.[o.index];l?.type&&(l?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:l.function?.name,index:o.index,arguments:l.function.arguments,parsed_arguments:l.function.parsed_arguments,arguments_delta:o.function?.arguments??""}):(l?.type,void 0))}}},Aa=function(t,s){if(w(this,Se,"m",Qr).call(this,t).done_tool_calls.has(s))return;const i=t.message.tool_calls?.[s];if(!i)throw new Error("no tool call snapshot");if(!i.type)throw new Error("tool call snapshot missing `type`");if(i.type==="function"){const a=w(this,an,"f")?.tools?.find(o=>Pi(o)&&o.function.name===i.function.name);this._emit("tool_calls.function.arguments.done",{name:i.function.name,index:s,arguments:i.function.arguments,parsed_arguments:jr(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},Ca=function(t){const s=w(this,Se,"m",Qr).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;const r=w(this,Se,"m",Pa).call(this);this._emit("content.done",{content:t.message.content,parsed:r?r.$parseRaw(t.message.content):null})}t.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:t.message.refusal})),t.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:t.logprobs.content})),t.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:t.logprobs.refusal}))},Zr=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");const t=w(this,Cn,"f");if(!t)throw new j("request ended without sending any chunks");return V(this,Cn,void 0),V(this,ks,[]),E_(t,w(this,an,"f"))},Pa=function(){const t=w(this,an,"f")?.response_format;return Ho(t)?t:null},nc=function(t){var s,r,i,a;let o=w(this,Cn,"f");const{choices:l,...c}=t;o?Object.assign(o,c):o=V(this,Cn,{...c,choices:[]});for(const{delta:d,finish_reason:u,index:h,logprobs:f=null,...p}of t.choices){let m=o.choices[h];if(m||(m=o.choices[h]={finish_reason:u,index:h,message:{},logprobs:f,...p}),f)if(!m.logprobs)m.logprobs=Object.assign({},f);else{const{content:F,refusal:x,...A}=f;Object.assign(m.logprobs,A),F&&((s=m.logprobs).content??(s.content=[]),m.logprobs.content.push(...F)),x&&((r=m.logprobs).refusal??(r.refusal=[]),m.logprobs.refusal.push(...x))}if(u&&(m.finish_reason=u,w(this,an,"f")&&fd(w(this,an,"f")))){if(u==="length")throw new Hu;if(u==="content_filter")throw new Vu}if(Object.assign(m,p),!d)continue;const{content:v,refusal:_,function_call:y,role:b,tool_calls:E,...C}=d;if(Object.assign(m.message,C),_&&(m.message.refusal=(m.message.refusal||"")+_),b&&(m.message.role=b),y&&(m.message.function_call?(y.name&&(m.message.function_call.name=y.name),y.arguments&&((i=m.message.function_call).arguments??(i.arguments=""),m.message.function_call.arguments+=y.arguments)):m.message.function_call=y),v&&(m.message.content=(m.message.content||"")+v,!m.message.refusal&&w(this,Se,"m",Pa).call(this)&&(m.message.parsed=tc(m.message.content))),E){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:F,id:x,type:A,function:I,...$}of E){const D=(a=m.message.tool_calls)[F]??(a[F]={});Object.assign(D,$),x&&(D.id=x),A&&(D.type=A),I&&(D.function??(D.function={name:I.name??"",arguments:""})),I?.name&&(D.function.name=I.name),I?.arguments&&(D.function.arguments+=I.arguments,m_(w(this,an,"f"),D)&&(D.function.parsed_arguments=tc(D.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("chunk",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new Xt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function E_(n,e){const{id:t,choices:s,created:r,model:i,system_fingerprint:a,...o}=n,l={...o,id:t,choices:s.map(({message:c,finish_reason:d,index:u,logprobs:h,...f})=>{if(!d)throw new j(`missing finish_reason for choice ${u}`);const{content:p=null,function_call:m,tool_calls:v,..._}=c,y=c.role;if(!y)throw new j(`missing role for choice ${u}`);if(m){const{arguments:b,name:E}=m;if(b==null)throw new j(`missing function_call.arguments for choice ${u}`);if(!E)throw new j(`missing function_call.name for choice ${u}`);return{...f,message:{content:p,function_call:{arguments:b,name:E},role:y,refusal:c.refusal??null},finish_reason:d,index:u,logprobs:h}}return v?{...f,index:u,finish_reason:d,logprobs:h,message:{..._,role:y,content:p,refusal:c.refusal??null,tool_calls:v.map((b,E)=>{const{function:C,type:F,id:x,...A}=b,{arguments:I,name:$,...D}=C||{};if(x==null)throw new j(`missing choices[${u}].tool_calls[${E}].id
|
||
${ei(n)}`);if(F==null)throw new j(`missing choices[${u}].tool_calls[${E}].type
|
||
${ei(n)}`);if($==null)throw new j(`missing choices[${u}].tool_calls[${E}].function.name
|
||
${ei(n)}`);if(I==null)throw new j(`missing choices[${u}].tool_calls[${E}].function.arguments
|
||
${ei(n)}`);return{...A,id:x,type:F,function:{...D,name:$,arguments:I}}})}}:{...f,message:{..._,content:p,role:y,refusal:c.refusal??null},finish_reason:d,index:u,logprobs:h}}),created:r,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return f_(l,e)}function ei(n){return JSON.stringify(n)}class Mi extends Pr{static fromReadableStream(e){const t=new Mi(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const r=new Mi(t),i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}}let Jo=class extends U{constructor(){super(...arguments),this.messages=new dd(this._client)}create(e,t){return this._client.post("/chat/completions",{body:e,...t,stream:e.stream??!1})}retrieve(e,t){return this._client.get(S`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(S`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",ke,{query:e,...t})}delete(e,t){return this._client.delete(S`/chat/completions/${e}`,t)}parse(e,t){return g_(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>Vo(s,e))}runTools(e,t){return e.stream?Mi.runTools(this._client,e,t):Ko.runTools(this._client,e,t)}stream(e,t){return Pr.createChatCompletion(this._client,e,t)}};Jo.Messages=dd;class Xo extends U{constructor(){super(...arguments),this.completions=new Jo(this._client)}}Xo.Completions=Jo;const Rd=Symbol("brand.privateNullableHeaders");function*S_(n){if(!n)return;if(Rd in n){const{values:s,nulls:r}=n;yield*s.entries();for(const i of r)yield[i,null];return}let e=!1,t;n instanceof Headers?t=n.entries():Ul(n)?t=n:(e=!0,t=Object.entries(n??{}));for(let s of t){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=Ul(s[1])?s[1]:[s[1]];let a=!1;for(const o of i)o!==void 0&&(e&&!a&&(a=!0,yield[r,null]),yield[r,o])}}const N=n=>{const e=new Headers,t=new Set;for(const s of n){const r=new Set;for(const[i,a]of S_(s)){const o=i.toLowerCase();r.has(o)||(e.delete(i),r.add(o)),a===null?(e.delete(i),t.add(o)):(e.append(i,a),t.delete(o))}}return{[Rd]:!0,values:e,nulls:t}};class Md extends U{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:N([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Fd extends U{create(e,t){return this._client.post("/audio/transcriptions",fs({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Nd extends U{create(e,t){return this._client.post("/audio/translations",fs({body:e,...t,__metadata:{model:e.model}},this._client))}}class zr extends U{constructor(){super(...arguments),this.transcriptions=new Fd(this._client),this.translations=new Nd(this._client),this.speech=new Md(this._client)}}zr.Transcriptions=Fd;zr.Translations=Nd;zr.Speech=Md;class Od extends U{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(S`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",ke,{query:e,...t})}cancel(e,t){return this._client.post(S`/batches/${e}/cancel`,t)}}class Dd extends U{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(S`/assistants/${e}`,{...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(S`/assistants/${e}`,{body:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",ke,{query:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(S`/assistants/${e}`,{...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let Ld=class extends U{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class Bd extends U{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let ea=class extends U{constructor(){super(...arguments),this.sessions=new Ld(this._client),this.transcriptionSessions=new Bd(this._client)}};ea.Sessions=Ld;ea.TranscriptionSessions=Bd;class Ud extends U{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:N([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(S`/chatkit/sessions/${e}/cancel`,{...t,headers:N([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let jd=class extends U{retrieve(e,t){return this._client.get(S`/chatkit/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Ci,{query:e,...t,headers:N([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(S`/chatkit/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},s){return this._client.getAPIList(S`/chatkit/threads/${e}/items`,Ci,{query:t,...s,headers:N([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class ta extends U{constructor(){super(...arguments),this.sessions=new Ud(this._client),this.threads=new jd(this._client)}}ta.Sessions=Ud;ta.Threads=jd;class zd extends U{create(e,t,s){return this._client.post(S`/threads/${e}/messages`,{body:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(S`/threads/${r}/messages/${e}`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(S`/threads/${r}/messages/${e}`,{body:i,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(S`/threads/${e}/messages`,ke,{query:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:r}=t;return this._client.delete(S`/threads/${r}/messages/${e}`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class qd extends U{retrieve(e,t,s){const{thread_id:r,run_id:i,...a}=t;return this._client.get(S`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:r,...i}=t;return this._client.getAPIList(S`/threads/${r}/runs/${e}/steps`,ke,{query:i,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const A_=n=>{if(typeof Buffer<"u"){const e=Buffer.from(n,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(n),t=e.length,s=new Uint8Array(t);for(let r=0;r<t;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}},Es=n=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[n]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(n)?.trim()};var Le,Gn,ho,jt,ui,Tt,Qn,Rs,Yn,Fi,lt,di,fi,yr,fr,hr,sc,rc,ic,ac,oc,lc,cc;class wr extends Yo{constructor(){super(...arguments),Le.add(this),ho.set(this,[]),jt.set(this,{}),ui.set(this,{}),Tt.set(this,void 0),Qn.set(this,void 0),Rs.set(this,void 0),Yn.set(this,void 0),Fi.set(this,void 0),lt.set(this,void 0),di.set(this,void 0),fi.set(this,void 0),yr.set(this,void 0)}[(ho=new WeakMap,jt=new WeakMap,ui=new WeakMap,Tt=new WeakMap,Qn=new WeakMap,Rs=new WeakMap,Yn=new WeakMap,Fi=new WeakMap,lt=new WeakMap,di=new WeakMap,fi=new WeakMap,yr=new WeakMap,Le=new WeakSet,Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){const t=new Gn;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=Xt.fromReadableStream(e,this.controller);for await(const i of r)w(this,Le,"m",fr).call(this,i);if(r.controller.signal?.aborted)throw new dt;return this._addRun(w(this,Le,"m",hr).call(this))}toReadableStream(){return new Xt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r){const i=new Gn;return i._run(()=>i._runToolAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},o=await e.submitToolOutputs(t,a,{...r,signal:this.controller.signal});this._connected();for await(const l of o)w(this,Le,"m",fr).call(this,l);if(o.controller.signal?.aborted)throw new dt;return this._addRun(w(this,Le,"m",hr).call(this))}static createThreadAssistantStream(e,t,s){const r=new Gn;return r._run(()=>r._threadAssistantStream(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,t,s,r){const i=new Gn;return i._run(()=>i._runAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return w(this,di,"f")}currentRun(){return w(this,fi,"f")}currentMessageSnapshot(){return w(this,Tt,"f")}currentRunStepSnapshot(){return w(this,yr,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,jt,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,ui,"f"))}async finalRun(){if(await this.done(),!w(this,Qn,"f"))throw Error("Final run was not received.");return w(this,Qn,"f")}async _createThreadAssistantStream(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...t,stream:!0},a=await e.createAndRun(i,{...s,signal:this.controller.signal});this._connected();for await(const o of a)w(this,Le,"m",fr).call(this,o);if(a.controller.signal?.aborted)throw new dt;return this._addRun(w(this,Le,"m",hr).call(this))}async _createAssistantStream(e,t,s,r){const i=r?.signal;i&&(i.aborted&&this.controller.abort(),i.addEventListener("abort",()=>this.controller.abort()));const a={...s,stream:!0},o=await e.create(t,a,{...r,signal:this.controller.signal});this._connected();for await(const l of o)w(this,Le,"m",fr).call(this,l);if(o.controller.signal?.aborted)throw new dt;return this._addRun(w(this,Le,"m",hr).call(this))}static accumulateDelta(e,t){for(const[s,r]of Object.entries(t)){if(!e.hasOwnProperty(s)){e[s]=r;continue}let i=e[s];if(i==null){e[s]=r;continue}if(s==="index"||s==="type"){e[s]=r;continue}if(typeof i=="string"&&typeof r=="string")i+=r;else if(typeof i=="number"&&typeof r=="number")i+=r;else if(ba(i)&&ba(r))i=this.accumulateDelta(i,r);else if(Array.isArray(i)&&Array.isArray(r)){if(i.every(a=>typeof a=="string"||typeof a=="number")){i.push(...r);continue}for(const a of r){if(!ba(a))throw new Error(`Expected array delta entry to be an object but got: ${a}`);const o=a.index;if(o==null)throw new Error("Expected array delta entry to have an `index` property");if(typeof o!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${o}`);const l=i[o];l==null?i.push(a):i[o]=this.accumulateDelta(l,a)}continue}else throw Error(`Unhandled record type: ${s}, deltaValue: ${r}, accValue: ${i}`);e[s]=i}return e}_addRun(e){return e}async _threadAssistantStream(e,t,s){return await this._createThreadAssistantStream(t,e,s)}async _runAssistantStream(e,t,s,r){return await this._createAssistantStream(t,e,s,r)}async _runToolAssistantStream(e,t,s,r){return await this._createToolAssistantStream(t,e,s,r)}}Gn=wr,fr=function(e){if(!this.ended)switch(V(this,di,e),w(this,Le,"m",ic).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":w(this,Le,"m",cc).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":w(this,Le,"m",rc).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":w(this,Le,"m",sc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},hr=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");if(!w(this,Qn,"f"))throw Error("Final run has not been received");return w(this,Qn,"f")},sc=function(e){const[t,s]=w(this,Le,"m",oc).call(this,e,w(this,Tt,"f"));V(this,Tt,t),w(this,ui,"f")[t.id]=t;for(const r of s){const i=t.content[r.index];i?.type=="text"&&this._emit("textCreated",i.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,t),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let i=r.text,a=t.content[r.index];if(a&&a.type=="text")this._emit("textDelta",i,a.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(r.index!=w(this,Rs,"f")){if(w(this,Yn,"f"))switch(w(this,Yn,"f").type){case"text":this._emit("textDone",w(this,Yn,"f").text,w(this,Tt,"f"));break;case"image_file":this._emit("imageFileDone",w(this,Yn,"f").image_file,w(this,Tt,"f"));break}V(this,Rs,r.index)}V(this,Yn,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,Rs,"f")!==void 0){const r=e.data.content[w(this,Rs,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,w(this,Tt,"f"));break;case"text":this._emit("textDone",r.text,w(this,Tt,"f"));break}}w(this,Tt,"f")&&this._emit("messageDone",e.data),V(this,Tt,void 0)}},rc=function(e){const t=w(this,Le,"m",ac).call(this,e);switch(V(this,yr,t),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":const s=e.data.delta;if(s.step_details&&s.step_details.type=="tool_calls"&&s.step_details.tool_calls&&t.step_details.type=="tool_calls")for(const i of s.step_details.tool_calls)i.index==w(this,Fi,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(w(this,lt,"f")&&this._emit("toolCallDone",w(this,lt,"f")),V(this,Fi,i.index),V(this,lt,t.step_details.tool_calls[i.index]),w(this,lt,"f")&&this._emit("toolCallCreated",w(this,lt,"f")));this._emit("runStepDelta",e.data.delta,t);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":V(this,yr,void 0),e.data.step_details.type=="tool_calls"&&w(this,lt,"f")&&(this._emit("toolCallDone",w(this,lt,"f")),V(this,lt,void 0)),this._emit("runStepDone",e.data,t);break}},ic=function(e){w(this,ho,"f").push(e),this._emit("event",e)},ac=function(e){switch(e.event){case"thread.run.step.created":return w(this,jt,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=w(this,jt,"f")[e.data.id];if(!t)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=Gn.accumulateDelta(t,s.delta);w(this,jt,"f")[e.data.id]=r}return w(this,jt,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":w(this,jt,"f")[e.data.id]=e.data;break}if(w(this,jt,"f")[e.data.id])return w(this,jt,"f")[e.data.id];throw new Error("No snapshot available")},oc=function(e,t){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!t)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let r=e.data;if(r.delta.content)for(const i of r.delta.content)if(i.index in t.content){let a=t.content[i.index];t.content[i.index]=w(this,Le,"m",lc).call(this,i,a)}else t.content[i.index]=i,s.push(i);return[t,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(t)return[t,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},lc=function(e,t){return Gn.accumulateDelta(t,e)},cc=function(e){switch(V(this,fi,e.data),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":V(this,Qn,e.data),w(this,lt,"f")&&(this._emit("toolCallDone",w(this,lt,"f")),V(this,lt,void 0));break}};let Go=class extends U{constructor(){super(...arguments),this.steps=new qd(this._client)}create(e,t,s){const{include:r,...i}=t;return this._client.post(S`/threads/${e}/runs`,{query:{include:r},body:i,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(S`/threads/${r}/runs/${e}`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(S`/threads/${r}/runs/${e}`,{body:i,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(S`/threads/${e}/runs`,ke,{query:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:r}=t;return this._client.post(S`/threads/${r}/runs/${e}/cancel`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,t,s){return wr.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r=N([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(e,t,{...s,headers:{...s?.headers,...r}}).withResponse();switch(i.status){case"queued":case"in_progress":case"cancelling":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const l=a.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Br(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,s){return wr.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:r,...i}=t;return this._client.post(S`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}async submitToolOutputsAndPoll(e,t,s){const r=await this.submitToolOutputs(e,t,s);return await this.poll(r.id,t,s)}submitToolOutputsStream(e,t,s){return wr.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};Go.Steps=qd;class na extends U{constructor(){super(...arguments),this.runs=new Go(this._client),this.messages=new zd(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(S`/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(S`/threads/${e}`,{body:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(S`/threads/${e}`,{...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,t){const s=await this.createAndRun(e,t);return await this.runs.poll(s.id,{thread_id:s.thread_id},t)}createAndRunStream(e,t){return wr.createThreadAssistantStream(e,this._client.beta.threads,t)}}na.Runs=Go;na.Messages=zd;class Zs extends U{constructor(){super(...arguments),this.realtime=new ea(this._client),this.chatkit=new ta(this._client),this.assistants=new Dd(this._client),this.threads=new na(this._client)}}Zs.Realtime=ea;Zs.ChatKit=ta;Zs.Assistants=Dd;Zs.Threads=na;class Wd extends U{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class Hd extends U{retrieve(e,t,s){const{container_id:r}=t;return this._client.get(S`/containers/${r}/files/${e}/content`,{...s,headers:N([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let Qo=class extends U{constructor(){super(...arguments),this.content=new Hd(this._client)}create(e,t,s){return this._client.post(S`/containers/${e}/files`,fs({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:r}=t;return this._client.get(S`/containers/${r}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(S`/containers/${e}/files`,ke,{query:t,...s})}delete(e,t,s){const{container_id:r}=t;return this._client.delete(S`/containers/${r}/files/${e}`,{...s,headers:N([{Accept:"*/*"},s?.headers])})}};Qo.Content=Hd;class Zo extends U{constructor(){super(...arguments),this.files=new Qo(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(S`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",ke,{query:e,...t})}delete(e,t){return this._client.delete(S`/containers/${e}`,{...t,headers:N([{Accept:"*/*"},t?.headers])})}}Zo.Files=Qo;class Vd extends U{create(e,t,s){const{include:r,...i}=t;return this._client.post(S`/conversations/${e}/items`,{query:{include:r},body:i,...s})}retrieve(e,t,s){const{conversation_id:r,...i}=t;return this._client.get(S`/conversations/${r}/items/${e}`,{query:i,...s})}list(e,t={},s){return this._client.getAPIList(S`/conversations/${e}/items`,Ci,{query:t,...s})}delete(e,t,s){const{conversation_id:r}=t;return this._client.delete(S`/conversations/${r}/items/${e}`,s)}}class el extends U{constructor(){super(...arguments),this.items=new Vd(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(S`/conversations/${e}`,t)}update(e,t,s){return this._client.post(S`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(S`/conversations/${e}`,t)}}el.Items=Vd;class Yd extends U{create(e,t){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&Oe(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:r},...t});return s?i:(Oe(this._client).debug("embeddings/decoding base64 embeddings from base64"),i._thenUnwrap(a=>(a&&a.data&&a.data.forEach(o=>{const l=o.embedding;o.embedding=A_(l)}),a)))}}class Kd extends U{retrieve(e,t,s){const{eval_id:r,run_id:i}=t;return this._client.get(S`/evals/${r}/runs/${i}/output_items/${e}`,s)}list(e,t,s){const{eval_id:r,...i}=t;return this._client.getAPIList(S`/evals/${r}/runs/${e}/output_items`,ke,{query:i,...s})}}class tl extends U{constructor(){super(...arguments),this.outputItems=new Kd(this._client)}create(e,t,s){return this._client.post(S`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:r}=t;return this._client.get(S`/evals/${r}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(S`/evals/${e}/runs`,ke,{query:t,...s})}delete(e,t,s){const{eval_id:r}=t;return this._client.delete(S`/evals/${r}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:r}=t;return this._client.post(S`/evals/${r}/runs/${e}`,s)}}tl.OutputItems=Kd;class nl extends U{constructor(){super(...arguments),this.runs=new tl(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(S`/evals/${e}`,t)}update(e,t,s){return this._client.post(S`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",ke,{query:e,...t})}delete(e,t){return this._client.delete(S`/evals/${e}`,t)}}nl.Runs=tl;let Jd=class extends U{create(e,t){return this._client.post("/files",fs({body:e,...t},this._client))}retrieve(e,t){return this._client.get(S`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",ke,{query:e,...t})}delete(e,t){return this._client.delete(S`/files/${e}`,t)}content(e,t){return this._client.get(S`/files/${e}/content`,{...t,headers:N([{Accept:"application/binary"},t?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:s=1800*1e3}={}){const r=new Set(["processed","error","deleted"]),i=Date.now();let a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Br(t),a=await this.retrieve(e),Date.now()-i>s)throw new Gi({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};class Xd extends U{}let Gd=class extends U{run(e,t){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...t})}validate(e,t){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...t})}};class sl extends U{constructor(){super(...arguments),this.graders=new Gd(this._client)}}sl.Graders=Gd;class Qd extends U{create(e,t,s){return this._client.getAPIList(S`/fine_tuning/checkpoints/${e}/permissions`,Zi,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(S`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(S`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let rl=class extends U{constructor(){super(...arguments),this.permissions=new Qd(this._client)}};rl.Permissions=Qd;class Zd extends U{list(e,t={},s){return this._client.getAPIList(S`/fine_tuning/jobs/${e}/checkpoints`,ke,{query:t,...s})}}class il extends U{constructor(){super(...arguments),this.checkpoints=new Zd(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(S`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",ke,{query:e,...t})}cancel(e,t){return this._client.post(S`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(S`/fine_tuning/jobs/${e}/events`,ke,{query:t,...s})}pause(e,t){return this._client.post(S`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(S`/fine_tuning/jobs/${e}/resume`,t)}}il.Checkpoints=Zd;class er extends U{constructor(){super(...arguments),this.methods=new Xd(this._client),this.jobs=new il(this._client),this.checkpoints=new rl(this._client),this.alpha=new sl(this._client)}}er.Methods=Xd;er.Jobs=il;er.Checkpoints=rl;er.Alpha=sl;class ef extends U{}class al extends U{constructor(){super(...arguments),this.graderModels=new ef(this._client)}}al.GraderModels=ef;class tf extends U{createVariation(e,t){return this._client.post("/images/variations",fs({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",fs({body:e,...t,stream:e.stream??!1},this._client))}generate(e,t){return this._client.post("/images/generations",{body:e,...t,stream:e.stream??!1})}}class nf extends U{retrieve(e,t){return this._client.get(S`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",Zi,e)}delete(e,t){return this._client.delete(S`/models/${e}`,t)}}class sf extends U{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class rf extends U{accept(e,t,s){return this._client.post(S`/realtime/calls/${e}/accept`,{body:t,...s,headers:N([{Accept:"*/*"},s?.headers])})}hangup(e,t){return this._client.post(S`/realtime/calls/${e}/hangup`,{...t,headers:N([{Accept:"*/*"},t?.headers])})}refer(e,t,s){return this._client.post(S`/realtime/calls/${e}/refer`,{body:t,...s,headers:N([{Accept:"*/*"},s?.headers])})}reject(e,t={},s){return this._client.post(S`/realtime/calls/${e}/reject`,{body:t,...s,headers:N([{Accept:"*/*"},s?.headers])})}}class af extends U{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class sa extends U{constructor(){super(...arguments),this.clientSecrets=new af(this._client),this.calls=new rf(this._client)}}sa.ClientSecrets=af;sa.Calls=rf;function C_(n,e){return!e||!T_(e)?{...n,output_parsed:null,output:n.output.map(t=>t.type==="function_call"?{...t,parsed_arguments:null}:t.type==="message"?{...t,content:t.content.map(s=>({...s,parsed:null}))}:t)}:of(n,e)}function of(n,e){const t=n.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:R_(e,r)};if(r.type==="message"){const i=r.content.map(a=>a.type==="output_text"?{...a,parsed:P_(e,a.text)}:a);return{...r,content:i}}return r}),s=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||po(s),Object.defineProperty(s,"output_parsed",{enumerable:!0,get(){for(const r of s.output)if(r.type==="message"){for(const i of r.content)if(i.type==="output_text"&&i.parsed!==null)return i.parsed}return null}}),s}function P_(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function T_(n){return!!Ho(n.text?.format)}function I_(n){return n?.$brand==="auto-parseable-tool"}function $_(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function R_(n,e){const t=$_(n.tools??[],e.name);return{...e,...e,parsed_arguments:I_(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function po(n){const e=[];for(const t of n.output)if(t.type==="message")for(const s of t.content)s.type==="output_text"&&e.push(s.text);n.output_text=e.join("")}var Ss,ti,Pn,ni,uc,dc,fc,hc;class ol extends Yo{constructor(e){super(),Ss.add(this),ti.set(this,void 0),Pn.set(this,void 0),ni.set(this,void 0),V(this,ti,e)}static createResponse(e,t,s){const r=new ol(t);return r._run(()=>r._createOrRetrieveResponse(e,t,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,t,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),w(this,Ss,"m",uc).call(this);let i,a=null;"response_id"in t?(i=await e.responses.retrieve(t.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),a=t.starting_after??null):i=await e.responses.create({...t,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const o of i)w(this,Ss,"m",dc).call(this,o,a);if(i.controller.signal?.aborted)throw new dt;return w(this,Ss,"m",fc).call(this)}[(ti=new WeakMap,Pn=new WeakMap,ni=new WeakMap,Ss=new WeakSet,uc=function(){this.ended||V(this,Pn,void 0)},dc=function(t,s){if(this.ended)return;const r=(a,o)=>{(s==null||o.sequence_number>s)&&this._emit(a,o)},i=w(this,Ss,"m",hc).call(this,t);switch(r("event",t),t.type){case"response.output_text.delta":{const a=i.output[t.output_index];if(!a)throw new j(`missing output at index ${t.output_index}`);if(a.type==="message"){const o=a.content[t.content_index];if(!o)throw new j(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new j(`expected content to be 'output_text', got ${o.type}`);r("response.output_text.delta",{...t,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const a=i.output[t.output_index];if(!a)throw new j(`missing output at index ${t.output_index}`);a.type==="function_call"&&r("response.function_call_arguments.delta",{...t,snapshot:a.arguments});break}default:r(t.type,t);break}},fc=function(){if(this.ended)throw new j("stream has ended, this shouldn't happen");const t=w(this,Pn,"f");if(!t)throw new j("request ended without sending any events");V(this,Pn,void 0);const s=M_(t,w(this,ti,"f"));return V(this,ni,s),s},hc=function(t){let s=w(this,Pn,"f");if(!s){if(t.type!=="response.created")throw new j(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=V(this,Pn,t.response),s}switch(t.type){case"response.output_item.added":{s.output.push(t.item);break}case"response.content_part.added":{const r=s.output[t.output_index];if(!r)throw new j(`missing output at index ${t.output_index}`);const i=r.type,a=t.part;i==="message"&&a.type!=="reasoning_text"?r.content.push(a):i==="reasoning"&&a.type==="reasoning_text"&&(r.content||(r.content=[]),r.content.push(a));break}case"response.output_text.delta":{const r=s.output[t.output_index];if(!r)throw new j(`missing output at index ${t.output_index}`);if(r.type==="message"){const i=r.content[t.content_index];if(!i)throw new j(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new j(`expected content to be 'output_text', got ${i.type}`);i.text+=t.delta}break}case"response.function_call_arguments.delta":{const r=s.output[t.output_index];if(!r)throw new j(`missing output at index ${t.output_index}`);r.type==="function_call"&&(r.arguments+=t.delta);break}case"response.reasoning_text.delta":{const r=s.output[t.output_index];if(!r)throw new j(`missing output at index ${t.output_index}`);if(r.type==="reasoning"){const i=r.content?.[t.content_index];if(!i)throw new j(`missing content at index ${t.content_index}`);if(i.type!=="reasoning_text")throw new j(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=t.delta}break}case"response.completed":{V(this,Pn,t.response);break}}return s},Symbol.asyncIterator)](){const e=[],t=[];let s=!1;return this.on("event",r=>{const i=t.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of t)r.resolve(void 0);t.length=0}),this.on("abort",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),this.on("error",r=>{s=!0;for(const i of t)i.reject(r);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>t.push({resolve:i,reject:a})).then(i=>i?{value:i,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();const e=w(this,ni,"f");if(!e)throw new j("stream ended without producing a ChatCompletion");return e}}function M_(n,e){return C_(n,e)}class lf extends U{list(e,t={},s){return this._client.getAPIList(S`/responses/${e}/input_items`,ke,{query:t,...s})}}class cf extends U{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class ra extends U{constructor(){super(...arguments),this.inputItems=new lf(this._client),this.inputTokens=new cf(this._client)}create(e,t){return this._client.post("/responses",{body:e,...t,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&po(s),s))}retrieve(e,t={},s){return this._client.get(S`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&po(r),r))}delete(e,t){return this._client.delete(S`/responses/${e}`,{...t,headers:N([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>of(s,e))}stream(e,t){return ol.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(S`/responses/${e}/cancel`,t)}}ra.InputItems=lf;ra.InputTokens=cf;class uf extends U{create(e,t,s){return this._client.post(S`/uploads/${e}/parts`,fs({body:t,...s},this._client))}}class ll extends U{constructor(){super(...arguments),this.parts=new uf(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(S`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(S`/uploads/${e}/complete`,{body:t,...s})}}ll.Parts=uf;const F_=async n=>{const e=await Promise.allSettled(n),t=e.filter(r=>r.status==="rejected");if(t.length){for(const r of t);throw new Error(`${t.length} promise(s) failed - see the above errors`)}const s=[];for(const r of e)r.status==="fulfilled"&&s.push(r.value);return s};class df extends U{create(e,t,s){return this._client.post(S`/vector_stores/${e}/file_batches`,{body:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(S`/vector_stores/${r}/file_batches/${e}`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:r}=t;return this._client.post(S`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t);return await this.poll(e,r.id,s)}listFiles(e,t,s){const{vector_store_id:r,...i}=t;return this._client.getAPIList(S`/vector_stores/${r}/file_batches/${e}/files`,ke,{query:i,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const r=N([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse();switch(i.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const l=a.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Br(o);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:t,fileIds:s=[]},r){if(t==null||t.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");const i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,l=t.values(),c=[...s];async function d(h){for(let f of h){const p=await o.files.create({file:f,purpose:"assistants"},r);c.push(p.id)}}const u=Array(a).fill(l).map(d);return await F_(u),await this.createAndPoll(e,{file_ids:c})}}class ff extends U{create(e,t,s){return this._client.post(S`/vector_stores/${e}/files`,{body:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(S`/vector_stores/${r}/files/${e}`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:r,...i}=t;return this._client.post(S`/vector_stores/${r}/files/${e}`,{body:i,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(S`/vector_stores/${e}/files`,ke,{query:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:r}=t;return this._client.delete(S`/vector_stores/${r}/files/${e}`,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,t,s){const r=await this.create(e,t,s);return await this.poll(e,r.id,s)}async poll(e,t,s){const r=N([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const i=await this.retrieve(t,{vector_store_id:e},{...s,headers:r}).withResponse(),a=i.data;switch(a.status){case"in_progress":let o=5e3;if(s?.pollIntervalMs)o=s.pollIntervalMs;else{const l=i.response.headers.get("openai-poll-after-ms");if(l){const c=parseInt(l);isNaN(c)||(o=c)}}await Br(o);break;case"failed":case"completed":return a}}}async upload(e,t,s){const r=await this._client.files.create({file:t,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,t,s){const r=await this.upload(e,t,s);return await this.poll(e,r.id,s)}content(e,t,s){const{vector_store_id:r}=t;return this._client.getAPIList(S`/vector_stores/${r}/files/${e}/content`,Zi,{...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class ia extends U{constructor(){super(...arguments),this.files=new ff(this._client),this.fileBatches=new df(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(S`/vector_stores/${e}`,{...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(S`/vector_stores/${e}`,{body:t,...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",ke,{query:e,...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(S`/vector_stores/${e}`,{...t,headers:N([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(S`/vector_stores/${e}/search`,Zi,{body:t,method:"post",...s,headers:N([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}ia.Files=ff;ia.FileBatches=df;class hf extends U{create(e,t){return this._client.post("/videos",Ql({body:e,...t},this._client))}retrieve(e,t){return this._client.get(S`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Ci,{query:e,...t})}delete(e,t){return this._client.delete(S`/videos/${e}`,t)}downloadContent(e,t={},s){return this._client.get(S`/videos/${e}/content`,{query:t,...s,headers:N([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,t,s){return this._client.post(S`/videos/${e}/remix`,Ql({body:t,...s},this._client))}}var Ps,pf,hi;class mf extends U{constructor(){super(...arguments),Ps.add(this)}async unwrap(e,t,s=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,s,r),JSON.parse(e)}async verifySignature(e,t,s=this._client.webhookSecret,r=300){if(typeof crypto>"u"||typeof crypto.subtle.importKey!="function"||typeof crypto.subtle.verify!="function")throw new Error("Webhook signature verification is only supported when the `crypto` global is defined");w(this,Ps,"m",pf).call(this,s);const i=N([t]).values,a=w(this,Ps,"m",hi).call(this,i,"webhook-signature"),o=w(this,Ps,"m",hi).call(this,i,"webhook-timestamp"),l=w(this,Ps,"m",hi).call(this,i,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new $s("Invalid webhook timestamp format");const d=Math.floor(Date.now()/1e3);if(d-c>r)throw new $s("Webhook timestamp is too old");if(c>d+r)throw new $s("Webhook timestamp is too new");const u=a.split(" ").map(m=>m.startsWith("v1,")?m.substring(3):m),h=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),f=l?`${l}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey("raw",h,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const m of u)try{const v=Buffer.from(m,"base64");if(await crypto.subtle.verify("HMAC",p,v,new TextEncoder().encode(f)))return}catch{continue}throw new $s("The given webhook signature does not match the expected signature")}}Ps=new WeakSet,pf=function(e){if(typeof e!="string"||e.length===0)throw new Error("The webhook secret must either be set using the env var, OPENAI_WEBHOOK_SECRET, on the client class, OpenAI({ webhookSecret: '123' }), or passed to this function")},hi=function(e,t){if(!e)throw new Error("Headers are required");const s=e.get(t);if(s==null)throw new Error(`Missing required header: ${t}`);return s};var mo,cl,pi,gf;class Q{constructor({baseURL:e=Es("OPENAI_BASE_URL"),apiKey:t=Es("OPENAI_API_KEY"),organization:s=Es("OPENAI_ORG_ID")??null,project:r=Es("OPENAI_PROJECT_ID")??null,webhookSecret:i=Es("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(mo.add(this),pi.set(this,void 0),this.completions=new Wd(this),this.chat=new Xo(this),this.embeddings=new Yd(this),this.files=new Jd(this),this.images=new tf(this),this.audio=new zr(this),this.moderations=new sf(this),this.models=new nf(this),this.fineTuning=new er(this),this.graders=new al(this),this.vectorStores=new ia(this),this.webhooks=new mf(this),this.beta=new Zs(this),this.batches=new Od(this),this.uploads=new ll(this),this.responses=new ra(this),this.realtime=new sa(this),this.conversations=new el(this),this.evals=new nl(this),this.containers=new Zo(this),this.videos=new hf(this),t===void 0)throw new j("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:t,organization:s,project:r,webhookSecret:i,...a,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&Lv())throw new j(`It looks like you're running in a browser-like environment.
|
||
|
||
This is disabled by default, as it risks exposing your secret API credentials to attackers.
|
||
If you understand the risks and have appropriate mitigations in place,
|
||
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
|
||
|
||
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
|
||
|
||
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
|
||
`);this.baseURL=o.baseURL,this.timeout=o.timeout??cl.DEFAULT_TIMEOUT,this.logger=o.logger??console;const l="warn";this.logLevel=l,this.logLevel=Xl(o.logLevel,"ClientOptions.logLevel",this)??Xl(Es("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??qv(),V(this,pi,Hv),this._options=o,this.apiKey=typeof t=="string"?t:"Missing Key",this.organization=s,this.project=r,this.webhookSecret=i}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t}){}async authHeaders(e){return N([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Gv(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${As}`}defaultIdempotencyKey(){return`stainless-node-retry-${Wu()}`}makeStatusError(e,t,s,r){return Me.generate(e,t,s,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let t;try{t=await e()}catch(s){throw s instanceof j?s:new j(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new j(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,s){const r=!w(this,mo,"m",gf).call(this)&&s||this.baseURL,i=Mv(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return Fv(a)||(t={...a,...t}),typeof t=="object"&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:t,options:s}){}get(e,t){return this.methodRequest("get",e,t)}post(e,t){return this.methodRequest("post",e,t)}patch(e,t){return this.methodRequest("patch",e,t)}put(e,t){return this.methodRequest("put",e,t)}delete(e,t){return this.methodRequest("delete",e,t)}methodRequest(e,t,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:t,...r})))}request(e,t=null){return new Ur(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,s){const r=await e,i=r.maxRetries??this.maxRetries;t==null&&(t=i),await this.prepareOptions(r);const{req:a,url:o,timeout:l}=await this.buildRequest(r,{retryCount:i-t});await this.prepareRequest(a,{url:o,options:r});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),d=s===void 0?"":`, retryOf: ${s}`,u=Date.now();if(Oe(this).debug(`[${c}] sending request`,Hn({retryOfRequestLogID:s,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new dt;const h=new AbortController,f=await this.fetchWithTimeout(o,a,l,h).catch(no),p=Date.now();if(f instanceof globalThis.Error){const _=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new dt;const y=to(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return Oe(this).info(`[${c}] connection ${y?"timed out":"failed"} - ${_}`),Oe(this).debug(`[${c}] connection ${y?"timed out":"failed"} (${_})`,Hn({retryOfRequestLogID:s,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,s??c);throw Oe(this).info(`[${c}] connection ${y?"timed out":"failed"} - error; no more retries left`),Oe(this).debug(`[${c}] connection ${y?"timed out":"failed"} (error; no more retries left)`,Hn({retryOfRequestLogID:s,url:o,durationMs:p-u,message:f.message})),y?new Gi:new Lr({cause:f})}const m=[...f.headers.entries()].filter(([_])=>_==="x-request-id").map(([_,y])=>", "+_+": "+JSON.stringify(y)).join(""),v=`[${c}${d}${m}] ${a.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-u}ms`;if(!f.ok){const _=await this.shouldRetry(f);if(t&&_){const x=`retrying, ${t} attempts remaining`;return await Wv(f.body),Oe(this).info(`${v} - ${x}`),Oe(this).debug(`[${c}] response error (${x})`,Hn({retryOfRequestLogID:s,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),this.retryRequest(r,t,s??c,f.headers)}const y=_?"error; no more retries left":"error; not retryable";Oe(this).info(`${v} - ${y}`);const b=await f.text().catch(x=>no(x).message),E=Dv(b),C=E?void 0:b;throw Oe(this).debug(`[${c}] response error (${y})`,Hn({retryOfRequestLogID:s,url:f.url,status:f.status,headers:f.headers,message:C,durationMs:Date.now()-u})),this.makeStatusError(f.status,E,C,f.headers)}return Oe(this).info(v),Oe(this).debug(`[${c}] response start`,Hn({retryOfRequestLogID:s,url:f.url,status:f.status,headers:f.headers,durationMs:p-u})),{response:f,options:r,controller:h,requestLogID:c,retryOfRequestLogID:s,startTime:u}}getAPIList(e,t,s){return this.requestAPIList(t,{method:"get",path:e,...s})}requestAPIList(e,t){const s=this.makeRequest(t,null,void 0);return new rd(this,s,e)}async fetchWithTimeout(e,t,s,r){const{signal:i,method:a,...o}=t||{};i&&i.addEventListener("abort",()=>r.abort());const l=setTimeout(()=>r.abort(),s),c=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body=="object"&&o.body!==null&&Symbol.asyncIterator in o.body,d={signal:r.signal,...c?{duplex:"half"}:{},method:"GET",...o};a&&(d.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,d)}finally{clearTimeout(l)}}async shouldRetry(e){const t=e.headers.get("x-should-retry");return t==="true"?!0:t==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,s,r){let i;const a=r?.get("retry-after-ms");if(a){const l=parseFloat(a);Number.isNaN(l)||(i=l)}const o=r?.get("retry-after");if(o&&!i){const l=parseFloat(o);Number.isNaN(l)?i=Date.parse(o)-Date.now():i=l*1e3}if(!(i&&0<=i&&i<60*1e3)){const l=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,l)}return await Br(i),this.makeRequest(e,t-1,s)}calculateDefaultRetryTimeoutMillis(e,t){const i=t-e,a=Math.min(.5*Math.pow(2,i),8),o=1-Math.random()*.25;return a*o*1e3}async buildRequest(e,{retryCount:t=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:o}=s,l=this.buildURL(i,a,o);"timeout"in s&&Ov("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:c,body:d}=this.buildBody({options:s}),u=await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t});return{req:{method:r,headers:u,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&d instanceof globalThis.ReadableStream&&{duplex:"half"},...d&&{body:d},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&t!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=N([i,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(r),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...zv(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},await this.authHeaders(e),this._options.defaultHeaders,s,e.headers]);return this.validateHeaders(a),a.values}buildBody({options:{body:e,headers:t}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=N([t]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&s.values.has("content-type")||globalThis.Blob&&e instanceof globalThis.Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Ju(e)}:w(this,pi,"f").call(this,{body:e,headers:s})}}cl=Q,pi=new WeakMap,mo=new WeakSet,gf=function(){return this.baseURL!=="https://api.openai.com/v1"};Q.OpenAI=cl;Q.DEFAULT_TIMEOUT=6e5;Q.OpenAIError=j;Q.APIError=Me;Q.APIConnectionError=Lr;Q.APIConnectionTimeoutError=Gi;Q.APIUserAbortError=dt;Q.NotFoundError=Do;Q.ConflictError=Lo;Q.RateLimitError=Uo;Q.BadRequestError=Fo;Q.AuthenticationError=No;Q.InternalServerError=jo;Q.PermissionDeniedError=Oo;Q.UnprocessableEntityError=Bo;Q.InvalidWebhookSignatureError=$s;Q.toFile=cd;Q.Completions=Wd;Q.Chat=Xo;Q.Embeddings=Yd;Q.Files=Jd;Q.Images=tf;Q.Audio=zr;Q.Moderations=sf;Q.Models=nf;Q.FineTuning=er;Q.Graders=al;Q.VectorStores=ia;Q.Webhooks=mf;Q.Beta=Zs;Q.Batches=Od;Q.Uploads=ll;Q.Responses=ra;Q.Realtime=sa;Q.Conversations=el;Q.Evals=nl;Q.Containers=Zo;Q.Videos=hf;const N_=Object.freeze(Object.defineProperty({__proto__:null,APIConnectionError:Lr,APIConnectionTimeoutError:Gi,APIError:Me,APIPromise:Ur,APIUserAbortError:dt,AuthenticationError:No,BadRequestError:Fo,ConflictError:Lo,InternalServerError:jo,InvalidWebhookSignatureError:$s,NotFoundError:Do,OpenAI:Q,OpenAIError:j,PagePromise:rd,PermissionDeniedError:Oo,RateLimitError:Uo,UnprocessableEntityError:Bo,default:Q,toFile:cd},Symbol.toStringTag,{value:"Module"}));module.exports=$v;
|
||
|
||
/* nosourcemap */ |