Files
cours/.obsidian/plugins/podnotes/main.js
T

241 lines
292 KiB
JavaScript
Raw Blame History

This file contains invisible Unicode characters
This file contains invisible Unicode characters that are indistinguishable to humans but may be processed differently by a computer. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
"use strict";var If=Object.defineProperty;var _l=n=>{throw TypeError(n)};var $f=(n,e,t)=>e in n?If(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var zt=(n,e,t)=>$f(n,typeof e!="symbol"?e+"":e,t),ma=(n,e,t)=>e.has(n)||_l("Cannot "+t);var x=(n,e,t)=>(ma(n,e,"read from private field"),t?t.call(n):e.get(n)),le=(n,e,t)=>e.has(n)?_l("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(n):e.set(n,t),Z=(n,e,t,s)=>(ma(n,e,"write to private field"),s?s.call(n,t):e.set(n,t),t),ge=(n,e,t)=>(ma(n,e,"access private method"),t);const C=require("obsidian"),wl=globalThis.process?.env?.NODE_ENV,U=wl&&!wl.toLowerCase().startsWith("prod");var Vi=Array.isArray,Rf=Array.prototype.indexOf,So=Array.from,An=Object.defineProperty,fs=Object.getOwnPropertyDescriptor,Sc=Object.getOwnPropertyDescriptors,Mf=Object.prototype,Ff=Array.prototype,Ao=Object.getPrototypeOf,bl=Object.isExtensible;function Nf(n){return typeof n=="function"}const Ft=()=>{};function Df(n){return typeof n?.then=="function"}function Of(n){return n()}function Da(n){for(var e=0;e<n.length;e++)n[e]()}function Ac(){var n,e,t=new Promise((s,r)=>{n=s,e=r});return{promise:t,resolve:n,reject:e}}const He=2,Co=4,Ki=8,an=16,In=32,ws=64,Yi=128,Dt=512,qe=1024,ct=2048,on=4096,_t=8192,bn=16384,Ji=32768,vs=65536,ki=1<<17,Cc=1<<18,Qs=1<<19,Pc=1<<20,qn=32768,Oa=1<<21,Xi=1<<22,Bn=1<<23,tn=Symbol("$state"),Lf=Symbol("legacy props"),Bf=Symbol(""),Tc=Symbol("proxy path"),Ds=new class extends Error{constructor(){super(...arguments);zt(this,"name","StaleReactionError");zt(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};function Ic(n){return n===this.v}function $c(n,e){return n!=n?e==e:n!==e||n!==null&&typeof n=="object"||typeof n=="function"}function Rc(n){return!$c(n,this.v)}function Gi(n){if(U){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 Uf(){if(U){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 jf(){if(U){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 zf(n){if(U){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 qf(){if(U){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 Wf(n){if(U){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 Hf(){if(U){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 Vf(n){if(U){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 Kf(n){if(U){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 Yf(n){if(U){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 Jf(){if(U){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 Xf(){if(U){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 Gf(){if(U){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 Qf(){if(U){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 Zs=!1,Zf=!1;function eh(){Zs=!0}const Mc=1,Fc=2,Nc=4,th=8,nh=16,sh=1,rh=2,ih=4,ah=8,oh=16,lh=4,ch=1,uh=2,Be=Symbol(),dh=Symbol("filename"),fh="http://www.w3.org/1999/xhtml";function hh(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:(An(t,"stack",{value:i.join(`
`)}),An(t,"name",{value:n}),t)}function Wt(n,e){return n.label=e,Dc(n.v,e),n}function Dc(n,e){return n?.[Tc]?.(e),n}let ue=null;function Vs(n){ue=n}let Mr=null;function Ei(n){Mr=n}let qr=null;function xl(n){qr=n}function be(n,e=!1,t){ue={p:ue,i:!1,c:null,e:null,s:n,x:null,l:Zs&&!e?{s:null,u:null,$:[]}:null},U&&(ue.function=t,qr=t)}function xe(n){var e=ue,t=e.e;if(t!==null){e.e=null;for(var s of t)au(s)}return e.i=!0,ue=e.p,U&&(qr=ue?.function??null),{}}function er(){return!Zs||ue!==null&&ue.l===null}let ss=[];function Oc(){var n=ss;ss=[],Da(n)}function Vn(n){if(ss.length===0&&!Us){var e=ss;queueMicrotask(()=>{e===ss&&Oc()})}ss.push(n)}function ph(){for(;ss.length>0;)Oc()}const mh=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function Os(n){if(typeof n!="object"||n===null||tn in n)return n;const e=Ao(n);if(e!==Mf&&e!==Ff)return n;var t=new Map,s=Vi(n),r=Rn(0),i=hs,a=d=>{if(hs===i)return d();var u=ae,h=hs;it(null),Cl(i);var f=d();return it(u),Cl(h),f};s&&(t.set("length",Rn(n.length)),U&&(n=vh(n)));var o="";let l=!1;function c(d){if(!l){l=!0,o=d,Wt(r,`${o} version`);for(const[u,h]of t)Wt(h,Gn(o,u));l=!1}}return new Proxy(n,{defineProperty(d,u,h){(!("value"in h)||h.configurable===!1||h.enumerable===!1||h.writable===!1)&&Jf();var f=t.get(u);return f===void 0?f=a(()=>{var p=Rn(h.value);return t.set(u,p),U&&typeof u=="string"&&Wt(p,Gn(o,u)),p}):E(f,h.value,!0),!0},deleteProperty(d,u){var h=t.get(u);if(h===void 0){if(u in d){const f=a(()=>Rn(Be));t.set(u,f),Sr(r),U&&Wt(f,Gn(o,u))}}else E(h,Be),Sr(r);return!0},get(d,u,h){if(u===tn)return n;if(U&&u===Tc)return c;var f=t.get(u),p=u in d;if(f===void 0&&(!p||fs(d,u)?.writable)&&(f=a(()=>{var v=Os(p?d[u]:Be),y=Rn(v);return U&&Wt(y,Gn(o,u)),y}),t.set(u,f)),f!==void 0){var m=g(f);return m===Be?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!==Be)return{enumerable:!0,configurable:!0,value:m,writable:!0}}return h},has(d,u){if(u===tn)return!0;var h=t.get(u),f=h!==void 0&&h.v!==Be||Reflect.has(d,u);if(h!==void 0||ce!==null&&(!f||fs(d,u)?.writable)){h===void 0&&(h=a(()=>{var m=f?Os(d[u]):Be,v=Rn(m);return U&&Wt(v,Gn(o,u)),v}),t.set(u,h));var p=g(h);if(p===Be)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 y=t.get(v+"");y!==void 0?E(y,Be):v in d&&(y=a(()=>Rn(Be)),t.set(v+"",y),U&&Wt(y,Gn(o,v)))}if(p===void 0)(!m||fs(d,u)?.writable)&&(p=a(()=>Rn(void 0)),U&&Wt(p,Gn(o,u)),E(p,Os(h)),t.set(u,p));else{m=p.v!==Be;var _=a(()=>Os(h));E(p,_)}var b=Reflect.getOwnPropertyDescriptor(d,u);if(b?.set&&b.set.call(f,h),!m){if(s&&typeof u=="string"){var k=t.get("length"),P=Number(u);Number.isInteger(P)&&P>=k.v&&E(k,P+1)}Sr(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!==Be});for(var[h,f]of t)f.v!==Be&&!(h in d)&&u.push(h);return u},setPrototypeOf(){Xf()}})}function Gn(n,e){return typeof e=="symbol"?`${n}[Symbol(${e.description??""})]`:mh.test(e)?`${n}.${e}`:/^\d+$/.test(e)?`${n}[${e}]`:`${n}['${e}']`}function ga(n){try{if(n!==null&&typeof n=="object"&&tn in n)return n[tn]}catch{}return n}const gh=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function vh(n){return new Proxy(n,{get(e,t,s){var r=Reflect.get(e,t,s);return gh.has(t)?function(...i){Oh();var a=r.apply(this,i);return Gc(),a}:r}})}function yh(){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(ga(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(ga(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(ga(this[l])===i){break}}return o},Array.__svelte_cleanup=()=>{n.indexOf=t,n.lastIndexOf=s,n.includes=r}}var kl,Po,Lc,Bc;function _h(){if(kl===void 0){kl=window,Po=/Firefox/.test(navigator.userAgent);var n=Element.prototype,e=Node.prototype,t=Text.prototype;Lc=fs(e,"firstChild").get,Bc=fs(e,"nextSibling").get,bl(n)&&(n.__click=void 0,n.__className=void 0,n.__attributes=null,n.__style=void 0,n.__e=void 0),bl(t)&&(t.__t=void 0),U&&(n.__svelte_meta=null,yh())}}function Cn(n=""){return document.createTextNode(n)}function Si(n){return Lc.call(n)}function Wr(n){return Bc.call(n)}function I(n,e){return Si(n)}function Ke(n,e=!1){{var t=Si(n);return t instanceof Comment&&t.data===""?Wr(t):t}}function K(n,e=1,t=!1){let s=n;for(;e--;)s=Wr(s);return s}function wh(n){n.textContent=""}function Uc(){return!1}const La=new WeakMap;function jc(n){var e=ce;if(e===null)return ae.f|=Bn,n;if(U&&n instanceof Error&&!La.has(n)&&La.set(n,bh(n,e)),(e.f&Ji)===0){if((e.f&Yi)===0)throw U&&!e.parent&&n instanceof Error&&zc(n),n;e.b.error(n)}else Ks(n,e)}function Ks(n,e){for(;e!==null;){if((e.f&Yi)!==0)try{e.b.error(n);return}catch(t){n=t}e=e.parent}throw U&&n instanceof Error&&zc(n),n}function bh(n,e){const t=fs(n,"message");if(!(t&&!t.configurable)){for(var s=Po?" ":" ",r=`
${s}in ${e.fn?.name||"<unknown>"}`,i=e.ctx;i!==null;)r+=`
${s}in ${i.function?.[dh].split("/").pop()}`,i=i.p;return{message:n.message+`
${r}
`,stack:n.stack?.split(`
`).filter(a=>!a.includes("svelte/src/internal")).join(`
`)}}}function zc(n){const e=La.get(n);e&&(An(n,"message",{value:e.message}),An(n,"stack",{value:e.stack}))}const ti=new Set;let we=null,It=null,Ct=[],Qi=null,Ba=!1,Us=!1;var zs,qs,as,os,Ur,Ws,Hs,Ie,Ua,Qn,ja,qc,Wc;const qi=class qi{constructor(){le(this,Ie);zt(this,"committed",!1);zt(this,"current",new Map);zt(this,"previous",new Map);le(this,zs,new Set);le(this,qs,new Set);le(this,as,0);le(this,os,0);le(this,Ur,null);le(this,Ws,[]);le(this,Hs,[]);zt(this,"skipped_effects",new Set);zt(this,"is_fork",!1)}is_deferred(){return this.is_fork||x(this,os)>0}process(e){Ct=[],this.apply();var t={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const s of e)ge(this,Ie,Ua).call(this,s,t);this.is_fork||ge(this,Ie,qc).call(this),this.is_deferred()?(ge(this,Ie,Qn).call(this,t.effects),ge(this,Ie,Qn).call(this,t.render_effects),ge(this,Ie,Qn).call(this,t.block_effects)):(we=null,El(t.render_effects),El(t.effects),x(this,Ur)?.resolve()),It=null}capture(e,t){this.previous.has(e)||this.previous.set(e,t),(e.f&Bn)===0&&(this.current.set(e,e.v),It?.set(e,e.v))}activate(){we=this,this.apply()}deactivate(){we===this&&(we=null,It=null)}flush(){if(this.activate(),Ct.length>0){if(Hc(),we!==null&&we!==this)return}else x(this,as)===0&&this.process([]);this.deactivate()}discard(){for(const e of x(this,qs))e(this);x(this,qs).clear()}increment(e){Z(this,as,x(this,as)+1),e&&Z(this,os,x(this,os)+1)}decrement(e){Z(this,as,x(this,as)-1),e&&Z(this,os,x(this,os)-1),this.revive()}revive(){for(const e of x(this,Ws))We(e,ct),ys(e);for(const e of x(this,Hs))We(e,on),ys(e);Z(this,Ws,[]),Z(this,Hs,[]),this.flush()}oncommit(e){x(this,zs).add(e)}ondiscard(e){x(this,qs).add(e)}settled(){return(x(this,Ur)??Z(this,Ur,Ac())).promise}static ensure(){if(we===null){const e=we=new qi;ti.add(we),Us||qi.enqueue(()=>{we===e&&e.flush()})}return we}static enqueue(e){Vn(e)}apply(){}};zs=new WeakMap,qs=new WeakMap,as=new WeakMap,os=new WeakMap,Ur=new WeakMap,Ws=new WeakMap,Hs=new WeakMap,Ie=new WeakSet,Ua=function(e,t){e.f^=qe;for(var s=e.first;s!==null;){var r=s.f,i=(r&(In|ws))!==0,a=i&&(r&qe)!==0,o=a||(r&_t)!==0||this.skipped_effects.has(s);if((s.f&Yi)!==0&&s.b?.is_pending()&&(t={parent:t,effect:s,effects:[],render_effects:[],block_effects:[]}),!o&&s.fn!==null){i?s.f^=qe:(r&Co)!==0?t.effects.push(s):tr(s)&&((s.f&an)!==0&&t.block_effects.push(s),Xs(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&&(ge(this,Ie,Qn).call(this,t.effects),ge(this,Ie,Qn).call(this,t.render_effects),ge(this,Ie,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&ct)!==0?x(this,Ws):x(this,Hs)).push(t),ge(this,Ie,ja).call(this,t.deps),We(t,qe)},ja=function(e){if(e!==null)for(const t of e)(t.f&He)===0||(t.f&qn)===0||(t.f^=qn,ge(this,Ie,ja).call(this,t.deps))},qc=function(){if(x(this,os)===0){for(const e of x(this,zs))e();x(this,zs).clear()}x(this,as)===0&&ge(this,Ie,Wc).call(this)},Wc=function(){var i;if(ti.size>1){this.previous.clear();var e=It,t=!0,s={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const a of ti){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=Ct;Ct=[];const c=new Set,d=new Map;for(const u of o)Vc(u,l,c,d);if(Ct.length>0){we=a,a.apply();for(const u of Ct)ge(i=a,Ie,Ua).call(i,u,s);a.deactivate()}Ct=r}}we=null,It=e}this.committed=!0,ti.delete(this)};let Gt=qi;function xh(n){var e=Us;Us=!0;try{for(var t;;){if(ph(),Ct.length===0&&(we?.flush(),Ct.length===0))return Qi=null,t;Hc()}}finally{Us=e}}function Hc(){var n=zn;Ba=!0;var e=U?new Set:null;try{var t=0;for(Ai(!0);Ct.length>0;){var s=Gt.ensure();if(t++>1e3){if(U){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}kh()}if(s.process(Ct),jn.clear(),U)for(const a of s.current.keys())e.add(a)}}finally{if(Ba=!1,Ai(n),Qi=null,U)for(const a of e)a.updated=null}}function kh(){try{Hf()}catch(n){U&&An(n,"stack",{value:""}),Ks(n,Qi)}}let vn=null;function El(n){var e=n.length;if(e!==0){for(var t=0;t<e;){var s=n[t++];if((s.f&(bn|_t))===0&&tr(s)&&(vn=new Set,Xs(s),s.deps===null&&s.first===null&&s.nodes_start===null&&(s.teardown===null&&s.ac===null?cu(s):s.fn=null),vn?.size>0)){jn.clear();for(const r of vn){if((r.f&(bn|_t))!==0)continue;const i=[r];let a=r.parent;for(;a!==null;)vn.has(a)&&(vn.delete(a),i.push(a)),a=a.parent;for(let o=i.length-1;o>=0;o--){const l=i[o];(l.f&(bn|_t))===0&&Xs(l)}}vn.clear()}}vn=null}}function Vc(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&He)!==0?Vc(r,e,t,s):(i&(Xi|an))!==0&&(i&ct)===0&&Kc(r,e,s)&&(We(r,ct),ys(r))}}function Kc(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&He)!==0&&Kc(r,e,t))return t.set(r,!0),!0}return t.set(n,!1),!1}function ys(n){for(var e=Qi=n;e.parent!==null;){e=e.parent;var t=e.f;if(Ba&&e===ce&&(t&an)!==0&&(t&Cc)===0)return;if((t&(ws|In))!==0){if((t&qe)===0)return;e.f^=qe}}Ct.push(e)}function Eh(n){let e=0,t=Pn(0),s;return U&&Wt(t,"createSubscriber version"),()=>{Zi()&&(g(t),sr(()=>(e===0&&(s=j(()=>n(()=>Sr(t)))),e+=1,()=>{Vn(()=>{e-=1,e===0&&(s?.(),s=void 0,Sr(t))})})))}}var Sh=vs|Qs|Yi;function Ah(n,e,t){new Ch(n,e,t)}var Et,St,Eo,Kt,ls,Yt,At,st,Jt,yn,On,cs,Ln,us,_n,Wi,De,Ph,Th,za,di,fi,qa;class Ch{constructor(e,t,s){le(this,De);zt(this,"parent");le(this,Et,!1);le(this,St);le(this,Eo,null);le(this,Kt);le(this,ls);le(this,Yt);le(this,At,null);le(this,st,null);le(this,Jt,null);le(this,yn,null);le(this,On,null);le(this,cs,0);le(this,Ln,0);le(this,us,!1);le(this,_n,null);le(this,Wi,Eh(()=>(Z(this,_n,Pn(x(this,cs))),U&&Wt(x(this,_n),"$effect.pending()"),()=>{Z(this,_n,null)})));Z(this,St,e),Z(this,Kt,t),Z(this,ls,s),this.parent=ce.b,Z(this,Et,!!x(this,Kt).pending),Z(this,Yt,ea(()=>{ce.b=this;{var r=ge(this,De,za).call(this);try{Z(this,At,Pt(()=>s(r)))}catch(i){this.error(i)}x(this,Ln)>0?ge(this,De,fi).call(this):Z(this,Et,!1)}return()=>{x(this,On)?.remove()}},Sh))}is_pending(){return x(this,Et)||!!this.parent&&this.parent.is_pending()}has_pending_snippet(){return!!x(this,Kt).pending}update_pending_count(e){ge(this,De,qa).call(this,e),Z(this,cs,x(this,cs)+e),x(this,_n)&&xn(x(this,_n),x(this,cs))}get_effect_pending(){return x(this,Wi).call(this),g(x(this,_n))}error(e){var t=x(this,Kt).onerror;let s=x(this,Kt).failed;if(x(this,us)||!t&&!s)throw e;x(this,At)&&(ot(x(this,At)),Z(this,At,null)),x(this,st)&&(ot(x(this,st)),Z(this,st,null)),x(this,Jt)&&(ot(x(this,Jt)),Z(this,Jt,null));var r=!1,i=!1;const a=()=>{if(r){return}r=!0,i&&Qf(),Gt.ensure(),Z(this,cs,0),x(this,Jt)!==null&&js(x(this,Jt),()=>{Z(this,Jt,null)}),Z(this,Et,this.has_pending_snippet()),Z(this,At,ge(this,De,di).call(this,()=>(Z(this,us,!1),Pt(()=>x(this,ls).call(this,x(this,St)))))),x(this,Ln)>0?ge(this,De,fi).call(this):Z(this,Et,!1)};var o=ae;try{it(null),i=!0,t?.(e,a),i=!1}catch(l){Ks(l,x(this,Yt)&&x(this,Yt).parent)}finally{it(o)}s&&Vn(()=>{Z(this,Jt,ge(this,De,di).call(this,()=>{Gt.ensure(),Z(this,us,!0);try{return Pt(()=>{s(x(this,St),()=>e,()=>a)})}catch(l){return Ks(l,x(this,Yt).parent),null}finally{Z(this,us,!1)}}))})}}Et=new WeakMap,St=new WeakMap,Eo=new WeakMap,Kt=new WeakMap,ls=new WeakMap,Yt=new WeakMap,At=new WeakMap,st=new WeakMap,Jt=new WeakMap,yn=new WeakMap,On=new WeakMap,cs=new WeakMap,Ln=new WeakMap,us=new WeakMap,_n=new WeakMap,Wi=new WeakMap,De=new WeakSet,Ph=function(){try{Z(this,At,Pt(()=>x(this,ls).call(this,x(this,St))))}catch(e){this.error(e)}Z(this,Et,!1)},Th=function(){const e=x(this,Kt).pending;e&&(Z(this,st,Pt(()=>e(x(this,St)))),Gt.enqueue(()=>{var t=ge(this,De,za).call(this);Z(this,At,ge(this,De,di).call(this,()=>(Gt.ensure(),Pt(()=>x(this,ls).call(this,t))))),x(this,Ln)>0?ge(this,De,fi).call(this):(js(x(this,st),()=>{Z(this,st,null)}),Z(this,Et,!1))}))},za=function(){var e=x(this,St);return x(this,Et)&&(Z(this,On,Cn()),x(this,St).before(x(this,On)),e=x(this,On)),e},di=function(e){var t=ce,s=ae,r=ue;Nt(x(this,Yt)),it(x(this,Yt)),Vs(x(this,Yt).ctx);try{return e()}catch(i){return jc(i),null}finally{Nt(t),it(s),Vs(r)}},fi=function(){const e=x(this,Kt).pending;x(this,At)!==null&&(Z(this,yn,document.createDocumentFragment()),x(this,yn).append(x(this,On)),fu(x(this,At),x(this,yn))),x(this,st)===null&&Z(this,st,Pt(()=>e(x(this,St))))},qa=function(e){var t;if(!this.has_pending_snippet()){this.parent&&ge(t=this.parent,De,qa).call(t,e);return}Z(this,Ln,x(this,Ln)+e),x(this,Ln)===0&&(Z(this,Et,!1),x(this,st)&&js(x(this,st),()=>{Z(this,st,null)}),x(this,yn)&&(x(this,St).before(x(this,yn)),Z(this,yn,null)))};function Yc(n,e){return e}function Ih(n,e,t){for(var s=[],r=e.length,i=0;i<r;i++)Ro(e[i].e,s,!0);uu(s,()=>{var a=s.length===0&&t!==null;if(a){var o=t,l=o.parentNode;wh(l),l.append(o),n.items.clear(),Ht(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),Ht(n,d.prev,d.next)),ot(d.e,!a)}n.first===e[0]&&(n.first=e[0].prev)})}function Ys(n,e,t,s,r,i=null){var a=n,o=new Map,l=null,c=(e&Nc)!==0,d=(e&Mc)!==0,u=(e&Fc)!==0;if(c){var h=n;a=h.appendChild(Cn())}var f=null,p=Ne(()=>{var k=t();return Vi(k)?k:k==null?[]:So(k)}),m,v=!0;function y(){$h(b,m,a,e,s),f!==null&&(m.length===0?(f.fragment?(a.before(f.fragment),f.fragment=null):Mo(f.effect),_.first=f.effect):js(f.effect,()=>{f=null}))}var _=ea(()=>{m=g(p);for(var k=m.length,P=new Set,M=we,S=null,T=Uc(),R=0;R<k;R+=1){var F=m[R],W=s(F,R),ee=v?null:o.get(W);ee?(d&&xn(ee.v,F),u?xn(ee.i,R):ee.i=R,T&&M.skipped_effects.delete(ee.e)):(ee=Rh(v?a:null,S,F,W,R,r,e,t),v&&(ee.o=!0,S===null?l=ee:S.next=ee,S=ee),o.set(W,ee)),P.add(W)}if(k===0&&i&&!f)if(v)f={fragment:null,effect:Pt(()=>i(a))};else{var ye=document.createDocumentFragment(),oe=Cn();ye.append(oe),f={fragment:ye,effect:Pt(()=>i(oe))}}if(!v)if(T){for(const[V,ie]of o)P.has(V)||M.skipped_effects.add(ie.e);M.oncommit(y),M.ondiscard(()=>{})}else y();g(p)}),b={effect:_,items:o,first:l};v=!1}function $h(n,e,t,s,r){var i=(s&th)!==0,a=e.length,o=n.items,l=n.first,c,d=null,u,h=[],f=[],p,m,v,y;if(i)for(y=0;y<a;y+=1)p=e[y],m=r(p,y),v=o.get(m),v.a?.measure(),(u??(u=new Set)).add(v);for(y=0;y<a;y+=1){if(p=e[y],m=r(p,y),v=o.get(m),n.first??(n.first=v),!v.o){v.o=!0;var _=d?d.next:l;Ht(n,d,v),Ht(n,v,_),va(v,_,t),d=v,h=[],f=[],l=d.next;continue}if((v.e.f&_t)!==0&&(Mo(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],k;d=b.prev;var P=h[0],M=h[h.length-1];for(k=0;k<h.length;k+=1)va(h[k],b,t);for(k=0;k<f.length;k+=1)c.delete(f[k]);Ht(n,P.prev,M.next),Ht(n,d,P),Ht(n,M,b),l=b,d=M,y-=1,h=[],f=[]}else c.delete(v),va(v,l,t),Ht(n,v.prev,v.next),Ht(n,v,d===null?n.first:d.next),Ht(n,d,v),d=v;continue}for(h=[],f=[];l!==null&&l.k!==m;)(l.e.f&_t)===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 S=c===void 0?[]:So(c);l!==null;)(l.e.f&_t)===0&&S.push(l),l=l.next;var T=S.length;if(T>0){var R=(s&Nc)!==0&&a===0?t:null;if(i){for(y=0;y<T;y+=1)S[y].a?.measure();for(y=0;y<T;y+=1)S[y].a?.fix()}Ih(n,S,R)}}i&&Vn(()=>{if(u!==void 0)for(v of u)v.a?.apply()})}function Rh(n,e,t,s,r,i,a,o){var l=(a&Mc)!==0,c=(a&nh)===0,d=l?c?H(t,!1,!1):Pn(t):t,u=(a&Fc)===0?r:Pn(r);U&&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=Cn())}return h.e=Pt(()=>i(n,d,u,o)),e!==null&&(e.next=h),h}finally{}}function va(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=Wr(i);r.before(i),i=a}}function Ht(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 Mh(n,e,t,s){const r=er()?Hr:Ne;if(t.length===0&&n.length===0){s(e.map(r));return}var i=we,a=ce,o=Jc();function l(){Promise.all(t.map(c=>Nh(c))).then(c=>{o();try{s([...e.map(r),...c])}catch(d){(a.f&bn)===0&&Ks(d,a)}i?.deactivate(),Fr()}).catch(c=>{Ks(c,a)})}n.length>0?Promise.all(n).then(()=>{o();try{return l()}finally{i?.deactivate(),Fr()}}):l()}function Jc(){var n=ce,e=ae,t=ue,s=we;if(U)var r=Mr;return function(a=!0){Nt(n),it(e),Vs(t),a&&s?.activate(),U&&Ei(r)}}function Fr(){Nt(null),it(null),Vs(null),U&&Ei(null)}const Fh=new Set;function Hr(n){var e=He|ct,t=ae!==null&&(ae.f&He)!==0?ae:null;return ce!==null&&(ce.f|=Qs),{ctx:ue,deps:null,effects:null,equals:Ic,f:e,fn:n,reactions:null,rv:0,v:Be,wv:0,parent:t??ce,ac:null}}function Nh(n,e){let t=ce;t===null&&Uf();var s=t.b,r=void 0,i=Pn(Be),a=!ae,o=new Map;return Wh(()=>{var l=Ac();r=l.promise;try{Promise.resolve(n()).then(l.resolve,l.reject).then(()=>{c===we&&c.committed&&c.deactivate(),Fr()})}catch(h){l.reject(h),Fr()}var c=we;if(a){var d=!s.is_pending();s.update_pending_count(1),c.increment(d),o.get(c)?.reject(Ds),o.delete(c),o.set(c,l)}const u=(h,f=void 0)=>{if(c.activate(),f)f!==Ds&&(i.f|=Bn,xn(i,f));else{(i.f&Bn)!==0&&(i.f^=Bn),xn(i,h);for(const[p,m]of o){if(o.delete(p),p===c)break;m.reject(Ds)}}a&&(s.update_pending_count(-1),c.decrement(d))};l.promise.then(u,h=>u(null,h||"unknown"))}),nr(()=>{for(const l of o.values())l.reject(Ds)}),U&&(i.f|=Xi),new Promise(l=>{function c(d){function u(){d===r?l(i):c(r)}d.then(u,u)}c(r)})}function Un(n){const e=Hr(n);return Zc(e),e}function Ne(n){const e=Hr(n);return e.equals=Rc,e}function Wa(n){var e=n.effects;if(e!==null){n.effects=null;for(var t=0;t<e.length;t+=1)ot(e[t])}}let ya=[];function Dh(n){for(var e=n.parent;e!==null;){if((e.f&He)===0)return(e.f&bn)===0?e:null;e=e.parent}return null}function To(n){var e,t=ce;if(Nt(Dh(n)),U){let s=Js;Sl(new Set);try{ya.includes(n)&&jf(),ya.push(n),n.f&=~qn,Wa(n),e=Ha(n)}finally{Nt(t),Sl(s),ya.pop()}}else try{n.f&=~qn,Wa(n),e=Ha(n)}finally{Nt(t)}return e}function Xc(n){var e=To(n);if(n.equals(e)||(we?.is_fork||(n.v=e),n.wv=tu()),!bs)if(It!==null)Zi()&&It.set(n,e);else{var t=(n.f&Dt)===0?on:qe;We(n,t)}}let Js=new Set;const jn=new Map;function Sl(n){Js=n}let Io=!1;function Oh(){Io=!0}function Pn(n,e){var t={f:0,v:n,reactions:null,equals:Ic,rv:0,wv:0};return t}function Rn(n,e){const t=Pn(n);return Zc(t),t}function H(n,e=!1,t=!0){var r;const s=Pn(n);return e||(s.equals=Rc),Zs&&t&&ue!==null&&ue.l!==null&&((r=ue.l).s??(r.s=[])).push(s),s}function Er(n,e){return E(n,j(()=>g(n))),e}function E(n,e,t=!1){ae!==null&&(!Qt||(ae.f&ki)!==0)&&er()&&(ae.f&(He|an|Xi|ki))!==0&&!kn?.includes(n)&&Gf();let s=t?Os(e):e;return U&&Dc(s,n.label),xn(n,s)}function xn(n,e){if(!n.equals(e)){var t=n.v;bs?jn.set(n,e):jn.set(n,t),n.v=e;var s=Gt.ensure();if(s.capture(n,t),U){if(ce!==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=hh("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++}}}ce!==null&&(n.set_during_effect=!0)}(n.f&He)!==0&&((n.f&ct)!==0&&To(n),We(n,(n.f&Dt)!==0?qe:on)),n.wv=tu(),Qc(n,ct),er()&&ce!==null&&(ce.f&qe)!==0&&(ce.f&(In|ws))===0&&(xt===null?Lh([n]):xt.push(n)),!s.is_fork&&Js.size>0&&!Io&&Gc()}return e}function Gc(){Io=!1;var n=zn;Ai(!0);const e=Array.from(Js);try{for(const t of e)(t.f&qe)!==0&&We(t,on),tr(t)&&Xs(t)}finally{Ai(n)}Js.clear()}function Sr(n){E(n,n.v+1)}function Qc(n,e){var t=n.reactions;if(t!==null)for(var s=er(),r=t.length,i=0;i<r;i++){var a=t[i],o=a.f;if(!(!s&&a===ce)){if(U&&(o&ki)!==0){Js.add(a);continue}var l=(o&ct)===0;if(l&&We(a,e),(o&He)!==0){var c=a;It?.delete(c),(o&qn)===0&&(o&Dt&&(a.f|=qn),Qc(c,on))}else l&&((o&an)!==0&&vn!==null&&vn.add(a),ys(a))}}}function $o(n,e,t,s=!0){s&&t();for(var r of e)n.addEventListener(r,t);nr(()=>{for(var i of e)n.removeEventListener(i,t)})}function Vr(n){var e=ae,t=ce;it(null),Nt(null);try{return n()}finally{it(e),Nt(t)}}let zn=!1;function Ai(n){zn=n}let bs=!1;function Al(n){bs=n}let ae=null,Qt=!1;function it(n){ae=n}let ce=null;function Nt(n){ce=n}let kn=null;function Zc(n){ae!==null&&(kn===null?kn=[n]:kn.push(n))}let Qe=null,ft=0,xt=null;function Lh(n){xt=n}let eu=1,Nr=0,hs=Nr;function Cl(n){hs=n}function tu(){return++eu}function tr(n){var e=n.f;if((e&ct)!==0)return!0;if(e&He&&(n.f&=~qn),(e&on)!==0){var t=n.deps;if(t!==null)for(var s=t.length,r=0;r<s;r++){var i=t[r];if(tr(i)&&Xc(i),i.wv>n.wv)return!0}(e&Dt)!==0&&It===null&&We(n,qe)}return!1}function nu(n,e,t=!0){var s=n.reactions;if(s!==null&&!kn?.includes(n))for(var r=0;r<s.length;r++){var i=s[r];(i.f&He)!==0?nu(i,e,!1):e===i&&(t?We(i,ct):(i.f&qe)!==0&&We(i,on),ys(i))}}function Ha(n){var p;var e=Qe,t=ft,s=xt,r=ae,i=kn,a=ue,o=Qt,l=hs,c=n.f;Qe=null,ft=0,xt=null,ae=(c&(In|ws))===0?n:null,kn=null,Vs(n.ctx),Qt=!1,hs=++Nr,n.ac!==null&&(Vr(()=>{n.ac.abort(Ds)}),n.ac=null);try{n.f|=Oa;var d=n.fn,u=d(),h=n.deps;if(Qe!==null){var f;if(Ci(n,ft),h!==null&&ft>0)for(h.length=ft+Qe.length,f=0;f<Qe.length;f++)h[ft+f]=Qe[f];else n.deps=h=Qe;if(zn&&Zi()&&(n.f&Dt)!==0)for(f=ft;f<h.length;f++)((p=h[f]).reactions??(p.reactions=[])).push(n)}else h!==null&&ft<h.length&&(Ci(n,ft),h.length=ft);if(er()&&xt!==null&&!Qt&&h!==null&&(n.f&(He|on|ct))===0)for(f=0;f<xt.length;f++)nu(xt[f],n);return r!==null&&r!==n&&(Nr++,xt!==null&&(s===null?s=xt:s.push(...xt))),(n.f&Bn)!==0&&(n.f^=Bn),u}catch(m){return jc(m)}finally{n.f^=Oa,Qe=e,ft=t,xt=s,ae=r,kn=i,Vs(a),Qt=o,hs=l}}function Bh(n,e){let t=e.reactions;if(t!==null){var s=Rf.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&He)!==0&&(Qe===null||!Qe.includes(e))&&(We(e,on),(e.f&Dt)!==0&&(e.f^=Dt,e.f&=~qn),Wa(e),Ci(e,0))}function Ci(n,e){var t=n.deps;if(t!==null)for(var s=e;s<t.length;s++)Bh(n,t[s])}function Xs(n){var e=n.f;if((e&bn)===0){We(n,qe);var t=ce,s=zn;if(ce=n,zn=!0,U){var r=qr;xl(n.component_function);var i=Mr;Ei(n.dev_stack??Mr)}try{(e&an)!==0?Hh(n):lu(n),ou(n);var a=Ha(n);n.teardown=typeof a=="function"?a:null,n.wv=eu;var o;U&&Zf&&(n.f&ct)!==0&&n.deps}finally{zn=s,ce=t,U&&(xl(r),Ei(i))}}}function g(n){var e=n.f,t=(e&He)!==0;if(ae!==null&&!Qt){var s=ce!==null&&(ce.f&bn)!==0;if(!s&&!kn?.includes(n)){var r=ae.deps;if((ae.f&Oa)!==0)n.rv<Nr&&(n.rv=Nr,Qe===null&&r!==null&&r[ft]===n?ft++:Qe===null?Qe=[n]:Qe.includes(n)||Qe.push(n));else{(ae.deps??(ae.deps=[])).push(n);var i=n.reactions;i===null?n.reactions=[ae]:i.includes(ae)||i.push(ae)}}}if(U&&Fh.delete(n),bs){if(jn.has(n))return jn.get(n);if(t){var a=n,o=a.v;return((a.f&qe)===0&&a.reactions!==null||ru(a))&&(o=To(a)),jn.set(a,o),o}}else t&&!It?.has(n)&&(a=n,tr(a)&&Xc(a),zn&&Zi()&&(a.f&Dt)===0&&su(a));if(It?.has(n))return It.get(n);if((n.f&Bn)!==0)throw n.v;return n.v}function su(n){if(n.deps!==null){n.f^=Dt;for(const e of n.deps)(e.reactions??(e.reactions=[])).push(n),(e.f&He)!==0&&(e.f&Dt)===0&&su(e)}}function ru(n){if(n.v===Be)return!0;if(n.deps===null)return!1;for(const e of n.deps)if(jn.has(e)||(e.f&He)!==0&&ru(e))return!0;return!1}function j(n){var e=Qt;try{return Qt=!0,n()}finally{Qt=e}}const Uh=-7169;function We(n,e){n.f=n.f&Uh|e}function N(n){if(!(typeof n!="object"||!n||n instanceof EventTarget)){if(tn in n)Va(n);else if(!Array.isArray(n))for(let e in n){const t=n[e];typeof t=="object"&&t&&tn in t&&Va(t)}}}function Va(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{Va(n[s],e)}catch{}const t=Ao(n);if(t!==Object.prototype&&t!==Array.prototype&&t!==Map.prototype&&t!==Set.prototype&&t!==Date.prototype){const s=Sc(t);for(let r in s){const i=s[r].get;if(i)try{i.call(n)}catch{}}}}}function iu(n){ce===null&&(ae===null&&Wf(n),qf()),bs&&zf(n)}function jh(n,e){var t=e.last;t===null?e.last=e.first=n:(t.next=n,n.prev=t,e.last=n)}function ln(n,e,t){var s=ce;if(U)for(;s!==null&&(s.f&ki)!==0;)s=s.parent;s!==null&&(s.f&_t)!==0&&(n|=_t);var r={ctx:ue,deps:null,nodes_start:null,nodes_end:null,f:n|ct|Dt,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(U&&(r.component_function=qr),t)try{Xs(r),r.f|=Ji}catch(o){throw ot(r),o}else e!==null&&ys(r);var i=r;if(t&&i.deps===null&&i.teardown===null&&i.nodes_start===null&&i.first===i.last&&(i.f&Qs)===0&&(i=i.first,(n&an)!==0&&(n&vs)!==0&&i!==null&&(i.f|=vs)),i!==null&&(i.parent=s,s!==null&&jh(i,s),ae!==null&&(ae.f&He)!==0&&(n&ws)===0)){var a=ae;(a.effects??(a.effects=[])).push(i)}return r}function Zi(){return ae!==null&&!Qt}function nr(n){const e=ln(Ki,null,!1);return We(e,qe),e.teardown=n,e}function Ka(n){iu("$effect"),U&&An(n,"name",{value:"$effect"});var e=ce.f,t=!ae&&(e&In)!==0&&(e&Ji)===0;if(t){var s=ue;(s.e??(s.e=[])).push(n)}else return au(n)}function au(n){return ln(Co|Pc,n,!1)}function zh(n){return iu("$effect.pre"),U&&An(n,"name",{value:"$effect.pre"}),ln(Ki|Pc,n,!0)}function qh(n){Gt.ensure();const e=ln(ws|Qs,n,!0);return(t={})=>new Promise(s=>{t.outro?js(e,()=>{ot(e),s(void 0)}):(ot(e),s(void 0))})}function Gs(n){return ln(Co,n,!1)}function Se(n,e){var t=ue,s={effect:null,ran:!1,deps:n};t.l.$.push(s),s.effect=sr(()=>{n(),!s.ran&&(s.ran=!0,j(e))})}function Ot(){var n=ue;sr(()=>{for(var e of n.l.$){e.deps();var t=e.effect;(t.f&qe)!==0&&We(t,on),tr(t)&&Xs(t),e.ran=!1}})}function Wh(n){return ln(Xi|Qs,n,!0)}function sr(n,e=0){return ln(Ki|e,n,!0)}function ve(n,e=[],t=[],s=[]){Mh(s,e,t,r=>{ln(Ki,()=>n(...r.map(g)),!0)})}function ea(n,e=0){var t=ln(an|e,n,!0);return U&&(t.dev_stack=Mr),t}function Pt(n){return ln(In|Qs,n,!0)}function ou(n){var e=n.teardown;if(e!==null){const t=bs,s=ae;Al(!0),it(null);try{e.call(null)}finally{Al(t),it(s)}}}function lu(n,e=!1){var t=n.first;for(n.first=n.last=null;t!==null;){const r=t.ac;r!==null&&Vr(()=>{r.abort(Ds)});var s=t.next;(t.f&ws)!==0?t.parent=null:ot(t,e),t=s}}function Hh(n){for(var e=n.first;e!==null;){var t=e.next;(e.f&In)===0&&ot(e),e=t}}function ot(n,e=!0){var t=!1;(e||(n.f&Cc)!==0)&&n.nodes_start!==null&&n.nodes_end!==null&&(Vh(n.nodes_start,n.nodes_end),t=!0),lu(n,e&&!t),Ci(n,0),We(n,bn);var s=n.transitions;if(s!==null)for(const i of s)i.stop();ou(n);var r=n.parent;r!==null&&r.first!==null&&cu(n),U&&(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 Vh(n,e){for(;n!==null;){var t=n===e?null:Wr(n);n.remove(),n=t}}function cu(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 js(n,e,t=!0){var s=[];Ro(n,s,!0),uu(s,()=>{t&&ot(n),e&&e()})}function uu(n,e){var t=n.length;if(t>0){var s=()=>--t||e();for(var r of n)r.out(s)}else e()}function Ro(n,e,t){if((n.f&_t)===0){if(n.f^=_t,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&vs)!==0||(s.f&In)!==0&&(n.f&an)!==0;Ro(s,e,i?t:!1),s=r}}}function Mo(n){du(n,!0)}function du(n,e){if((n.f&_t)!==0){n.f^=_t,(n.f&qe)===0&&(We(n,ct),ys(n));for(var t=n.first;t!==null;){var s=t.next,r=(t.f&vs)!==0||(t.f&In)!==0;du(t,r?e:!1),t=s}if(n.transitions!==null)for(const i of n.transitions)(i.is_global||e)&&i.in()}}function fu(n,e){for(var t=n.nodes_start,s=n.nodes_end;t!==null;){var r=t===s?null:Wr(t);e.append(t),t=r}}const Kh=["touchstart","touchmove"];function Yh(n){return Kh.includes(n)}var Pl=new Map;function Jh(n,e){var t=Pl.get(n);t||(t=new Set,Pl.set(n,t)),t.add(e)}const Xh=new Set,Tl=new Set;function Gh(n,e,t,s={}){function r(i){if(s.capture||pr.call(e,i),!i.cancelBubble)return Vr(()=>t?.call(this,i))}return n.startsWith("pointer")||n.startsWith("touch")||n==="wheel"?Vn(()=>{e.addEventListener(n,r,s)}):e.addEventListener(n,r,s),r}function fe(n,e,t,s,r){var i={capture:s,passive:r},a=Gh(n,e,t,i);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&nr(()=>{e.removeEventListener(n,a,i)})}let Il=null;function pr(n){var e=this,t=e.ownerDocument,s=n.type,r=n.composedPath?.()||[],i=r[0]||n.target;Il=n;var a=0,o=Il===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){An(n,"currentTarget",{configurable:!0,get(){return i||t}});var d=ae,u=ce;it(null),Nt(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,it(d),Nt(u)}}}function Qh(n){var e=document.createElement("template");return e.innerHTML=n.replaceAll("<!>","<!---->"),e.content}function Pi(n,e){var t=ce;t.nodes_start===null&&(t.nodes_start=n,t.nodes_end=e)}function G(n,e){var t=(e&ch)!==0,s=(e&uh)!==0,r,i=!n.startsWith("<!>");return()=>{r===void 0&&(r=Qh(i?n:"<!>"+n),t||(r=Si(r)));var a=s||Po?document.importNode(r,!0):r.cloneNode(!0);if(t){var o=Si(a),l=a.lastChild;Pi(o,l)}else Pi(a,a);return a}}function Zh(n=""){{var e=Cn(n+"");return Pi(e,e),e}}function gt(){var n=document.createDocumentFragment(),e=document.createComment(""),t=Cn();return n.append(e,t),Pi(e,t),n}function B(n,e){n!==null&&n.before(e)}let Ya=!0;function Fe(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 Ja(n,e){return ep(n,e)}const Ps=new Map;function ep(n,{target:e,anchor:t,props:s={},events:r,context:i,intro:a=!0}){_h();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=Yh(f);e.addEventListener(f,pr,{passive:p});var m=Ps.get(f);m===void 0?(document.addEventListener(f,pr,{passive:p}),Ps.set(f,1)):Ps.set(f,m+1)}}};l(So(Xh)),Tl.add(l);var c=void 0,d=qh(()=>{var u=t??e.appendChild(Cn());return Ah(u,{pending:()=>{}},h=>{if(i){be({});var f=ue;f.c=i}r&&(s.$$events=r),Ya=a,c=n(h,s)||{},Ya=!0,i&&xe()}),()=>{for(var h of o){e.removeEventListener(h,pr);var f=Ps.get(h);--f===0?(document.removeEventListener(h,pr),Ps.delete(h)):Ps.set(h,f)}Tl.delete(l),u!==t&&u.parentNode?.removeChild(u)}});return Xa.set(c,d),c}let Xa=new WeakMap;function Ga(n,e){const t=Xa.get(n);return t?(Xa.delete(n),t(e)):(U&&(tn in n?void 0:void 0),Promise.resolve())}var Mt,Xt,pt,ds,jr,zr,Hi;class hu{constructor(e,t=!0){zt(this,"anchor");le(this,Mt,new Map);le(this,Xt,new Map);le(this,pt,new Map);le(this,ds,new Set);le(this,jr,!0);le(this,zr,()=>{var e=we;if(x(this,Mt).has(e)){var t=x(this,Mt).get(e),s=x(this,Xt).get(t);if(s)Mo(s),x(this,ds).delete(t);else{var r=x(this,pt).get(t);r&&(x(this,Xt).set(t,r.effect),x(this,pt).delete(t),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),s=r.effect)}for(const[i,a]of x(this,Mt)){if(x(this,Mt).delete(i),i===e)break;const o=x(this,pt).get(a);o&&(ot(o.effect),x(this,pt).delete(a))}for(const[i,a]of x(this,Xt)){if(i===t||x(this,ds).has(i))continue;const o=()=>{if(Array.from(x(this,Mt).values()).includes(i)){var c=document.createDocumentFragment();fu(a,c),c.append(Cn()),x(this,pt).set(i,{effect:a,fragment:c})}else ot(a);x(this,ds).delete(i),x(this,Xt).delete(i)};x(this,jr)||!s?(x(this,ds).add(i),js(a,o,!1)):o()}}});le(this,Hi,e=>{x(this,Mt).delete(e);const t=Array.from(x(this,Mt).values());for(const[s,r]of x(this,pt))t.includes(s)||(ot(r.effect),x(this,pt).delete(s))});this.anchor=e,Z(this,jr,t)}ensure(e,t){var s=we,r=Uc();if(t&&!x(this,Xt).has(e)&&!x(this,pt).has(e))if(r){var i=document.createDocumentFragment(),a=Cn();i.append(a),x(this,pt).set(e,{effect:Pt(()=>t(a)),fragment:i})}else x(this,Xt).set(e,Pt(()=>t(this.anchor)));if(x(this,Mt).set(s,e),r){for(const[o,l]of x(this,Xt))o===e?s.skipped_effects.delete(l):s.skipped_effects.add(l);for(const[o,l]of x(this,pt))o===e?s.skipped_effects.delete(l.effect):s.skipped_effects.add(l.effect);s.oncommit(x(this,zr)),s.ondiscard(x(this,Hi))}else x(this,zr).call(this)}}Mt=new WeakMap,Xt=new WeakMap,pt=new WeakMap,ds=new WeakMap,jr=new WeakMap,zr=new WeakMap,Hi=new WeakMap;const tp=0,_a=1;function np(n,e,t,s,r){var i=er(),a=Be,o=i?Pn(a):H(a,!1,!1),l=i?Pn(a):H(a,!1,!1),c=new hu(n);ea(()=>{var d=e(),u=!1;if(Df(d)){var h=Jc(),f=!1;const p=m=>{if(!u){f=!0,h(!1),Gt.ensure();try{m()}finally{Fr(),Us||xh()}}};d.then(m=>{p(()=>{xn(o,m),c.ensure(_a,s&&(v=>s(v,o)))})},m=>{p(()=>{if(xn(l,m),c.ensure(_a,r&&(v=>r(v,l))),!r)throw l.v})}),Vn(()=>{f||p(()=>{c.ensure(tp,t)})})}else xn(o,d),c.ensure(_a,s&&(p=>s(p,o)));return()=>{u=!0}})}function me(n,e,t=!1){var s=new hu(n),r=t?vs:0;function i(a,o){s.ensure(a,o)}ea(()=>{var a=!1;e((o,l=!0)=>{a=!0,i(l,o)}),a||i(!1,null)},r)}function pu(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 $e(n,e){Gs(()=>{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),U&&Jh(e.hash,r)}})}function mu(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=mu(n[e]))&&(s&&(s+=" "),s+=t)}else for(t in n)n[t]&&(s&&(s+=" "),s+=t);return s}function sp(){for(var n,e,t=0,s="",r=arguments.length;t<r;t++)(n=arguments[t])&&(e=mu(n))&&(s&&(s+=" "),s+=e);return s}function $l(n){return typeof n=="object"?sp(n):n??""}const Rl=[...`
\r\f \v\uFEFF`];function rp(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||Rl.includes(s[a-1]))&&(o===s.length||Rl.includes(s[o]))?s=(a===0?"":s.substring(0,a))+s.substring(o+1):a=o}}return s===""?null:s}function Ml(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 wa(n){return n[0]!=="-"||n[1]!=="-"?n.toLowerCase():n}function ip(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(wa)),r&&l.push(...Object.keys(r).map(wa));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=wa(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+=Ml(s)),r&&(t+=Ml(r,!0)),t=t.trim(),t===""?null:t}return n==null?null:String(n)}function nn(n,e,t,s,r,i){var a=n.__className;if(a!==t||a===void 0){var o=rp(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 ba(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 Dr(n,e,t,s){var r=n.__style;if(r!==e){var i=ip(e,s);i==null?n.removeAttribute("style"):n.style.cssText=i,n.__style=e}else s&&(Array.isArray(s)?(ba(n,t?.[0],s[0]),ba(n,t?.[1],s[1],"important")):ba(n,t,s));return s}const ap=Symbol("is custom element"),op=Symbol("is html");function de(n,e,t,s){var r=lp(n);r[e]!==(r[e]=t)&&(e==="loading"&&(n[Bf]=t),t==null?n.removeAttribute(e):typeof t!="string"&&cp(n).includes(e)?n[e]=t:n.setAttribute(e,t))}function lp(n){return n.__attributes??(n.__attributes={[ap]:n.nodeName.includes("-"),[op]:n.namespaceURI===fh})}var Fl=new Map;function cp(n){var e=n.getAttribute("is")||n.nodeName,t=Fl.get(e);if(t)return t;Fl.set(e,t=[]);for(var s,r=n,i=Element.prototype;i!==r;){s=Sc(r);for(var a in s)s[a].set&&t.push(a);r=Ao(r)}return t}const up=()=>performance.now(),wn={tick:n=>requestAnimationFrame(n),now:()=>up(),tasks:new Set};function gu(){const n=wn.now();wn.tasks.forEach(e=>{e.c(n)||(wn.tasks.delete(e),e.f())}),wn.tasks.size!==0&&wn.tick(gu)}function dp(n){let e;return wn.tasks.size===0&&wn.tick(gu),{promise:new Promise(t=>{wn.tasks.add(e={c:n,f:t})}),abort(){wn.tasks.delete(e)}}}function ni(n,e){Vr(()=>{n.dispatchEvent(new CustomEvent(e))})}function fp(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 Nl(n){const e={},t=n.split(";");for(const s of t){const[r,i]=s.split(":");if(!r||i===void 0)break;const a=fp(r.trim());e[a]=i.trim()}return e}const hp=n=>n;function vu(n,e,t,s){var r=(n&lh)!==0,i="both",a,o=e.inert,l=e.style.overflow,c,d;function u(){return Vr(()=>a??(a=t()(e,s?.()??{},{direction:i})))}var h={is_global:r,in(){e.inert=o,ni(e,"introstart"),c=Qa(e,u(),d,1,()=>{ni(e,"introend"),c?.abort(),c=a=void 0,e.style.overflow=l})},out(v){e.inert=!0,ni(e,"outrostart"),d=Qa(e,u(),c,0,()=>{ni(e,"outroend"),v?.()})},stop:()=>{c?.abort(),d?.abort()}},f=ce;if((f.transitions??(f.transitions=[])).push(h),Ya){var p=r;if(!p){for(var m=f.parent;m&&(m.f&vs)!==0;)for(;(m=m.parent)&&(m.f&an)===0;);p=!m||(m.f&Ji)!==0}p&&Gs(()=>{j(()=>h.in())})}}function Qa(n,e,t,s,r){var i=s===1;if(Nf(e)){var a,o=!1;return Vn(()=>{if(!o){var v=e({direction:i?"in":"out"});a=Qa(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:Ft,deactivate:Ft,reset:Ft,t:()=>s};const{delay:l=0,css:c,tick:d,easing:u=hp}=e;var h=[];if(i&&t===void 0&&(d&&d(0,1),c)){var f=Nl(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 y=s-v,_=e.duration*Math.abs(y),b=[];if(_>0){var k=!1;if(c)for(var P=Math.ceil(_/16.666666666666668),M=0;M<=P;M+=1){var S=v+y*u(M/P),T=Nl(c(S,1-S));b.push(T),k||(k=T.overflow==="hidden")}k&&(n.style.overflow="hidden"),p=()=>{var R=m.currentTime;return v+y*u(R/_)},d&&dp(()=>{if(m.playState!=="running")return!1;var R=p();return d(R,1-R),!0})}m=n.animate(b,{duration:_,fill:"forwards"}),m.onfinish=()=>{p=()=>s,d?.(s,1-s),r()}},{abort:()=>{m&&(m.cancel(),m.effect=null,m.onfinish=Ft)},deactivate:()=>{r=Ft},reset:()=>{s===0&&d?.(1,0)},t:()=>p()}}function pp(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),sr(()=>{var a=Number(e());r!==a&&!isNaN(a)&&(n.currentTime=r=a)}),nr(()=>{cancelAnimationFrame(s),n.removeEventListener("timeupdate",i)})}function mp(n,e,t=e){Gs(()=>{var s=Number(e());s!==n.playbackRate&&!isNaN(s)&&(n.playbackRate=s)}),Gs(()=>{$o(n,["ratechange"],()=>{t(n.playbackRate)})})}function gp(n,e,t=e){var s=e(),r=()=>{s!==n.paused&&t(s=n.paused)};$o(n,["play","pause","canplay"],r,s==null),Gs(()=>{(s=!!e())!==n.paused&&(s?n.pause():n.play().catch(()=>{t(s=!0)}))})}function vp(n,e,t=e){var s=()=>{t(n.volume)};e()==null&&s(),$o(n,["volumechange"],s,!1),sr(()=>{var r=Number(e());r!==n.volume&&!isNaN(r)&&(n.volume=r)})}function Dl(n,e){return n===e||n?.[tn]===e}function Wn(n={},e,t,s){return Gs(()=>{var r,i;return sr(()=>{r=i,i=[],j(()=>{n!==t(...i)&&(e(n,...i),r&&Dl(t(...r),n)&&e(null,...r))})}),()=>{Vn(()=>{i&&Dl(t(...i),n)&&e(null,...i)})}}),n}function yp(n,e,t,s,r){var i=()=>{s(t[n])};t.addEventListener(e,i),i(),(t===document.body||t===window||t===document)&&nr(()=>{t.removeEventListener(e,i)})}function _p(n){return function(...e){var t=e[0];return t.preventDefault(),n?.apply(this,e)}}function ke(n=!1){const e=ue,t=e.l.u;if(!t)return;let s=()=>N(e.s);if(n){let r=0,i={};const a=Hr(()=>{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&&zh(()=>{Ol(e,s),Da(t.b)}),Ka(()=>{const r=j(()=>t.m.map(Of));return()=>{for(const i of r)typeof i=="function"&&i()}}),t.a.length&&Ka(()=>{Ol(e,s),Da(t.a)})}function Ol(n,e){if(n.l.s)for(const t of n.l.s)g(t);e()}function yu(n,e){var t=n.$$events?.[e.type],s=Vi(t)?t.slice():t==null?[]:[t];for(var r of s)r.call(this,e)}let mr=!1,Za=Symbol();function Me(n,e,t){const s=t[e]??(t[e]={store:null,source:H(void 0),unsubscribe:Ft});if(U&&(s.source.label=e),s.store!==n&&!(Za in t))if(s.unsubscribe(),s.store=n??null,n==null)s.source.v=void 0,s.unsubscribe=Ft;else{var r=!0;s.unsubscribe=bu(n,i=>{r?s.source.v=i:E(s.source,i)}),r=!1}return n&&Za in t?Y(n):g(s.source)}function Ar(n,e){return n.set(e),e}function Kr(){const n={};function e(){nr(()=>{for(var t in n)n[t].unsubscribe();An(n,Za,{enumerable:!1,value:!0})})}return[n,e]}function wp(){mr=!0}function bp(n){var e=mr;try{return mr=!1,[n(),mr]}finally{mr=e}}function $(n,e,t,s){var r=!Zs||(t&rh)!==0,i=(t&ah)!==0,a=(t&oh)!==0,o=s,l=!0,c=()=>(l&&(l=!1,o=a?j(s):s),o),d;if(i){var u=tn in n||Lf in n;d=fs(n,e)?.set??(u&&e in n?b=>n[e]=b:void 0)}var h,f=!1;i?[h,f]=bp(()=>n[e]):h=n[e],h===void 0&&s!==void 0&&(h=c(),d&&(r&&Kf(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&ih)===0)return p;if(d){var m=n.$$legacy;return(function(b,k){return arguments.length>0?((!r||!k||m||f)&&d(k?p():b),b):p()})}var v=!1,y=((t&sh)!==0?Hr:Ne)(()=>(v=!1,p()));U&&(y.label=e),i&&g(y);var _=ce;return(function(b,k){if(arguments.length>0){const P=k?g(y):r&&i?Os(b):b;return E(y,P),v=!0,o!==void 0&&(o=P),b}return bs&&v||(_.f&bn)!==0?y.v:g(y)})}if(U){let n=function(e){if(!(e in globalThis)){let t;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(t!==void 0)return t;Yf(e)},set:s=>{t=s}})}};n("$state"),n("$effect"),n("$derived"),n("$inspect"),n("$props"),n("$bindable")}function cn(n){ue===null&&Gi("onMount"),Zs&&ue.l!==null?wu(ue).m.push(n):Ka(()=>{const e=j(n);if(typeof e=="function")return e})}function ta(n){ue===null&&Gi("onDestroy"),cn(()=>()=>j(n))}function xp(n,e,{bubbles:t=!1,cancelable:s=!1}={}){return new CustomEvent(n,{detail:e,bubbles:t,cancelable:s})}function Je(){const n=ue;return n===null&&Gi("createEventDispatcher"),(e,t,s)=>{const r=n.s.$$events?.[e];if(r){const i=Vi(r)?r.slice():[r],a=xp(e,t,s);for(const o of i)o.call(n.x,a);return!a.defaultPrevented}return!0}}function _u(n){ue===null&&Gi("afterUpdate"),ue.l===null&&Vf("afterUpdate"),wu(ue).a.push(n)}function wu(n){var e=n.l;return e.u??(e.u={a:[],b:[],m:[]})}function bu(n,e,t){if(n==null)return e(void 0),Ft;const s=j(()=>n.subscribe(e,t));return s.unsubscribe?()=>s.unsubscribe():s}const Ts=[];function kp(n,e){return{subscribe:Ce(n,e).subscribe}}function Ce(n,e=Ft){let t=null;const s=new Set;function r(o){if($c(n,o)&&(n=o,t)){const l=!Ts.length;for(const c of s)c[1](),Ts.push(c,n);if(l){for(let c=0;c<Ts.length;c+=2)Ts[c][0](Ts[c+1]);Ts.length=0}}}function i(o){r(o(n))}function a(o,l=Ft){const c=[o,l];return s.add(c),s.size===1&&(t=e(r,i)||Ft),o(n),()=>{s.delete(c),s.size===0&&t&&(t(),t=null)}}return{set:r,update:i,subscribe:a}}function Y(n){let e;return bu(n,t=>e=t)(),e}var re=(n=>(n[n.PodcastGrid=0]="PodcastGrid",n[n.EpisodeList=1]="EpisodeList",n[n.Player=2]="Player",n))(re||{});function sn(n){return!n||!n.title?"":n.podcastName?`${n.podcastName}::${n.title}`:n.title}function Ep(n,e){return!n||!e?!1:sn(n)===e?!0:n.title===e}function eo(n,e){if(!e)return;const t=sn(e);if(t&&n[t])return n[t];if(e.title&&n[e.title])return n[e.title]}function Cr(n,e){return eo(e,n)?.finished??!1}function Fo(n){return n.podcastName?`${n.podcastName}::${n.title}`:n.title}function Sp(n,e,t){const s=new Set,r=Fo(e);for(const[i,a]of Object.entries(n))(i===t||i===r||Cp(a,e))&&s.add(i);return Array.from(s)}function xu(n){const e=new Map;for(const[t,s]of Object.entries(n)){if(!s.finished)continue;const r=Fo(s);(!e.get(r)||Ap(t))&&e.set(r,{key:t,episode:s})}return Array.from(e.values())}function Ap(n){return n.includes("::")}function Cp(n,e){return n.title!==e.title?!1:!n.podcastName||!e.podcastName?!0:n.podcastName===e.podcastName}const rn=Ce(),kt=Ce(0),Pr=Ce(null),Ti=Ce(0),ps=Ce(1),Ii=Ce(!1),et=(()=>{const n=Ce(),{subscribe:e,update:t}=n;return{subscribe:e,update:t,set:(s,r=!0)=>{t(i=>{if(i){r&&Fp(i);const a=Y(kt),o=Y(Ti),l=a===o;Ye.setEpisodeTime(i,a,o,l)}return s})}}})(),Tt=Ce(!0),Ye=(()=>{const n=Ce({}),{subscribe:e,update:t,set:s}=n;return{subscribe:e,set:s,update:t,get:r=>eo(Y(n),r),setEpisodeTime:(r,i,a,o)=>{r&&t(l=>{const c=sn(r);return c&&(l[c]={title:r.title,podcastName:r.podcastName,time:i,duration:a,finished:o}),l})},markAsPlayed:r=>{r&&t(i=>{const a=sn(r);if(!a)return i;const o=eo(i,r)||{title:r.title,podcastName:r.podcastName,time:0,duration:0,finished:!1};return o.time=o.duration,o.finished=!0,i[a]=o,i})},markAsUnplayed:r=>{r&&t(i=>{const a=sn(r);return a&&Ll(i,{title:r.title,podcastName:r.podcastName},a),i})},markKeyAsUnplayed:r=>{r&&t(i=>{const a=i[r];return a&&Ll(i,a,r),i})}}})();function Ll(n,e,t){const s=Sp(n,e,t),r=s.length>0?s:[t];for(const i of r){const a=n[i]||{title:e.title,podcastName:e.podcastName,time:0,duration:0,finished:!1};n[i]={...a,time:0,finished:!1}}}const Pp=Ce(0),En=Ce({}),Dn=Ce({}),ku=10;function $i(n){return n?.episodeDate?Number(n.episodeDate):0}function Tp(n){return n?.length?n.slice(0,ku).sort((e,t)=>$i(t)-$i(e)):[]}function Ip(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 Bl=n=>`${n.podcastName}::${n.title}`;function $p(n,e,t){const s=[...n],r=$i(e);let i=0,a=s.length;for(;i<a;){const o=i+a>>1,l=$i(s[o]);r>l?a=o:i=o+1}return s.splice(i,0,e),s.length>t&&(s.length=t),s}function Eu(n,e=[]){if(!e?.length)return n;const t=new Set(e.map(Bl));return n.filter(s=>!t.has(Bl(s)))}function Rp(n,e,t,s){let r=Eu(n,e);if(!t?.length)return r;for(const i of t)r=$p(r,i,s);return r}const Mp=kp([],n=>{let e=new Map,t=new Map,s=[];const r=Dn.subscribe(i=>{const a=Object.entries(i),o=a.length,l=Math.max(1,ku*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)||[],y=m===p&&v?v:Tp(p);h.set(f,y),Ip(v,y)||(c=!0,d=Rp(d,v,y,l))}for(const f of e.keys())u.has(f)||(c=!0,d=Eu(d,e.get(f)));t=u,e=h,c&&(s=d,n(s))});return()=>{e.clear(),t.clear(),s=[],r()}}),lt=(()=>{const n=Ce({}),{subscribe:e,update:t,set:s}=n;function r(i){return Y(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 C.TFile&&app.vault.delete(u)}catch{}return o[i.podcastName]=l,o})},getEpisode:i=>Y(n)[i.podcastName]?.find(a=>a.title===i.title)}})(),at=(()=>{const n=Ce({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&&et.set(i,!1),r})}}})(),Sn=Ce({icon:"lucide-star",name:"Favorites",episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1}),ms=(()=>{const n=Ce({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=>Y(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})}}})(),vt=Ce({}),to=Ce(),Ve=(()=>{const n=Ce(re.PodcastGrid),{subscribe:e,set:t}=n;return{subscribe:e,set:s=>{t(s),Y(to)?.scrollIntoView()}}})();function Fp(n){at.update(e=>{const t=[n,...e.episodes];return e.episodes=t,e})}class Np{constructor(){this.activeUrls=new Map}async createUrl(e){this.revokeUrl(e);const t=app.vault.getAbstractFileByPath(e);if(!t||!(t instanceof C.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 Su=new Np;async function Au(n){return Su.createUrl(n)}function Or(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 Dp(n,e,t){const s=new URL("obsidian://podnotes");return s.searchParams.set("episodeName",n),s.searchParams.set("url",e),t!==void 0&&s.searchParams.set("time",t.toString()),s}function Cu(n){return n.podcastName==="local file"}const Op=n=>Math.min(1,Math.max(0,n));class Lp{get podcast(){return Y(et)}get length(){return Y(Ti)}get currentTime(){return Y(kt)}set currentTime(e){kt.update(t=>e)}get isPlaying(){return!Y(Tt)}get volume(){return Y(ps)}set volume(e){ps.set(Op(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=Or(r,e);if(!t)return i;const o=Cu(this.podcast)?lt.getEpisode(this.podcast)?.filePath:this.podcast.feedUrl;if(!o||o==="")return i;const l=Dp(this.podcast.title,o,r);return`[${i}](${l.href})`}start(){Tt.update(e=>!1)}stop(){Tt.update(e=>!0)}togglePlayback(){Tt.update(e=>!e)}skipBackward(){const e=Y(rn).settings.skipBackwardLength;this.currentTime-=e}skipForward(){const e=Y(rn).settings.skipForwardLength;this.currentTime+=e}}const Zn="podcast_player_view",Pu={icon:"lucide-star",name:"Favorites",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},Tu={icon:"list-ordered",name:"Queue",shouldEpisodeRemoveAfterPlay:!0,shouldRepeat:!1},Iu={icon:"folder",name:"Local Files",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},xa={icon:"check-square",name:"Played",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},Ul={savedFeeds:{},podNotes:{},defaultPlaybackRate:1,defaultVolume:1,hidePlayedEpisodes:!1,playedEpisodes:{},favorites:{...Pu,episodes:[]},queue:{...Tu,episodes:[]},playlists:{},skipBackwardLength:15,skipForwardLength:15,currentEpisode:void 0,timestamp:{template:"- {{time}} ",offset:0},note:{path:"",template:""},download:{path:""},downloadedEpisodes:{},localFiles:{...Iu,episodes:[]},openAIApiKey:"",transcript:{path:"transcripts/{{podcast}}/{{title}}.md",template:`# {{title}}
Podcast: {{podcast}}
Date: {{date}}
{{transcript}}`},feedCache:{enabled:!0,ttlHours:6}},Bp="5";var Ec;typeof window<"u"&&((Ec=window.__svelte??(window.__svelte={})).v??(Ec.v=new Set)).add(Bp);eh();const Up=3e4;class hi extends Error{constructor(e,t,s){super(e),this.url=t,this.cause=s,this.name="NetworkError"}}class jp extends hi{constructor(e,t){super(`Request timed out after ${t}ms`,e),this.name="TimeoutError"}}async function No(n,e={}){const{timeoutMs:t=Up,method:s,headers:r,body:i}=e;let a;const o=new Promise((l,c)=>{a=setTimeout(()=>{c(new jp(n,t))},t)});try{const l=await Promise.race([C.requestUrl({url:n,method:s,headers:r,body:i,throw:!1}),o]);if(l.status>=400)throw new hi(`HTTP ${l.status}: ${l.text?.slice(0,100)||"Unknown error"}`,n);return l}catch(l){throw l instanceof hi?l:new hi(l instanceof Error?l.message:String(l),n,l)}finally{a&&clearTimeout(a)}}async function $u(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 No(e.href,{timeoutMs:15e3})).json.results||[]).map(r=>({title:r.collectionName,url:r.feedUrl,artworkUrl:r.artworkUrl100,collectionId:r.collectionId}))}catch{return[]}}class na{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),y=l?.getAttribute("href")||this.feed?.artworkUrl,_=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:y,episodeDate:v,feedUrl:this.feed?.url||"",itunesTitle:_||"",chaptersUrl:b}}async parseFeed(e){const t=await No(e,{timeoutMs:3e4});return new DOMParser().parseFromString(t.text,"text/xml")}}function zp(n){try{return new URL(n)}catch{return null}}function rr(n){return Object.entries(n).map(([e,t])=>`${e}: ${t}`).join("; ")}var qp=G("<span></span>");function Do(n,e){be(e,!1);let t=$(e,"value",12,""),s=$(e,"disabled",8,!1),r=$(e,"placeholder",8,""),i=$(e,"type",8,"text"),a=$(e,"el",12,null),o=H();const l=Je();let c=H(),d=$(e,"style",24,()=>({})),u=null,h=null,f=!1;cn(()=>{E(c,new C.TextComponent(g(o)))}),ta(()=>{g(c)?.inputEl&&u&&g(c).inputEl.removeEventListener("input",u)});function p(b){if(f)return;const P=b.target?.value??"";t(P),l("input",{value:P})}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 y(b,k,P,M,S,T){const R=typeof b.getValue=="function"?b.getValue():b.inputEl?.value;k!==void 0&&R!==k&&(f=!0,b.setValue(k),f=!1),b?.inputEl&&(b.inputEl.disabled!==P&&b.setDisabled(P),M&&b.inputEl.placeholder!==M&&b.setPlaceholder(M),b.inputEl.type!==S&&(b.inputEl.type=S),T&&b.inputEl.setAttr("style",rr(T)),a(b.inputEl))}Se(()=>(g(c),N(t()),N(s()),N(r()),N(i()),N(d())),()=>{g(c)&&(v(g(c)),y(g(c),t(),s(),r(),i(),d()))}),Ot(),ke();var _=qp();Wn(_,b=>E(o,b),()=>g(o)),B(n,_),xe()}var Wp=G("<span></span>");function Lr(n,e){be(e,!1);let t=$(e,"text",8,""),s=$(e,"tooltip",8,""),r=$(e,"ariaLabel",8,""),i=$(e,"icon",8,void 0),a=$(e,"disabled",8,!1),o=$(e,"warning",8,!1),l=$(e,"cta",8,!1),c=H(),d=$(e,"class",8),u=$(e,"style",8),h;const f=Je();cn(()=>p(g(c))),_u(()=>m(h));function p(y){h=new C.ButtonComponent(y),m(h)}function m(y){t()&&y.setButtonText(t()),s()&&y.setTooltip(s()),i()&&y.setIcon(i()),a()&&y.setDisabled(a()),o()?y.setWarning():y.buttonEl.classList.remove("mod-warning"),d()&&y.setClass(d()),l()?y.setCta():y.removeCta(),y.onClick(_=>{f("click",{event:_})}),u()&&y.buttonEl.setAttr("style",rr(u())),r()?y.buttonEl.setAttr("aria-label",r()):y.buttonEl.removeAttribute("aria-label")}ke();var v=Wp();Wn(v,y=>E(c,y),()=>g(c)),B(n,v),xe()}const Hp=n=>n;function Ru(n,{delay:e=0,duration:t=400,easing:s=Hp}={}){const r=+getComputedStyle(n).opacity;return{delay:e,duration:t,easing:s,css:i=>`opacity: ${i*r}`}}var Vp=G('<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 Kp={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 Yp(n,e){be(e,!1),$e(n,Kp);let t=$(e,"podcast",8),s=$(e,"isSaved",8,!1);const r=Je();ke();var i=Vp(),a=I(i),o=I(a),l=K(a,2),c=I(l),d=I(c),u=K(l,2),h=I(u);{var f=m=>{{let v=Ne(()=>(N(t()),j(()=>`Remove ${t().title} podcast`)));Lr(m,{icon:"trash",get ariaLabel(){return g(v)},$$events:{click:()=>r("removePodcast",{podcast:t()})}})}},p=m=>{{let v=Ne(()=>(N(t()),j(()=>`Add ${t().title} podcast`)));Lr(m,{icon:"plus",get ariaLabel(){return g(v)},$$events:{click:()=>r("addPodcast",{podcast:t()})}})}};me(h,m=>{s()?m(f):m(p,!1)})}ve(()=>{de(o,"src",(N(t()),j(()=>t().artworkUrl))),de(o,"alt",(N(t()),j(()=>`Artwork for ${t().title}`))),Fe(d,(N(t()),j(()=>t().title)))}),vu(3,i,()=>Ru,()=>({duration:300})),B(n,i),xe()}var Jp=G('<div role="listitem"><!></div>'),Xp=G('<div class="podcast-query-container svelte-8ek8i8"><!> <div class="podcast-query-results svelte-8ek8i8" role="list" aria-label="Podcast search results"></div></div>');const Gp={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 Qp(n,e){be(e,!1),$e(n,Gp);const t=()=>Me(En,"$savedFeeds",r),s=()=>Me(Pp,"$podcastsUpdated",r),[r,i]=Kr();let a=H([]),o=H("grid-3"),l=H(""),c=H();cn(()=>{d(),g(c)&&g(c).focus()});function d(){g(l).trim()===""&&E(a,Object.values(t()))}const u=C.debounce(async({detail:{value:y}})=>{E(l,y);const _=zp(y);if(_){const b=await new na().getFeed(_.href);E(a,[b])}else y.trim()===""?d():E(a,await $u(y))},300,!0);function h(y){const{podcast:_}=y.detail;En.update(b=>({...b,[_.title]:_})),d()}function f(y){const{podcast:_}=y.detail;En.update(b=>{const k={...b};return delete k[_.title],k}),d()}Se(()=>(g(l),t(),s()),()=>{g(l).trim()===""&&E(a,Object.values(t())),s()}),Se(()=>g(a),()=>{g(a).length%3===0||g(a).length>3?E(o,"grid-3"):g(a).length%2===0?E(o,"grid-2"):g(a).length%1===0&&E(o,"grid-1")}),Ot(),ke();var p=Xp(),m=I(p);Do(m,{placeholder:"Search or enter feed URL...",style:{width:"100%","margin-bottom":"1rem"},get el(){return g(c)},set el(y){E(c,y)},$$events:{change:u},$$legacy:!0});var v=K(m,2);Ys(v,5,()=>g(a),y=>y.url,(y,_)=>{var b=Jp(),k=I(b);{let P=Ne(()=>(g(_),t(),j(()=>typeof g(_).url=="string"&&t()[g(_).title]?.url===g(_).url)));Yp(k,{get podcast(){return g(_)},get isSaved(){return g(P)},$$events:{addPodcast:h,removePodcast:f}})}B(y,b)}),vu(3,p,()=>Ru,()=>({duration:300})),B(n,p),xe(),i()}var Zp=G('<button type="button" class="icon-button svelte-11mdast"><span></span></button>'),em=G('<span class="icon-static svelte-11mdast"></span>');const tm={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 Ze(n,e){be(e,!1),$e(n,tm);let t=$(e,"size",8,16),s=$(e,"icon",8),r=$(e,"clickable",8,!0),i=$(e,"label",8,""),a=$(e,"pressed",8,void 0),o=$(e,"disabled",8,!1),l=H(),c=$(e,"style",24,()=>({})),d=H(),u=H();const h=Je();cn(()=>{C.setIcon(g(l),s()),f()}),_u(()=>{C.setIcon(g(l),s()),f()});function f(){g(l)&&(Er(l,g(l).style.cssText=g(d)),t()&&(Er(l,g(l).style.width=`${t()}px`),Er(l,g(l).style.height=`${t()}px`)))}function p(b){!r()||o()||h("click",{event:b})}Se(()=>N(c()),()=>{E(d,rr(c()))}),Se(()=>N(a()),()=>{E(u,a()===void 0?void 0:a()?"true":"false")}),Ot(),ke();var m=gt(),v=Ke(m);{var y=b=>{var k=Zp(),P=I(k);Wn(P,M=>E(l,M),()=>g(l)),ve(()=>{de(k,"aria-label",i()),de(k,"aria-pressed",g(u)),k.disabled=o()}),fe("click",k,p),B(b,k)},_=b=>{var k=em();Wn(k,P=>E(l,P),()=>g(l)),ve(()=>{de(k,"aria-label",i()||void 0),de(k,"aria-hidden",i()?void 0:"true")}),B(b,k)};me(v,b=>{r()?b(y):b(_,!1)})}B(n,m),xe()}var nm=G('<button type="button"><!></button>'),sm=G('<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 rm={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 ka(n,e){be(e,!1),$e(n,rm);let t=$(e,"playlist",8),s=$(e,"showDeleteButton",8,!0),r=H(!1);const i=Je();function a(){if(g(r)){i("delete",{value:t()});return}E(r,!0),setTimeout(()=>{E(r,!1)},2e3)}ke();var o=sm(),l=I(o),c=I(l);Ze(c,{get icon(){return N(t()),j(()=>t().icon)},clickable:!1,size:18});var d=K(c,2),u=I(d),h=K(d,2),f=I(h),p=K(l,2),m=I(p);{var v=y=>{var _=nm();let b;var k=I(_);{let P=Ne(()=>g(r)?"check":"trash");Ze(k,{get icon(){return g(P)},clickable:!1,size:16})}ve(()=>{b=nn(_,1,"delete-button svelte-jzsw7l",null,b,{confirm:g(r)}),de(_,"aria-label",g(r)?"Confirm deletion":"Delete playlist")}),fe("click",_,a),B(y,_)};me(m,y=>{s()&&y(v)})}ve(()=>{Fe(u,(N(t()),j(()=>t().name))),Fe(f,`(${N(t()),j(()=>t().episodes.length)??""})`)}),B(n,o),xe()}var im=G("<span></span>");function am(n,e){be(e,!1);let t=$(e,"value",8,""),s=$(e,"options",24,()=>({})),r=$(e,"disabled",8,!1),i=H(),a,o=$(e,"style",8);const l=Je();cn(()=>{a=new C.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",rr(o()))}ke();var d=im();Wn(d,u=>E(i,u),()=>g(i)),B(n,d),xe()}const om=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"]),Ea=Array.from(om);var lm=G('<div class="playlist-manager-container svelte-w5in4v"><div class="playlist-list svelte-w5in4v"><!> <!> <!></div> <div class="add-playlist-container svelte-w5in4v"><!> <!> <!></div></div>');const cm={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 um(n,e){be(e,!1),$e(n,cm);const t=()=>Me(at,"$queue",r),s=()=>Me(Sn,"$favorites",r),[r,i]=Kr();let a=H([]),o=H(""),l=Ea.reduce((S,T)=>(S[T]=T,S),{}),c=H(Ea[0]);cn(()=>{const S=vt.subscribe(T=>{E(a,Object.values(T))});return()=>{S()}});function d(){vt.update(S=>(S[g(o)]={name:g(o),icon:g(c),episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},S)),E(o,""),E(c,Ea[0])}function u(S){E(c,S.detail.value)}function h(S){vt.update(T=>(delete T[S.detail.value.name],T))}function f(S){vt.update(T=>(T[S.detail.value.name].shouldRepeat=!T[S.detail.value.name].shouldRepeat,T))}ke();var p=lm(),m=I(p),v=I(m);ka(v,{get playlist(){return t()},showDeleteButton:!1});var y=K(v,2);ka(y,{get playlist(){return s()},showDeleteButton:!1});var _=K(y,2);Ys(_,1,()=>g(a),Yc,(S,T)=>{ka(S,{get playlist(){return g(T)},$$events:{delete:h,toggleRepeat:f}})});var b=K(m,2),k=I(b);am(k,{get options(){return l},get value(){return g(c)},set value(S){E(c,S)},$$events:{change:u},$$legacy:!0});var P=K(k,2);Do(P,{placeholder:"Playlist name",get value(){return g(o)},set value(S){E(o,S)},$$legacy:!0});var M=K(P,2);Lr(M,{icon:"plus",cta:!0,$$events:{click:d}}),B(n,p),xe(),i()}function Tn(n){return Array.isArray?Array.isArray(n):Nu(n)==="[object Array]"}function dm(n){if(typeof n=="string")return n;let e=n+"";return e=="0"&&1/n==-1/0?"-0":e}function fm(n){return n==null?"":dm(n)}function Zt(n){return typeof n=="string"}function Mu(n){return typeof n=="number"}function hm(n){return n===!0||n===!1||pm(n)&&Nu(n)=="[object Boolean]"}function Fu(n){return typeof n=="object"}function pm(n){return Fu(n)&&n!==null}function mt(n){return n!=null}function Sa(n){return!n.trim().length}function Nu(n){return n==null?n===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(n)}const mm="Incorrect 'index' type",gm=n=>`Invalid value for key ${n}`,vm=n=>`Pattern length exceeds max of ${n}.`,ym=n=>`Missing ${n} property in key`,_m=n=>`Property 'weight' in key '${n}' must be a positive integer`,jl=Object.prototype.hasOwnProperty;class wm{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(s=>{let r=Du(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 Du(n){let e=null,t=null,s=null,r=1,i=null;if(Zt(n)||Tn(n))s=n,e=zl(n),t=no(n);else{if(!jl.call(n,"name"))throw new Error(ym("name"));const a=n.name;if(s=a,jl.call(n,"weight")&&(r=n.weight,r<=0))throw new Error(_m(a));e=zl(a),t=no(a),i=n.getFn}return{path:e,id:t,weight:r,src:s,getFn:i}}function zl(n){return Tn(n)?n:n.split(".")}function no(n){return Tn(n)?n.join("."):n}function bm(n,e){let t=[],s=!1;const r=(i,a,o)=>{if(mt(i))if(!a[o])t.push(i);else{let l=a[o];const c=i[l];if(!mt(c))return;if(o===a.length-1&&(Zt(c)||Mu(c)||hm(c)))t.push(fm(c));else if(Tn(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,Zt(e)?e.split("."):e,0),s?t:t[0]}const xm={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},km={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},Em={location:0,threshold:.6,distance:100},Sm={useExtendedSearch:!1,getFn:bm,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1};var X={...km,...xm,...Em,...Sm};const Am=/[^ ]+/g;function Cm(n=1,e=3){const t=new Map,s=Math.pow(10,e);return{get(r){const i=r.match(Am).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 Oo{constructor({getFn:e=X.getFn,fieldNormWeight:t=X.fieldNormWeight}={}){this.norm=Cm(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,Zt(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();Zt(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(!mt(e)||Sa(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(mt(a)){if(Tn(a)){let o=[];const l=[{nestedArrIndex:-1,value:a}];for(;l.length;){const{nestedArrIndex:c,value:d}=l.pop();if(mt(d))if(Zt(d)&&!Sa(d)){let u={v:d,i:c,n:this.norm.get(d)};o.push(u)}else Tn(d)&&d.forEach((u,h)=>{l.push({nestedArrIndex:h,value:u})})}s.$[i]=o}else if(Zt(a)&&!Sa(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 Ou(n,e,{getFn:t=X.getFn,fieldNormWeight:s=X.fieldNormWeight}={}){const r=new Oo({getFn:t,fieldNormWeight:s});return r.setKeys(n.map(Du)),r.setSources(e),r.create(),r}function Pm(n,{getFn:e=X.getFn,fieldNormWeight:t=X.fieldNormWeight}={}){const{keys:s,records:r}=n,i=new Oo({getFn:e,fieldNormWeight:t});return i.setKeys(s),i.setIndexRecords(r),i}function si(n,{errors:e=0,currentLocation:t=0,expectedLocation:s=0,distance:r=X.distance,ignoreLocation:i=X.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 Tm(n=[],e=X.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 ts=32;function Im(n,e,t,{location:s=X.location,distance:r=X.distance,threshold:i=X.threshold,findAllMatches:a=X.findAllMatches,minMatchCharLength:o=X.minMatchCharLength,includeMatches:l=X.includeMatches,ignoreLocation:c=X.ignoreLocation}={}){if(e.length>ts)throw new Error(vm(ts));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 y;for(;(y=n.indexOf(e,p))>-1;){let S=si(e,{currentLocation:y,expectedLocation:h,distance:r,ignoreLocation:c});if(f=Math.min(S,f),p=y+d,m){let T=0;for(;T<d;)v[y+T]=1,T+=1}}p=-1;let _=[],b=1,k=d+u;const P=1<<d-1;for(let S=0;S<d;S+=1){let T=0,R=k;for(;T<R;)si(e,{errors:S,currentLocation:h+R,expectedLocation:h,distance:r,ignoreLocation:c})<=f?T=R:k=R,R=Math.floor((k-T)/2+T);k=R;let F=Math.max(1,h-R+1),W=a?u:Math.min(h+R,u)+d,ee=Array(W+2);ee[W+1]=(1<<S)-1;for(let oe=W;oe>=F;oe-=1){let V=oe-1,ie=t[n.charAt(V)];if(m&&(v[V]=+!!ie),ee[oe]=(ee[oe+1]<<1|1)&ie,S&&(ee[oe]|=(_[oe+1]|_[oe])<<1|1|_[oe+1]),ee[oe]&P&&(b=si(e,{errors:S,currentLocation:V,expectedLocation:h,distance:r,ignoreLocation:c}),b<=f)){if(f=b,p=V,p<=h)break;F=Math.max(1,2*h-p)}}if(si(e,{errors:S+1,currentLocation:h,expectedLocation:h,distance:r,ignoreLocation:c})>f)break;_=ee}const M={isMatch:p>=0,score:Math.max(.001,b)};if(m){const S=Tm(v,o);S.length?l&&(M.indices=S):M.isMatch=!1}return M}function $m(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 Ri=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 Lu{constructor(e,{location:t=X.location,threshold:s=X.threshold,distance:r=X.distance,includeMatches:i=X.includeMatches,findAllMatches:a=X.findAllMatches,minMatchCharLength:o=X.minMatchCharLength,isCaseSensitive:l=X.isCaseSensitive,ignoreDiacritics:c=X.ignoreDiacritics,ignoreLocation:d=X.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?Ri(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;const u=(f,p)=>{this.chunks.push({pattern:f,alphabet:$m(f),startIndex:p})},h=this.pattern.length;if(h>ts){let f=0;const p=h%ts,m=h-p;for(;f<m;)u(this.pattern.substr(f,ts),f),f+=ts;if(p){const v=h-ts;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?Ri(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:y})=>{const{isMatch:_,score:b,indices:k}=Im(e,m,v,{location:i+y,distance:a,threshold:o,findAllMatches:l,minMatchCharLength:c,includeMatches:r,ignoreLocation:d});_&&(f=!0),h+=b,_&&k&&(u=[...u,...k])});let p={isMatch:f,score:f?h/this.chunks.length:1};return f&&r&&(p.indices=u),p}}class Kn{constructor(e){this.pattern=e}static isMultiMatch(e){return ql(e,this.multiRegex)}static isSingleMatch(e){return ql(e,this.singleRegex)}search(){}}function ql(n,e){const t=n.match(e);return t?t[1]:null}class Rm extends Kn{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 Mm extends Kn{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 Fm extends Kn{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 Nm extends Kn{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 Dm extends Kn{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 Om extends Kn{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 Bu extends Kn{constructor(e,{location:t=X.location,threshold:s=X.threshold,distance:r=X.distance,includeMatches:i=X.includeMatches,findAllMatches:a=X.findAllMatches,minMatchCharLength:o=X.minMatchCharLength,isCaseSensitive:l=X.isCaseSensitive,ignoreDiacritics:c=X.ignoreDiacritics,ignoreLocation:d=X.ignoreLocation}={}){super(e),this._bitapSearch=new Lu(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 Uu extends Kn{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 so=[Rm,Uu,Fm,Nm,Om,Dm,Mm,Bu],Wl=so.length,Lm=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,Bm="|";function Um(n,e={}){return n.split(Bm).map(t=>{let s=t.trim().split(Lm).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<Wl;){const d=so[c];let u=d.isMultiMatch(o);u&&(r.push(new d(u,e)),l=!0)}if(!l)for(c=-1;++c<Wl;){const d=so[c];let u=d.isSingleMatch(o);if(u){r.push(new d(u,e));break}}}return r})}const jm=new Set([Bu.type,Uu.type]);class zm{constructor(e,{isCaseSensitive:t=X.isCaseSensitive,ignoreDiacritics:s=X.ignoreDiacritics,includeMatches:r=X.includeMatches,minMatchCharLength:i=X.minMatchCharLength,ignoreLocation:a=X.ignoreLocation,findAllMatches:o=X.findAllMatches,location:l=X.location,threshold:c=X.threshold,distance:d=X.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?Ri(e):e,this.pattern=e,this.query=Um(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?Ri(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:y}=p.search(e);if(m){if(a+=1,l+=y,s){const _=p.constructor.type;jm.has(_)?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 ro=[];function qm(...n){ro.push(...n)}function io(n,e){for(let t=0,s=ro.length;t<s;t+=1){let r=ro[t];if(r.condition(n,e))return new r(n,e)}return new Lu(n,e)}const Mi={AND:"$and",OR:"$or"},ao={PATH:"$path",PATTERN:"$val"},oo=n=>!!(n[Mi.AND]||n[Mi.OR]),Wm=n=>!!n[ao.PATH],Hm=n=>!Tn(n)&&Fu(n)&&!oo(n),Hl=n=>({[Mi.AND]:Object.keys(n).map(e=>({[e]:n[e]}))});function ju(n,e,{auto:t=!0}={}){const s=r=>{let i=Object.keys(r);const a=Wm(r);if(!a&&i.length>1&&!oo(r))return s(Hl(r));if(Hm(r)){const l=a?r[ao.PATH]:i[0],c=a?r[ao.PATTERN]:r[l];if(!Zt(c))throw new Error(gm(l));const d={keyId:no(l),pattern:c};return t&&(d.searcher=io(c,e)),d}let o={children:[],operator:i[0]};return i.forEach(l=>{const c=r[l];Tn(c)&&c.forEach(d=>{o.children.push(s(d))})}),o};return oo(n)||(n=Hl(n)),s(n)}function Vm(n,{ignoreFieldNorm:e=X.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 Km(n,e){const t=n.matches;e.matches=[],mt(t)&&t.forEach(s=>{if(!mt(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 Ym(n,e){e.score=n.score}function Jm(n,e,{includeMatches:t=X.includeMatches,includeScore:s=X.includeScore}={}){const r=[];return t&&r.push(Km),s&&r.push(Ym),n.map(i=>{const{idx:a}=i,o={item:e[a],refIndex:a};return r.length&&r.forEach(l=>{l(i,o)}),o})}class xs{constructor(e,t={},s){this.options={...X,...t},this.options.useExtendedSearch,this._keyStore=new wm(this.options.keys),this.setCollection(e,s)}setCollection(e,t){if(this._docs=e,t&&!(t instanceof Oo))throw new Error(mm);this._myIndex=t||Ou(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){mt(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=Zt(e)?Zt(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e);return Vm(l,{ignoreFieldNorm:o}),i&&l.sort(a),Mu(t)&&t>-1&&(l=l.slice(0,t)),Jm(l,this._docs,{includeMatches:s,includeScore:r})}_searchStringList(e){const t=io(e,this.options),{records:s}=this._myIndex,r=[];return s.forEach(({v:i,i:a,n:o})=>{if(!mt(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=ju(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===Mi.AND)return[]}return d},r=this._myIndex.records,i={},a=[];return r.forEach(({$:o,i:l})=>{if(mt(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=io(e,this.options),{keys:s,records:r}=this._myIndex,i=[];return r.forEach(({$:a,i:o})=>{if(!mt(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(!mt(t))return[];let r=[];if(Tn(t))t.forEach(({v:i,i:a,n:o})=>{if(!mt(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}}xs.version="7.1.0";xs.createIndex=Ou;xs.parseIndex=Pm;xs.config=X;xs.parseQuery=ju;qm(zm);function Lo(n){const t=new RegExp(/\.([0-9a-z]+)(?:[?#]|$)/i).exec(n);if(!t)return"";const[,s]=t;return s}function sa(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=M=>M.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=M=>{const S=["th","st","nd","rd"],T=M%100;return M+(S[(T-20)%10]||S[T]||S[0])},m=a%12||12,v=a>=12,y={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"},_=Object.keys(y).sort((M,S)=>S.length-M.length).map(M=>M.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),b=new RegExp(`\\[([^\\]]*)]|(${_})|.`,"g");let k="",P;for(;(P=b.exec(e))!==null;)P[1]!==void 0?k+=P[1]:P[2]!==void 0?k+=y[P[2]]:k+=P[0];return k}function Yr(){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 xs(Object.keys(n),{shouldSort:!0,findAllMatches:!1,threshold:.4,isCaseSensitive:!1}).search(i);return new C.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 Xm(n,e){const[t,s]=Yr();return s("title",e.title),s("description",r=>{const i=C.htmlToMarkdown(e.description).replace(/\n{3,}/g,`
`);return r?i.split(`
`).map(a=>`${r}${a}`).join(`
`):i}),s("content",r=>r?C.htmlToMarkdown(e.content).split(`
`).map(i=>`${r}${i}`).join(`
`):C.htmlToMarkdown(e.content)),s("safetitle",Hn(e.title)),s("stream",e.streamUrl),s("url",e.url),s("date",r=>e.episodeDate?sa(e.episodeDate,r??"YYYY-MM-DD"):""),s("podcast",Hn(e.podcastName)),s("artwork",e.artworkUrl??""),t(n)}function zu(n){const[e,t]=Yr(),{api:s,settings:r}=Y(rn),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 gs(n,e){const[t,s]=Yr();return s("title",r=>{const i=Hn(e.title);return r?i.replace(/\s+/g,r):i}),s("podcast",r=>{const i=Hn(e.podcastName);return r?i.replace(/\s+/g,r):i}),s("date",r=>e.episodeDate?sa(e.episodeDate,r??"YYYY-MM-DD"):""),t(n)}function Bo(n,e){const t=Lo(n),s=t?n.replace(t,""):n,[r,i]=Yr();return i("title",a=>{const o=Hn(e.title);return a?o.replace(/\s+/g,a):o}),i("podcast",a=>{const o=Hn(e.podcastName);return a?o.replace(/\s+/g,a):o}),i("date",a=>e.episodeDate?sa(e.episodeDate,a??"YYYY-MM-DD"):""),r(s)}function Gm(n,e,t){const[s,r]=Yr();return r("title",i=>{const a=Hn(e.title);return i?a.replace(/\s+/g,i):a}),r("podcast",i=>{const a=Hn(e.podcastName);return i?a.replace(/\s+/g,i):a}),r("date",i=>e.episodeDate?sa(e.episodeDate,i??"YYYY-MM-DD"):""),r("transcript",t),r("description",i=>i?C.htmlToMarkdown(e.description).split(`
`).map(a=>`${i}${a}`).join(`
`):C.htmlToMarkdown(e.description)),r("url",e.url),r("artwork",e.artworkUrl??""),s(n)}function Hn(n){return n.replace(/[\\,#%&{}/*<>$'":@\u2023|\\.?]/g,"").replace(/\n/," ").replace(" "," ")}function Qm(n,e){let t=e;const s=Date.now();let r,i;const a=new C.Notice(e,0);function o(u){return`${n} (${c()}):
${u}`}function l(u){t=u,a.setMessage(o(t))}function c(){return Zm(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 Zm(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 eg(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=Y(En),a=r.filter(f=>!Object.values(i).some(p=>p.url===f.url)),o=Qm("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 na().getFeed(f.url);return l++,c(),p}catch{return l++,c(),null}}));o.stop();const u=d.filter(f=>f!==null);En.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 C.Notice(`Failed to import ${f} podcasts. Check console for details.`,1e4)}setTimeout(()=>o.hide(),5e3)}catch(e){new C.Notice(`Error importing OPML: ${e instanceof Error?e.message:"Unknown error"}`,1e4)}}async function tg(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 C.Notice(`Exported ${e.length} podcast feeds to file "${t}".`)}catch(u){u instanceof Error?u.message.includes("Folder does not exist")?new C.Notice("Unable to create export file: Folder does not exist."):new C.Notice(`Unable to create podcast export file:
${u.message}`):new C.Notice("An unexpected error occurred during export.")}}const Tr="podnotes:feed-cache:v1",ng=1e3*60*60*6,sg=75,Vl=4*1024*1024;let je=null;function Uo(){try{return typeof localStorage>"u"?null:localStorage}catch{return null}}function qu(){if(je)return je;const n=Uo();if(!n)return je={},je;try{const e=n.getItem(Tr);return e?(je=JSON.parse(e),je):(je={},je)}catch{return je={},je}}function rg(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 Wu(){const n=Uo();if(!(!n||!je))try{let e=JSON.stringify(je);e.length>Vl&&(je=rg(je,Vl*.8),e=JSON.stringify(je)),n.setItem(Tr,e)}catch(e){if(e instanceof DOMException&&(e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"))try{je={},n.setItem(Tr,"{}")}catch{n.removeItem(Tr)}}}function ig(n){return{...n,episodeDate:n.episodeDate?.toISOString()}}function ag(n){return{...n,episodeDate:n.episodeDate?new Date(n.episodeDate):void 0}}function Hu(n){return n.url??n.title}function og(n,e=ng){const t=qu(),s=Hu(n),r=t[s];return r?Date.now()-r.updatedAt>e?(delete t[s],Wu(),null):r.episodes.map(ag):null}function lg(n,e){if(!e.length)return;const t=qu(),s=Hu(n);t[s]={updatedAt:Date.now(),episodes:e.slice(0,sg).map(ig)},Wu()}function cg(){je={};const n=Uo();try{n?.removeItem(Tr)}catch{}}class ug extends C.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 C.Setting(s).setName("Search Podcasts").setHeading().setDesc("Search for podcasts by name or custom feed URL.");const r=s.createDiv();this.podcastQueryGrid=Ja(Qp,{target:r}),new C.Setting(s).setName("Playlists").setHeading().setDesc("Add playlists to gather podcast episodes.");const i=s.createDiv();this.playlistManager=Ja(um,{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&&(Ga(this.podcastQueryGrid),this.podcastQueryGrid=null),this.playlistManager&&(Ga(this.playlistManager),this.playlistManager=null)}addDefaultPlaybackRateSetting(e){new C.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 C.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 C.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 C.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 C.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=zu(d);r.empty(),C.MarkdownRenderer.renderMarkdown(u,r,"",new C.Component)};new C.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=Aa(),o=new C.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=gs(u,a);l.empty(),C.MarkdownRenderer.renderMarkdown(h,l,"",new C.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 C.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}}
![]({{artwork}})
### 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=Aa(),s=new C.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=Bo(a,t);r.empty(),C.MarkdownRenderer.renderMarkdown(`${o}.mp3`,r,"",new C.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 C.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 C.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 C.Setting(e).setName("Clear cached feeds").setDesc("Remove stored feed data. PodNotes will refetch feeds as needed.").addButton(t=>t.setButtonText("Clear cache").onClick(()=>{cg(),Dn.set({}),new C.Notice("Cleared cached podcast feeds.")}))}addImportExportSettings(e){e.createEl("h3",{text:"Import/Export"}),new C.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 eg(d)}catch(u){new C.Notice(`Error importing OPML: ${u instanceof Error?u.message:"Unknown error"}`,1e4)}},l.readAsText(o)}else new C.Notice("No file selected")}}));let t="PodNotes_Export.opml";new C.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(Y(En));if(r.length===0){new C.Notice("No podcasts to export.");return}tg(this.app,r,t.endsWith(".opml")?t:`${t}.opml`)}))}addTranscriptSettings(e){e.createEl("h4",{text:"Transcript settings"});const t=Aa();new C.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 C.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=gs(a,t);s.empty(),s.createEl("p",{text:`Example: ${o}`})};r(this.plugin.settings.transcript.path);const i=new C.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 Aa(){const n={description:"demo",content:"demo",podcastName:"demo",title:"demo",url:"demo",artworkUrl:"demo",streamUrl:"demo",episodeDate:new Date,feedUrl:"demo"},e=Object.values(Y(Dn));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 dg=G('<button type="button" class="playlist-card svelte-5dhk44"><!> <span class="svelte-5dhk44"> </span></button>');const fg={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 hg(n,e){be(e,!1),$e(n,fg);let t=$(e,"playlist",8);const s=Je();function r(c){s("clickPlaylist",{playlist:t(),event:c})}ke();var i=dg(),a=I(i);Ze(a,{get icon(){return N(t()),j(()=>t().icon)},size:40,clickable:!1});var o=K(a,2),l=I(o);ve(()=>{de(i,"aria-label",(N(t()),j(()=>t().name))),Fe(l,`(${N(t()),j(()=>t().episodes.length)??""})`)}),fe("click",i,r),B(n,i),xe()}var pg=G('<button type="button" class="pn_image_container svelte-ds4mor"><img draggable="false"/></button>'),mg=G('<div class="pn_image_container pn_image_container--static svelte-ds4mor"><img draggable="false"/></div>');const gg={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 jo(n,e){be(e,!1),$e(n,gg);let t=$(e,"src",8),s=$(e,"alt",8),r=$(e,"fadeIn",8,!1),i=$(e,"opacity",8,0),a=$(e,"interactive",8,!1),o=$(e,"loading",8,"lazy"),l=$(e,"class",8,""),c=H(!1),d=H(!0),u=H(!1);const h=Je();function f(_){h("click",{event:_})}ke();var p=gt(),m=Ke(p);{var v=_=>{var b=gt(),k=Ke(b);{var P=S=>{var T=pg(),R=I(T);let F;ve(()=>{de(R,"src",t()),de(R,"alt",s()),de(R,"loading",o()),nn(R,1,$l(l()),"svelte-ds4mor"),F=Dr(R,"",F,{opacity:i()?i():r()?g(c)?1:0:1,transition:r()?"opacity 0.5s ease-out":""})}),fe("load",R,()=>{E(c,!0),E(d,!1)}),fe("error",R,()=>{E(u,!0),E(d,!1)}),fe("click",T,f),B(S,T)},M=S=>{var T=mg(),R=I(T);let F;ve(()=>{de(R,"src",t()),de(R,"alt",s()),de(R,"loading",o()),nn(R,1,$l(l()),"svelte-ds4mor"),F=Dr(R,"",F,{opacity:i()?i():r()?g(c)?1:0:1,transition:r()?"opacity 0.5s ease-out":""})}),fe("load",R,()=>{E(c,!0),E(d,!1)}),fe("error",R,()=>{E(u,!0),E(d,!1)}),B(S,T)};me(k,S=>{a()?S(P):S(M,!1)})}B(_,b)},y=_=>{var b=gt(),k=Ke(b);{var P=M=>{var S=gt(),T=Ke(S);pu(T,e,"fallback",{},null),B(M,S)};me(k,M=>{g(u)&&M(P)},!0)}B(_,b)};me(m,_=>{g(d)||g(c)?_(v):_(y,!1)})}B(n,p),xe()}const vg={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 yg(n,e){be(e,!1),$e(n,vg);let t=$(e,"feed",8);const s=Je();function r(a){s("clickPodcast",{feed:a})}ke();var i=Un(()=>r.bind(null,t()));jo(n,{get src(){return N(t()),j(()=>t().artworkUrl)},get alt(){return N(t()),j(()=>t().title)},interactive:!0,class:"podcast-image",$$events:{click(...a){g(i)?.apply(this,a)}}}),xe()}var _g=G("<div><p>No saved podcasts.</p></div>"),wg=G('<div class="podcast-grid svelte-1x0bcng"><!> <!></div>');const bg={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 xg(n,e){be(e,!1),$e(n,bg);let t=$(e,"feeds",24,()=>[]),s=$(e,"playlists",24,()=>[]);const r=Je();function i({detail:{playlist:h,event:f}}){r("clickPlaylist",{playlist:h,event:f})}ke();var a=wg(),o=I(a);{var l=h=>{var f=gt(),p=Ke(f);Ys(p,1,s,m=>m.name,(m,v)=>{hg(m,{get playlist(){return g(v)},$$events:{clickPlaylist:i}})}),B(h,f)};me(o,h=>{N(s()),j(()=>s().length>0)&&h(l)})}var c=K(o,2);{var d=h=>{var f=gt(),p=Ke(f);Ys(p,1,t,m=>m.url,(m,v)=>{yg(m,{get feed(){return g(v)},$$events:{clickPodcast(y){yu.call(this,e,y)}}})}),B(h,f)},u=h=>{var f=_g();B(h,f)};me(c,h=>{N(t()),j(()=>t().length>0)?h(d):h(u,!1)})}B(n,a),xe()}async function kg(n){if(!n)return[];try{const e=await No(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 Eg=G("<span></span>");function Kl(n,e){be(e,!1);let t=$(e,"value",8),s=$(e,"limits",8),r=H();const i=Je();let a=H(),o=$(e,"style",24,()=>({})),l=null,c=!1;cn(()=>{E(a,new C.SliderComponent(g(r))),l=h=>{if(c)return;const f=Number(h.target.value);i("change",{value:f})},g(a).sliderEl.addEventListener("input",l)}),ta(()=>{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",rr(m))}Se(()=>(g(a),N(t()),N(s()),N(o())),()=>{g(a)&&d(g(a),t(),s(),o())}),Ot(),ke();var u=Eg();Wn(u,h=>E(r,h),()=>g(r)),B(n,u),xe()}var Sg=G('<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 Ag={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 Vu(n){$e(n,Ag);var e=Sg();B(n,e)}var Cg=G('<div class="image-loader svelte-jp8vu"><!></div>');const Pg={hash:"svelte-jp8vu",code:".image-loader.svelte-jp8vu {position:relative;width:100%;}"};function Tg(n,e){be(e,!1),$e(n,Pg);const t=H(),s=H(),r=H();let i=$(e,"src",8),a=$(e,"alt",8),o=$(e,"fadeIn",8,!1),l=$(e,"interactive",8,!1),c=$(e,"width",8),d=$(e,"height",8),u=$(e,"aspectRatio",8,"1 / 1"),h=$(e,"loading",8,"lazy"),f=$(e,"class",8,"");const p=Je(),m=b=>typeof b=="number"?`${b}px`:b;Se(()=>N(c()),()=>{E(t,m(c()))}),Se(()=>N(d()),()=>{E(s,m(d()))}),Se(()=>(g(s),N(u())),()=>{E(r,g(s)?void 0:u())}),Ot(),ke();var v=Cg();let y;var _=I(v);jo(_,{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})}}),ve(()=>y=Dr(v,"",y,{width:g(t),height:g(s),"aspect-ratio":g(r)})),B(n,v),xe()}var Ig=G('<div class="podcast-episode-thumbnail-container svelte-dmhmse"><!></div>'),$g=G('<div class="podcast-episode-thumbnail-container svelte-dmhmse"></div>'),Rg=G('<span class="episode-item-status svelte-dmhmse"> </span>'),Mg=G('<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 Fg={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-item.svelte-dmhmse:has(.episode-item-status:where(.svelte-dmhmse)) {opacity:0.75;}.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;}.episode-item-status.svelte-dmhmse {font-size:0.75rem;color:var(--text-muted);}`};function Ng(n,e){be(e,!1),$e(n,Fg);let t=$(e,"episode",8),s=$(e,"episodeFinished",8,!1),r=$(e,"showEpisodeImage",8,!1),i=$(e,"unavailableReason",8,void 0);const a=Je(),o=new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"long",year:"numeric"}),l=new Map;function c(){a("clickEpisode",{episode:t()})}function d(F){a("contextMenu",{episode:t(),event:F})}function u(F){if(!F)return null;const W=new Date(F);return Number.isNaN(W.getTime())?null:W}function h(F,W){return`${F.url??F.streamUrl??F.title??"episode"}|${W.getTime()}`}function f(F){const W=u(F?.episodeDate);if(!W)return"";const ee=h(F,W),ye=l.get(ee);if(ye)return ye;const oe=o.format(W).toUpperCase();return l.set(ee,oe),oe}let p=H("");Se(()=>N(t()),()=>{E(p,f(t()))}),Ot(),ke();var m=Mg(),v=I(m);{var y=F=>{var W=Ig(),ee=I(W);Tg(ee,{get src(){return N(t()),j(()=>t().artworkUrl)},get alt(){return N(t()),j(()=>t().title)},fadeIn:!0,width:"100%",height:"100%",class:"podcast-episode-thumbnail"}),B(F,W)},_=F=>{var W=gt(),ee=Ke(W);{var ye=oe=>{var V=$g();B(oe,V)};me(ee,oe=>{r()&&oe(ye)},!0)}B(F,W)};me(v,F=>{N(r()),N(t()),j(()=>r()&&t()?.artworkUrl)?F(y):F(_,!1)})}var b=K(v,2),k=I(b),P=I(k),M=K(k,2),S=I(M),T=K(M,2);{var R=F=>{var W=Rg(),ee=I(W);ve(()=>Fe(ee,i())),B(F,W)};me(T,F=>{i()&&F(R)})}ve(()=>{de(m,"title",(N(i()),N(t()),j(()=>i()??t().title))),Fe(P,g(p)),nn(M,1,`episode-item-title ${s()&&"strikeout"}`,"svelte-dmhmse"),Fe(S,(N(t()),j(()=>t().title)))}),fe("click",m,c),fe("contextmenu",m,d),B(n,m),xe()}function Dg(n){return{episode:n,isAvailable:!0}}function Og(n){return n.map(Dg)}function Lg(n,e){const t=jg(e.flat());return xu(n).map(({key:s,episode:r})=>Bg(s,r,t)).sort(zg)}function Bg(n,e,t){const s=Ug(n,e,t);return s?{episode:s,isAvailable:!0,playedEpisode:e,playedEpisodeKey:n}:{episode:Ku(e),isAvailable:!1,unavailableReason:"Unavailable in current feeds",playedEpisode:e,playedEpisodeKey:n}}function Ug(n,e,t){const s=[n,Fo(e),e.title];for(const r of s){const i=t.get(r);if(i)return i}}function jg(n){const e=new Map;for(const t of n){const s=[sn(t),t.podcastName?`${t.podcastName}::${t.title}`:"",t.title].filter(Boolean);for(const r of s)e.has(r)||e.set(r,t)}return e}function Ku(n){return{title:n.title,podcastName:n.podcastName,streamUrl:"",url:"",description:"",content:""}}function zg(n,e){if(n.isAvailable!==e.isAvailable)return n.isAvailable?-1:1;const t=Yl(n.episode),s=Yl(e.episode);return t!==s?s-t:n.episode.title.localeCompare(e.episode.title)}function Yl(n){if(!n.episodeDate)return 0;const e=Number(new Date(n.episodeDate));return Number.isNaN(e)?0:e}var qg=G('<div class="episode-list-menu svelte-ozfrsd"><div class="episode-list-search svelte-ozfrsd"><!></div> <!> <!></div>'),Wg=G('<div class="episode-list-loading svelte-ozfrsd" role="status" aria-live="polite"><!> <span>Fetching episodes...</span></div>'),Hg=G('<p class="svelte-ozfrsd">No episodes found.</p>'),Vg=G('<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 Yu(n,e){be(e,!1),$e(n,Kg);const t=()=>Me(Ii,"$hidePlayedEpisodes",r),s=()=>Me(Ye,"$playedEpisodes",r),[r,i]=Kr(),a=H(),o=H(),l=H();let c=$(e,"episodes",24,()=>[]),d=$(e,"episodeEntries",8,null),u=$(e,"showThumbnails",8,!1),h=$(e,"showListMenu",8,!0),f=$(e,"showPlayedToggle",8,!0),p=$(e,"alwaysShowPlayedEpisodes",8,!1),m=$(e,"isLoading",8,!1),v=H("");const y=Je();function _(V,ie){y("clickEpisode",{episode:ie.detail.episode,entry:V})}function b(V,ie){y("contextMenuEpisode",{episode:ie.detail.episode,entry:V,event:ie.detail.event})}function k(V){y("search",{query:V.detail.value})}Se(()=>(N(d()),N(c())),()=>{E(a,d()??Og(c()))}),Se(()=>(t(),N(p())),()=>{E(o,t()&&!p())}),Se(()=>(g(a),g(o),s()),()=>{E(l,g(a).filter(V=>!g(o)||!Cr(V.episode,s())))}),Ot(),ke();var P=Vg(),M=I(P);pu(M,e,"header",{},V=>{var ie=Zh("Fallback");B(V,ie)});var S=K(M,2);{var T=V=>{var ie=qg(),Lt=I(ie),un=I(Lt);Do(un,{placeholder:"Search episodes",style:{width:"100%"},get value(){return g(v)},set value(Ut){E(v,Ut)},$$events:{input:k},$$legacy:!0});var dn=K(Lt,2);{var Bt=Ut=>{{let Yn=Ne(()=>t()?"eye-off":"eye"),ks=Ne(()=>t()?"Show played episodes":"Hide played episodes");Ze(Ut,{get icon(){return g(Yn)},size:25,get label(){return g(ks)},get pressed(){return t()},$$events:{click:()=>Ii.update(or=>!or)}})}};me(dn,Ut=>{f()&&Ut(Bt)})}var fn=K(dn,2);Ze(fn,{icon:"refresh-cw",size:25,label:"Refresh episodes",$$events:{click:()=>y("clickRefresh")}}),B(V,ie)};me(S,V=>{h()&&V(T)})}var R=K(S,2),F=I(R);{var W=V=>{var ie=Wg(),Lt=I(ie);Vu(Lt),B(V,ie)};me(F,V=>{m()&&V(W)})}var ee=K(F,2);{var ye=V=>{var ie=Hg();B(V,ie)};me(ee,V=>{g(l),N(m()),j(()=>g(l).length===0&&!m())&&V(ye)})}var oe=K(ee,2);Ys(oe,3,()=>g(l),(V,ie)=>sn(V.episode)??`${V.episode.title}-${V.episode.episodeDate??""}-${ie}`,(V,ie)=>{var Lt=Un(()=>_.bind(null,g(ie))),un=Un(()=>b.bind(null,g(ie)));{let dn=Ne(()=>(N(Cr),g(ie),s(),j(()=>Cr(g(ie).episode,s()))));Ng(V,{get episode(){return g(ie),j(()=>g(ie).episode)},get episodeFinished(){return g(dn)},get showEpisodeImage(){return u()},get unavailableReason(){return g(ie),j(()=>g(ie).unavailableReason)},$$events:{clickEpisode(...Bt){g(Lt)?.apply(this,Bt)},contextMenu(...Bt){g(un)?.apply(this,Bt)}}})}}),B(n,P),xe(),i()}var Yg=G('<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>'),Jg=G('<ul class="chapters svelte-1vxfdxx"></ul>'),Xg=G('<div class="chapter-list svelte-1vxfdxx"><button type="button" class="chapter-header svelte-1vxfdxx"><!> <h3 class="svelte-1vxfdxx"> </h3></button> <!></div>');const Gg={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 Qg(n,e){be(e,!1),$e(n,Gg);const t=H();let s=$(e,"chapters",24,()=>[]),r=$(e,"currentTime",8,0);const i=Je();let a=H(!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})}Se(()=>{},()=>{E(t,o())}),Ot(),ke();var c=gt(),d=Ke(c);{var u=h=>{var f=Xg(),p=I(f),m=I(p);{let k=Ne(()=>g(a)?"chevron-down":"chevron-right");Ze(m,{get icon(){return g(k)},size:16})}var v=K(m,2),y=I(v),_=K(p,2);{var b=k=>{var P=Jg();Ys(P,5,s,Yc,(M,S,T)=>{var R=Yg();let F;var W=I(R),ee=I(W),ye=I(ee),oe=K(ee,2),V=I(oe);ve(ie=>{F=nn(R,1,"svelte-1vxfdxx",null,F,{active:T===g(t)}),Fe(ye,ie),Fe(V,(g(S),j(()=>g(S).title)))},[()=>(N(Or),g(S),j(()=>Or(g(S).startTime,"H:mm:ss")))]),fe("click",W,()=>l(g(S))),B(M,R)}),B(k,P)};me(_,k=>{g(a)&&k(b)})}ve(()=>{de(p,"aria-expanded",g(a)),Fe(y,`Chapters (${N(s()),j(()=>s().length)??""})`)}),fe("click",p,()=>E(a,!g(a))),B(h,f)};me(d,h=>{N(s()),j(()=>s().length>0)&&h(u)})}B(n,c),xe()}var Zg=G('<div class="progress svelte-aac6sw" role="slider" tabindex="0" aria-valuemin="0"><div class="progress__bar svelte-aac6sw"></div></div>');const ev={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 tv(n,e){be(e,!1),$e(n,ev);let t=$(e,"max",8),s=$(e,"value",8),r=!1,i=$(e,"style",24,()=>({})),a=H(),o=H();const l=Je();function c(v,y){l("click",{event:v,percent:y})}function d(){r=!0}function u(){r=!1}function h(v){r&&c(v)}function f(v){if(!g(a)||!t())return;const y=t()*.05;let _=s();switch(v.key){case"ArrowRight":case"ArrowUp":_=Math.min(t(),s()+y);break;case"ArrowLeft":case"ArrowDown":_=Math.max(0,s()-y);break;case"Home":_=0;break;case"End":_=t();break;case"Enter":case" ":_=s();break;default:return}v.preventDefault();const b=t()?_/t():0;c(v,b)}Se(()=>N(i()),()=>{E(o,rr(i()))}),Ot(),ke();var p=Zg(),m=I(p);Wn(p,v=>E(a,v),()=>g(a)),ve(v=>{de(p,"aria-valuemax",t()),de(p,"aria-valuenow",s()),Dr(p,g(o)),Dr(m,v)},[()=>(N(t()),N(s()),j(()=>`width: ${t()?Math.min(100,s()/t()*100):0}%;`))]),fe("click",p,c),fe("mousedown",p,d),fe("mouseup",p,u),fe("mousemove",p,h),fe("keydown",p,f),B(n,p),xe()}function Ju(n,e){const t=e.startsWith(".")?e:`.${e}`;return n.endsWith(t)?n:`${n}${t}`}async function Xu(n){const e=Y(rn),t=gs(e.settings.note.path,n),s=Ju(t,"md"),r=Xm(e.settings.note.template,n);try{const i=await sv(s,r,n);app.workspace.getLeaf().openFile(i)}catch{new C.Notice(`Failed to create note: "${s}"`)}}function zo(n){const e=Y(rn),t=gs(e.settings.note.path,n),s=Ju(t,"md"),r=app.vault.getAbstractFileByPath(s);return!r||!(r instanceof C.TFile)?null:r}function nv(n){const e=zo(n);if(!e){new C.Notice(`Note for "${n.title}" does not exist`);return}app.workspace.getLeaf().openFile(e)}async function sv(n,e,t,s=!0){const r=zo(t);if(r)return new C.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 rv=/[()]/g,iv={"(":"%28",")":"%29"};function Gu(n){const e=n.trim();if(!e)return e;let t;try{t=new URL(e).toString()}catch{t=av(e)}return t.replace(rv,r=>iv[r]??r)}function av(n){return n.replace(/\s/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)}const ov=[{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 Qu(n){if(!n)return null;for(const{pattern:e,extension:t}of ov)if(e.test(n))return t;return null}function ra(n){return n instanceof Error?n.message:String(n)}async function Zu(n,e){const t=Gu(n);try{const s=await C.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}:
${ra(s)}`);throw e?.onError?.(r),r}}async function ed(n,e){const{doc:t,update:s}=lv(`Download "${n.title}"`),r=999999999,i=new C.Notice(t,r);s(u=>u.createEl("p",{text:"Starting download..."})),s(u=>{u.createEl("p",{text:"Downloading..."})});const{blob:a}=await Zu(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 dv(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 td({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:ra(u)});f.style.fontStyle="italic"})}setTimeout(()=>i.hide(),1e4)}function lv(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 td({episode:n,downloadPathTemplate:e,blob:t,extension:s}){const i=`${Bo(e,n)}.${s}`,a=await t.arrayBuffer();try{await app.vault.createBinary(i,a)}catch(o){throw new Error(`Failed to write file "${i}": ${ra(o)}`)}lt.addEpisode(n,i,t.size)}function cv(n){const e=lt.getEpisode(n),t=[n.filePath,e?.filePath,uv(n.url)];for(const s of t){if(!s)continue;const r=app.vault.getAbstractFileByPath(s);if(r instanceof C.TFile)return r.path}return null}function uv(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 C.TFile)return i.path;const a=app.metadataCache?.getFirstLinkpathDest(r,"");return a instanceof C.TFile?a.path:null}async function dv(n,e){const t=await pv(e);if(t)return t;const s=Lo(n.streamUrl);return s||Qu(e.type)}async function fv(n,e){if(Cu(n)){const a=cv(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=Bo(e,n),s=await hv(n.streamUrl),r=`${t}.${s}`;if(app.vault.getAbstractFileByPath(r)instanceof C.TFile)return r;try{const{blob:a}=await Zu(n.streamUrl);if(!a.type.includes("audio")&&!s)throw new Error("Not an audio file.");return await td({episode:n,downloadPathTemplate:e,blob:a,extension:s}),r}catch(a){throw new Error(`Failed to download ${n.title}: ${ra(a)}`)}}async function hv(n){const e=Gu(n),t=Lo(e);if(t)return t;try{const r=(await fetch(e,{method:"HEAD"})).headers.get("content-type"),i=Qu(r);if(i)return i}catch{}return"mp3"}async function pv(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 lo(n,e,t,s){const r=new C.Menu;if(t?.play||r.addItem(i=>i.setIcon("play").setTitle("Play").onClick(()=>{et.set(n),Ve.set(re.Player)})),!t?.markPlayed){const i=Y(Ye),a=s?i[s]?.finished??Cr(n,i):Cr(n,i);r.addItem(o=>o.setIcon(a?"x":"check").setTitle(`Mark as ${a?"Unplayed":"Played"}`).onClick(()=>{a?s?Ye.markKeyAsUnplayed(s):Ye.markAsUnplayed(n):Ye.markAsPlayed(n)}))}if(!t?.download){const i=lt.isEpisodeDownloaded(n);r.addItem(a=>a.setIcon(i?"cross":"download").setTitle(i?"Remove file":"Download").onClick(()=>{if(i)lt.removeEpisode(n,!0);else{const o=Y(rn).settings.download.path;if(!o){new C.Notice("Please set a download path in the settings.");return}ed(n,o)}}))}if(!t?.createNote){const i=!!zo(n);r.addItem(a=>a.setIcon("pencil").setTitle(`${i?"Open":"Create"} Note`).onClick(async()=>{if(i)nv(n);else{const{path:o,template:l}=Y(rn).settings.note;if(!!!(o&&l)){new C.Notice("Please set a note path and template in the settings.");return}await Xu(n)}}))}if(!t?.favorite){const i=Y(Sn).episodes.find(a=>a.title===n.title);r.addItem(a=>a.setIcon("lucide-star").setTitle(`${i?"Remove from":"Add to"} Favorites`).onClick(()=>{i?Sn.update(o=>(o.episodes=o.episodes.filter(l=>l.title!==n.title),o)):Sn.update(o=>{const l=[...o.episodes,n];return o.episodes=l,o})}))}if(!t?.queue){const i=Y(at).episodes.find(a=>a.title===n.title);r.addItem(a=>a.setIcon("list-ordered").setTitle(`${i?"Remove from":"Add to"} Queue`).onClick(()=>{i?at.update(o=>(o.episodes=o.episodes.filter(l=>l.title!==n.title),o)):at.update(o=>{const l=[...o.episodes,n];return o.episodes=l,o})}))}if(!t?.playlists){r.addSeparator();const i=Y(vt);for(const a of Object.values(i)){const o=a.episodes.find(l=>l.title===n.title);r.addItem(l=>l.setIcon(a.icon).setTitle(`${o?"Remove from":"Add to"} ${a.name}`).onClick(()=>{o?vt.update(c=>(c[a.name].episodes=c[a.name].episodes.filter(d=>d.title!==n.title),c)):vt.update(c=>{const d=[...c[a.name].episodes,n];return c[a.name].episodes=d,c})}))}}r.showAtMouseEvent(e)}var mv=G("<div><!></div>"),gv=G('<div class="podcast-artwork-isloading-overlay svelte-vlhi04"><!></div>'),vv=G("<div><!></div>"),yv=G("<audio></audio>"),_v=G("<h3>Queue</h3>"),wv=G('<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 bv={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 xv(n,e){be(e,!1),$e(n,bv);const t=()=>Me(rn,"$plugin",d),s=()=>Me(Ti,"$duration",d),r=()=>Me(et,"$currentEpisode",d),i=()=>Me(Ye,"$playedEpisodes",d),a=()=>Me(Pr,"$requestedPlaybackTime",d),o=()=>Me(kt,"$currentTime",d),l=()=>Me(Tt,"$isPaused",d),c=()=>Me(at,"$queue",d),[d,u]=Kr();class h{constructor(){this.playbackRate=t().settings.defaultPlaybackRate||1}get _playbackRate(){return this.playbackRate}set _playbackRate(te){}}const f=H(new h),p=L=>Math.min(1,Math.max(0,L));let m=H(!1),v=H(!0),y=H(1),_=H([]),b;function k(){Tt.update(L=>!L)}function P({detail:{event:L,percent:te}}){if(typeof te=="number"){kt.set(te*s());return}if(L instanceof MouseEvent){const se=L.currentTarget,pe=se.offsetWidth?L.offsetX/se.offsetWidth:0;kt.set(pe*s())}}function M(){vt.update(L=>(Object.values(L).forEach(te=>{te.episodes=te.episodes.filter(se=>se.title!==r().title)}),L)),at.remove(r())}function S(){Ye.markAsPlayed(r()),M(),at.playNext()}function T(L){Er(f,g(f).playbackRate=L.detail.value)}function R(L){const te=p(L.detail.value);ps.set(te)}function F(L){kt.set(L.detail.time)}function W(){E(v,!1),ee()}function ee(){const L=i(),te=r(),se=a();if(!te){kt.set(0),Tt.set(!1);return}if(se!==null){if(Pr.set(null),!Ep(te,se.episodeKey)){ye(te,L);return}kt.set(se.time),Tt.set(!1);return}ye(te,L)}function ye(L,te){const se=sn(L),pe=se&&te[se]||te[L.title];pe?.time?kt.set(pe.time):kt.set(0),Tt.set(!1)}let oe=H(un(r()));cn(()=>{const L=lt.subscribe(pe=>{E(oe,un(r()))}),te=et.subscribe(pe=>{E(oe,un(r()));const nt=pe?.chaptersUrl;nt&&nt!==b?(b=nt,kg(nt).then(fr=>{E(_,fr)})):nt||(b=void 0,E(_,[]))}),se=ps.subscribe(pe=>{E(y,p(pe))});return()=>{L(),te(),se()}}),ta(()=>{Ye.setEpisodeTime(r(),o(),s(),o()===s()),Tt.set(!0)});function V({detail:{event:L,episode:te}}){lo(te,L)}function ie(L){lo(r(),L,{play:!0,markPlayed:!0})}function Lt(L){const{episode:te}=L.detail;et.set(te),Ve.set(re.Player)}async function un(L){if(lt.isEpisodeDownloaded(L)){const te=lt.getEpisode(L);return te?Au(te.filePath):""}return L.streamUrl}ke();var dn=wv(),Bt=I(dn),fn=I(Bt),Ut=I(fn);{let L=Ne(()=>r().artworkUrl??""),te=Ne(()=>g(m)||l()?.5:1);jo(Ut,{class:"podcast-artwork",get src(){return g(L)},get alt(){return r().title},get opacity(){return g(te)},$$slots:{fallback:(se,pe)=>{var nt=mv(),fr=I(nt);Ze(fr,{icon:"image",size:150,clickable:!1}),ve(()=>nn(nt,1,"podcast-artwork-placeholder"+(g(m)||l()?" opacity-50":""),"svelte-vlhi04")),B(se,nt)}}})}var Yn=K(Ut,2);{var ks=L=>{var te=gv(),se=I(te);Vu(se),B(L,te)},or=L=>{var te=vv();let se;var pe=I(te);{let nt=Ne(()=>l()?"play":"pause");Ze(pe,{get icon(){return g(nt)},clickable:!1})}ve(()=>se=nn(te,1,"podcast-artwork-overlay svelte-vlhi04",null,se,{visible:g(m)||l()})),B(L,te)};me(Yn,L=>{g(v)?L(ks):L(or,!1)})}var ei=K(Bt,2),pa=I(ei),O=K(ei,2);np(O,()=>g(oe),null,(L,te)=>{var se=yv();se.autoplay=!0,ve(()=>de(se,"src",g(te))),yp("duration","durationchange",se,pe=>Ar(Ti,pe)),pp(se,o,pe=>Ar(kt,pe)),gp(se,l,pe=>Ar(Tt,pe)),mp(se,()=>g(f)._playbackRate,pe=>Er(f,g(f)._playbackRate=pe)),vp(se,()=>g(y),pe=>E(y,pe)),fe("ended",se,S),fe("loadedmetadata",se,W),fe("play",se,_p(function(pe){yu.call(this,e,pe)})),B(L,se)});var Q=K(O,2),he=I(Q),_e=I(he),hn=K(he,2);tv(hn,{get value(){return o()},get max(){return s()},$$events:{click:P}});var wt=K(hn,2),Ee=I(wt),tt=K(Q,2),Le=I(tt),Xe=Un(()=>t().api.skipBackward.bind(t().api));Lr(Le,{icon:"skip-back",tooltip:"Skip backward",class:"player-control-button",$$events:{click(...L){g(Xe)?.apply(this,L)}}});var $t=K(Le,2),Es=Un(()=>t().api.skipForward.bind(t().api));Lr($t,{icon:"skip-forward",tooltip:"Skip forward",class:"player-control-button",$$events:{click(...L){g(Es)?.apply(this,L)}}});var Jn=K(tt,2),Ss=I(Jn),lr=I(Ss),Xn=I(lr),cr=K(lr,2);Kl(cr,{get value(){return g(y)},limits:[0,1,.05],$$events:{change:R}});var ur=K(Ss,2),As=I(ur),bt=I(As),jt=K(As,2);Kl(jt,{get value(){return g(f).playbackRate},limits:[.5,3.5,.1],$$events:{change:T}});var pn=K(Jn,2),Cs=I(pn);Qg(Cs,{get chapters(){return g(_)},get currentTime(){return o()},$$events:{seek:F}});var dr=K(Cs,2);Yu(dr,{get episodes(){return c().episodes},showListMenu:!1,showThumbnails:!0,$$events:{contextMenuEpisode:V,clickEpisode:Lt},$$slots:{header:(L,te)=>{var se=_v();B(L,se)}}}),ve((L,te,se)=>{Fe(pa,r().title),Fe(_e,L),Fe(Ee,te),Fe(Xn,`Volume: ${se??""}%`),Fe(bt,`${g(f).playbackRate??""}x`)},[()=>Or(o(),"HH:mm:ss"),()=>Or(s()-o(),"HH:mm:ss"),()=>Math.round(g(y)*100)]),fe("click",fn,k),fe("contextmenu",fn,ie),fe("mouseenter",fn,()=>E(m,!0)),fe("mouseleave",fn,()=>E(m,!1)),B(n,dn),xe(),u()}var kv=G('<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 Sv(n,e){be(e,!1),$e(n,Ev);const t=H(),s=H();let r=$(e,"viewState",28,()=>re.PodcastGrid),i=$(e,"canShowEpisodeList",8,!1),a=$(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(P){r()!==P&&(P===re.EpisodeList&&!i()||P===re.Player&&!a()||r(P))}Se(()=>N(i()),()=>{E(t,i()?"View episode list":l)}),Se(()=>N(a()),()=>{E(s,a()?"Open player":c)}),Ot(),ke();var u=kv(),h=I(u),f=Un(()=>d.bind(null,re.PodcastGrid));de(h,"title",o);var p=I(h);Ze(p,{icon:"grid",size:20,clickable:!1});var m=K(h,2),v=Un(()=>d.bind(null,re.EpisodeList)),y=I(m);Ze(y,{icon:"list-minus",size:20,clickable:!1});var _=K(m,2),b=Un(()=>d.bind(null,re.Player)),k=I(_);Ze(k,{icon:"play",size:20,clickable:!1}),ve(()=>{nn(h,1,(N(r()),N(re),j(()=>`
topbar-menu-button
topbar-selectable
${r()===re.PodcastGrid?"topbar-selected":""}
`)),"svelte-1uvslqs"),de(h,"aria-pressed",(N(r()),N(re),j(()=>r()===re.PodcastGrid))),nn(m,1,(N(r()),N(re),N(i()),j(()=>`
topbar-menu-button
${r()===re.EpisodeList?"topbar-selected":""}
${i()?"topbar-selectable":"topbar-disabled"}
`)),"svelte-1uvslqs"),de(m,"aria-label",i()?"Episode list":"Episode list (select a podcast or playlist first)"),de(m,"aria-pressed",(N(r()),N(re),j(()=>r()===re.EpisodeList))),m.disabled=!i(),de(m,"title",g(t)),nn(_,1,(N(r()),N(re),N(a()),j(()=>`
topbar-menu-button
${r()===re.Player?"topbar-selected":""}
${a()?"topbar-selectable":"topbar-disabled"}
`)),"svelte-1uvslqs"),de(_,"aria-label",a()?"Player":"Player (start playing an episode to open the player)"),de(_,"aria-pressed",(N(r()),N(re),j(()=>r()===re.Player))),_.disabled=!a(),de(_,"title",g(s))}),fe("click",h,function(...P){g(f)?.apply(this,P)}),fe("click",m,function(...P){g(v)?.apply(this,P)}),fe("click",_,function(...P){g(b)?.apply(this,P)}),B(n,u),xe()}var Av=G('<img id="podcast-artwork" class="svelte-4w31cc"/>'),Cv=G('<div class="podcast-header svelte-4w31cc"><!> <h2 class="podcast-heading svelte-4w31cc"> </h2></div>');const Pv={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 Ca(n,e){$e(n,Pv);let t=$(e,"text",8,""),s=$(e,"artworkUrl",8,"");var r=Cv(),i=I(r);{var a=c=>{var d=Av();ve(()=>{de(d,"src",s()),de(d,"alt",t())}),B(c,d)};me(i,c=>{s()&&c(a)})}var o=K(i,2),l=I(o);ve(()=>Fe(l,t())),B(n,r)}const Tv={shouldSort:!0,findAllMatches:!0,threshold:.4,isCaseSensitive:!1,keys:["title"]},Jl=new WeakMap;function Iv(n){const e=Jl.get(n);if(e&&e.size===n.length)return e.fuse;const t=new xs(n,Tv);return Jl.set(n,{fuse:t,size:n.length}),t}function Mn(n,e){return e.length===0?[]:n.length===0?e:Iv(e).search(n).map(r=>r.item)}var $v=G('<span class="feed-loading-names svelte-14kt8yt"> </span>'),Rv=G('<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>'),Mv=G('<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <!>',1),Fv=G('<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <div class="playlist-header-icon svelte-14kt8yt"><!></div> <!>',1),Nv=G("<!> <!>",1),Dv=G('<div class="podcast-view svelte-14kt8yt"><!> <!></div>');const Ov={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 Lv(n,e){be(e,!1),$e(n,Ov);const t=()=>Me(at,"$queue",a),s=()=>Me(et,"$currentEpisode",a),r=()=>Me(to,"$podcastView",a),i=()=>Me(Ve,"$viewState",a),[a,o]=Kr();let l=H([]),c=H(null),d=H(null),u=H(!1),h=H([]),f=H(null),p=H([]),m=[],v=H(!1),y=H(new Set),_="",b=H([]),k=H(""),P=!0;ta(()=>{P=!1}),cn(()=>{const O=()=>{const Ee=Object.values(Y(vt));E(p,[Y(at),Y(Sn),Y(ms),S(),...Ee])},Q=[vt.subscribe(O),at.subscribe(O),Sn.subscribe(O),ms.subscribe(O),Ye.subscribe(()=>{O(),g(u)&&F()})],he=En.subscribe(Ee=>{const tt=Object.values(Ee),Le=new Set(g(l).map($t=>$t.title));E(l,tt);const Xe=tt.filter($t=>!Le.has($t.title));Xe.length>0&&ie(Xe)});let _e=Y(Ve);const hn=Ve.subscribe(Ee=>{_e=Ee}),wt=Mp.subscribe(Ee=>{m=Ee,_e===re.EpisodeList&&!g(c)&&!g(d)&&!g(u)&&E(h,_?Mn(_,Ee):Ee)});return()=>{wt(),hn(),he(),Q.forEach(Ee=>Ee())}});async function M(O,Q=!0){const _e=Y(rn)?.settings?.feedCache,hn=_e?.enabled!==!1,wt=Math.max(1,_e?.ttlHours??6)*60*60*1e3,tt=Y(Dn)[O.title];if(Q&&tt&&tt.length>0)return tt;if(Q&&hn){const Le=og(O,wt);if(Le?.length)return Dn.update(Xe=>({...Xe,[O.title]:Le})),Le}try{const Le=await new na(O).getEpisodes(O.url);return Dn.update(Xe=>({...Xe,[O.title]:Le})),hn&&lg(O,Le),Le}catch{return Y(lt)[O.title]||[]}}function S(){return{...xa,episodes:xu(Y(Ye)).map(({episode:O})=>Ku(O)),isVirtual:!0}}function T(){const O=Object.values(Y(Dn)),Q=Object.values(Y(lt)),he=Object.values(Y(vt)).map(_e=>_e.episodes);return[...O,...Q,Y(at).episodes,Y(Sn).episodes,Y(ms).episodes,...he]}function R(O,Q){if(!Q)return O;const he=new Map(O.map(_e=>[_e.episode,_e]));return Mn(Q,O.map(_e=>_e.episode)).map(_e=>he.get(_e)).filter(_e=>!!_e)}function F(){const O=Lg(Y(Ye),T());E(f,R(O,_)),E(h,g(f).map(Q=>Q.episode))}function W(){return g(u)&&g(d)?.isVirtual&&g(d).name===xa.name}function ee(){W()&&F()}function ye(){E(c,null),E(d,null),E(u,!1),E(f,null),E(h,_?Mn(_,m):m),Ve.set(re.EpisodeList)}function oe(O){if("playedEpisodeKey"in O)return typeof O.playedEpisodeKey=="string"?O.playedEpisodeKey:void 0}function V(O,Q){if(!P)return;const he=new Set(g(y));Q?he.add(O):he.delete(O),E(y,he)}function ie(O,Q=!0){return O.length?Promise.all(O.map(async he=>{V(he.title,!0);try{await M(he,Q)}finally{V(he.title,!1)}})).then(()=>{}):Promise.resolve()}async function Lt(O){const{feed:Q}=O.detail;E(c,Q),E(d,null),E(u,!1),E(f,null),E(h,[]),Ve.set(re.EpisodeList),V(Q.title,!0);try{const he=await M(Q);E(h,_?Mn(_,he):he)}finally{V(Q.title,!1)}}function un(O){const{episode:Q,entry:he}=O.detail;if(!he.isAvailable){new C.Notice("This played episode is no longer available in current feeds.");return}et.set(Q),Ve.set(re.Player)}function dn({detail:{event:O,episode:Q,entry:he}}){lo(Q,O,he.isAvailable?void 0:{play:!0,download:!0,createNote:!0,favorite:!0,queue:!0,playlists:!0},oe(he))}async function Bt(){if(g(u)){await ie(g(l),!1),ee();return}if(g(c)){V(g(c).title,!0);try{const O=await M(g(c),!1);E(f,null),E(h,_?Mn(_,O):O)}finally{V(g(c).title,!1)}}}const fn=C.debounce(O=>{const{query:Q}=O.detail;if(_=Q,g(u)){F();return}if(g(c)){const _e=Y(Dn)[g(c).title]??[];E(f,null),E(h,Mn(Q,_e));return}if(g(d)){E(f,null),E(h,Mn(Q,g(d).episodes));return}E(f,null),E(h,Mn(Q,m))},250);function Ut(O){const{playlist:Q}=O.detail;if(Q.isVirtual&&Q.name===xa.name){E(c,null),E(d,Q),E(u,!0),E(h,[]),E(f,[]),Ve.set(re.EpisodeList),ie(g(l)).then(()=>{ee()});return}Q.name===t().name&&t().episodes.length>0?(E(c,null),E(d,null),E(u,!1),E(f,null),s()||et.set(t().episodes[0]),Ve.set(re.Player)):(E(c,null),E(d,Q),E(u,!1),E(f,null),E(h,Q.episodes),Ve.set(re.EpisodeList))}Se(()=>g(y),()=>{E(b,Array.from(g(y)))}),Se(()=>g(b),()=>{E(k,g(b).length>3?`${g(b).slice(0,3).join(", ")} +${g(b).length-3} more`:g(b).join(", "))}),Se(()=>g(b),()=>{E(v,g(b).length>0)}),Ot(),ke();var Yn=Dv(),ks=I(Yn);{let O=Ne(()=>!!s());Sv(ks,{canShowEpisodeList:!0,get canShowPlayer(){return g(O)},get viewState(){return wp(),i()},set viewState(Q){Ar(Ve,Q)},$$legacy:!0})}var or=K(ks,2);{var ei=O=>{xv(O,{})},pa=O=>{var Q=gt(),he=Ke(Q);{var _e=wt=>{var Ee=Nv(),tt=Ke(Ee);{var Le=$t=>{var Es=Rv(),Jn=I(Es),Ss=I(Jn);Ze(Ss,{icon:"loader-2",size:18,clickable:!1});var lr=K(Jn,2),Xn=I(lr),cr=I(Xn),ur=K(Xn,2);{var As=bt=>{var jt=$v(),pn=I(jt);ve(()=>Fe(pn,g(k))),B(bt,jt)};me(ur,bt=>{g(k)&&bt(As)})}ve(()=>Fe(cr,`Updating ${g(b),j(()=>g(b).length)??""} feed${g(b),j(()=>g(b).length===1?"":"s")??""}`)),B($t,Es)};me(tt,$t=>{g(b),j(()=>g(b).length>0)&&$t(Le)})}var Xe=K(tt,2);{let $t=Ne(()=>!g(d)||g(u)),Es=Ne(()=>!g(u)),Jn=Ne(()=>(g(c),g(y),g(v),j(()=>g(c)?g(y).has(g(c).title):g(v))));Yu(Xe,{get episodes(){return g(h)},get episodeEntries(){return g(f)},get showThumbnails(){return g($t)},get showPlayedToggle(){return g(Es)},get alwaysShowPlayedEpisodes(){return g(u)},get isLoading(){return g(Jn)},$$events:{clickEpisode:un,contextMenuEpisode:dn,clickRefresh:Bt,search:fn},$$slots:{header:(Ss,lr)=>{var Xn=gt(),cr=Ke(Xn);{var ur=bt=>{var jt=Mv(),pn=Ke(jt),Cs=I(pn);Ze(Cs,{icon:"arrow-left",size:20,clickable:!1});var dr=K(pn,2);Ca(dr,{get text(){return g(c),j(()=>g(c).title)},get artworkUrl(){return g(c),j(()=>g(c).artworkUrl)}}),fe("click",pn,ye),B(bt,jt)},As=bt=>{var jt=gt(),pn=Ke(jt);{var Cs=L=>{var te=Fv(),se=Ke(te),pe=I(se);Ze(pe,{icon:"arrow-left",size:20,clickable:!1});var nt=K(se,2),fr=I(nt);Ze(fr,{get icon(){return g(d),j(()=>g(d).icon)},size:40,clickable:!1});var Tf=K(nt,2);Ca(Tf,{get text(){return g(d),j(()=>g(d).name)}}),fe("click",se,ye),B(L,te)},dr=L=>{Ca(L,{text:"Latest Episodes"})};me(pn,L=>{g(d)?L(Cs):L(dr,!1)},!0)}B(bt,jt)};me(cr,bt=>{g(c)?bt(ur):bt(As,!1)})}B(Ss,Xn)}}})}B(wt,Ee)},hn=wt=>{var Ee=gt(),tt=Ke(Ee);{var Le=Xe=>{xg(Xe,{get feeds(){return g(l)},get playlists(){return g(p)},$$events:{clickPodcast:Lt,clickPlaylist:Ut}})};me(tt,Xe=>{i(),N(re),j(()=>i()===re.PodcastGrid)&&Xe(Le)},!0)}B(wt,Ee)};me(he,wt=>{i(),N(re),j(()=>i()===re.EpisodeList)?wt(_e):wt(hn,!1)},!0)}B(O,Q)};me(or,O=>{i(),N(re),j(()=>i()===re.Player)?O(ei):O(pa,!1)})}Wn(Yn,O=>Ar(to,O),()=>r()),B(n,Yn),xe(),o()}class Bv extends C.ItemView{constructor(e,t){super(e),this.plugin=t,this.podcastView=null}getViewType(){return Zn}getDisplayText(){return"Podcast Player"}getIcon(){return"play-circle"}async onOpen(){this.podcastView=Ja(Lv,{target:this.contentEl})}async onClose(){this.podcastView&&(await Ga(this.podcastView),this.podcastView=null),this.contentEl.empty()}}class $n{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 Uv extends $n{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.playedEpisodes=e,this.plugin.saveSettings()}}class jv extends $n{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.savedFeeds=e,this.plugin.saveSettings()}}class zv extends $n{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.playlists=e,this.plugin.saveSettings()}}class qv extends $n{constructor(e,t){super(e),this.unsubscribeCurrentEpisode=null,this.plugin=t}onChange(e){this.plugin.settings.queue={...e,...Tu},this.plugin.saveSettings()}on(){return this.removeCurrentEpisodeFromQueue(),super.on()}off(){return this.unsubscribeCurrentEpisode?.(),super.off()}removeCurrentEpisodeFromQueue(){this.unsubscribeCurrentEpisode=et.subscribe(e=>{if(!e)return;const s=Y(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 $n{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.favorites={...e,...Pu},this.plugin.saveSettings()}}class Hv extends $n{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.currentEpisode=e,this.plugin.saveSettings()}}class Vv extends $n{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 $n{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.downloadedEpisodes=e,this.plugin.saveSettings()}}class Yv extends $n{constructor(e,t){super(e),this.plugin=t}onChange(e){this.plugin.settings.localFiles={...e,...Iu},this.plugin.saveSettings()}}async function Jv({url:n,episodeName:e,time:t},s){if(!n||!e||t===void 0){new C.Notice("URL, episode name, and timestamp are required to play an episode");return}const r=parseFloat(t);if(!Number.isFinite(r)){new C.Notice("Timestamp must be a valid number");return}const i=e.replace(/\+/g," "),a=Y(et),o=a?.title===i,l=Y(Ve)===re.Player;if(o){Pr.set({episodeKey:sn(a),time:r}),Ve.set(re.Player),s.currentTime=r,Tt.set(!1),l&&Pr.set(null);return}const c=n.replace(/\+/g," "),d=app.vault.getAbstractFileByPath(c);let u;if(d?u=ms.getLocalEpisode(i):u=await new na().findItemByTitle(i,n),!u){new C.Notice("Episode not found");return}Pr.set({episodeKey:sn(u),time:r}),et.set(u),Ve.set(re.Player)}function Xv(n){return n.workspace.on("file-menu",(e,t)=>{t instanceof C.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 Au(t.path),filePath:t.path,episodeDate:new Date(t.stat.ctime)};lt.isEpisodeDownloaded(r)||(lt.addEpisode(r,t.path,t.stat.size),ms.addEpisode(r)),Y(Ye)[t.basename]?.finished&&Ye.markAsUnplayed(r),et.set(r),Ve.set(re.Player)}))})}async function Gv(n){const{title:e,itunesTitle:t,podcastName:s,feedUrl:r}=n.podcast;try{const a=(await $u(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 C.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 C.Notice("Universal episode link copied to clipboard.")}catch{new C.Notice("Could not get podcast link.");return}}function Qv(n,e){let t=e;const s=Date.now();let r;const i=new C.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 Zv(r?r-s:Date.now()-s)}return{update:o,hide:()=>i.hide(),stop:()=>{r=Date.now(),clearInterval(l)}}}function Zv(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 ey{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 C.Notice("Please add your OpenAI API key in the transcript settings first.");return}const e=this.plugin.api.podcast;if(!e){new C.Notice("No episode is currently playing.");return}const t=gs(this.plugin.settings.transcript.path,e);if(this.plugin.app.vault.getAbstractFileByPath(t)instanceof C.TFile){new C.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 C.Notice("This episode is already queued or transcribing.");return}this.pendingEpisodes.push(e),new C.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=Qv(`Transcription: ${e.title}`,"Preparing to transcribe...");try{const s=gs(this.plugin.settings.transcript.path,e);if(this.plugin.app.vault.getAbstractFileByPath(s)instanceof C.TFile){t.stop(),t.update(`Transcript already exists - skipped (${s}).`);return}t.update("Downloading episode...");const i=await fv(e,this.plugin.settings.download.path),a=this.plugin.app.vault.getAbstractFileByPath(i);if(!a||!(a instanceof C.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=gs(this.plugin.settings.transcript.path,e),r=t.replace(/\.\s+/g,`.
`),i=Gm(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 C.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(()=>i_);return this.client=new t({apiKey:e,dangerouslyAllowBrowser:!0}),this.cachedApiKey=e,this.client}}class ty extends C.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(){rn.set(this),await this.loadSettings(),Ye.set(this.settings.playedEpisodes),En.set(this.settings.savedFeeds),vt.set(this.settings.playlists),at.set(this.settings.queue),Sn.set(this.settings.favorites),ms.set(this.settings.localFiles),lt.set(this.settings.downloadedEpisodes),this.settings.currentEpisode&&et.set(this.settings.currentEpisode),Ii.set(this.settings.hidePlayedEpisodes),ps.set(Math.min(1,Math.max(0,this.settings.defaultVolume??1))),this.playedEpisodeController=new Uv(Ye,this).on(),this.savedFeedsController=new jv(En,this).on(),this.playlistController=new zv(vt,this).on(),this.queueController=new qv(at,this).on(),this.favoritesController=new Wv(Sn,this).on(),this.localFilesController=new Yv(ms,this).on(),this.downloadedEpisodesController=new Kv(lt,this).on(),this.currentEpisodeController=new Hv(et,this).on(),this.hidePlayedEpisodesController=new Vv(Ii,this).on(),this.api=new Lp,this.volumeUnsubscribe=ps.subscribe(e=>{const t=Math.min(1,Math.max(0,e));if(t!==e){ps.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(Zn).length;this.app.workspace.getRightLeaf(!1)?.setViewState({type:Zn})}}),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;ed(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=zu(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;Xu(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;Gv(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 ug(this.app,this)),this.registerView(Zn,e=>(this.view=new Bv(e,this),this.view)),this.app.workspace.onLayoutReady(this.onLayoutReady.bind(this)),this.registerObsidianProtocolHandler("podnotes",e=>Jv(e,this.api)),this.registerEvent(Xv(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(Zn).length)return;const e=this.app.workspace.getRightLeaf(!1);e&&e.setViewState({type:Zn})}getTranscriptionService(){return this.transcriptionService||(this.transcriptionService=new ey(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?.(),Su.revokeAll(),this.app.workspace.detachLeavesOfType(Zn)}async loadSettings(){const e=await this.loadData();this.settings=Object.assign({},Ul,e),this.settings.timestamp={...Ul.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 J(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 nd=function(){const{crypto:n}=globalThis;if(n?.randomUUID)return nd=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 co(n){return typeof n=="object"&&n!==null&&("name"in n&&n.name==="AbortError"||"message"in n&&String(n.message).includes("FetchRequestCanceledException"))}const uo=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 q extends Error{}class Oe extends q{constructor(e,t,s,r){super(`${Oe.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 Jr({message:s,cause:uo(t)});const i=t?.error;return e===400?new qo(e,i,s,r):e===401?new Wo(e,i,s,r):e===403?new Ho(e,i,s,r):e===404?new Vo(e,i,s,r):e===409?new Ko(e,i,s,r):e===422?new Yo(e,i,s,r):e===429?new Jo(e,i,s,r):e>=500?new Xo(e,i,s,r):new Oe(e,i,s,r)}}class yt extends Oe{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Jr extends Oe{constructor({message:e,cause:t}){super(void 0,void 0,e||"Connection error.",void 0),t&&(this.cause=t)}}class ia extends Jr{constructor({message:e}={}){super({message:e??"Request timed out."})}}class qo extends Oe{}class Wo extends Oe{}class Ho extends Oe{}class Vo extends Oe{}class Ko extends Oe{}class Yo extends Oe{}class Jo extends Oe{}class Xo extends Oe{}class sd extends q{constructor(){super("Could not parse response content as the length limit was reached")}}class rd extends q{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class Ls extends Error{constructor(e){super(e)}}const ny=/^[a-z][a-z0-9+.-]*:/i,sy=n=>ny.test(n);let rt=n=>(rt=Array.isArray,rt(n)),Xl=rt;function id(n){return typeof n!="object"?{}:n??{}}function ry(n){if(!n)return!0;for(const e in n)return!1;return!0}function iy(n,e){return Object.prototype.hasOwnProperty.call(n,e)}function Pa(n){return n!=null&&typeof n=="object"&&!Array.isArray(n)}const ay=(n,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new q(`${n} must be an integer`);if(e<0)throw new q(`${n} must be a positive integer`);return e},oy=n=>{try{return JSON.parse(n)}catch{return}},Xr=n=>new Promise(e=>setTimeout(e,n)),Ms="6.9.1",ly=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function cy(){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 uy=()=>{const n=cy();if(n==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ms,"X-Stainless-OS":Ql(Deno.build.os),"X-Stainless-Arch":Gl(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":Ms,"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":Ms,"X-Stainless-OS":Ql(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Gl(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=dy();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ms,"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":Ms,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function dy(){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 Gl=n=>n==="x32"?"x32":n==="x86_64"||n==="x64"?"x64":n==="arm"?"arm":n==="aarch64"||n==="arm64"?"arm64":n?`other:${n}`:"unknown",Ql=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 Zl;const fy=()=>Zl??(Zl=uy());function hy(){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 ad(...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 od(n){let e=Symbol.asyncIterator in n?n[Symbol.asyncIterator]():n[Symbol.iterator]();return ad({start(){},async pull(t){const{done:s,value:r}=await e.next();s?t.close():t.enqueue(r)},async cancel(){await e.return?.()}})}function ld(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 py(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 my=({headers:n,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),cd="RFC3986",ud=n=>String(n),ec={RFC1738:n=>String(n).replace(/%20/g,"+"),RFC3986:ud},gy="RFC1738";let fo=(n,e)=>(fo=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),fo(n,e));const qt=(()=>{const n=[];for(let e=0;e<256;++e)n.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return n})(),Ta=1024,vy=(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+=Ta){const l=i.length>=Ta?i.slice(o,o+Ta):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===gy&&(u===40||u===41)){c[c.length]=l.charAt(d);continue}if(u<128){c[c.length]=qt[u];continue}if(u<2048){c[c.length]=qt[192|u>>6]+qt[128|u&63];continue}if(u<55296||u>=57344){c[c.length]=qt[224|u>>12]+qt[128|u>>6&63]+qt[128|u&63];continue}d+=1,u=65536+((u&1023)<<10|l.charCodeAt(d)&1023),c[c.length]=qt[240|u>>18]+qt[128|u>>12&63]+qt[128|u>>6&63]+qt[128|u&63]}a+=c.join("")}return a};function yy(n){return!n||typeof n!="object"?!1:!!(n.constructor&&n.constructor.isBuffer&&n.constructor.isBuffer(n))}function tc(n,e){if(rt(n)){const t=[];for(let s=0;s<n.length;s+=1)t.push(e(n[s]));return t}return e(n)}const dd={brackets(n){return String(n)+"[]"},comma:"comma",indices(n,e){return String(n)+"["+e+"]"},repeat(n){return String(n)}},fd=function(n,e){Array.prototype.push.apply(n,rt(e)?e:[e])};let nc;const Te={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:vy,encodeValuesOnly:!1,format:cd,formatter:ud,indices:!1,serializeDate(n){return(nc??(nc=Function.prototype.call.bind(Date.prototype.toISOString)))(n)},skipNulls:!1,strictNullHandling:!1};function _y(n){return typeof n=="string"||typeof n=="number"||typeof n=="boolean"||typeof n=="symbol"||typeof n=="bigint"}const Ia={};function hd(n,e,t,s,r,i,a,o,l,c,d,u,h,f,p,m,v,y){let _=n,b=y,k=0,P=!1;for(;(b=b.get(Ia))!==void 0&&!P;){const F=b.get(n);if(k+=1,typeof F<"u"){if(F===k)throw new RangeError("Cyclic object value");P=!0}typeof b.get(Ia)>"u"&&(k=0)}if(typeof c=="function"?_=c(e,_):_ instanceof Date?_=h?.(_):t==="comma"&&rt(_)&&(_=tc(_,function(F){return F instanceof Date?h?.(F):F})),_===null){if(i)return l&&!m?l(e,Te.encoder,v,"key",f):e;_=""}if(_y(_)||yy(_)){if(l){const F=m?e:l(e,Te.encoder,v,"key",f);return[p?.(F)+"="+p?.(l(_,Te.encoder,v,"value",f))]}return[p?.(e)+"="+p?.(String(_))]}const M=[];if(typeof _>"u")return M;let S;if(t==="comma"&&rt(_))m&&l&&(_=tc(_,l)),S=[{value:_.length>0?_.join(",")||null:void 0}];else if(rt(c))S=c;else{const F=Object.keys(_);S=d?F.sort(d):F}const T=o?String(e).replace(/\./g,"%2E"):String(e),R=s&&rt(_)&&_.length===1?T+"[]":T;if(r&&rt(_)&&_.length===0)return R+"[]";for(let F=0;F<S.length;++F){const W=S[F],ee=typeof W=="object"&&typeof W.value<"u"?W.value:_[W];if(a&&ee===null)continue;const ye=u&&o?W.replace(/\./g,"%2E"):W,oe=rt(_)?typeof t=="function"?t(R,ye):R:R+(u?"."+ye:"["+ye+"]");y.set(n,k);const V=new WeakMap;V.set(Ia,y),fd(M,hd(ee,oe,t,s,r,i,a,o,t==="comma"&&m&&rt(_)?null:l,c,d,u,h,f,p,m,v,V))}return M}function wy(n=Te){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||Te.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=cd;if(typeof n.format<"u"){if(!fo(ec,n.format))throw new TypeError("Unknown format option provided.");t=n.format}const s=ec[t];let r=Te.filter;(typeof n.filter=="function"||rt(n.filter))&&(r=n.filter);let i;if(n.arrayFormat&&n.arrayFormat in dd?i=n.arrayFormat:"indices"in n?i=n.indices?"indices":"repeat":i=Te.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:Te.allowDots:!!n.allowDots;return{addQueryPrefix:typeof n.addQueryPrefix=="boolean"?n.addQueryPrefix:Te.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof n.allowEmptyArrays=="boolean"?!!n.allowEmptyArrays:Te.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof n.charsetSentinel=="boolean"?n.charsetSentinel:Te.charsetSentinel,commaRoundTrip:!!n.commaRoundTrip,delimiter:typeof n.delimiter>"u"?Te.delimiter:n.delimiter,encode:typeof n.encode=="boolean"?n.encode:Te.encode,encodeDotInKeys:typeof n.encodeDotInKeys=="boolean"?n.encodeDotInKeys:Te.encodeDotInKeys,encoder:typeof n.encoder=="function"?n.encoder:Te.encoder,encodeValuesOnly:typeof n.encodeValuesOnly=="boolean"?n.encodeValuesOnly:Te.encodeValuesOnly,filter:r,format:t,formatter:s,serializeDate:typeof n.serializeDate=="function"?n.serializeDate:Te.serializeDate,skipNulls:typeof n.skipNulls=="boolean"?n.skipNulls:Te.skipNulls,sort:typeof n.sort=="function"?n.sort:null,strictNullHandling:typeof n.strictNullHandling=="boolean"?n.strictNullHandling:Te.strictNullHandling}}function by(n,e={}){let t=n;const s=wy(e);let r,i;typeof s.filter=="function"?(i=s.filter,t=i("",t)):rt(s.filter)&&(i=s.filter,r=i);const a=[];if(typeof t!="object"||t===null)return"";const o=dd[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||fd(a,hd(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 xy(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 sc;function Go(n){let e;return(sc??(e=new globalThis.TextEncoder,sc=e.encode.bind(e)))(n)}let rc;function ic(n){let e;return(rc??(e=new globalThis.TextDecoder,rc=e.decode.bind(e)))(n)}var ut,dt;class aa{constructor(){ut.set(this,void 0),dt.set(this,void 0),J(this,ut,new Uint8Array),J(this,dt,null)}decode(e){if(e==null)return[];const t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?Go(e):e;J(this,ut,xy([w(this,ut,"f"),t]));const s=[];let r;for(;(r=ky(w(this,ut,"f"),w(this,dt,"f")))!=null;){if(r.carriage&&w(this,dt,"f")==null){J(this,dt,r.index);continue}if(w(this,dt,"f")!=null&&(r.index!==w(this,dt,"f")+1||r.carriage)){s.push(ic(w(this,ut,"f").subarray(0,w(this,dt,"f")-1))),J(this,ut,w(this,ut,"f").subarray(w(this,dt,"f"))),J(this,dt,null);continue}const i=w(this,dt,"f")!==null?r.preceding-1:r.preceding,a=ic(w(this,ut,"f").subarray(0,i));s.push(a),J(this,ut,w(this,ut,"f").subarray(r.index)),J(this,dt,null)}return s}flush(){return w(this,ut,"f").length?this.decode(`
`):[]}}ut=new WeakMap,dt=new WeakMap;aa.NEWLINE_CHARS=new Set([`
`,"\r"]);aa.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function ky(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 Ey(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 Fi={off:0,error:200,warn:300,info:400,debug:500},ac=(n,e,t)=>{if(n){if(iy(Fi,n))return n;Ue(t).warn(`${e} was set to ${JSON.stringify(n)}, expected one of ${JSON.stringify(Object.keys(Fi))}`)}};function gr(){}function ri(n,e,t){return!e||Fi[n]>Fi[t]?gr:e[n].bind(e)}const Sy={error:gr,warn:gr,info:gr,debug:gr};let oc=new WeakMap;function Ue(n){const e=n.logger,t=n.logLevel??"off";if(!e)return Sy;const s=oc.get(e);if(s&&s[0]===t)return s[1];const r={error:ri("error",e,t),warn:ri("warn",e,t),info:ri("info",e,t),debug:ri("debug",e,t)};return oc.set(e,[t,r]),r}const es=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 hr;class en{constructor(e,t,s){this.iterator=e,hr.set(this,void 0),this.controller=t,J(this,hr,s)}static fromSSEResponse(e,t,s){let r=!1;const i=s?Ue(s):console;async function*a(){if(r)throw new q("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");r=!0;let o=!1;try{for await(const l of Ay(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 Oe(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 Oe(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}o=!0}catch(l){if(co(l))return;throw l}finally{o||t.abort()}}return new en(a,t,s)}static fromReadableStream(e,t,s){let r=!1;async function*i(){const o=new aa,l=ld(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 q("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(co(l))return;throw l}finally{o||t.abort()}}return new en(a,t,s)}[(hr=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 en(()=>r(e),this.controller,w(this,hr,"f")),new en(()=>r(t),this.controller,w(this,hr,"f"))]}toReadableStream(){const e=this;let t;return ad({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=Go(JSON.stringify(r)+`
`);s.enqueue(a)}catch(r){s.error(r)}},async cancel(){await t.return?.()}})}}async function*Ay(n,e){if(!n.body)throw e.abort(),typeof globalThis.navigator<"u"&&globalThis.navigator.product==="ReactNative"?new q("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 q("Attempted to iterate over a response with no body");const t=new Py,s=new aa,r=ld(n.body);for await(const i of Cy(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*Cy(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"?Go(t):t;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=Ey(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class Py{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]=Ty(e,":");return r.startsWith(" ")&&(r=r.substring(1)),t==="event"?this.event=r:t==="data"&&this.data.push(r),null}}function Ty(n,e){const t=n.indexOf(e);return t!==-1?[n.substring(0,t),e,n.substring(t+e.length)]:[n,"",""]}async function pd(n,e){const{response:t,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Ue(n).debug("response",t.status,t.url,t.headers,t.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(t,e.controller,n):en.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 md(u,t)}return await t.text()})();return Ue(n).debug(`[${s}] response parsed`,es({retryOfRequestLogID:r,url:t.url,status:t.status,body:a,durationMs:Date.now()-i})),a}function md(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 vr;class Gr extends Promise{constructor(e,t,s=pd){super(r=>{r(null)}),this.responsePromise=t,this.parseResponse=s,vr.set(this,void 0),J(this,vr,e)}_thenUnwrap(e){return new Gr(w(this,vr,"f"),this.responsePromise,async(t,s)=>md(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,vr,"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)}}vr=new WeakMap;var ii;class Qo{constructor(e,t,s,r){ii.set(this,void 0),J(this,ii,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 q("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await w(this,ii,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(ii=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const t of e.getPaginatedItems())yield t}}class gd extends Gr{constructor(e,t,s){super(e,t,async(r,i)=>new s(r,i.response,await pd(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const t of e)yield t}}class oa 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 Ae 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:{...id(this.options.query),after:t}}:null}}class Ni 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:{...id(this.options.query),after:e}}:null}}const vd=()=>{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 Ir(n,e,t){return vd(),new File(n,e??"unknown_file",t)}function pi(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 Zo=n=>n!=null&&typeof n=="object"&&typeof n[Symbol.asyncIterator]=="function",lc=async(n,e)=>ho(n.body)?{...n,body:await yd(n.body,e)}:n,_s=async(n,e)=>({...n,body:await yd(n.body,e)}),cc=new WeakMap;function Iy(n){const e=typeof n=="function"?n:n.fetch,t=cc.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 cc.set(e,s),s}const yd=async(n,e)=>{if(!await Iy(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])=>po(t,s,r))),t},_d=n=>n instanceof Blob&&"name"in n,$y=n=>typeof n=="object"&&n!==null&&(n instanceof Response||Zo(n)||_d(n)),ho=n=>{if($y(n))return!0;if(Array.isArray(n))return n.some(ho);if(n&&typeof n=="object"){for(const e in n)if(ho(n[e]))return!0}return!1},po=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,Ir([await t.blob()],pi(t)));else if(Zo(t))n.append(e,Ir([await new Response(od(t)).blob()],pi(t)));else if(_d(t))n.append(e,t,pi(t));else if(Array.isArray(t))await Promise.all(t.map(s=>po(n,e+"[]",s)));else if(typeof t=="object")await Promise.all(Object.entries(t).map(([s,r])=>po(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`)}},wd=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",Ry=n=>n!=null&&typeof n=="object"&&typeof n.name=="string"&&typeof n.lastModified=="number"&&wd(n),My=n=>n!=null&&typeof n=="object"&&typeof n.url=="string"&&typeof n.blob=="function";async function bd(n,e,t){if(vd(),n=await n,Ry(n))return n instanceof File?n:Ir([await n.arrayBuffer()],n.name);if(My(n)){const r=await n.blob();return e||(e=new URL(n.url).pathname.split(/[\\/]/).pop()),Ir(await mo(r),e,t)}const s=await mo(n);if(e||(e=pi(n)),!t?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(t={...t,type:r})}return Ir(s,e,t)}async function mo(n){let e=[];if(typeof n=="string"||ArrayBuffer.isView(n)||n instanceof ArrayBuffer)e.push(n);else if(wd(n))e.push(n instanceof Blob?n:await n.arrayBuffer());else if(Zo(n))for await(const t of n)e.push(...await mo(t));else{const t=n?.constructor?.name;throw new Error(`Unexpected data type: ${typeof n}${t?`; constructor: ${t}`:""}${Fy(n)}`)}return e}function Fy(n){return typeof n!="object"||n===null?"":`; props: [${Object.getOwnPropertyNames(n).map(t=>`"${t}"`).join(", ")}]`}class z{constructor(e){this._client=e}}function xd(n){return n.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const uc=Object.freeze(Object.create(null)),Ny=(n=xd)=>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??uc)??uc)?.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 q(`Path parameters result in path with invalid segments:
${i.map(h=>h.error).join(`
`)}
${a}
${u}`)}return a},A=Ny(xd);let kd=class extends z{list(e,t={},s){return this._client.getAPIList(A`/chat/completions/${e}/messages`,Ae,{query:t,...s})}};function Di(n){return n!==void 0&&"function"in n&&n.function!==void 0}function el(n){return n?.$brand==="auto-parseable-response-format"}function Qr(n){return n?.$brand==="auto-parseable-tool"}function Dy(n,e){return!e||!Ed(e)?{...n,choices:n.choices.map(t=>(Sd(t.message.tool_calls),{...t,message:{...t.message,parsed:null,...t.message.tool_calls?{tool_calls:t.message.tool_calls}:void 0}}))}:tl(n,e)}function tl(n,e){const t=n.choices.map(s=>{if(s.finish_reason==="length")throw new sd;if(s.finish_reason==="content_filter")throw new rd;return Sd(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>Ly(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?Oy(e,s.message.content):null}}});return{...n,choices:t}}function Oy(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 Ly(n,e){const t=n.tools?.find(s=>Di(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:Qr(t)?t.$parseRaw(e.function.arguments):t?.function.strict?JSON.parse(e.function.arguments):null}}}function By(n,e){if(!n||!("tools"in n)||!n.tools)return!1;const t=n.tools?.find(s=>Di(s)&&s.function?.name===e.function.name);return Di(t)&&(Qr(t)||t?.function.strict||!1)}function Ed(n){return el(n.response_format)?!0:n.tools?.some(e=>Qr(e)||e.type==="function"&&e.function.strict===!0)??!1}function Sd(n){for(const e of n||[])if(e.type!=="function")throw new q(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Uy(n){for(const e of n??[]){if(e.type!=="function")throw new q(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new q(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}const Oi=n=>n?.role==="assistant",Ad=n=>n?.role==="tool";var go,mi,gi,yr,_r,vi,wr,gn,br,Li,Bi,Fs,Cd;class nl{constructor(){go.add(this),this.controller=new AbortController,mi.set(this,void 0),gi.set(this,()=>{}),yr.set(this,()=>{}),_r.set(this,void 0),vi.set(this,()=>{}),wr.set(this,()=>{}),gn.set(this,{}),br.set(this,!1),Li.set(this,!1),Bi.set(this,!1),Fs.set(this,!1),J(this,mi,new Promise((e,t)=>{J(this,gi,e,"f"),J(this,yr,t,"f")})),J(this,_r,new Promise((e,t)=>{J(this,vi,e,"f"),J(this,wr,t,"f")})),w(this,mi,"f").catch(()=>{}),w(this,_r,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},w(this,go,"m",Cd).bind(this))},0)}_connected(){this.ended||(w(this,gi,"f").call(this),this._emit("connect"))}get ended(){return w(this,br,"f")}get errored(){return w(this,Li,"f")}get aborted(){return w(this,Bi,"f")}abort(){this.controller.abort()}on(e,t){return(w(this,gn,"f")[e]||(w(this,gn,"f")[e]=[])).push({listener:t}),this}off(e,t){const s=w(this,gn,"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,gn,"f")[e]||(w(this,gn,"f")[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,s)=>{J(this,Fs,!0),e!=="error"&&this.once("error",s),this.once(e,t)})}async done(){J(this,Fs,!0),await w(this,_r,"f")}_emit(e,...t){if(w(this,br,"f"))return;e==="end"&&(J(this,br,!0),w(this,vi,"f").call(this));const s=w(this,gn,"f")[e];if(s&&(w(this,gn,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...t))),e==="abort"){const r=t[0];!w(this,Fs,"f")&&!s?.length&&Promise.reject(r),w(this,yr,"f").call(this,r),w(this,wr,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=t[0];!w(this,Fs,"f")&&!s?.length&&Promise.reject(r),w(this,yr,"f").call(this,r),w(this,wr,"f").call(this,r),this._emit("end")}}_emitFinal(){}}mi=new WeakMap,gi=new WeakMap,yr=new WeakMap,_r=new WeakMap,vi=new WeakMap,wr=new WeakMap,gn=new WeakMap,br=new WeakMap,Li=new WeakMap,Bi=new WeakMap,Fs=new WeakMap,go=new WeakSet,Cd=function(e){if(J(this,Li,!0),e instanceof Error&&e.name==="AbortError"&&(e=new yt),e instanceof yt)return J(this,Bi,!0),this._emit("abort",e);if(e instanceof q)return this._emit("error",e);if(e instanceof Error){const t=new q(e.message);return t.cause=e,this._emit("error",t)}return this._emit("error",new q(String(e)))};function jy(n){return typeof n.parse=="function"}var Ge,vo,Ui,yo,_o,wo,Pd,Td;const zy=10;class Id extends nl{constructor(){super(...arguments),Ge.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),Ad(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Oi(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 q("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),w(this,Ge,"m",vo).call(this)}async finalMessage(){return await this.done(),w(this,Ge,"m",Ui).call(this)}async finalFunctionToolCall(){return await this.done(),w(this,Ge,"m",yo).call(this)}async finalFunctionToolCallResult(){return await this.done(),w(this,Ge,"m",_o).call(this)}async totalUsage(){return await this.done(),w(this,Ge,"m",wo).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const t=w(this,Ge,"m",Ui).call(this);t&&this._emit("finalMessage",t);const s=w(this,Ge,"m",vo).call(this);s&&this._emit("finalContent",s);const r=w(this,Ge,"m",yo).call(this);r&&this._emit("finalFunctionToolCall",r);const i=w(this,Ge,"m",_o).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",w(this,Ge,"m",wo).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,Ge,"m",Pd).call(this,t);const i=await e.chat.completions.create({...t,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(tl(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=zy}=s||{},d=t.tools.map(f=>{if(Qr(f)){if(!f.$callback)throw new q("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 q("missing message in ChatCompletion response");if(!m.tool_calls?.length)return;for(const v of m.tool_calls){if(v.type!=="function")continue;const y=v.id,{name:_,arguments:b}=v.function,k=u[_];if(k){if(l&&l!==_){const T=`Invalid tool_call: ${JSON.stringify(_)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:y,content:T});continue}}else{const T=`Invalid tool_call: ${JSON.stringify(_)}. Available options are: ${Object.keys(u).map(R=>JSON.stringify(R)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:y,content:T});continue}let P;try{P=jy(k)?await k.parse(b):b}catch(T){const R=T instanceof Error?T.message:String(T);this._addMessage({role:r,tool_call_id:y,content:R});continue}const M=await k.function(P,this),S=w(this,Ge,"m",Td).call(this,M);if(this._addMessage({role:r,tool_call_id:y,content:S}),l)return}}}}Ge=new WeakSet,vo=function(){return w(this,Ge,"m",Ui).call(this).content??null},Ui=function(){let e=this.messages.length;for(;e-- >0;){const t=this.messages[e];if(Oi(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new q("stream ended without producing a ChatCompletionMessage with role=assistant")},yo=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Oi(t)&&t?.tool_calls?.length)return t.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},_o=function(){for(let e=this.messages.length-1;e>=0;e--){const t=this.messages[e];if(Ad(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}},wo=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},Pd=function(e){if(e.n!=null&&e.n>1)throw new q("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Td=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class sl extends Id{static runTools(e,t,s){const r=new sl,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),Oi(e)&&e.content&&this._emit("content",e.content)}}const $d=1,Rd=2,Md=4,Fd=8,Nd=16,Dd=32,Od=64,Ld=128,Bd=256,Ud=Ld|Bd,jd=Nd|Dd|Ud|Od,zd=$d|Rd|jd,qd=Md|Fd,qy=zd|qd,Re={STR:$d,NUM:Rd,ARR:Md,OBJ:Fd,NULL:Nd,BOOL:Dd,NAN:Od,INFINITY:Ld,MINUS_INFINITY:Bd,INF:Ud,SPECIAL:jd,ATOM:zd,COLLECTION:qd,ALL:qy};class Wy extends Error{}class Hy extends Error{}function Vy(n,e=Re.ALL){if(typeof n!="string")throw new TypeError(`expecting str, got ${typeof n}`);if(!n.trim())throw new Error(`${n} is empty`);return Ky(n.trim(),e)}const Ky=(n,e)=>{const t=n.length;let s=0;const r=h=>{throw new Wy(`${h} at position ${s}`)},i=h=>{throw new Hy(`${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"||Re.NULL&e&&t-s<4&&"null".startsWith(n.substring(s))?(s+=4,null):n.substring(s,s+4)==="true"||Re.BOOL&e&&t-s<4&&"true".startsWith(n.substring(s))?(s+=4,!0):n.substring(s,s+5)==="false"||Re.BOOL&e&&t-s<5&&"false".startsWith(n.substring(s))?(s+=5,!1):n.substring(s,s+8)==="Infinity"||Re.INFINITY&e&&t-s<8&&"Infinity".startsWith(n.substring(s))?(s+=8,1/0):n.substring(s,s+9)==="-Infinity"||Re.MINUS_INFINITY&e&&1<t-s&&t-s<9&&"-Infinity".startsWith(n.substring(s))?(s+=9,-1/0):n.substring(s,s+3)==="NaN"||Re.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(Re.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&&Re.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(Re.OBJ&e)return h;throw p}u(),n[s]===","&&s++}}catch{if(Re.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(Re.ARR&e)return h;r("Expected ']' at end of array")}return s++,h},d=()=>{if(s===0){n==="-"&&Re.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(n)}catch(f){if(Re.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&&!(Re.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(n.substring(h,s))}catch{n.substring(h,s)==="-"&&Re.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()},dc=n=>Vy(n,Re.ALL^Re.NUM);var Pe,mn,Is,Fn,$a,ai,Ra,Ma,Fa,oi,Na,fc;class Br extends Id{constructor(e){super(),Pe.add(this),mn.set(this,void 0),Is.set(this,void 0),Fn.set(this,void 0),J(this,mn,e),J(this,Is,[])}get currentChatCompletionSnapshot(){return w(this,Fn,"f")}static fromReadableStream(e){const t=new Br(null);return t._run(()=>t._fromReadableStream(e)),t}static createChatCompletion(e,t,s){const r=new Br(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,Pe,"m",$a).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,Pe,"m",Ra).call(this,a);if(i.controller.signal?.aborted)throw new yt;return this._addChatCompletion(w(this,Pe,"m",oi).call(this))}async _fromReadableStream(e,t){const s=t?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),w(this,Pe,"m",$a).call(this),this._connected();const r=en.fromReadableStream(e,this.controller);let i;for await(const a of r)i&&i!==a.id&&this._addChatCompletion(w(this,Pe,"m",oi).call(this)),w(this,Pe,"m",Ra).call(this,a),i=a.id;if(r.controller.signal?.aborted)throw new yt;return this._addChatCompletion(w(this,Pe,"m",oi).call(this))}[(mn=new WeakMap,Is=new WeakMap,Fn=new WeakMap,Pe=new WeakSet,$a=function(){this.ended||J(this,Fn,void 0)},ai=function(t){let s=w(this,Is,"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,Is,"f")[t.index]=s,s)},Ra=function(t){if(this.ended)return;const s=w(this,Pe,"m",fc).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,Pe,"m",ai).call(this,i);i.finish_reason&&(w(this,Pe,"m",Fa).call(this,i),a.current_tool_call_index!=null&&w(this,Pe,"m",Ma).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,Pe,"m",Fa).call(this,i),a.current_tool_call_index!=null&&w(this,Pe,"m",Ma).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))}}},Ma=function(t,s){if(w(this,Pe,"m",ai).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,mn,"f")?.tools?.find(o=>Di(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:Qr(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},Fa=function(t){const s=w(this,Pe,"m",ai).call(this,t);if(t.message.content&&!s.content_done){s.content_done=!0;const r=w(this,Pe,"m",Na).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}))},oi=function(){if(this.ended)throw new q("stream has ended, this shouldn't happen");const t=w(this,Fn,"f");if(!t)throw new q("request ended without sending any chunks");return J(this,Fn,void 0),J(this,Is,[]),Yy(t,w(this,mn,"f"))},Na=function(){const t=w(this,mn,"f")?.response_format;return el(t)?t:null},fc=function(t){var s,r,i,a;let o=w(this,Fn,"f");const{choices:l,...c}=t;o?Object.assign(o,c):o=J(this,Fn,{...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:M,refusal:S,...T}=f;Object.assign(m.logprobs,T),M&&((s=m.logprobs).content??(s.content=[]),m.logprobs.content.push(...M)),S&&((r=m.logprobs).refusal??(r.refusal=[]),m.logprobs.refusal.push(...S))}if(u&&(m.finish_reason=u,w(this,mn,"f")&&Ed(w(this,mn,"f")))){if(u==="length")throw new sd;if(u==="content_filter")throw new rd}if(Object.assign(m,p),!d)continue;const{content:v,refusal:y,function_call:_,role:b,tool_calls:k,...P}=d;if(Object.assign(m.message,P),y&&(m.message.refusal=(m.message.refusal||"")+y),b&&(m.message.role=b),_&&(m.message.function_call?(_.name&&(m.message.function_call.name=_.name),_.arguments&&((i=m.message.function_call).arguments??(i.arguments=""),m.message.function_call.arguments+=_.arguments)):m.message.function_call=_),v&&(m.message.content=(m.message.content||"")+v,!m.message.refusal&&w(this,Pe,"m",Na).call(this)&&(m.message.parsed=dc(m.message.content))),k){m.message.tool_calls||(m.message.tool_calls=[]);for(const{index:M,id:S,type:T,function:R,...F}of k){const W=(a=m.message.tool_calls)[M]??(a[M]={});Object.assign(W,F),S&&(W.id=S),T&&(W.type=T),R&&(W.function??(W.function={name:R.name??"",arguments:""})),R?.name&&(W.function.name=R.name),R?.arguments&&(W.function.arguments+=R.arguments,By(w(this,mn,"f"),W)&&(W.function.parsed_arguments=dc(W.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 en(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function Yy(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 q(`missing finish_reason for choice ${u}`);const{content:p=null,function_call:m,tool_calls:v,...y}=c,_=c.role;if(!_)throw new q(`missing role for choice ${u}`);if(m){const{arguments:b,name:k}=m;if(b==null)throw new q(`missing function_call.arguments for choice ${u}`);if(!k)throw new q(`missing function_call.name for choice ${u}`);return{...f,message:{content:p,function_call:{arguments:b,name:k},role:_,refusal:c.refusal??null},finish_reason:d,index:u,logprobs:h}}return v?{...f,index:u,finish_reason:d,logprobs:h,message:{...y,role:_,content:p,refusal:c.refusal??null,tool_calls:v.map((b,k)=>{const{function:P,type:M,id:S,...T}=b,{arguments:R,name:F,...W}=P||{};if(S==null)throw new q(`missing choices[${u}].tool_calls[${k}].id
${li(n)}`);if(M==null)throw new q(`missing choices[${u}].tool_calls[${k}].type
${li(n)}`);if(F==null)throw new q(`missing choices[${u}].tool_calls[${k}].function.name
${li(n)}`);if(R==null)throw new q(`missing choices[${u}].tool_calls[${k}].function.arguments
${li(n)}`);return{...T,id:S,type:M,function:{...W,name:F,arguments:R}}})}}:{...f,message:{...y,content:p,role:_,refusal:c.refusal??null},finish_reason:d,index:u,logprobs:h}}),created:r,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return Dy(l,e)}function li(n){return JSON.stringify(n)}class ji extends Br{static fromReadableStream(e){const t=new ji(null);return t._run(()=>t._fromReadableStream(e)),t}static runTools(e,t,s){const r=new ji(t),i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,t,i)),r}}let rl=class extends z{constructor(){super(...arguments),this.messages=new kd(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(A`/chat/completions/${e}`,t)}update(e,t,s){return this._client.post(A`/chat/completions/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/chat/completions",Ae,{query:e,...t})}delete(e,t){return this._client.delete(A`/chat/completions/${e}`,t)}parse(e,t){return Uy(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>tl(s,e))}runTools(e,t){return e.stream?ji.runTools(this._client,e,t):sl.runTools(this._client,e,t)}stream(e,t){return Br.createChatCompletion(this._client,e,t)}};rl.Messages=kd;class il extends z{constructor(){super(...arguments),this.completions=new rl(this._client)}}il.Completions=rl;const Wd=Symbol("brand.privateNullableHeaders");function*Jy(n){if(!n)return;if(Wd 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():Xl(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=Xl(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 D=n=>{const e=new Headers,t=new Set;for(const s of n){const r=new Set;for(const[i,a]of Jy(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{[Wd]:!0,values:e,nulls:t}};class Hd extends z{create(e,t){return this._client.post("/audio/speech",{body:e,...t,headers:D([{Accept:"application/octet-stream"},t?.headers]),__binaryResponse:!0})}}class Vd extends z{create(e,t){return this._client.post("/audio/transcriptions",_s({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class Kd extends z{create(e,t){return this._client.post("/audio/translations",_s({body:e,...t,__metadata:{model:e.model}},this._client))}}class Zr extends z{constructor(){super(...arguments),this.transcriptions=new Vd(this._client),this.translations=new Kd(this._client),this.speech=new Hd(this._client)}}Zr.Transcriptions=Vd;Zr.Translations=Kd;Zr.Speech=Hd;class Yd extends z{create(e,t){return this._client.post("/batches",{body:e,...t})}retrieve(e,t){return this._client.get(A`/batches/${e}`,t)}list(e={},t){return this._client.getAPIList("/batches",Ae,{query:e,...t})}cancel(e,t){return this._client.post(A`/batches/${e}/cancel`,t)}}class Jd extends z{create(e,t){return this._client.post("/assistants",{body:e,...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(A`/assistants/${e}`,{...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(A`/assistants/${e}`,{body:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/assistants",Ae,{query:e,...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(A`/assistants/${e}`,{...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let Xd=class extends z{create(e,t){return this._client.post("/realtime/sessions",{body:e,...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}};class Gd extends z{create(e,t){return this._client.post("/realtime/transcription_sessions",{body:e,...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}}let la=class extends z{constructor(){super(...arguments),this.sessions=new Xd(this._client),this.transcriptionSessions=new Gd(this._client)}};la.Sessions=Xd;la.TranscriptionSessions=Gd;class Qd extends z{create(e,t){return this._client.post("/chatkit/sessions",{body:e,...t,headers:D([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}cancel(e,t){return this._client.post(A`/chatkit/sessions/${e}/cancel`,{...t,headers:D([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}}let Zd=class extends z{retrieve(e,t){return this._client.get(A`/chatkit/threads/${e}`,{...t,headers:D([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}list(e={},t){return this._client.getAPIList("/chatkit/threads",Ni,{query:e,...t,headers:D([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}delete(e,t){return this._client.delete(A`/chatkit/threads/${e}`,{...t,headers:D([{"OpenAI-Beta":"chatkit_beta=v1"},t?.headers])})}listItems(e,t={},s){return this._client.getAPIList(A`/chatkit/threads/${e}/items`,Ni,{query:t,...s,headers:D([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class ca extends z{constructor(){super(...arguments),this.sessions=new Qd(this._client),this.threads=new Zd(this._client)}}ca.Sessions=Qd;ca.Threads=Zd;class ef extends z{create(e,t,s){return this._client.post(A`/threads/${e}/messages`,{body:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(A`/threads/${r}/messages/${e}`,{...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(A`/threads/${r}/messages/${e}`,{body:i,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(A`/threads/${e}/messages`,Ae,{query:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{thread_id:r}=t;return this._client.delete(A`/threads/${r}/messages/${e}`,{...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class tf extends z{retrieve(e,t,s){const{thread_id:r,run_id:i,...a}=t;return this._client.get(A`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t,s){const{thread_id:r,...i}=t;return this._client.getAPIList(A`/threads/${r}/runs/${e}/steps`,Ae,{query:i,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const Xy=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))}},$s=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 ze,rs,bo,Vt,yi,Rt,is,Bs,ns,zi,ht,_i,wi,$r,xr,kr,hc,pc,mc,gc,vc,yc,_c;class Rr extends nl{constructor(){super(...arguments),ze.add(this),bo.set(this,[]),Vt.set(this,{}),yi.set(this,{}),Rt.set(this,void 0),is.set(this,void 0),Bs.set(this,void 0),ns.set(this,void 0),zi.set(this,void 0),ht.set(this,void 0),_i.set(this,void 0),wi.set(this,void 0),$r.set(this,void 0)}[(bo=new WeakMap,Vt=new WeakMap,yi=new WeakMap,Rt=new WeakMap,is=new WeakMap,Bs=new WeakMap,ns=new WeakMap,zi=new WeakMap,ht=new WeakMap,_i=new WeakMap,wi=new WeakMap,$r=new WeakMap,ze=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 rs;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=en.fromReadableStream(e,this.controller);for await(const i of r)w(this,ze,"m",xr).call(this,i);if(r.controller.signal?.aborted)throw new yt;return this._addRun(w(this,ze,"m",kr).call(this))}toReadableStream(){return new en(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,s,r){const i=new rs;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,ze,"m",xr).call(this,l);if(o.controller.signal?.aborted)throw new yt;return this._addRun(w(this,ze,"m",kr).call(this))}static createThreadAssistantStream(e,t,s){const r=new rs;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 rs;return i._run(()=>i._runAssistantStream(e,t,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return w(this,_i,"f")}currentRun(){return w(this,wi,"f")}currentMessageSnapshot(){return w(this,Rt,"f")}currentRunStepSnapshot(){return w(this,$r,"f")}async finalRunSteps(){return await this.done(),Object.values(w(this,Vt,"f"))}async finalMessages(){return await this.done(),Object.values(w(this,yi,"f"))}async finalRun(){if(await this.done(),!w(this,is,"f"))throw Error("Final run was not received.");return w(this,is,"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,ze,"m",xr).call(this,o);if(a.controller.signal?.aborted)throw new yt;return this._addRun(w(this,ze,"m",kr).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,ze,"m",xr).call(this,l);if(o.controller.signal?.aborted)throw new yt;return this._addRun(w(this,ze,"m",kr).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(Pa(i)&&Pa(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(!Pa(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)}}rs=Rr,xr=function(e){if(!this.ended)switch(J(this,_i,e),w(this,ze,"m",mc).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,ze,"m",_c).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,ze,"m",pc).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,ze,"m",hc).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},kr=function(){if(this.ended)throw new q("stream has ended, this shouldn't happen");if(!w(this,is,"f"))throw Error("Final run has not been received");return w(this,is,"f")},hc=function(e){const[t,s]=w(this,ze,"m",vc).call(this,e,w(this,Rt,"f"));J(this,Rt,t),w(this,yi,"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,Bs,"f")){if(w(this,ns,"f"))switch(w(this,ns,"f").type){case"text":this._emit("textDone",w(this,ns,"f").text,w(this,Rt,"f"));break;case"image_file":this._emit("imageFileDone",w(this,ns,"f").image_file,w(this,Rt,"f"));break}J(this,Bs,r.index)}J(this,ns,t.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(w(this,Bs,"f")!==void 0){const r=e.data.content[w(this,Bs,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,w(this,Rt,"f"));break;case"text":this._emit("textDone",r.text,w(this,Rt,"f"));break}}w(this,Rt,"f")&&this._emit("messageDone",e.data),J(this,Rt,void 0)}},pc=function(e){const t=w(this,ze,"m",gc).call(this,e);switch(J(this,$r,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,zi,"f")?this._emit("toolCallDelta",i,t.step_details.tool_calls[i.index]):(w(this,ht,"f")&&this._emit("toolCallDone",w(this,ht,"f")),J(this,zi,i.index),J(this,ht,t.step_details.tool_calls[i.index]),w(this,ht,"f")&&this._emit("toolCallCreated",w(this,ht,"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":J(this,$r,void 0),e.data.step_details.type=="tool_calls"&&w(this,ht,"f")&&(this._emit("toolCallDone",w(this,ht,"f")),J(this,ht,void 0)),this._emit("runStepDone",e.data,t);break}},mc=function(e){w(this,bo,"f").push(e),this._emit("event",e)},gc=function(e){switch(e.event){case"thread.run.step.created":return w(this,Vt,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let t=w(this,Vt,"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=rs.accumulateDelta(t,s.delta);w(this,Vt,"f")[e.data.id]=r}return w(this,Vt,"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,Vt,"f")[e.data.id]=e.data;break}if(w(this,Vt,"f")[e.data.id])return w(this,Vt,"f")[e.data.id];throw new Error("No snapshot available")},vc=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,ze,"m",yc).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")},yc=function(e,t){return rs.accumulateDelta(t,e)},_c=function(e){switch(J(this,wi,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":J(this,is,e.data),w(this,ht,"f")&&(this._emit("toolCallDone",w(this,ht,"f")),J(this,ht,void 0));break}};let al=class extends z{constructor(){super(...arguments),this.steps=new tf(this._client)}create(e,t,s){const{include:r,...i}=t;return this._client.post(A`/threads/${e}/runs`,{query:{include:r},body:i,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:t.stream??!1})}retrieve(e,t,s){const{thread_id:r}=t;return this._client.get(A`/threads/${r}/runs/${e}`,{...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{thread_id:r,...i}=t;return this._client.post(A`/threads/${r}/runs/${e}`,{body:i,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(A`/threads/${e}/runs`,Ae,{query:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{thread_id:r}=t;return this._client.post(A`/threads/${r}/runs/${e}/cancel`,{...s,headers:D([{"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 Rr.createAssistantStream(e,this._client.beta.threads.runs,t,s)}async poll(e,t,s){const r=D([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 Xr(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,t,s){return Rr.createAssistantStream(e,this._client.beta.threads.runs,t,s)}submitToolOutputs(e,t,s){const{thread_id:r,...i}=t;return this._client.post(A`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...s,headers:D([{"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 Rr.createToolAssistantStream(e,this._client.beta.threads.runs,t,s)}};al.Steps=tf;class ua extends z{constructor(){super(...arguments),this.runs=new al(this._client),this.messages=new ef(this._client)}create(e={},t){return this._client.post("/threads",{body:e,...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(A`/threads/${e}`,{...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(A`/threads/${e}`,{body:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t){return this._client.delete(A`/threads/${e}`,{...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}createAndRun(e,t){return this._client.post("/threads/runs",{body:e,...t,headers:D([{"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 Rr.createThreadAssistantStream(e,this._client.beta.threads,t)}}ua.Runs=al;ua.Messages=ef;class ir extends z{constructor(){super(...arguments),this.realtime=new la(this._client),this.chatkit=new ca(this._client),this.assistants=new Jd(this._client),this.threads=new ua(this._client)}}ir.Realtime=la;ir.ChatKit=ca;ir.Assistants=Jd;ir.Threads=ua;class nf extends z{create(e,t){return this._client.post("/completions",{body:e,...t,stream:e.stream??!1})}}class sf extends z{retrieve(e,t,s){const{container_id:r}=t;return this._client.get(A`/containers/${r}/files/${e}/content`,{...s,headers:D([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let ol=class extends z{constructor(){super(...arguments),this.content=new sf(this._client)}create(e,t,s){return this._client.post(A`/containers/${e}/files`,_s({body:t,...s},this._client))}retrieve(e,t,s){const{container_id:r}=t;return this._client.get(A`/containers/${r}/files/${e}`,s)}list(e,t={},s){return this._client.getAPIList(A`/containers/${e}/files`,Ae,{query:t,...s})}delete(e,t,s){const{container_id:r}=t;return this._client.delete(A`/containers/${r}/files/${e}`,{...s,headers:D([{Accept:"*/*"},s?.headers])})}};ol.Content=sf;class ll extends z{constructor(){super(...arguments),this.files=new ol(this._client)}create(e,t){return this._client.post("/containers",{body:e,...t})}retrieve(e,t){return this._client.get(A`/containers/${e}`,t)}list(e={},t){return this._client.getAPIList("/containers",Ae,{query:e,...t})}delete(e,t){return this._client.delete(A`/containers/${e}`,{...t,headers:D([{Accept:"*/*"},t?.headers])})}}ll.Files=ol;class rf extends z{create(e,t,s){const{include:r,...i}=t;return this._client.post(A`/conversations/${e}/items`,{query:{include:r},body:i,...s})}retrieve(e,t,s){const{conversation_id:r,...i}=t;return this._client.get(A`/conversations/${r}/items/${e}`,{query:i,...s})}list(e,t={},s){return this._client.getAPIList(A`/conversations/${e}/items`,Ni,{query:t,...s})}delete(e,t,s){const{conversation_id:r}=t;return this._client.delete(A`/conversations/${r}/items/${e}`,s)}}class cl extends z{constructor(){super(...arguments),this.items=new rf(this._client)}create(e={},t){return this._client.post("/conversations",{body:e,...t})}retrieve(e,t){return this._client.get(A`/conversations/${e}`,t)}update(e,t,s){return this._client.post(A`/conversations/${e}`,{body:t,...s})}delete(e,t){return this._client.delete(A`/conversations/${e}`,t)}}cl.Items=rf;class af extends z{create(e,t){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&Ue(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:(Ue(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=Xy(l)}),a)))}}class of extends z{retrieve(e,t,s){const{eval_id:r,run_id:i}=t;return this._client.get(A`/evals/${r}/runs/${i}/output_items/${e}`,s)}list(e,t,s){const{eval_id:r,...i}=t;return this._client.getAPIList(A`/evals/${r}/runs/${e}/output_items`,Ae,{query:i,...s})}}class ul extends z{constructor(){super(...arguments),this.outputItems=new of(this._client)}create(e,t,s){return this._client.post(A`/evals/${e}/runs`,{body:t,...s})}retrieve(e,t,s){const{eval_id:r}=t;return this._client.get(A`/evals/${r}/runs/${e}`,s)}list(e,t={},s){return this._client.getAPIList(A`/evals/${e}/runs`,Ae,{query:t,...s})}delete(e,t,s){const{eval_id:r}=t;return this._client.delete(A`/evals/${r}/runs/${e}`,s)}cancel(e,t,s){const{eval_id:r}=t;return this._client.post(A`/evals/${r}/runs/${e}`,s)}}ul.OutputItems=of;class dl extends z{constructor(){super(...arguments),this.runs=new ul(this._client)}create(e,t){return this._client.post("/evals",{body:e,...t})}retrieve(e,t){return this._client.get(A`/evals/${e}`,t)}update(e,t,s){return this._client.post(A`/evals/${e}`,{body:t,...s})}list(e={},t){return this._client.getAPIList("/evals",Ae,{query:e,...t})}delete(e,t){return this._client.delete(A`/evals/${e}`,t)}}dl.Runs=ul;let lf=class extends z{create(e,t){return this._client.post("/files",_s({body:e,...t},this._client))}retrieve(e,t){return this._client.get(A`/files/${e}`,t)}list(e={},t){return this._client.getAPIList("/files",Ae,{query:e,...t})}delete(e,t){return this._client.delete(A`/files/${e}`,t)}content(e,t){return this._client.get(A`/files/${e}/content`,{...t,headers:D([{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 Xr(t),a=await this.retrieve(e),Date.now()-i>s)throw new ia({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};class cf extends z{}let uf=class extends z{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 fl extends z{constructor(){super(...arguments),this.graders=new uf(this._client)}}fl.Graders=uf;class df extends z{create(e,t,s){return this._client.getAPIList(A`/fine_tuning/checkpoints/${e}/permissions`,oa,{body:t,method:"post",...s})}retrieve(e,t={},s){return this._client.get(A`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...s})}delete(e,t,s){const{fine_tuned_model_checkpoint:r}=t;return this._client.delete(A`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let hl=class extends z{constructor(){super(...arguments),this.permissions=new df(this._client)}};hl.Permissions=df;class ff extends z{list(e,t={},s){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/checkpoints`,Ae,{query:t,...s})}}class pl extends z{constructor(){super(...arguments),this.checkpoints=new ff(this._client)}create(e,t){return this._client.post("/fine_tuning/jobs",{body:e,...t})}retrieve(e,t){return this._client.get(A`/fine_tuning/jobs/${e}`,t)}list(e={},t){return this._client.getAPIList("/fine_tuning/jobs",Ae,{query:e,...t})}cancel(e,t){return this._client.post(A`/fine_tuning/jobs/${e}/cancel`,t)}listEvents(e,t={},s){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/events`,Ae,{query:t,...s})}pause(e,t){return this._client.post(A`/fine_tuning/jobs/${e}/pause`,t)}resume(e,t){return this._client.post(A`/fine_tuning/jobs/${e}/resume`,t)}}pl.Checkpoints=ff;class ar extends z{constructor(){super(...arguments),this.methods=new cf(this._client),this.jobs=new pl(this._client),this.checkpoints=new hl(this._client),this.alpha=new fl(this._client)}}ar.Methods=cf;ar.Jobs=pl;ar.Checkpoints=hl;ar.Alpha=fl;class hf extends z{}class ml extends z{constructor(){super(...arguments),this.graderModels=new hf(this._client)}}ml.GraderModels=hf;class pf extends z{createVariation(e,t){return this._client.post("/images/variations",_s({body:e,...t},this._client))}edit(e,t){return this._client.post("/images/edits",_s({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 mf extends z{retrieve(e,t){return this._client.get(A`/models/${e}`,t)}list(e){return this._client.getAPIList("/models",oa,e)}delete(e,t){return this._client.delete(A`/models/${e}`,t)}}class gf extends z{create(e,t){return this._client.post("/moderations",{body:e,...t})}}class vf extends z{accept(e,t,s){return this._client.post(A`/realtime/calls/${e}/accept`,{body:t,...s,headers:D([{Accept:"*/*"},s?.headers])})}hangup(e,t){return this._client.post(A`/realtime/calls/${e}/hangup`,{...t,headers:D([{Accept:"*/*"},t?.headers])})}refer(e,t,s){return this._client.post(A`/realtime/calls/${e}/refer`,{body:t,...s,headers:D([{Accept:"*/*"},s?.headers])})}reject(e,t={},s){return this._client.post(A`/realtime/calls/${e}/reject`,{body:t,...s,headers:D([{Accept:"*/*"},s?.headers])})}}class yf extends z{create(e,t){return this._client.post("/realtime/client_secrets",{body:e,...t})}}class da extends z{constructor(){super(...arguments),this.clientSecrets=new yf(this._client),this.calls=new vf(this._client)}}da.ClientSecrets=yf;da.Calls=vf;function Gy(n,e){return!e||!Zy(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)}:_f(n,e)}function _f(n,e){const t=n.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:n_(e,r)};if(r.type==="message"){const i=r.content.map(a=>a.type==="output_text"?{...a,parsed:Qy(e,a.text)}:a);return{...r,content:i}}return r}),s=Object.assign({},n,{output:t});return Object.getOwnPropertyDescriptor(n,"output_text")||xo(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 Qy(n,e){return n.text?.format?.type!=="json_schema"?null:"$parseRaw"in n.text?.format?(n.text?.format).$parseRaw(e):JSON.parse(e)}function Zy(n){return!!el(n.text?.format)}function e_(n){return n?.$brand==="auto-parseable-tool"}function t_(n,e){return n.find(t=>t.type==="function"&&t.name===e)}function n_(n,e){const t=t_(n.tools??[],e.name);return{...e,...e,parsed_arguments:e_(t)?t.$parseRaw(e.arguments):t?.strict?JSON.parse(e.arguments):null}}function xo(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 Rs,ci,Nn,ui,wc,bc,xc,kc;class gl extends nl{constructor(e){super(),Rs.add(this),ci.set(this,void 0),Nn.set(this,void 0),ui.set(this,void 0),J(this,ci,e)}static createResponse(e,t,s){const r=new gl(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,Rs,"m",wc).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,Rs,"m",bc).call(this,o,a);if(i.controller.signal?.aborted)throw new yt;return w(this,Rs,"m",xc).call(this)}[(ci=new WeakMap,Nn=new WeakMap,ui=new WeakMap,Rs=new WeakSet,wc=function(){this.ended||J(this,Nn,void 0)},bc=function(t,s){if(this.ended)return;const r=(a,o)=>{(s==null||o.sequence_number>s)&&this._emit(a,o)},i=w(this,Rs,"m",kc).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 q(`missing output at index ${t.output_index}`);if(a.type==="message"){const o=a.content[t.content_index];if(!o)throw new q(`missing content at index ${t.content_index}`);if(o.type!=="output_text")throw new q(`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 q(`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}},xc=function(){if(this.ended)throw new q("stream has ended, this shouldn't happen");const t=w(this,Nn,"f");if(!t)throw new q("request ended without sending any events");J(this,Nn,void 0);const s=s_(t,w(this,ci,"f"));return J(this,ui,s),s},kc=function(t){let s=w(this,Nn,"f");if(!s){if(t.type!=="response.created")throw new q(`When snapshot hasn't been set yet, expected 'response.created' event, got ${t.type}`);return s=J(this,Nn,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 q(`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 q(`missing output at index ${t.output_index}`);if(r.type==="message"){const i=r.content[t.content_index];if(!i)throw new q(`missing content at index ${t.content_index}`);if(i.type!=="output_text")throw new q(`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 q(`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 q(`missing output at index ${t.output_index}`);if(r.type==="reasoning"){const i=r.content?.[t.content_index];if(!i)throw new q(`missing content at index ${t.content_index}`);if(i.type!=="reasoning_text")throw new q(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=t.delta}break}case"response.completed":{J(this,Nn,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,ui,"f");if(!e)throw new q("stream ended without producing a ChatCompletion");return e}}function s_(n,e){return Gy(n,e)}class wf extends z{list(e,t={},s){return this._client.getAPIList(A`/responses/${e}/input_items`,Ae,{query:t,...s})}}class bf extends z{count(e={},t){return this._client.post("/responses/input_tokens",{body:e,...t})}}class fa extends z{constructor(){super(...arguments),this.inputItems=new wf(this._client),this.inputTokens=new bf(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"&&xo(s),s))}retrieve(e,t={},s){return this._client.get(A`/responses/${e}`,{query:t,...s,stream:t?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&xo(r),r))}delete(e,t){return this._client.delete(A`/responses/${e}`,{...t,headers:D([{Accept:"*/*"},t?.headers])})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(s=>_f(s,e))}stream(e,t){return gl.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(A`/responses/${e}/cancel`,t)}}fa.InputItems=wf;fa.InputTokens=bf;class xf extends z{create(e,t,s){return this._client.post(A`/uploads/${e}/parts`,_s({body:t,...s},this._client))}}class vl extends z{constructor(){super(...arguments),this.parts=new xf(this._client)}create(e,t){return this._client.post("/uploads",{body:e,...t})}cancel(e,t){return this._client.post(A`/uploads/${e}/cancel`,t)}complete(e,t,s){return this._client.post(A`/uploads/${e}/complete`,{body:t,...s})}}vl.Parts=xf;const r_=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 kf extends z{create(e,t,s){return this._client.post(A`/vector_stores/${e}/file_batches`,{body:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(A`/vector_stores/${r}/file_batches/${e}`,{...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,t,s){const{vector_store_id:r}=t;return this._client.post(A`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:D([{"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(A`/vector_stores/${r}/file_batches/${e}/files`,Ae,{query:i,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,t,s){const r=D([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 Xr(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 r_(u),await this.createAndPoll(e,{file_ids:c})}}class Ef extends z{create(e,t,s){return this._client.post(A`/vector_stores/${e}/files`,{body:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,t,s){const{vector_store_id:r}=t;return this._client.get(A`/vector_stores/${r}/files/${e}`,{...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,t,s){const{vector_store_id:r,...i}=t;return this._client.post(A`/vector_stores/${r}/files/${e}`,{body:i,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,t={},s){return this._client.getAPIList(A`/vector_stores/${e}/files`,Ae,{query:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,t,s){const{vector_store_id:r}=t;return this._client.delete(A`/vector_stores/${r}/files/${e}`,{...s,headers:D([{"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=D([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 Xr(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(A`/vector_stores/${r}/files/${e}/content`,oa,{...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class ha extends z{constructor(){super(...arguments),this.files=new Ef(this._client),this.fileBatches=new kf(this._client)}create(e,t){return this._client.post("/vector_stores",{body:e,...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}retrieve(e,t){return this._client.get(A`/vector_stores/${e}`,{...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}update(e,t,s){return this._client.post(A`/vector_stores/${e}`,{body:t,...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},t){return this._client.getAPIList("/vector_stores",Ae,{query:e,...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}delete(e,t){return this._client.delete(A`/vector_stores/${e}`,{...t,headers:D([{"OpenAI-Beta":"assistants=v2"},t?.headers])})}search(e,t,s){return this._client.getAPIList(A`/vector_stores/${e}/search`,oa,{body:t,method:"post",...s,headers:D([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}ha.Files=Ef;ha.FileBatches=kf;class Sf extends z{create(e,t){return this._client.post("/videos",lc({body:e,...t},this._client))}retrieve(e,t){return this._client.get(A`/videos/${e}`,t)}list(e={},t){return this._client.getAPIList("/videos",Ni,{query:e,...t})}delete(e,t){return this._client.delete(A`/videos/${e}`,t)}downloadContent(e,t={},s){return this._client.get(A`/videos/${e}/content`,{query:t,...s,headers:D([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,t,s){return this._client.post(A`/videos/${e}/remix`,lc({body:t,...s},this._client))}}var Ns,Af,bi;class Cf extends z{constructor(){super(...arguments),Ns.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,Ns,"m",Af).call(this,s);const i=D([t]).values,a=w(this,Ns,"m",bi).call(this,i,"webhook-signature"),o=w(this,Ns,"m",bi).call(this,i,"webhook-timestamp"),l=w(this,Ns,"m",bi).call(this,i,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new Ls("Invalid webhook timestamp format");const d=Math.floor(Date.now()/1e3);if(d-c>r)throw new Ls("Webhook timestamp is too old");if(c>d+r)throw new Ls("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 Ls("The given webhook signature does not match the expected signature")}}Ns=new WeakSet,Af=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")},bi=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 ko,yl,xi,Pf;class ne{constructor({baseURL:e=$s("OPENAI_BASE_URL"),apiKey:t=$s("OPENAI_API_KEY"),organization:s=$s("OPENAI_ORG_ID")??null,project:r=$s("OPENAI_PROJECT_ID")??null,webhookSecret:i=$s("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(ko.add(this),xi.set(this,void 0),this.completions=new nf(this),this.chat=new il(this),this.embeddings=new af(this),this.files=new lf(this),this.images=new pf(this),this.audio=new Zr(this),this.moderations=new gf(this),this.models=new mf(this),this.fineTuning=new ar(this),this.graders=new ml(this),this.vectorStores=new ha(this),this.webhooks=new Cf(this),this.beta=new ir(this),this.batches=new Yd(this),this.uploads=new vl(this),this.responses=new fa(this),this.realtime=new da(this),this.conversations=new cl(this),this.evals=new dl(this),this.containers=new ll(this),this.videos=new Sf(this),t===void 0)throw new q("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&&ly())throw new q(`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??yl.DEFAULT_TIMEOUT,this.logger=o.logger??console;const l="warn";this.logLevel=l,this.logLevel=ac(o.logLevel,"ClientOptions.logLevel",this)??ac($s("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??hy(),J(this,xi,my),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 D([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return by(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ms}`}defaultIdempotencyKey(){return`stainless-node-retry-${nd()}`}makeStatusError(e,t,s,r){return Oe.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 q?s:new q(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof t!="string"||!t)throw new q(`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,ko,"m",Pf).call(this)&&s||this.baseURL,i=sy(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return ry(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 Gr(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(Ue(this).debug(`[${c}] sending request`,es({retryOfRequestLogID:s,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new yt;const h=new AbortController,f=await this.fetchWithTimeout(o,a,l,h).catch(uo),p=Date.now();if(f instanceof globalThis.Error){const y=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new yt;const _=co(f)||/timed? ?out/i.test(String(f)+("cause"in f?String(f.cause):""));if(t)return Ue(this).info(`[${c}] connection ${_?"timed out":"failed"} - ${y}`),Ue(this).debug(`[${c}] connection ${_?"timed out":"failed"} (${y})`,es({retryOfRequestLogID:s,url:o,durationMs:p-u,message:f.message})),this.retryRequest(r,t,s??c);throw Ue(this).info(`[${c}] connection ${_?"timed out":"failed"} - error; no more retries left`),Ue(this).debug(`[${c}] connection ${_?"timed out":"failed"} (error; no more retries left)`,es({retryOfRequestLogID:s,url:o,durationMs:p-u,message:f.message})),_?new ia:new Jr({cause:f})}const m=[...f.headers.entries()].filter(([y])=>y==="x-request-id").map(([y,_])=>", "+y+": "+JSON.stringify(_)).join(""),v=`[${c}${d}${m}] ${a.method} ${o} ${f.ok?"succeeded":"failed"} with status ${f.status} in ${p-u}ms`;if(!f.ok){const y=await this.shouldRetry(f);if(t&&y){const S=`retrying, ${t} attempts remaining`;return await py(f.body),Ue(this).info(`${v} - ${S}`),Ue(this).debug(`[${c}] response error (${S})`,es({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";Ue(this).info(`${v} - ${_}`);const b=await f.text().catch(S=>uo(S).message),k=oy(b),P=k?void 0:b;throw Ue(this).debug(`[${c}] response error (${_})`,es({retryOfRequestLogID:s,url:f.url,status:f.status,headers:f.headers,message:P,durationMs:Date.now()-u})),this.makeStatusError(f.status,k,P,f.headers)}return Ue(this).info(v),Ue(this).debug(`[${c}] response start`,es({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 gd(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 Xr(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&&ay("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=D([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))}:{},...fy(),"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=D([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:od(e)}:w(this,xi,"f").call(this,{body:e,headers:s})}}yl=ne,xi=new WeakMap,ko=new WeakSet,Pf=function(){return this.baseURL!=="https://api.openai.com/v1"};ne.OpenAI=yl;ne.DEFAULT_TIMEOUT=6e5;ne.OpenAIError=q;ne.APIError=Oe;ne.APIConnectionError=Jr;ne.APIConnectionTimeoutError=ia;ne.APIUserAbortError=yt;ne.NotFoundError=Vo;ne.ConflictError=Ko;ne.RateLimitError=Jo;ne.BadRequestError=qo;ne.AuthenticationError=Wo;ne.InternalServerError=Xo;ne.PermissionDeniedError=Ho;ne.UnprocessableEntityError=Yo;ne.InvalidWebhookSignatureError=Ls;ne.toFile=bd;ne.Completions=nf;ne.Chat=il;ne.Embeddings=af;ne.Files=lf;ne.Images=pf;ne.Audio=Zr;ne.Moderations=gf;ne.Models=mf;ne.FineTuning=ar;ne.Graders=ml;ne.VectorStores=ha;ne.Webhooks=Cf;ne.Beta=ir;ne.Batches=Yd;ne.Uploads=vl;ne.Responses=fa;ne.Realtime=da;ne.Conversations=cl;ne.Evals=dl;ne.Containers=ll;ne.Videos=Sf;const i_=Object.freeze(Object.defineProperty({__proto__:null,APIConnectionError:Jr,APIConnectionTimeoutError:ia,APIError:Oe,APIPromise:Gr,APIUserAbortError:yt,AuthenticationError:Wo,BadRequestError:qo,ConflictError:Ko,InternalServerError:Xo,InvalidWebhookSignatureError:Ls,NotFoundError:Vo,OpenAI:ne,OpenAIError:q,PagePromise:gd,PermissionDeniedError:Ho,RateLimitError:Jo,UnprocessableEntityError:Yo,default:ne,toFile:bd},Symbol.toStringTag,{value:"Module"}));module.exports=ty;
/* nosourcemap */