333 lines
341 KiB
JavaScript
333 lines
341 KiB
JavaScript
"use strict";var Jp=Object.defineProperty;var Wc=t=>{throw TypeError(t)};var Gp=(t,e,n)=>e in t?Jp(t,e,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[e]=n;var cn=(t,e,n)=>Gp(t,typeof e!="symbol"?e+"":e,n),go=(t,e,n)=>e.has(t)||Wc("Cannot "+n);var C=(t,e,n)=>(go(t,e,"read from private field"),n?n.call(t):e.get(t)),fe=(t,e,n)=>e.has(t)?Wc("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,n),se=(t,e,n,s)=>(go(t,e,"write to private field"),s?s.call(t,n):e.set(t,n),n),Se=(t,e,n)=>(go(t,e,"access private method"),n);const _=require("obsidian"),Kc=globalThis.process?.env?.NODE_ENV,X=Kc&&!Kc.toLowerCase().startsWith("prod");var Oa=Array.isArray,Qp=Array.prototype.indexOf,zl=Array.from,qn=Object.defineProperty,Ps=Object.getOwnPropertyDescriptor,_d=Object.getOwnPropertyDescriptors,Zp=Object.prototype,em=Array.prototype,ql=Object.getPrototypeOf,Yc=Object.isExtensible;function tm(t){return typeof t=="function"}const tn=()=>{};function nm(t){return t()}function Ho(t){for(var e=0;e<t.length;e++)t[e]()}function xd(){var t,e,n=new Promise((s,r)=>{t=s,e=r});return{promise:n,resolve:t,reject:e}}const tt=2,Hl=4,Ba=8,kn=16,Wn=32,Os=64,Ua=128,rn=512,Qe=1024,St=2048,En=4096,Dt=8192,Un=16384,ja=32768,Is=65536,ua=1<<17,kd=1<<18,kr=1<<19,Ed=1<<20,is=32768,Vo=1<<21,za=1<<22,es=1<<23,xn=Symbol("$state"),sm=Symbol("legacy props"),rm=Symbol(""),Sd=Symbol("proxy path"),ir=new class extends Error{constructor(){super(...arguments);cn(this,"name","StaleReactionError");cn(this,"message","The reaction that called `getAbortSignal()` was re-run or destroyed")}};function Ad(t){return t===this.v}function Cd(t,e){return t!=t?e==e:t!==e||t!==null&&typeof t=="object"||typeof t=="function"}function Td(t){return!Cd(t,this.v)}function qa(t){if(X){const e=new Error(`lifecycle_outside_component
|
||
\`${t}(...)\` 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 im(){if(X){const t=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 t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/async_derived_orphan")}function am(){if(X){const t=new Error(`derived_references_self
|
||
A derived value cannot reference itself recursively
|
||
https://svelte.dev/e/derived_references_self`);throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/derived_references_self")}function om(t){if(X){const e=new Error(`effect_in_teardown
|
||
\`${t}\` 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 lm(){if(X){const t=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 t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_in_unowned_derived")}function cm(t){if(X){const e=new Error(`effect_orphan
|
||
\`${t}\` 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 um(){if(X){const t=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 t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/effect_update_depth_exceeded")}function dm(t){if(X){const e=new Error(`lifecycle_legacy_only
|
||
\`${t}(...)\` 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 fm(t){if(X){const e=new Error(`props_invalid_value
|
||
Cannot do \`bind:${t}={undefined}\` when \`${t}\` 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 hm(t){if(X){const e=new Error(`rune_outside_svelte
|
||
The \`${t}\` 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 pm(){if(X){const t=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 t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_descriptors_fixed")}function mm(){if(X){const t=new Error("state_prototype_fixed\nCannot set prototype of `$state` object\nhttps://svelte.dev/e/state_prototype_fixed");throw t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_prototype_fixed")}function gm(){if(X){const t=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 t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/state_unsafe_mutation")}function vm(){if(X){const t=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 t.name="Svelte error",t}else throw new Error("https://svelte.dev/e/svelte_boundary_reset_onerror")}let Er=!1,ym=!1;function wm(){Er=!0}const Pd=1,$d=2,Id=4,bm=8,_m=16,xm=1,km=2,Em=4,Sm=8,Am=16,Cm=4,Tm=1,Pm=2,st=Symbol(),$m=Symbol("filename"),Im="http://www.w3.org/1999/xhtml";function Nm(t){const e=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let n=Error();Error.stackTraceLimit=e;const s=n.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:(qn(n,"stack",{value:i.join(`
|
||
`)}),qn(n,"name",{value:t}),n)}function dn(t,e){return t.label=e,Nd(t.v,e),t}function Nd(t,e){return t?.[Sd]?.(e),t}let ve=null;function mr(t){ve=t}let oi=null;function da(t){oi=t}let wi=null;function Xc(t){wi=t}function Te(t,e=!1,n){ve={p:ve,i:!1,c:null,e:null,s:t,x:null,l:Er&&!e?{s:null,u:null,$:[]}:null},X&&(ve.function=n,wi=n)}function Pe(t){var e=ve,n=e.e;if(n!==null){e.e=null;for(var s of n)Zd(s)}return e.i=!0,ve=e.p,X&&(wi=ve?.function??null),{}}function bi(){return!Er||ve!==null&&ve.l===null}let ar=[];function Rm(){var t=ar;ar=[],Ho(t)}function Bs(t){if(ar.length===0){var e=ar;queueMicrotask(()=>{e===ar&&Rm()})}ar.push(t)}const Fm=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function or(t){if(typeof t!="object"||t===null||xn in t)return t;const e=ql(t);if(e!==Zp&&e!==em)return t;var n=new Map,s=Oa(t),r=Kn(0),i=$s,a=u=>{if($s===i)return u();var d=ce,f=$s;xt(null),eu(i);var h=u();return xt(d),eu(f),h};s&&(n.set("length",Kn(t.length)),X&&(t=Dm(t)));var o="";let l=!1;function c(u){if(!l){l=!0,o=u,dn(r,`${o} version`);for(const[d,f]of n)dn(f,hs(o,d));l=!1}}return new Proxy(t,{defineProperty(u,d,f){(!("value"in f)||f.configurable===!1||f.enumerable===!1||f.writable===!1)&&pm();var h=n.get(d);return h===void 0?h=a(()=>{var m=Kn(f.value);return n.set(d,m),X&&typeof d=="string"&&dn(m,hs(o,d)),m}):E(h,f.value,!0),!0},deleteProperty(u,d){var f=n.get(d);if(f===void 0){if(d in u){const h=a(()=>Kn(st));n.set(d,h),Zr(r),X&&dn(h,hs(o,d))}}else E(f,st),Zr(r);return!0},get(u,d,f){if(d===xn)return t;if(X&&d===Sd)return c;var h=n.get(d),m=d in u;if(h===void 0&&(!m||Ps(u,d)?.writable)&&(h=a(()=>{var y=or(m?u[d]:st),b=Kn(y);return X&&dn(b,hs(o,d)),b}),n.set(d,h)),h!==void 0){var g=p(h);return g===st?void 0:g}return Reflect.get(u,d,f)},getOwnPropertyDescriptor(u,d){var f=Reflect.getOwnPropertyDescriptor(u,d);if(f&&"value"in f){var h=n.get(d);h&&(f.value=p(h))}else if(f===void 0){var m=n.get(d),g=m?.v;if(m!==void 0&&g!==st)return{enumerable:!0,configurable:!0,value:g,writable:!0}}return f},has(u,d){if(d===xn)return!0;var f=n.get(d),h=f!==void 0&&f.v!==st||Reflect.has(u,d);if(f!==void 0||he!==null&&(!h||Ps(u,d)?.writable)){f===void 0&&(f=a(()=>{var g=h?or(u[d]):st,y=Kn(g);return X&&dn(y,hs(o,d)),y}),n.set(d,f));var m=p(f);if(m===st)return!1}return h},set(u,d,f,h){var m=n.get(d),g=d in u;if(s&&d==="length")for(var y=f;y<m.v;y+=1){var b=n.get(y+"");b!==void 0?E(b,st):y in u&&(b=a(()=>Kn(st)),n.set(y+"",b),X&&dn(b,hs(o,y)))}if(m===void 0)(!g||Ps(u,d)?.writable)&&(m=a(()=>Kn(void 0)),X&&dn(m,hs(o,d)),E(m,or(f)),n.set(d,m));else{g=m.v!==st;var v=a(()=>or(f));E(m,v)}var w=Reflect.getOwnPropertyDescriptor(u,d);if(w?.set&&w.set.call(h,f),!g){if(s&&typeof d=="string"){var k=n.get("length"),P=Number(d);Number.isInteger(P)&&P>=k.v&&E(k,P+1)}Zr(r)}return!0},ownKeys(u){p(r);var d=Reflect.ownKeys(u).filter(m=>{var g=n.get(m);return g===void 0||g.v!==st});for(var[f,h]of n)h.v!==st&&!(f in u)&&d.push(f);return d},setPrototypeOf(){mm()}})}function hs(t,e){return typeof e=="symbol"?`${t}[Symbol(${e.description??""})]`:Fm.test(e)?`${t}.${e}`:/^\d+$/.test(e)?`${t}[${e}]`:`${t}['${e}']`}function vo(t){try{if(t!==null&&typeof t=="object"&&xn in t)return t[xn]}catch{}return t}const Mm=new Set(["copyWithin","fill","pop","push","reverse","shift","sort","splice","unshift"]);function Dm(t){return new Proxy(t,{get(e,n,s){var r=Reflect.get(e,n,s);return Mm.has(n)?function(...i){rg();var a=r.apply(this,i);return qd(),a}:r}})}function Lm(){const t=Array.prototype,e=Array.__svelte_cleanup;e&&e();const{indexOf:n,lastIndexOf:s,includes:r}=t;t.indexOf=function(i,a){const o=n.call(this,i,a);if(o===-1){for(let l=a??0;l<this.length;l+=1)if(vo(this[l])===i){break}}return o},t.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(vo(this[l])===i){break}}return o},t.includes=function(i,a){const o=r.call(this,i,a);if(!o){for(let l=0;l<this.length;l+=1)if(vo(this[l])===i){break}}return o},Array.__svelte_cleanup=()=>{t.indexOf=n,t.lastIndexOf=s,t.includes=r}}var Jc,Vl,Rd,Fd;function Om(){if(Jc===void 0){Jc=window,Vl=/Firefox/.test(navigator.userAgent);var t=Element.prototype,e=Node.prototype,n=Text.prototype;Rd=Ps(e,"firstChild").get,Fd=Ps(e,"nextSibling").get,Yc(t)&&(t.__click=void 0,t.__className=void 0,t.__attributes=null,t.__style=void 0,t.__e=void 0),Yc(n)&&(n.__t=void 0),X&&(t.__svelte_meta=null,Lm())}}function Hn(t=""){return document.createTextNode(t)}function fa(t){return Rd.call(t)}function _i(t){return Fd.call(t)}function F(t,e){return fa(t)}function Ve(t,e=!1){{var n=fa(t);return n instanceof Comment&&n.data===""?_i(n):n}}function W(t,e=1,n=!1){let s=t;for(;e--;)s=_i(s);return s}function Bm(t){t.textContent=""}function Md(){return!1}const Wo=new WeakMap;function Dd(t){var e=he;if(e===null)return ce.f|=es,t;if(X&&t instanceof Error&&!Wo.has(t)&&Wo.set(t,Um(t,e)),(e.f&ja)===0){if((e.f&Ua)===0)throw X&&!e.parent&&t instanceof Error&&Ld(t),t;e.b.error(t)}else gr(t,e)}function gr(t,e){for(;e!==null;){if((e.f&Ua)!==0)try{e.b.error(t);return}catch(n){t=n}e=e.parent}throw X&&t instanceof Error&&Ld(t),t}function Um(t,e){const n=Ps(t,"message");if(!(n&&!n.configurable)){for(var s=Vl?" ":" ",r=`
|
||
${s}in ${e.fn?.name||"<unknown>"}`,i=e.ctx;i!==null;)r+=`
|
||
${s}in ${i.function?.[$m].split("/").pop()}`,i=i.p;return{message:t.message+`
|
||
${r}
|
||
`,stack:t.stack?.split(`
|
||
`).filter(a=>!a.includes("svelte/src/internal")).join(`
|
||
`)}}}function Ld(t){const e=Wo.get(t);e&&(qn(t,"message",{value:e.message}),qn(t,"stack",{value:e.stack}))}const Li=new Set;let Me=null,Ht=null,hn=[],Wl=null,Ko=!1;var dr,fr,ks,Es,gi,hr,pr,je,Yo,ms,Xo,Od,Bd;const Ma=class Ma{constructor(){fe(this,je);cn(this,"committed",!1);cn(this,"current",new Map);cn(this,"previous",new Map);fe(this,dr,new Set);fe(this,fr,new Set);fe(this,ks,0);fe(this,Es,0);fe(this,gi,null);fe(this,hr,[]);fe(this,pr,[]);cn(this,"skipped_effects",new Set);cn(this,"is_fork",!1)}is_deferred(){return this.is_fork||C(this,Es)>0}process(e){hn=[],this.apply();var n={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const s of e)Se(this,je,Yo).call(this,s,n);this.is_fork||Se(this,je,Od).call(this),this.is_deferred()?(Se(this,je,ms).call(this,n.effects),Se(this,je,ms).call(this,n.render_effects),Se(this,je,ms).call(this,n.block_effects)):(Me=null,Gc(n.render_effects),Gc(n.effects),C(this,gi)?.resolve()),Ht=null}capture(e,n){this.previous.has(e)||this.previous.set(e,n),(e.f&es)===0&&(this.current.set(e,e.v),Ht?.set(e,e.v))}activate(){Me=this,this.apply()}deactivate(){Me===this&&(Me=null,Ht=null)}flush(){if(this.activate(),hn.length>0){if(jm(),Me!==null&&Me!==this)return}else C(this,ks)===0&&this.process([]);this.deactivate()}discard(){for(const e of C(this,fr))e(this);C(this,fr).clear()}increment(e){se(this,ks,C(this,ks)+1),e&&se(this,Es,C(this,Es)+1)}decrement(e){se(this,ks,C(this,ks)-1),e&&se(this,Es,C(this,Es)-1),this.revive()}revive(){for(const e of C(this,hr))Ze(e,St),Ns(e);for(const e of C(this,pr))Ze(e,En),Ns(e);se(this,hr,[]),se(this,pr,[]),this.flush()}oncommit(e){C(this,dr).add(e)}ondiscard(e){C(this,fr).add(e)}settled(){return(C(this,gi)??se(this,gi,xd())).promise}static ensure(){if(Me===null){const e=Me=new Ma;Li.add(Me),Ma.enqueue(()=>{Me===e&&e.flush()})}return Me}static enqueue(e){Bs(e)}apply(){}};dr=new WeakMap,fr=new WeakMap,ks=new WeakMap,Es=new WeakMap,gi=new WeakMap,hr=new WeakMap,pr=new WeakMap,je=new WeakSet,Yo=function(e,n){e.f^=Qe;for(var s=e.first;s!==null;){var r=s.f,i=(r&(Wn|Os))!==0,a=i&&(r&Qe)!==0,o=a||(r&Dt)!==0||this.skipped_effects.has(s);if((s.f&Ua)!==0&&s.b?.is_pending()&&(n={parent:n,effect:s,effects:[],render_effects:[],block_effects:[]}),!o&&s.fn!==null){i?s.f^=Qe:(r&Hl)!==0?n.effects.push(s):Sr(s)&&((s.f&kn)!==0&&n.block_effects.push(s),wr(s));var l=s.first;if(l!==null){s=l;continue}}var c=s.parent;for(s=s.next;s===null&&c!==null;)c===n.effect&&(Se(this,je,ms).call(this,n.effects),Se(this,je,ms).call(this,n.render_effects),Se(this,je,ms).call(this,n.block_effects),n=n.parent),s=c.next,c=c.parent}},ms=function(e){for(const n of e)((n.f&St)!==0?C(this,hr):C(this,pr)).push(n),Se(this,je,Xo).call(this,n.deps),Ze(n,Qe)},Xo=function(e){if(e!==null)for(const n of e)(n.f&tt)===0||(n.f&is)===0||(n.f^=is,Se(this,je,Xo).call(this,n.deps))},Od=function(){if(C(this,Es)===0){for(const e of C(this,dr))e();C(this,dr).clear()}C(this,ks)===0&&Se(this,je,Bd).call(this)},Bd=function(){var i;if(Li.size>1){this.previous.clear();var e=Ht,n=!0,s={parent:null,effect:null,effects:[],render_effects:[],block_effects:[]};for(const a of Li){if(a===this){n=!1;continue}const o=[];for(const[c,u]of this.current){if(a.current.has(c))if(n&&u!==a.current.get(c))a.current.set(c,u);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=hn;hn=[];const c=new Set,u=new Map;for(const d of o)Ud(d,l,c,u);if(hn.length>0){Me=a,a.apply();for(const d of hn)Se(i=a,je,Yo).call(i,d,s);a.deactivate()}hn=r}}Me=null,Ht=e}this.committed=!0,Li.delete(this)};let Bn=Ma;function jm(){var t=ss;Ko=!0;var e=X?new Set:null;try{var n=0;for(pa(!0);hn.length>0;){var s=Bn.ensure();if(n++>1e3){if(X){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}zm()}if(s.process(hn),ns.clear(),X)for(const a of s.current.keys())e.add(a)}}finally{if(Ko=!1,pa(t),Wl=null,X)for(const a of e)a.updated=null}}function zm(){try{um()}catch(t){X&&qn(t,"stack",{value:""}),gr(t,Wl)}}let Fn=null;function Gc(t){var e=t.length;if(e!==0){for(var n=0;n<e;){var s=t[n++];if((s.f&(Un|Dt))===0&&Sr(s)&&(Fn=new Set,wr(s),s.deps===null&&s.first===null&&s.nodes_start===null&&(s.teardown===null&&s.ac===null?nf(s):s.fn=null),Fn?.size>0)){ns.clear();for(const r of Fn){if((r.f&(Un|Dt))!==0)continue;const i=[r];let a=r.parent;for(;a!==null;)Fn.has(a)&&(Fn.delete(a),i.push(a)),a=a.parent;for(let o=i.length-1;o>=0;o--){const l=i[o];(l.f&(Un|Dt))===0&&wr(l)}}Fn.clear()}}Fn=null}}function Ud(t,e,n,s){if(!n.has(t)&&(n.add(t),t.reactions!==null))for(const r of t.reactions){const i=r.f;(i&tt)!==0?Ud(r,e,n,s):(i&(za|kn))!==0&&(i&St)===0&&jd(r,e,s)&&(Ze(r,St),Ns(r))}}function jd(t,e,n){const s=n.get(t);if(s!==void 0)return s;if(t.deps!==null)for(const r of t.deps){if(e.includes(r))return!0;if((r.f&tt)!==0&&jd(r,e,n))return n.set(r,!0),!0}return n.set(t,!1),!1}function Ns(t){for(var e=Wl=t;e.parent!==null;){e=e.parent;var n=e.f;if(Ko&&e===he&&(n&kn)!==0&&(n&kd)===0)return;if((n&(Os|Wn))!==0){if((n&Qe)===0)return;e.f^=Qe}}hn.push(e)}function qm(t){let e=0,n=Fs(0),s;return X&&dn(n,"createSubscriber version"),()=>{Ha()&&(p(n),Cr(()=>(e===0&&(s=O(()=>t(()=>Zr(n)))),e+=1,()=>{Bs(()=>{e-=1,e===0&&(s?.(),s=void 0,Zr(n))})})))}}var Hm=Is|kr|Ua;function Vm(t,e,n){new Wm(t,e,n)}var Ut,jt,jl,mn,Ss,gn,zt,bt,vn,Dn,Gn,As,Qn,Cs,Ln,Da,Ke,Km,Ym,Jo,Ji,Gi,Go;class Wm{constructor(e,n,s){fe(this,Ke);cn(this,"parent");fe(this,Ut,!1);fe(this,jt);fe(this,jl,null);fe(this,mn);fe(this,Ss);fe(this,gn);fe(this,zt,null);fe(this,bt,null);fe(this,vn,null);fe(this,Dn,null);fe(this,Gn,null);fe(this,As,0);fe(this,Qn,0);fe(this,Cs,!1);fe(this,Ln,null);fe(this,Da,qm(()=>(se(this,Ln,Fs(C(this,As))),X&&dn(C(this,Ln),"$effect.pending()"),()=>{se(this,Ln,null)})));se(this,jt,e),se(this,mn,n),se(this,Ss,s),this.parent=he.b,se(this,Ut,!!C(this,mn).pending),se(this,gn,Xl(()=>{he.b=this;{var r=Se(this,Ke,Jo).call(this);try{se(this,zt,qt(()=>s(r)))}catch(i){this.error(i)}C(this,Qn)>0?Se(this,Ke,Gi).call(this):se(this,Ut,!1)}return()=>{C(this,Gn)?.remove()}},Hm))}is_pending(){return C(this,Ut)||!!this.parent&&this.parent.is_pending()}has_pending_snippet(){return!!C(this,mn).pending}update_pending_count(e){Se(this,Ke,Go).call(this,e),se(this,As,C(this,As)+e),C(this,Ln)&&yr(C(this,Ln),C(this,As))}get_effect_pending(){return C(this,Da).call(this),p(C(this,Ln))}error(e){var n=C(this,mn).onerror;let s=C(this,mn).failed;if(C(this,Cs)||!n&&!s)throw e;C(this,zt)&&(kt(C(this,zt)),se(this,zt,null)),C(this,bt)&&(kt(C(this,bt)),se(this,bt,null)),C(this,vn)&&(kt(C(this,vn)),se(this,vn,null));var r=!1,i=!1;const a=()=>{if(r){return}r=!0,i&&vm(),Bn.ensure(),se(this,As,0),C(this,vn)!==null&&ur(C(this,vn),()=>{se(this,vn,null)}),se(this,Ut,this.has_pending_snippet()),se(this,zt,Se(this,Ke,Ji).call(this,()=>(se(this,Cs,!1),qt(()=>C(this,Ss).call(this,C(this,jt)))))),C(this,Qn)>0?Se(this,Ke,Gi).call(this):se(this,Ut,!1)};var o=ce;try{xt(null),i=!0,n?.(e,a),i=!1}catch(l){gr(l,C(this,gn)&&C(this,gn).parent)}finally{xt(o)}s&&Bs(()=>{se(this,vn,Se(this,Ke,Ji).call(this,()=>{Bn.ensure(),se(this,Cs,!0);try{return qt(()=>{s(C(this,jt),()=>e,()=>a)})}catch(l){return gr(l,C(this,gn).parent),null}finally{se(this,Cs,!1)}}))})}}Ut=new WeakMap,jt=new WeakMap,jl=new WeakMap,mn=new WeakMap,Ss=new WeakMap,gn=new WeakMap,zt=new WeakMap,bt=new WeakMap,vn=new WeakMap,Dn=new WeakMap,Gn=new WeakMap,As=new WeakMap,Qn=new WeakMap,Cs=new WeakMap,Ln=new WeakMap,Da=new WeakMap,Ke=new WeakSet,Km=function(){try{se(this,zt,qt(()=>C(this,Ss).call(this,C(this,jt))))}catch(e){this.error(e)}se(this,Ut,!1)},Ym=function(){const e=C(this,mn).pending;e&&(se(this,bt,qt(()=>e(C(this,jt)))),Bn.enqueue(()=>{var n=Se(this,Ke,Jo).call(this);se(this,zt,Se(this,Ke,Ji).call(this,()=>(Bn.ensure(),qt(()=>C(this,Ss).call(this,n))))),C(this,Qn)>0?Se(this,Ke,Gi).call(this):(ur(C(this,bt),()=>{se(this,bt,null)}),se(this,Ut,!1))}))},Jo=function(){var e=C(this,jt);return C(this,Ut)&&(se(this,Gn,Hn()),C(this,jt).before(C(this,Gn)),e=C(this,Gn)),e},Ji=function(e){var n=he,s=ce,r=ve;nn(C(this,gn)),xt(C(this,gn)),mr(C(this,gn).ctx);try{return e()}catch(i){return Dd(i),null}finally{nn(n),xt(s),mr(r)}},Gi=function(){const e=C(this,mn).pending;C(this,zt)!==null&&(se(this,Dn,document.createDocumentFragment()),C(this,Dn).append(C(this,Gn)),af(C(this,zt),C(this,Dn))),C(this,bt)===null&&se(this,bt,qt(()=>e(C(this,jt))))},Go=function(e){var n;if(!this.has_pending_snippet()){this.parent&&Se(n=this.parent,Ke,Go).call(n,e);return}se(this,Qn,C(this,Qn)+e),C(this,Qn)===0&&(se(this,Ut,!1),C(this,bt)&&ur(C(this,bt),()=>{se(this,bt,null)}),C(this,Dn)&&(C(this,jt).before(C(this,Dn)),se(this,Dn,null)))};function Xm(t,e){return e}function Jm(t,e,n){for(var s=[],r=e.length,i=0;i<r;i++)Jl(e[i].e,s,!0);sf(s,()=>{var a=s.length===0&&n!==null;if(a){var o=n,l=o.parentNode;Bm(l),l.append(o),t.items.clear(),fn(t,e[0].prev,e[r-1].next)}for(var c=0;c<r;c++){var u=e[c];a||(t.items.delete(u.k),fn(t,u.prev,u.next)),kt(u.e,!a)}t.first===e[0]&&(t.first=e[0].prev)})}function Rs(t,e,n,s,r,i=null){var a=t,o=new Map,l=null,c=(e&Id)!==0,u=(e&Pd)!==0,d=(e&$d)!==0;if(c){var f=t;a=f.appendChild(Hn())}var h=null,m=ke(()=>{var k=n();return Oa(k)?k:k==null?[]:zl(k)}),g,y=!0;function b(){Gm(w,g,a,e,s),h!==null&&(g.length===0?(h.fragment?(a.before(h.fragment),h.fragment=null):Gl(h.effect),v.first=h.effect):ur(h.effect,()=>{h=null}))}var v=Xl(()=>{g=p(m);for(var k=g.length,P=new Set,S=Me,A=null,$=Md(),R=0;R<k;R+=1){var K=g[R],Z=s(K,R),ee=y?null:o.get(Z);ee?(u&&yr(ee.v,K),d?yr(ee.i,R):ee.i=R,$&&S.skipped_effects.delete(ee.e)):(ee=Qm(y?a:null,A,K,Z,R,r,e,n),y&&(ee.o=!0,A===null?l=ee:A.next=ee,A=ee),o.set(Z,ee)),P.add(Z)}if(k===0&&i&&!h)if(y)h={fragment:null,effect:qt(()=>i(a))};else{var be=document.createDocumentFragment(),me=Hn();be.append(me),h={fragment:be,effect:qt(()=>i(me))}}if(!y)if($){for(const[D,Y]of o)P.has(D)||S.skipped_effects.add(Y.e);S.oncommit(b),S.ondiscard(()=>{})}else b();p(m)}),w={effect:v,items:o,first:l};y=!1}function Gm(t,e,n,s,r){var i=(s&bm)!==0,a=e.length,o=t.items,l=t.first,c,u=null,d,f=[],h=[],m,g,y,b;if(i)for(b=0;b<a;b+=1)m=e[b],g=r(m,b),y=o.get(g),y.a?.measure(),(d??(d=new Set)).add(y);for(b=0;b<a;b+=1){if(m=e[b],g=r(m,b),y=o.get(g),t.first??(t.first=y),!y.o){y.o=!0;var v=u?u.next:l;fn(t,u,y),fn(t,y,v),yo(y,v,n),u=y,f=[],h=[],l=u.next;continue}if((y.e.f&Dt)!==0&&(Gl(y.e),i&&(y.a?.unfix(),(d??(d=new Set)).delete(y))),y!==l){if(c!==void 0&&c.has(y)){if(f.length<h.length){var w=h[0],k;u=w.prev;var P=f[0],S=f[f.length-1];for(k=0;k<f.length;k+=1)yo(f[k],w,n);for(k=0;k<h.length;k+=1)c.delete(h[k]);fn(t,P.prev,S.next),fn(t,u,P),fn(t,S,w),l=w,u=S,b-=1,f=[],h=[]}else c.delete(y),yo(y,l,n),fn(t,y.prev,y.next),fn(t,y,u===null?t.first:u.next),fn(t,u,y),u=y;continue}for(f=[],h=[];l!==null&&l.k!==g;)(l.e.f&Dt)===0&&(c??(c=new Set)).add(l),h.push(l),l=l.next;if(l===null)continue;y=l}f.push(y),u=y,l=y.next}if(l!==null||c!==void 0){for(var A=c===void 0?[]:zl(c);l!==null;)(l.e.f&Dt)===0&&A.push(l),l=l.next;var $=A.length;if($>0){var R=(s&Id)!==0&&a===0?n:null;if(i){for(b=0;b<$;b+=1)A[b].a?.measure();for(b=0;b<$;b+=1)A[b].a?.fix()}Jm(t,A,R)}}i&&Bs(()=>{if(d!==void 0)for(y of d)y.a?.apply()})}function Qm(t,e,n,s,r,i,a,o){var l=(a&Pd)!==0,c=(a&_m)===0,u=l?c?V(n,!1,!1):Fs(n):n,d=(a&$d)===0?r:Fs(r);X&&l&&(u.trace=()=>{var m=typeof d=="number"?r:d.v;o()[m]});var f={i:d,v:u,k:s,a:null,e:null,o:!1,prev:e,next:null};try{if(t===null){var h=document.createDocumentFragment();h.append(t=Hn())}return f.e=qt(()=>i(t,u,d,o)),e!==null&&(e.next=f),f}finally{}}function yo(t,e,n){for(var s=t.next?t.next.e.nodes_start:n,r=e?e.e.nodes_start:n,i=t.e.nodes_start;i!==null&&i!==s;){var a=_i(i);r.before(i),i=a}}function fn(t,e,n){e===null?(t.first=n,t.effect.first=n&&n.e):(e.e.next&&(e.e.next.prev=null),e.next=n,e.e.next=n&&n.e),n===null?t.effect.last=e&&e.e:(n.e.prev&&(n.e.prev.next=null),n.prev=e,n.e.prev=e&&e.e)}function Zm(t,e,n,s){const r=bi()?xi:ke;if(n.length===0&&t.length===0){s(e.map(r));return}var i=Me,a=he,o=eg();function l(){Promise.all(n.map(c=>ng(c))).then(c=>{o();try{s([...e.map(r),...c])}catch(u){(a.f&Un)===0&&gr(u,a)}i?.deactivate(),ha()}).catch(c=>{gr(c,a)})}t.length>0?Promise.all(t).then(()=>{o();try{return l()}finally{i?.deactivate(),ha()}}):l()}function eg(){var t=he,e=ce,n=ve,s=Me;if(X)var r=oi;return function(a=!0){nn(t),xt(e),mr(n),a&&s?.activate(),X&&da(r)}}function ha(){nn(null),xt(null),mr(null),X&&da(null)}const tg=new Set;function xi(t){var e=tt|St,n=ce!==null&&(ce.f&tt)!==0?ce:null;return he!==null&&(he.f|=kr),{ctx:ve,deps:null,effects:null,equals:Ad,f:e,fn:t,reactions:null,rv:0,v:st,wv:0,parent:n??he,ac:null}}function ng(t,e){let n=he;n===null&&im();var s=n.b,r=void 0,i=Fs(st),a=!ce,o=new Map;return dg(()=>{var l=xd();r=l.promise;try{Promise.resolve(t()).then(l.resolve,l.reject).then(()=>{c===Me&&c.committed&&c.deactivate(),ha()})}catch(f){l.reject(f),ha()}var c=Me;if(a){var u=!s.is_pending();s.update_pending_count(1),c.increment(u),o.get(c)?.reject(ir),o.delete(c),o.set(c,l)}const d=(f,h=void 0)=>{if(c.activate(),h)h!==ir&&(i.f|=es,yr(i,h));else{(i.f&es)!==0&&(i.f^=es),yr(i,f);for(const[m,g]of o){if(o.delete(m),m===c)break;g.reject(ir)}}a&&(s.update_pending_count(-1),c.decrement(u))};l.promise.then(d,f=>d(null,f||"unknown"))}),Ar(()=>{for(const l of o.values())l.reject(ir)}),X&&(i.f|=za),new Promise(l=>{function c(u){function d(){u===r?l(i):c(r)}u.then(d,d)}c(r)})}function ts(t){const e=xi(t);return Wd(e),e}function ke(t){const e=xi(t);return e.equals=Td,e}function Qo(t){var e=t.effects;if(e!==null){t.effects=null;for(var n=0;n<e.length;n+=1)kt(e[n])}}let wo=[];function sg(t){for(var e=t.parent;e!==null;){if((e.f&tt)===0)return(e.f&Un)===0?e:null;e=e.parent}return null}function Kl(t){var e,n=he;if(nn(sg(t)),X){let s=vr;Qc(new Set);try{wo.includes(t)&&am(),wo.push(t),t.f&=~is,Qo(t),e=Zo(t)}finally{nn(n),Qc(s),wo.pop()}}else try{t.f&=~is,Qo(t),e=Zo(t)}finally{nn(n)}return e}function zd(t){var e=Kl(t);if(t.equals(e)||(Me?.is_fork||(t.v=e),t.wv=Yd()),!Us)if(Ht!==null)Ha()&&Ht.set(t,e);else{var n=(t.f&rn)===0?En:Qe;Ze(t,n)}}let vr=new Set;const ns=new Map;function Qc(t){vr=t}let Yl=!1;function rg(){Yl=!0}function Fs(t,e){var n={f:0,v:t,reactions:null,equals:Ad,rv:0,wv:0};return n}function Kn(t,e){const n=Fs(t);return Wd(n),n}function V(t,e=!1,n=!0){var r;const s=Fs(t);return e||(s.equals=Td),Er&&n&&ve!==null&&ve.l!==null&&((r=ve.l).s??(r.s=[])).push(s),s}function Qi(t,e){return E(t,O(()=>p(t))),e}function E(t,e,n=!1){ce!==null&&(!wn||(ce.f&ua)!==0)&&bi()&&(ce.f&(tt|kn|za|ua))!==0&&!jn?.includes(t)&&gm();let s=n?or(e):e;return X&&Nd(s,t.label),yr(t,s)}function yr(t,e){if(!t.equals(e)){var n=t.v;Us?ns.set(t,e):ns.set(t,n),t.v=e;var s=Bn.ensure();if(s.capture(t,n),X){if(he!==null){t.updated??(t.updated=new Map);const r=(t.updated.get("")?.count??0)+1;if(t.updated.set("",{error:null,count:r}),r>5){const i=Nm("updated at");if(i!==null){let a=t.updated.get(i.stack);a||(a={error:i,count:0},t.updated.set(i.stack,a)),a.count++}}}he!==null&&(t.set_during_effect=!0)}(t.f&tt)!==0&&((t.f&St)!==0&&Kl(t),Ze(t,(t.f&rn)!==0?Qe:En)),t.wv=Yd(),Hd(t,St),bi()&&he!==null&&(he.f&Qe)!==0&&(he.f&(Wn|Os))===0&&(Bt===null?ig([t]):Bt.push(t)),!s.is_fork&&vr.size>0&&!Yl&&qd()}return e}function qd(){Yl=!1;var t=ss;pa(!0);const e=Array.from(vr);try{for(const n of e)(n.f&Qe)!==0&&Ze(n,En),Sr(n)&&wr(n)}finally{pa(t)}vr.clear()}function Zr(t){E(t,t.v+1)}function Hd(t,e){var n=t.reactions;if(n!==null)for(var s=bi(),r=n.length,i=0;i<r;i++){var a=n[i],o=a.f;if(!(!s&&a===he)){if(X&&(o&ua)!==0){vr.add(a);continue}var l=(o&St)===0;if(l&&Ze(a,e),(o&tt)!==0){var c=a;Ht?.delete(c),(o&is)===0&&(o&rn&&(a.f|=is),Hd(c,En))}else l&&((o&kn)!==0&&Fn!==null&&Fn.add(a),Ns(a))}}}function Vd(t,e,n,s=!0){s&&n();for(var r of e)t.addEventListener(r,n);Ar(()=>{for(var i of e)t.removeEventListener(i,n)})}function ki(t){var e=ce,n=he;xt(null),nn(null);try{return t()}finally{xt(e),nn(n)}}let ss=!1;function pa(t){ss=t}let Us=!1;function Zc(t){Us=t}let ce=null,wn=!1;function xt(t){ce=t}let he=null;function nn(t){he=t}let jn=null;function Wd(t){ce!==null&&(jn===null?jn=[t]:jn.push(t))}let dt=null,$t=0,Bt=null;function ig(t){Bt=t}let Kd=1,li=0,$s=li;function eu(t){$s=t}function Yd(){return++Kd}function Sr(t){var e=t.f;if((e&St)!==0)return!0;if(e&tt&&(t.f&=~is),(e&En)!==0){var n=t.deps;if(n!==null)for(var s=n.length,r=0;r<s;r++){var i=n[r];if(Sr(i)&&zd(i),i.wv>t.wv)return!0}(e&rn)!==0&&Ht===null&&Ze(t,Qe)}return!1}function Xd(t,e,n=!0){var s=t.reactions;if(s!==null&&!jn?.includes(t))for(var r=0;r<s.length;r++){var i=s[r];(i.f&tt)!==0?Xd(i,e,!1):e===i&&(n?Ze(i,St):(i.f&Qe)!==0&&Ze(i,En),Ns(i))}}function Zo(t){var m;var e=dt,n=$t,s=Bt,r=ce,i=jn,a=ve,o=wn,l=$s,c=t.f;dt=null,$t=0,Bt=null,ce=(c&(Wn|Os))===0?t:null,jn=null,mr(t.ctx),wn=!1,$s=++li,t.ac!==null&&(ki(()=>{t.ac.abort(ir)}),t.ac=null);try{t.f|=Vo;var u=t.fn,d=u(),f=t.deps;if(dt!==null){var h;if(ma(t,$t),f!==null&&$t>0)for(f.length=$t+dt.length,h=0;h<dt.length;h++)f[$t+h]=dt[h];else t.deps=f=dt;if(ss&&Ha()&&(t.f&rn)!==0)for(h=$t;h<f.length;h++)((m=f[h]).reactions??(m.reactions=[])).push(t)}else f!==null&&$t<f.length&&(ma(t,$t),f.length=$t);if(bi()&&Bt!==null&&!wn&&f!==null&&(t.f&(tt|En|St))===0)for(h=0;h<Bt.length;h++)Xd(Bt[h],t);return r!==null&&r!==t&&(li++,Bt!==null&&(s===null?s=Bt:s.push(...Bt))),(t.f&es)!==0&&(t.f^=es),d}catch(g){return Dd(g)}finally{t.f^=Vo,dt=e,$t=n,Bt=s,ce=r,jn=i,mr(a),wn=o,$s=l}}function ag(t,e){let n=e.reactions;if(n!==null){var s=Qp.call(n,t);if(s!==-1){var r=n.length-1;r===0?n=e.reactions=null:(n[s]=n[r],n.pop())}}n===null&&(e.f&tt)!==0&&(dt===null||!dt.includes(e))&&(Ze(e,En),(e.f&rn)!==0&&(e.f^=rn,e.f&=~is),Qo(e),ma(e,0))}function ma(t,e){var n=t.deps;if(n!==null)for(var s=e;s<n.length;s++)ag(t,n[s])}function wr(t){var e=t.f;if((e&Un)===0){Ze(t,Qe);var n=he,s=ss;if(he=t,ss=!0,X){var r=wi;Xc(t.component_function);var i=oi;da(t.dev_stack??oi)}try{(e&kn)!==0?fg(t):tf(t),ef(t);var a=Zo(t);t.teardown=typeof a=="function"?a:null,t.wv=Kd;var o;X&&ym&&(t.f&St)!==0&&t.deps}finally{ss=s,he=n,X&&(Xc(r),da(i))}}}function p(t){var e=t.f,n=(e&tt)!==0;if(ce!==null&&!wn){var s=he!==null&&(he.f&Un)!==0;if(!s&&!jn?.includes(t)){var r=ce.deps;if((ce.f&Vo)!==0)t.rv<li&&(t.rv=li,dt===null&&r!==null&&r[$t]===t?$t++:dt===null?dt=[t]:dt.includes(t)||dt.push(t));else{(ce.deps??(ce.deps=[])).push(t);var i=t.reactions;i===null?t.reactions=[ce]:i.includes(ce)||i.push(ce)}}}if(X&&tg.delete(t),Us){if(ns.has(t))return ns.get(t);if(n){var a=t,o=a.v;return((a.f&Qe)===0&&a.reactions!==null||Gd(a))&&(o=Kl(a)),ns.set(a,o),o}}else n&&!Ht?.has(t)&&(a=t,Sr(a)&&zd(a),ss&&Ha()&&(a.f&rn)===0&&Jd(a));if(Ht?.has(t))return Ht.get(t);if((t.f&es)!==0)throw t.v;return t.v}function Jd(t){if(t.deps!==null){t.f^=rn;for(const e of t.deps)(e.reactions??(e.reactions=[])).push(t),(e.f&tt)!==0&&(e.f&rn)===0&&Jd(e)}}function Gd(t){if(t.v===st)return!0;if(t.deps===null)return!1;for(const e of t.deps)if(ns.has(e)||(e.f&tt)!==0&&Gd(e))return!0;return!1}function O(t){var e=wn;try{return wn=!0,t()}finally{wn=e}}const og=-7169;function Ze(t,e){t.f=t.f&og|e}function L(t){if(!(typeof t!="object"||!t||t instanceof EventTarget)){if(xn in t)el(t);else if(!Array.isArray(t))for(let e in t){const n=t[e];typeof n=="object"&&n&&xn in n&&el(n)}}}function el(t,e=new Set){if(typeof t=="object"&&t!==null&&!(t instanceof EventTarget)&&!e.has(t)){e.add(t),t instanceof Date&&t.getTime();for(let s in t)try{el(t[s],e)}catch{}const n=ql(t);if(n!==Object.prototype&&n!==Array.prototype&&n!==Map.prototype&&n!==Set.prototype&&n!==Date.prototype){const s=_d(n);for(let r in s){const i=s[r].get;if(i)try{i.call(t)}catch{}}}}}function Qd(t){he===null&&(ce===null&&cm(t),lm()),Us&&om(t)}function lg(t,e){var n=e.last;n===null?e.last=e.first=t:(n.next=t,t.prev=n,e.last=t)}function Sn(t,e,n){var s=he;if(X)for(;s!==null&&(s.f&ua)!==0;)s=s.parent;s!==null&&(s.f&Dt)!==0&&(t|=Dt);var r={ctx:ve,deps:null,nodes_start:null,nodes_end:null,f:t|St|rn,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(X&&(r.component_function=wi),n)try{wr(r),r.f|=ja}catch(o){throw kt(r),o}else e!==null&&Ns(r);var i=r;if(n&&i.deps===null&&i.teardown===null&&i.nodes_start===null&&i.first===i.last&&(i.f&kr)===0&&(i=i.first,(t&kn)!==0&&(t&Is)!==0&&i!==null&&(i.f|=Is)),i!==null&&(i.parent=s,s!==null&&lg(i,s),ce!==null&&(ce.f&tt)!==0&&(t&Os)===0)){var a=ce;(a.effects??(a.effects=[])).push(i)}return r}function Ha(){return ce!==null&&!wn}function Ar(t){const e=Sn(Ba,null,!1);return Ze(e,Qe),e.teardown=t,e}function tl(t){Qd("$effect"),X&&qn(t,"name",{value:"$effect"});var e=he.f,n=!ce&&(e&Wn)!==0&&(e&ja)===0;if(n){var s=ve;(s.e??(s.e=[])).push(t)}else return Zd(t)}function Zd(t){return Sn(Hl|Ed,t,!1)}function cg(t){return Qd("$effect.pre"),X&&qn(t,"name",{value:"$effect.pre"}),Sn(Ba|Ed,t,!0)}function ug(t){Bn.ensure();const e=Sn(Os|kr,t,!0);return(n={})=>new Promise(s=>{n.outro?ur(e,()=>{kt(e),s(void 0)}):(kt(e),s(void 0))})}function Va(t){return Sn(Hl,t,!1)}function ge(t,e){var n=ve,s={effect:null,ran:!1,deps:t};n.l.$.push(s),s.effect=Cr(()=>{t(),!s.ran&&(s.ran=!0,O(e))})}function yt(){var t=ve;Cr(()=>{for(var e of t.l.$){e.deps();var n=e.effect;(n.f&Qe)!==0&&Ze(n,En),Sr(n)&&wr(n),e.ran=!1}})}function dg(t){return Sn(za|kr,t,!0)}function Cr(t,e=0){return Sn(Ba|e,t,!0)}function we(t,e=[],n=[],s=[]){Zm(s,e,n,r=>{Sn(Ba,()=>t(...r.map(p)),!0)})}function Xl(t,e=0){var n=Sn(kn|e,t,!0);return X&&(n.dev_stack=oi),n}function qt(t){return Sn(Wn|kr,t,!0)}function ef(t){var e=t.teardown;if(e!==null){const n=Us,s=ce;Zc(!0),xt(null);try{e.call(null)}finally{Zc(n),xt(s)}}}function tf(t,e=!1){var n=t.first;for(t.first=t.last=null;n!==null;){const r=n.ac;r!==null&&ki(()=>{r.abort(ir)});var s=n.next;(n.f&Os)!==0?n.parent=null:kt(n,e),n=s}}function fg(t){for(var e=t.first;e!==null;){var n=e.next;(e.f&Wn)===0&&kt(e),e=n}}function kt(t,e=!0){var n=!1;(e||(t.f&kd)!==0)&&t.nodes_start!==null&&t.nodes_end!==null&&(hg(t.nodes_start,t.nodes_end),n=!0),tf(t,e&&!n),ma(t,0),Ze(t,Un);var s=t.transitions;if(s!==null)for(const i of s)i.stop();ef(t);var r=t.parent;r!==null&&r.first!==null&&nf(t),X&&(t.component_function=null),t.next=t.prev=t.teardown=t.ctx=t.deps=t.fn=t.nodes_start=t.nodes_end=t.ac=null}function hg(t,e){for(;t!==null;){var n=t===e?null:_i(t);t.remove(),t=n}}function nf(t){var e=t.parent,n=t.prev,s=t.next;n!==null&&(n.next=s),s!==null&&(s.prev=n),e!==null&&(e.first===t&&(e.first=s),e.last===t&&(e.last=n))}function ur(t,e,n=!0){var s=[];Jl(t,s,!0),sf(s,()=>{n&&kt(t),e&&e()})}function sf(t,e){var n=t.length;if(n>0){var s=()=>--n||e();for(var r of t)r.out(s)}else e()}function Jl(t,e,n){if((t.f&Dt)===0){if(t.f^=Dt,t.transitions!==null)for(const a of t.transitions)(a.is_global||n)&&e.push(a);for(var s=t.first;s!==null;){var r=s.next,i=(s.f&Is)!==0||(s.f&Wn)!==0&&(t.f&kn)!==0;Jl(s,e,i?n:!1),s=r}}}function Gl(t){rf(t,!0)}function rf(t,e){if((t.f&Dt)!==0){t.f^=Dt,(t.f&Qe)===0&&(Ze(t,St),Ns(t));for(var n=t.first;n!==null;){var s=n.next,r=(n.f&Is)!==0||(n.f&Wn)!==0;rf(n,r?e:!1),n=s}if(t.transitions!==null)for(const i of t.transitions)(i.is_global||e)&&i.in()}}function af(t,e){for(var n=t.nodes_start,s=t.nodes_end;n!==null;){var r=n===s?null:_i(n);e.append(n),n=r}}const pg=["touchstart","touchmove"];function mg(t){return pg.includes(t)}var tu=new Map;function gg(t,e){var n=tu.get(t);n||(n=new Set,tu.set(t,n)),n.add(e)}const vg=new Set,nu=new Set;function yg(t,e,n,s={}){function r(i){if(s.capture||jr.call(e,i),!i.cancelBubble)return ki(()=>n?.call(this,i))}return t.startsWith("pointer")||t.startsWith("touch")||t==="wheel"?Bs(()=>{e.addEventListener(t,r,s)}):e.addEventListener(t,r,s),r}function oe(t,e,n,s,r){var i={capture:s,passive:r},a=yg(t,e,n,i);(e===document.body||e===window||e===document||e instanceof HTMLMediaElement)&&Ar(()=>{e.removeEventListener(t,a,i)})}let su=null;function jr(t){var e=this,n=e.ownerDocument,s=t.type,r=t.composedPath?.()||[],i=r[0]||t.target;su=t;var a=0,o=su===t&&t.__root;if(o){var l=r.indexOf(o);if(l!==-1&&(e===document||e===window)){t.__root=e;return}var c=r.indexOf(e);if(c===-1)return;l<=c&&(a=l)}if(i=r[a]||t.target,i!==e){qn(t,"currentTarget",{configurable:!0,get(){return i||n}});var u=ce,d=he;xt(null),nn(null);try{for(var f,h=[];i!==null;){var m=i.assignedSlot||i.parentNode||i.host||null;try{var g=i["__"+s];g!=null&&(!i.disabled||t.target===i)&&g.call(i,t)}catch(y){f?h.push(y):f=y}if(t.cancelBubble||m===e||m===null)break;i=m}if(f){for(let y of h)queueMicrotask(()=>{throw y});throw f}}finally{t.__root=e,delete t.currentTarget,xt(u),nn(d)}}}function wg(t){var e=document.createElement("template");return e.innerHTML=t.replaceAll("<!>","<!---->"),e.content}function ga(t,e){var n=he;n.nodes_start===null&&(n.nodes_start=t,n.nodes_end=e)}function J(t,e){var n=(e&Tm)!==0,s=(e&Pm)!==0,r,i=!t.startsWith("<!>");return()=>{r===void 0&&(r=wg(i?t:"<!>"+t),n||(r=fa(r)));var a=s||Vl?document.importNode(r,!0):r.cloneNode(!0);if(n){var o=fa(a),l=a.lastChild;ga(o,l)}else ga(a,a);return a}}function bg(t=""){{var e=Hn(t+"");return ga(e,e),e}}function pt(){var t=document.createDocumentFragment(),e=document.createComment(""),n=Hn();return t.append(e,n),ga(e,n),t}function j(t,e){t!==null&&t.before(e)}let nl=!0;function Ae(t,e){var n=e==null?"":typeof e=="object"?e+"":e;n!==(t.__t??(t.__t=t.nodeValue))&&(t.__t=n,t.nodeValue=n+"")}function va(t,e){return _g(t,e)}const Gs=new Map;function _g(t,{target:e,anchor:n,props:s={},events:r,context:i,intro:a=!0}){Om();var o=new Set,l=d=>{for(var f=0;f<d.length;f++){var h=d[f];if(!o.has(h)){o.add(h);var m=mg(h);e.addEventListener(h,jr,{passive:m});var g=Gs.get(h);g===void 0?(document.addEventListener(h,jr,{passive:m}),Gs.set(h,1)):Gs.set(h,g+1)}}};l(zl(vg)),nu.add(l);var c=void 0,u=ug(()=>{var d=n??e.appendChild(Hn());return Vm(d,{pending:()=>{}},f=>{if(i){Te({});var h=ve;h.c=i}r&&(s.$$events=r),nl=a,c=t(f,s)||{},nl=!0,i&&Pe()}),()=>{for(var f of o){e.removeEventListener(f,jr);var h=Gs.get(f);--h===0?(document.removeEventListener(f,jr),Gs.delete(f)):Gs.set(f,h)}nu.delete(l),d!==n&&d.parentNode?.removeChild(d)}});return sl.set(c,u),c}let sl=new WeakMap;function ya(t,e){const n=sl.get(t);return n?(sl.delete(t),n(e)):(X&&(xn in t?void 0:void 0),Promise.resolve())}var Zt,yn,Nt,Ts,vi,yi,La;class xg{constructor(e,n=!0){cn(this,"anchor");fe(this,Zt,new Map);fe(this,yn,new Map);fe(this,Nt,new Map);fe(this,Ts,new Set);fe(this,vi,!0);fe(this,yi,()=>{var e=Me;if(C(this,Zt).has(e)){var n=C(this,Zt).get(e),s=C(this,yn).get(n);if(s)Gl(s),C(this,Ts).delete(n);else{var r=C(this,Nt).get(n);r&&(C(this,yn).set(n,r.effect),C(this,Nt).delete(n),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),s=r.effect)}for(const[i,a]of C(this,Zt)){if(C(this,Zt).delete(i),i===e)break;const o=C(this,Nt).get(a);o&&(kt(o.effect),C(this,Nt).delete(a))}for(const[i,a]of C(this,yn)){if(i===n||C(this,Ts).has(i))continue;const o=()=>{if(Array.from(C(this,Zt).values()).includes(i)){var c=document.createDocumentFragment();af(a,c),c.append(Hn()),C(this,Nt).set(i,{effect:a,fragment:c})}else kt(a);C(this,Ts).delete(i),C(this,yn).delete(i)};C(this,vi)||!s?(C(this,Ts).add(i),ur(a,o,!1)):o()}}});fe(this,La,e=>{C(this,Zt).delete(e);const n=Array.from(C(this,Zt).values());for(const[s,r]of C(this,Nt))n.includes(s)||(kt(r.effect),C(this,Nt).delete(s))});this.anchor=e,se(this,vi,n)}ensure(e,n){var s=Me,r=Md();if(n&&!C(this,yn).has(e)&&!C(this,Nt).has(e))if(r){var i=document.createDocumentFragment(),a=Hn();i.append(a),C(this,Nt).set(e,{effect:qt(()=>n(a)),fragment:i})}else C(this,yn).set(e,qt(()=>n(this.anchor)));if(C(this,Zt).set(s,e),r){for(const[o,l]of C(this,yn))o===e?s.skipped_effects.delete(l):s.skipped_effects.add(l);for(const[o,l]of C(this,Nt))o===e?s.skipped_effects.delete(l.effect):s.skipped_effects.add(l.effect);s.oncommit(C(this,yi)),s.ondiscard(C(this,La))}else C(this,yi).call(this)}}Zt=new WeakMap,yn=new WeakMap,Nt=new WeakMap,Ts=new WeakMap,vi=new WeakMap,yi=new WeakMap,La=new WeakMap;function ue(t,e,n=!1){var s=new xg(t),r=n?Is:0;function i(a,o){s.ensure(a,o)}Xl(()=>{var a=!1;e((o,l=!0)=>{a=!0,i(l,o)}),a||i(!1,null)},r)}function of(t,e,n,s,r){var i=e.$$slots?.[n],a=!1;i===!0&&(i=e[n==="default"?"children":n],a=!0),i===void 0?r!==null&&r(t):i(t,a?()=>s:s)}function Le(t,e){Va(()=>{var n=t.getRootNode(),s=n.host?n:n.head??n.ownerDocument.head;if(!s.querySelector("#"+e.hash)){const r=document.createElement("style");r.id=e.hash,r.textContent=e.code,s.appendChild(r),X&&gg(e.hash,r)}})}function lf(t){var e,n,s="";if(typeof t=="string"||typeof t=="number")s+=t;else if(typeof t=="object")if(Array.isArray(t)){var r=t.length;for(e=0;e<r;e++)t[e]&&(n=lf(t[e]))&&(s&&(s+=" "),s+=n)}else for(n in t)t[n]&&(s&&(s+=" "),s+=n);return s}function kg(){for(var t,e,n=0,s="",r=arguments.length;n<r;n++)(t=arguments[n])&&(e=lf(t))&&(s&&(s+=" "),s+=e);return s}function ru(t){return typeof t=="object"?kg(t):t??""}const iu=[...`
|
||
\r\f \v\uFEFF`];function Eg(t,e,n){var s=t==null?"":""+t;if(e&&(s=s?s+" "+e:e),n){for(var r in n)if(n[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||iu.includes(s[a-1]))&&(o===s.length||iu.includes(s[o]))?s=(a===0?"":s.substring(0,a))+s.substring(o+1):a=o}}return s===""?null:s}function au(t,e=!1){var n=e?" !important;":";",s="";for(var r in t){var i=t[r];i!=null&&i!==""&&(s+=" "+r+": "+i+n)}return s}function bo(t){return t[0]!=="-"||t[1]!=="-"?t.toLowerCase():t}function Sg(t,e){if(e){var n="",s,r;if(Array.isArray(e)?(s=e[0],r=e[1]):s=e,t){t=String(t).replaceAll(/\s*\/\*.*?\*\/\s*/g,"").trim();var i=!1,a=0,o=!1,l=[];s&&l.push(...Object.keys(s).map(bo)),r&&l.push(...Object.keys(r).map(bo));var c=0,u=-1;const g=t.length;for(var d=0;d<g;d++){var f=t[d];if(o?f==="/"&&t[d-1]==="*"&&(o=!1):i?i===f&&(i=!1):f==="/"&&t[d+1]==="*"?o=!0:f==='"'||f==="'"?i=f:f==="("?a++:f===")"&&a--,!o&&i===!1&&a===0){if(f===":"&&u===-1)u=d;else if(f===";"||d===g-1){if(u!==-1){var h=bo(t.substring(c,u).trim());if(!l.includes(h)){f!==";"&&d++;var m=t.substring(c,d).trim();n+=" "+m+";"}}c=d+1,u=-1}}}}return s&&(n+=au(s)),r&&(n+=au(r,!0)),n=n.trim(),n===""?null:n}return t==null?null:String(t)}function sn(t,e,n,s,r,i){var a=t.__className;if(a!==n||a===void 0){var o=Eg(n,s,i);o==null?t.removeAttribute("class"):t.className=o,t.__className=n}else if(i&&r!==i)for(var l in i){var c=!!i[l];(r==null||c!==!!r[l])&&t.classList.toggle(l,c)}return i}function _o(t,e={},n,s){for(var r in n){var i=n[r];e[r]!==i&&(n[r]==null?t.style.removeProperty(r):t.style.setProperty(r,i,s))}}function br(t,e,n,s){var r=t.__style;if(r!==e){var i=Sg(e,s);i==null?t.removeAttribute("style"):t.style.cssText=i,t.__style=e}else s&&(Array.isArray(s)?(_o(t,n?.[0],s[0]),_o(t,n?.[1],s[1],"important")):_o(t,n,s));return s}const Ag=Symbol("is custom element"),Cg=Symbol("is html");function le(t,e,n,s){var r=Tg(t);r[e]!==(r[e]=n)&&(e==="loading"&&(t[rm]=n),n==null?t.removeAttribute(e):typeof n!="string"&&Pg(t).includes(e)?t[e]=n:t.setAttribute(e,n))}function Tg(t){return t.__attributes??(t.__attributes={[Ag]:t.nodeName.includes("-"),[Cg]:t.namespaceURI===Im})}var ou=new Map;function Pg(t){var e=t.getAttribute("is")||t.nodeName,n=ou.get(e);if(n)return n;ou.set(e,n=[]);for(var s,r=t,i=Element.prototype;i!==r;){s=_d(r);for(var a in s)s[a].set&&n.push(a);r=ql(r)}return n}const $g=()=>performance.now(),On={tick:t=>requestAnimationFrame(t),now:()=>$g(),tasks:new Set};function cf(){const t=On.now();On.tasks.forEach(e=>{e.c(t)||(On.tasks.delete(e),e.f())}),On.tasks.size!==0&&On.tick(cf)}function Ig(t){let e;return On.tasks.size===0&&On.tick(cf),{promise:new Promise(n=>{On.tasks.add(e={c:t,f:n})}),abort(){On.tasks.delete(e)}}}function Oi(t,e){ki(()=>{t.dispatchEvent(new CustomEvent(e))})}function Ng(t){if(t==="float")return"cssFloat";if(t==="offset")return"cssOffset";if(t.startsWith("--"))return t;const e=t.split("-");return e.length===1?e[0]:e[0]+e.slice(1).map(n=>n[0].toUpperCase()+n.slice(1)).join("")}function lu(t){const e={},n=t.split(";");for(const s of n){const[r,i]=s.split(":");if(!r||i===void 0)break;const a=Ng(r.trim());e[a]=i.trim()}return e}const Rg=t=>t;function uf(t,e,n,s){var r=(t&Cm)!==0,i="both",a,o=e.inert,l=e.style.overflow,c,u;function d(){return ki(()=>a??(a=n()(e,s?.()??{},{direction:i})))}var f={is_global:r,in(){e.inert=o,Oi(e,"introstart"),c=rl(e,d(),u,1,()=>{Oi(e,"introend"),c?.abort(),c=a=void 0,e.style.overflow=l})},out(y){e.inert=!0,Oi(e,"outrostart"),u=rl(e,d(),c,0,()=>{Oi(e,"outroend"),y?.()})},stop:()=>{c?.abort(),u?.abort()}},h=he;if((h.transitions??(h.transitions=[])).push(f),nl){var m=r;if(!m){for(var g=h.parent;g&&(g.f&Is)!==0;)for(;(g=g.parent)&&(g.f&kn)===0;);m=!g||(g.f&ja)!==0}m&&Va(()=>{O(()=>f.in())})}}function rl(t,e,n,s,r){var i=s===1;if(tm(e)){var a,o=!1;return Bs(()=>{if(!o){var y=e({direction:i?"in":"out"});a=rl(t,y,n,s,r)}}),{abort:()=>{o=!0,a?.abort()},deactivate:()=>a.deactivate(),reset:()=>a.reset(),t:()=>a.t()}}if(n?.deactivate(),!e?.duration)return r(),{abort:tn,deactivate:tn,reset:tn,t:()=>s};const{delay:l=0,css:c,tick:u,easing:d=Rg}=e;var f=[];if(i&&n===void 0&&(u&&u(0,1),c)){var h=lu(c(0,1));f.push(h,h)}var m=()=>1-s,g=t.animate(f,{duration:l,fill:"forwards"});return g.onfinish=()=>{g.cancel();var y=n?.t()??1-s;n?.abort();var b=s-y,v=e.duration*Math.abs(b),w=[];if(v>0){var k=!1;if(c)for(var P=Math.ceil(v/16.666666666666668),S=0;S<=P;S+=1){var A=y+b*d(S/P),$=lu(c(A,1-A));w.push($),k||(k=$.overflow==="hidden")}k&&(t.style.overflow="hidden"),m=()=>{var R=g.currentTime;return y+b*d(R/v)},u&&Ig(()=>{if(g.playState!=="running")return!1;var R=m();return u(R,1-R),!0})}g=t.animate(w,{duration:v,fill:"forwards"}),g.onfinish=()=>{m=()=>s,u?.(s,1-s),r()}},{abort:()=>{g&&(g.cancel(),g.effect=null,g.onfinish=tn)},deactivate:()=>{r=tn},reset:()=>{s===0&&u?.(1,0)},t:()=>m()}}function cu(t,e,n=e){var s,r,i=()=>{cancelAnimationFrame(s),t.paused||(s=requestAnimationFrame(i));var a=t.currentTime;r!==a&&n(r=a)};s=requestAnimationFrame(i),t.addEventListener("timeupdate",i),Cr(()=>{var a=Number(e());r!==a&&!isNaN(a)&&(t.currentTime=r=a)}),Ar(()=>{cancelAnimationFrame(s),t.removeEventListener("timeupdate",i)})}function uu(t,e,n=e){var s=e(),r=()=>{s!==t.paused&&n(s=t.paused)};Vd(t,["play","pause","canplay"],r,s==null),Va(()=>{(s=!!e())!==t.paused&&(s?t.pause():t.play().catch(()=>{n(s=!0)}))})}function du(t,e,n=e){var s=()=>{n(t.volume)};e()==null&&s(),Vd(t,["volumechange"],s,!1),Cr(()=>{var r=Number(e());r!==t.volume&&!isNaN(r)&&(t.volume=r)})}function fu(t,e){return t===e||t?.[xn]===e}function an(t={},e,n,s){return Va(()=>{var r,i;return Cr(()=>{r=i,i=[],O(()=>{t!==n(...i)&&(e(t,...i),r&&fu(n(...r),t)&&e(null,...r))})}),()=>{Bs(()=>{i&&fu(n(...i),t)&&e(null,...i)})}}),t}function hu(t,e,n,s,r){var i=()=>{s(n[t])};n.addEventListener(e,i),i(),(n===document.body||n===window||n===document)&&Ar(()=>{n.removeEventListener(e,i)})}function pu(t){return function(...e){var n=e[0];return n.preventDefault(),t?.apply(this,e)}}function Re(t=!1){const e=ve,n=e.l.u;if(!n)return;let s=()=>L(e.s);if(t){let r=0,i={};const a=xi(()=>{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=()=>p(a)}n.b.length&&cg(()=>{mu(e,s),Ho(n.b)}),tl(()=>{const r=O(()=>n.m.map(nm));return()=>{for(const i of r)typeof i=="function"&&i()}}),n.a.length&&tl(()=>{mu(e,s),Ho(n.a)})}function mu(t,e){if(t.l.s)for(const n of t.l.s)p(n);e()}function il(t,e){var n=t.$$events?.[e.type],s=Oa(n)?n.slice():n==null?[]:[n];for(var r of s)r.call(this,e)}let zr=!1,al=Symbol();function Ne(t,e,n){const s=n[e]??(n[e]={store:null,source:V(void 0),unsubscribe:tn});if(X&&(s.source.label=e),s.store!==t&&!(al in n))if(s.unsubscribe(),s.store=t??null,t==null)s.source.v=void 0,s.unsubscribe=tn;else{var r=!0;s.unsubscribe=hf(t,i=>{r?s.source.v=i:E(s.source,i)}),r=!1}return t&&al in n?T(t):p(s.source)}function Jn(t,e){return t.set(e),e}function Tr(){const t={};function e(){Ar(()=>{for(var n in t)t[n].unsubscribe();qn(t,al,{enumerable:!1,value:!0})})}return[t,e]}function Fg(){zr=!0}function Mg(t){var e=zr;try{return zr=!1,[t(),zr]}finally{zr=e}}function B(t,e,n,s){var r=!Er||(n&km)!==0,i=(n&Sm)!==0,a=(n&Am)!==0,o=s,l=!0,c=()=>(l&&(l=!1,o=a?O(s):s),o),u;if(i){var d=xn in t||sm in t;u=Ps(t,e)?.set??(d&&e in t?w=>t[e]=w:void 0)}var f,h=!1;i?[f,h]=Mg(()=>t[e]):f=t[e],f===void 0&&s!==void 0&&(f=c(),u&&(r&&fm(e),u(f)));var m;if(r?m=()=>{var w=t[e];return w===void 0?c():(l=!0,w)}:m=()=>{var w=t[e];return w!==void 0&&(o=void 0),w===void 0?o:w},r&&(n&Em)===0)return m;if(u){var g=t.$$legacy;return(function(w,k){return arguments.length>0?((!r||!k||g||h)&&u(k?m():w),w):m()})}var y=!1,b=((n&xm)!==0?xi:ke)(()=>(y=!1,m()));X&&(b.label=e),i&&p(b);var v=he;return(function(w,k){if(arguments.length>0){const P=k?p(b):r&&i?or(w):w;return E(b,P),y=!0,o!==void 0&&(o=P),w}return Us&&y||(v.f&Un)!==0?b.v:p(b)})}if(X){let t=function(e){if(!(e in globalThis)){let n;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(n!==void 0)return n;hm(e)},set:s=>{n=s}})}};t("$state"),t("$effect"),t("$derived"),t("$inspect"),t("$props"),t("$bindable")}function An(t){ve===null&&qa("onMount"),Er&&ve.l!==null?ff(ve).m.push(t):tl(()=>{const e=O(t);if(typeof e=="function")return e})}function Wa(t){ve===null&&qa("onDestroy"),An(()=>()=>O(t))}function Dg(t,e,{bubbles:n=!1,cancelable:s=!1}={}){return new CustomEvent(t,{detail:e,bubbles:n,cancelable:s})}function it(){const t=ve;return t===null&&qa("createEventDispatcher"),(e,n,s)=>{const r=t.s.$$events?.[e];if(r){const i=Oa(r)?r.slice():[r],a=Dg(e,n,s);for(const o of i)o.call(t.x,a);return!a.defaultPrevented}return!0}}function df(t){ve===null&&qa("afterUpdate"),ve.l===null&&dm("afterUpdate"),ff(ve).a.push(t)}function ff(t){var e=t.l;return e.u??(e.u={a:[],b:[],m:[]})}function hf(t,e,n){if(t==null)return e(void 0),tn;const s=O(()=>t.subscribe(e,n));return s.unsubscribe?()=>s.unsubscribe():s}const Qs=[];function Lg(t,e){return{subscribe:$e(t,e).subscribe}}function $e(t,e=tn){let n=null;const s=new Set;function r(o){if(Cd(t,o)&&(t=o,n)){const l=!Qs.length;for(const c of s)c[1](),Qs.push(c,t);if(l){for(let c=0;c<Qs.length;c+=2)Qs[c][0](Qs[c+1]);Qs.length=0}}}function i(o){r(o(t))}function a(o,l=tn){const c=[o,l];return s.add(c),s.size===1&&(n=e(r,i)||tn),o(t),()=>{s.delete(c),s.size===0&&n&&(n(),n=null)}}return{set:r,update:i,subscribe:a}}function T(t){let e;return hf(t,n=>e=n)(),e}var ie=(t=>(t[t.PodcastGrid=0]="PodcastGrid",t[t.EpisodeList=1]="EpisodeList",t[t.Player=2]="Player",t))(ie||{});const xo=/\{\{\s*speaker\s*\}\}/gi,Ql="**{{speaker}}:** ";function rs(t){return typeof t=="object"&&t!==null}function pf(t){return typeof t=="string"?t.trim():""}function Og(t){if(!rs(t)||!Array.isArray(t.segments))return[];const e=[];for(const n of t.segments){if(!rs(n))continue;const s=pf(n.text);if(!s)continue;const r=typeof n.speaker=="string"&&n.speaker.trim()?n.speaker.trim():"?";e.push({speaker:r,text:s,start:typeof n.start=="number"?n.start:void 0,end:typeof n.end=="number"?n.end:void 0})}return ol(e)}function Bg(t){if(!rs(t)||!rs(t.results))return[];const e=t.results;if(Array.isArray(e.utterances)){const n=[];for(const s of e.utterances){if(!rs(s))continue;const r=pf(s.transcript);r&&n.push({speaker:mf(s.speaker),text:r,start:typeof s.start=="number"?s.start:void 0,end:typeof s.end=="number"?s.end:void 0})}return ol(n)}return ol(Ug(e))}function Ug(t){const e=t.channels;if(!Array.isArray(e)||!rs(e[0]))return[];const n=e[0].alternatives;if(!Array.isArray(n)||!rs(n[0]))return[];const s=n[0].words;if(!Array.isArray(s))return[];const r=[];for(const i of s){if(!rs(i))continue;const a=typeof i.punctuated_word=="string"?i.punctuated_word:typeof i.word=="string"?i.word:"";if(!a)continue;const o=mf(i.speaker),l=r[r.length-1];l&&l.speaker===o?(l.text+=` ${a}`,typeof i.end=="number"&&(l.end=i.end)):r.push({speaker:o,text:a,start:typeof i.start=="number"?i.start:void 0,end:typeof i.end=="number"?i.end:void 0})}return r}function mf(t){return typeof t=="number"&&Number.isFinite(t)?String(t+1):"?"}function ol(t){const e=[];for(const n of t){const s=e[e.length-1];s&&s.speaker===n.speaker?(s.text=`${s.text} ${n.text}`.trim(),n.end!==void 0&&(s.end=n.end)):e.push({...n})}return e}function jg(t,e){return xo.test(t)?(xo.lastIndex=0,t.replace(xo,e)):`${e}: ${t}`}function zg(t,e){const n=e||Ql;return t.map(s=>`${jg(n,s.speaker)}${s.text}`).join(`
|
||
|
||
`)}const Mn="podcast_player_view",ci=10,ll=75,gf={icon:"lucide-star",name:"Favorites",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},vf={icon:"list-ordered",name:"Queue",shouldEpisodeRemoveAfterPlay:!0,shouldRepeat:!1},Zl={icon:"folder",name:"Local Files",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},Zi={icon:"check-square",name:"Played",shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},ht={savedFeeds:{},podNotes:{},defaultPlaybackRate:1,defaultVolume:1,hidePlayedEpisodes:!1,episodeListLimit:ci,playedEpisodes:{},favorites:{...gf,episodes:[]},queue:{...vf,episodes:[]},autoQueue:!0,playlists:{},skipBackwardLength:15,skipForwardLength:15,currentEpisode:void 0,timestamp:{template:"- {{time}} ",offset:0},note:{path:"PodNotes/{{podcast}}/{{title}}.md",template:`---
|
||
type: podcastEpisode
|
||
podcast: "{{podcastlink}}"
|
||
date: {{date:YYYY-MM-DD}}
|
||
tags:
|
||
- podcastEpisode
|
||
status:
|
||
rating:
|
||
favorite: false
|
||
---
|
||
# {{title}}
|
||
|
||

|
||
|
||
[Resume in PodNotes]({{episodelink}})
|
||
|
||
{{url}}
|
||
|
||
{{description}}
|
||
`},feedNote:{path:"PodNotes/Podcasts/{{podcast}}.md",template:`---
|
||
type: podcast
|
||
podcast: "{{podcast}}"
|
||
image: "{{artwork}}"
|
||
url: "{{url}}"
|
||
feedUrl: "{{feedurl}}"
|
||
tags:
|
||
- podcast
|
||
---
|
||
# {{title}}
|
||
{{author}}
|
||
|
||

|
||
|
||
{{description}}
|
||
`},download:{path:"PodNotes/{{podcast}}/{{title}}"},downloadedEpisodes:{},localFiles:{...Zl,episodes:[]},openAIApiKey:"",diarizationApiKey:"",transcript:{path:"transcripts/{{podcast}}/{{title}}.md",template:`# {{title}}
|
||
|
||
Podcast: {{podcast}}
|
||
Date: {{date}}
|
||
|
||
{{transcript}}`,diarization:{enabled:!1,provider:"openai",speakerTemplate:Ql}},feedCache:{enabled:!0,ttlHours:6}},yf=.5,wf=4,cl=.1,ul=1;function Ms(t,e=ul){const n=typeof t=="number"?t:Number(t),s=Number.isFinite(e)?e:ul;return Number.isFinite(n)?vu(n):vu(s)}function gu(t,e){return Ms(bf(t+e))}function vu(t){return Math.min(wf,Math.max(yf,bf(t)))}function bf(t){return Math.round(t*10)/10}function gt(t){return!t||!t.title?"":t.podcastName?`${t.podcastName}::${t.title}`:t.title}function qr(t,e){return!t||!e?!1:gt(t)===e?!0:t.title===e}function Hr(t,e){return!t||!e?!1:qr(t,gt(e))?!0:!t.podcastName&&!!e.title&&t.title===e.title}function dl(t,e){if(!e)return;const n=gt(e);if(n&&t[n])return t[n];if(e.title&&t[e.title])return t[e.title]}function ei(t,e){return dl(e,t)?.finished??!1}function ec(t){return t.podcastName?`${t.podcastName}::${t.title}`:t.title}function qg(t,e,n){const s=new Set,r=ec(e);for(const[i,a]of Object.entries(t))(i===n||i===r||Vg(a,e))&&s.add(i);return Array.from(s)}function fl(t){const e=new Map;for(const[n,s]of Object.entries(t)){if(!s.finished)continue;const r=ec(s);(!e.get(r)||Hg(n))&&e.set(r,{key:n,episode:s})}return Array.from(e.values())}function Hg(t){return t.includes("::")}function Vg(t,e){return t.title!==e.title?!1:!t.podcastName||!e.podcastName?!0:t.podcastName===e.podcastName}const Wg=$e(0),Et=$e({}),en=$e({}),ui=$e(ci);function ws(t){const e=typeof t=="number"?t:Number(t);return!Number.isFinite(e)||e<1?ci:Math.min(Math.floor(e),ll)}function _r(t){if(!t?.episodeDate)return 0;const e=Number(t.episodeDate);return Number.isFinite(e)?e:0}function yu(t,e){return t?.length?[...t].sort((n,s)=>_r(s)-_r(n)).slice(0,e):[]}function wu(t,e){if(!t||!e||t.length!==e.length)return!1;for(let n=0;n<t.length;n+=1)if(t[n]!==e[n])return!1;return!0}const bu=t=>`${t.podcastName}::${t.title}`;function Kg(t,e,n){const s=[...t],r=_r(e);let i=0,a=s.length;for(;i<a;){const o=i+a>>1,l=_r(s[o]);r>l?a=o:i=o+1}return s.splice(i,0,e),s.length>n&&(s.length=n),s}function _f(t,e=[]){if(!e?.length)return t;const n=new Set(e.map(bu));return t.filter(s=>!n.has(bu(s)))}function Yg(t,e,n,s){let r=_f(t,e);if(!n?.length)return r;for(const i of n)r=Kg(r,i,s);return r}const Xg=Lg([],t=>{let e=new Map,n=new Map,s=[],r=ws(T(ui));function i(c){const u=Object.entries(c),d=u.length,f=Math.max(1,r*Math.max(d,1));let h=!1,m=s;const g=new Map,y=new Map;for(const[b,v]of u){g.set(b,v);const w=n.get(b),k=e.get(b)||[],P=w===v&&k?k:yu(v,r);y.set(b,P),wu(k,P)||(h=!0,m=Yg(m,k,P,f))}for(const b of e.keys())g.has(b)||(h=!0,m=_f(m,e.get(b)));n=g,e=y,h&&(s=m,t(s))}function a(){const c=T(en),u=Object.entries(c),d=u.length,f=Math.max(1,r*Math.max(d,1)),h=new Map,m=new Map,g=[];for(const[b,v]of u){const w=yu(v,r);h.set(b,v),m.set(b,w),g.push(...w)}const y=g.sort((b,v)=>_r(v)-_r(b)).slice(0,f);n=h,e=m,wu(s,y)||(s=y,t(s))}const o=en.subscribe(i),l=ui.subscribe(c=>{const u=ws(c);u!==r&&(r=u,a())});return()=>{e.clear(),n.clear(),s=[],l(),o()}}),et=(()=>{const t=$e({}),{subscribe:e,update:n,set:s}=t;function r(i){return T(t)[i.podcastName]?.some(a=>a.title===i.title)}return{subscribe:e,set:s,update:n,isEpisodeDownloaded:r,addEpisode:(i,a,o)=>{let l;return n(c=>{const u=c[i.podcastName]||[],d=u.findIndex(f=>f.title===i.title);if(d!==-1){const f=u[d].filePath;f&&f!==a&&(l=f),u[d]={...i,filePath:a,size:o}}else u.push({...i,filePath:a,size:o});return c[i.podcastName]=u,c}),l},removeEpisode:i=>{let a;return n(o=>{const l=o[i.podcastName]||[],c=l.findIndex(u=>u.title===i.title);return c===-1||(a=l[c].filePath,l.splice(c,1),o[i.podcastName]=l),o}),a},getEpisode:i=>T(t)[i.podcastName]?.find(a=>a.title===i.title)}})(),re=$e(),ut=$e(0),ti=$e(null),Gt=$e(null),bs=$e(0),Zn=$e(ul),zn=$e(1),di=$e(!1),vt=(()=>{const t=$e(),{subscribe:e,update:n}=t;return{subscribe:e,update:n,set:(s,r=!0)=>{n(i=>{if(i){r&&ev(i);const a=T(ut),o=T(bs),l=o>0&&a===o;We.setEpisodeTime(i,a,o,l)}return s})}}})(),rt=$e(!0),We=(()=>{const t=$e({}),{subscribe:e,update:n,set:s}=t;return{subscribe:e,set:s,update:n,get:r=>dl(T(t),r),setEpisodeTime:(r,i,a,o)=>{r&&n(l=>{const c=gt(r);return c&&(l[c]={title:r.title,podcastName:r.podcastName,time:i,duration:a,finished:o}),l})},markAsPlayed:r=>{r&&n(i=>{const a=gt(r);if(!a)return i;const o=dl(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&&n(i=>{const a=gt(r);return a&&_u(i,{title:r.title,podcastName:r.podcastName},a),i})},markKeyAsUnplayed:r=>{r&&n(i=>{const a=i[r];return a&&_u(i,a,r),i})}}})();function _u(t,e,n){const s=qg(t,e,n),r=s.length>0?s:[n];for(const i of r){const a=t[i]||{title:e.title,podcastName:e.podcastName,time:0,duration:0,finished:!1};t[i]={...a,time:0,finished:!1}}}function Jg(t,e,n){const s=t.length;if(e<0||e>=s||n<0||n>=s||e===n)return t;const r=[...t],[i]=r.splice(e,1);return r.splice(n,0,i),r}function Gg(t=[]){const e=new Set,n=[];for(const s of t)e.has(s.title)||(e.add(s.title),n.push(s));return n}const pe=(()=>{const t=$e({icon:"list-ordered",name:"Queue",episodes:[],shouldEpisodeRemoveAfterPlay:!0,shouldRepeat:!1}),{subscribe:e,update:n,set:s}=t,r=(a,o)=>a.some(l=>l.title===o.title);function i(a,o){const{episodes:l}=T(t),c=Jg(l,a,o);c!==l&&n(u=>(u.episodes=c,u))}return{subscribe:e,update:n,set:a=>s({...a,episodes:Gg(a.episodes)}),add:a=>{n(o=>(r(o.episodes,a)||o.episodes.push(a),o))},remove:a=>{n(o=>(o.episodes=o.episodes.filter(l=>l.title!==a.title),o))},playNext:()=>{xf()&&n(a=>{const o=a.episodes.shift();return o&&vt.set(o,!1),a})},move:i,moveUp:a=>i(a,a-1),moveDown:a=>i(a,a+1),moveToTop:a=>i(a,0),moveToBottom:a=>i(a,T(t).episodes.length-1)}})(),Ft=$e({icon:"lucide-star",name:"Favorites",episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1});function xu(t){return t.filePath}function Qg(t,e){if(t.length!==e.length)return!1;const n=new Map(t.map(s=>[gt(s),s]));for(const s of e){const r=gt(s),i=r?n.get(r):void 0;if(!i||i.streamUrl!==s.streamUrl||i.mediaType!==s.mediaType||xu(i)!==xu(s))return!1}return!0}const Vt=(()=>{const t=$e({icon:"folder",name:"Local Files",episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1}),{subscribe:e,update:n,set:s}=t;return{subscribe:e,update:n,set:s,syncWithDownloaded:r=>{const i=new Set,a=[];for(const o of Object.values(r).flat()){const l=gt(o);!l||i.has(l)||(i.add(l),a.push(o))}Qg(T(t).episodes,a)||n(o=>({...o,...Zl,episodes:a}))},getLocalEpisode:r=>{const{episodes:i}=T(t),a=r.trim().toLowerCase(),o=c=>c.title.trim().toLowerCase()===a;return i.find(c=>o(c)&&c.podcastName==="local file")??i.find(o)},updateStreamUrl:(r,i)=>{t.update(a=>{const o=a.episodes.findIndex(l=>l.title===r);return o!==-1&&(a.episodes[o].streamUrl=i),a})}}})(),mt=$e({}),hl=$e(),He=(()=>{const t=$e(ie.PodcastGrid),{subscribe:e,set:n}=t;return{subscribe:e,set:s=>{n(s),T(hl)?.scrollIntoView()}}})();function xf(){return T(re)?.settings?.autoQueue!==!1}function Zg(){return vt.subscribe(t=>{if(!t)return;const{episodes:e}=T(pe);e.some(s=>s.title===t.title)&&pe.update(s=>(s.episodes=s.episodes.filter(r=>r.title!==t.title),s))})}function ev(t){xf()&&pe.update(e=>{if(e.episodes.some(s=>s.title===t.title))return e;const n=[t,...e.episodes];return e.episodes=n,e})}function $n(t,e,n){return{subscribe:s=>t.subscribe(r=>s(r)),apply:(s,r)=>e(s,r),shouldPersist:n?(s,r)=>n(s,r):void 0}}const tv=[$n(We,(t,e)=>{t.playedEpisodes=e}),$n(Et,(t,e)=>{t.savedFeeds=e}),$n(mt,(t,e)=>{t.playlists=e}),$n(pe,(t,e)=>{t.queue={...e,...vf}}),$n(Ft,(t,e)=>{t.favorites={...e,...gf}}),$n(Vt,(t,e)=>{t.localFiles={...e,...Zl}}),$n(et,(t,e)=>{t.downloadedEpisodes=e}),$n(vt,(t,e)=>{t.currentEpisode=e}),$n(di,(t,e)=>{t.hidePlayedEpisodes=e},(t,e)=>t.hidePlayedEpisodes!==e)];function nv(t){const e=tv.map(n=>n.subscribe(s=>{n.shouldPersist&&!n.shouldPersist(t.settings,s)||(n.apply(t.settings,s),t.saveSettings())}));return()=>{for(const n of e)n()}}const sv="5";var bd;typeof window<"u"&&((bd=window.__svelte??(window.__svelte={})).v??(bd.v=new Set)).add(sv);wm();function Pr(t){return Object.entries(t).map(([e,n])=>`${e}: ${n}`).join("; ")}var rv=J('<button type="button" class="icon-button svelte-11mdast"><span></span></button>'),iv=J('<span class="icon-static svelte-11mdast"></span>');const av={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 Ce(t,e){Te(e,!1),Le(t,av);let n=B(e,"size",8,16),s=B(e,"icon",8),r=B(e,"clickable",8,!0),i=B(e,"label",8,""),a=B(e,"pressed",8,void 0),o=B(e,"disabled",8,!1),l=V(),c=B(e,"style",24,()=>({})),u=V(),d=V();const f=it();An(()=>{_.setIcon(p(l),s()),h()}),df(()=>{_.setIcon(p(l),s()),h()});function h(){p(l)&&(Qi(l,p(l).style.cssText=p(u)),n()&&(Qi(l,p(l).style.width=`${n()}px`),Qi(l,p(l).style.height=`${n()}px`)))}function m(w){!r()||o()||f("click",{event:w})}ge(()=>L(c()),()=>{E(u,Pr(c()))}),ge(()=>L(a()),()=>{E(d,a()===void 0?void 0:a()?"true":"false")}),yt(),Re();var g=pt(),y=Ve(g);{var b=w=>{var k=rv(),P=F(k);an(P,S=>E(l,S),()=>p(l)),we(()=>{le(k,"aria-label",i()),le(k,"aria-pressed",p(d)),k.disabled=o()}),oe("click",k,m),j(w,k)},v=w=>{var k=iv();an(k,P=>E(l,P),()=>p(l)),we(()=>{le(k,"aria-label",i()||void 0),le(k,"aria-hidden",i()?void 0:"true")}),j(w,k)};ue(y,w=>{r()?w(b):w(v,!1)})}j(t,g),Pe()}var ov=J('<p class="queue-reorder-empty svelte-ohpjsg">Your queue is empty.</p>'),lv=J('<span class="queue-reorder-podcast svelte-ohpjsg"> </span>'),cv=J('<li class="queue-reorder-item svelte-ohpjsg"><span class="queue-reorder-position svelte-ohpjsg"> </span> <div class="queue-reorder-info svelte-ohpjsg"><span class="queue-reorder-title svelte-ohpjsg"> </span> <!></div> <div class="queue-reorder-actions svelte-ohpjsg"><!> <!> <!> <!> <!></div></li>'),uv=J('<ol class="queue-reorder-list svelte-ohpjsg"></ol>'),dv=J('<div class="queue-reorder svelte-ohpjsg"><!> <div class="queue-reorder-footer svelte-ohpjsg"><button type="button" class="mod-cta">Done</button></div></div>');const fv={hash:"svelte-ohpjsg",code:`.queue-reorder.svelte-ohpjsg {display:flex;flex-direction:column;gap:0.75rem;}.queue-reorder-empty.svelte-ohpjsg {text-align:center;color:var(--text-muted);padding:1.5rem 0;}.queue-reorder-list.svelte-ohpjsg {list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.25rem;max-height:60vh;overflow-y:auto;}.queue-reorder-item.svelte-ohpjsg {display:flex;align-items:center;gap:0.625rem;padding:0.5rem 0.625rem;border:1px solid var(--background-modifier-border);border-radius:0.5rem;background:var(--background-secondary);}.queue-reorder-position.svelte-ohpjsg {flex:0 0 1.5rem;text-align:center;font-variant-numeric:tabular-nums;font-size:0.8rem;color:var(--text-muted);}.queue-reorder-info.svelte-ohpjsg {display:flex;flex-direction:column;gap:0.125rem;flex:1 1 auto;min-width:0;}.queue-reorder-title.svelte-ohpjsg {font-size:0.9rem;color:var(--text-normal);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.queue-reorder-podcast.svelte-ohpjsg {font-size:0.75rem;color:var(--text-muted);overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.queue-reorder-actions.svelte-ohpjsg {display:flex;align-items:center;gap:0.375rem;flex:0 0 auto;}
|
||
|
||
/*
|
||
* This modal is the designated mobile reorder surface, so its move/remove
|
||
* controls need a comfortable touch target. Scope the sizing to the modal's
|
||
* own buttons so the shared Icon component stays untouched elsewhere.
|
||
*/.queue-reorder-actions.svelte-ohpjsg .icon-button {min-width:2.25rem;min-height:2.25rem;padding:0.25rem;}.queue-reorder-footer.svelte-ohpjsg {display:flex;justify-content:flex-end;}`};function hv(t,e){Te(e,!1),Le(t,fv);const n=()=>Ne(pe,"$queue",s),[s,r]=Tr(),i=V();let a=B(e,"close",8,()=>{});function o(w){return n().episodes.findIndex(k=>k.title===w.title)}function l(w){const k=o(w);k>0&&pe.moveToTop(k)}function c(w){const k=o(w);k>0&&pe.moveUp(k)}function u(w){const k=o(w);k!==-1&&k<n().episodes.length-1&&pe.moveDown(k)}function d(w){const k=o(w);k!==-1&&k<n().episodes.length-1&&pe.moveToBottom(k)}function f(w){pe.remove(w)}ge(()=>n(),()=>{E(i,n().episodes)}),yt(),Re();var h=dv(),m=F(h);{var g=w=>{var k=ov();j(w,k)},y=w=>{var k=uv();Rs(k,7,()=>p(i),P=>P.title,(P,S,A)=>{var $=cv(),R=F($),K=F(R),Z=W(R,2),ee=F(Z),be=F(ee),me=W(ee,2);{var D=Ie=>{var At=lv(),Kt=F(At);we(()=>Ae(Kt,(p(S),O(()=>p(S).podcastName)))),j(Ie,At)};ue(me,Ie=>{p(S),O(()=>p(S).podcastName)&&Ie(D)})}var Y=W(Z,2),_e=F(Y);{let Ie=ke(()=>p(A)===0);Ce(_e,{icon:"chevrons-up",label:"Move to top",size:20,get disabled(){return p(Ie)},$$events:{click:()=>l(p(S))}})}var at=W(_e,2);{let Ie=ke(()=>p(A)===0);Ce(at,{icon:"chevron-up",label:"Move up",size:20,get disabled(){return p(Ie)},$$events:{click:()=>c(p(S))}})}var Oe=W(at,2);{let Ie=ke(()=>(L(p(A)),p(i),O(()=>p(A)===p(i).length-1)));Ce(Oe,{icon:"chevron-down",label:"Move down",size:20,get disabled(){return p(Ie)},$$events:{click:()=>u(p(S))}})}var wt=W(Oe,2);{let Ie=ke(()=>(L(p(A)),p(i),O(()=>p(A)===p(i).length-1)));Ce(wt,{icon:"chevrons-down",label:"Move to bottom",size:20,get disabled(){return p(Ie)},$$events:{click:()=>d(p(S))}})}var Wt=W(wt,2);Ce(Wt,{icon:"x",label:"Remove from queue",size:20,$$events:{click:()=>f(p(S))}}),we(()=>{Ae(K,p(A)+1),Ae(be,(p(S),O(()=>p(S).title)))}),j(P,$)}),j(w,k)};ue(m,w=>{p(i),O(()=>p(i).length===0)?w(g):w(y,!1)})}var b=W(m,2),v=F(b);oe("click",v,function(...w){a()?.apply(this,w)}),j(t,h),Pe(),r()}class pv extends _.Modal{constructor(e){super(e),this.component=null}onOpen(){this.titleEl.setText("Reorder Queue"),this.component=va(hv,{target:this.contentEl,props:{close:()=>this.close()}})}onClose(){this.component&&(ya(this.component),this.component=null),this.contentEl.empty()}}function Vn(t){return Array.isArray?Array.isArray(t):Sf(t)==="[object Array]"}function mv(t){if(typeof t=="string")return t;let e=t+"";return e=="0"&&1/t==-1/0?"-0":e}function gv(t){return t==null?"":mv(t)}function bn(t){return typeof t=="string"}function kf(t){return typeof t=="number"}function vv(t){return t===!0||t===!1||yv(t)&&Sf(t)=="[object Boolean]"}function Ef(t){return typeof t=="object"}function yv(t){return Ef(t)&&t!==null}function Rt(t){return t!=null}function ko(t){return!t.trim().length}function Sf(t){return t==null?t===void 0?"[object Undefined]":"[object Null]":Object.prototype.toString.call(t)}const wv="Incorrect 'index' type",bv=t=>`Invalid value for key ${t}`,_v=t=>`Pattern length exceeds max of ${t}.`,xv=t=>`Missing ${t} property in key`,kv=t=>`Property 'weight' in key '${t}' must be a positive integer`,ku=Object.prototype.hasOwnProperty;class Ev{constructor(e){this._keys=[],this._keyMap={};let n=0;e.forEach(s=>{let r=Af(s);this._keys.push(r),this._keyMap[r.id]=r,n+=r.weight}),this._keys.forEach(s=>{s.weight/=n})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}}function Af(t){let e=null,n=null,s=null,r=1,i=null;if(bn(t)||Vn(t))s=t,e=Eu(t),n=pl(t);else{if(!ku.call(t,"name"))throw new Error(xv("name"));const a=t.name;if(s=a,ku.call(t,"weight")&&(r=t.weight,r<=0))throw new Error(kv(a));e=Eu(a),n=pl(a),i=t.getFn}return{path:e,id:n,weight:r,src:s,getFn:i}}function Eu(t){return Vn(t)?t:t.split(".")}function pl(t){return Vn(t)?t.join("."):t}function Sv(t,e){let n=[],s=!1;const r=(i,a,o)=>{if(Rt(i))if(!a[o])n.push(i);else{let l=a[o];const c=i[l];if(!Rt(c))return;if(o===a.length-1&&(bn(c)||kf(c)||vv(c)))n.push(gv(c));else if(Vn(c)){s=!0;for(let u=0,d=c.length;u<d;u+=1)r(c[u],a,o+1)}else a.length&&r(c,a,o+1)}};return r(t,bn(e)?e.split("."):e,0),s?n:n[0]}const Av={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},Cv={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(t,e)=>t.score===e.score?t.idx<e.idx?-1:1:t.score<e.score?-1:1},Tv={location:0,threshold:.6,distance:100},Pv={useExtendedSearch:!1,getFn:Sv,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1};var ne={...Cv,...Av,...Tv,...Pv};const $v=/[^ ]+/g;function Iv(t=1,e=3){const n=new Map,s=Math.pow(10,e);return{get(r){const i=r.match($v).length;if(n.has(i))return n.get(i);const a=1/Math.pow(i,.5*t),o=parseFloat(Math.round(a*s)/s);return n.set(i,o),o},clear(){n.clear()}}}class tc{constructor({getFn:e=ne.getFn,fieldNormWeight:n=ne.fieldNormWeight}={}){this.norm=Iv(n,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((n,s)=>{this._keysMap[n.id]=s})}create(){this.isCreated||!this.docs.length||(this.isCreated=!0,bn(this.docs[0])?this.docs.forEach((e,n)=>{this._addString(e,n)}):this.docs.forEach((e,n)=>{this._addObject(e,n)}),this.norm.clear())}add(e){const n=this.size();bn(e)?this._addString(e,n):this._addObject(e,n)}removeAt(e){this.records.splice(e,1);for(let n=e,s=this.size();n<s;n+=1)this.records[n].i-=1}getValueForItemAtKeyId(e,n){return e[this._keysMap[n]]}size(){return this.records.length}_addString(e,n){if(!Rt(e)||ko(e))return;let s={v:e,i:n,n:this.norm.get(e)};this.records.push(s)}_addObject(e,n){let s={i:n,$:{}};this.keys.forEach((r,i)=>{let a=r.getFn?r.getFn(e):this.getFn(e,r.path);if(Rt(a)){if(Vn(a)){let o=[];const l=[{nestedArrIndex:-1,value:a}];for(;l.length;){const{nestedArrIndex:c,value:u}=l.pop();if(Rt(u))if(bn(u)&&!ko(u)){let d={v:u,i:c,n:this.norm.get(u)};o.push(d)}else Vn(u)&&u.forEach((d,f)=>{l.push({nestedArrIndex:f,value:d})})}s.$[i]=o}else if(bn(a)&&!ko(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 Cf(t,e,{getFn:n=ne.getFn,fieldNormWeight:s=ne.fieldNormWeight}={}){const r=new tc({getFn:n,fieldNormWeight:s});return r.setKeys(t.map(Af)),r.setSources(e),r.create(),r}function Nv(t,{getFn:e=ne.getFn,fieldNormWeight:n=ne.fieldNormWeight}={}){const{keys:s,records:r}=t,i=new tc({getFn:e,fieldNormWeight:n});return i.setKeys(s),i.setIndexRecords(r),i}function Bi(t,{errors:e=0,currentLocation:n=0,expectedLocation:s=0,distance:r=ne.distance,ignoreLocation:i=ne.ignoreLocation}={}){const a=e/t.length;if(i)return a;const o=Math.abs(s-n);return r?a+o/r:o?1:a}function Rv(t=[],e=ne.minMatchCharLength){let n=[],s=-1,r=-1,i=0;for(let a=t.length;i<a;i+=1){let o=t[i];o&&s===-1?s=i:!o&&s!==-1&&(r=i-1,r-s+1>=e&&n.push([s,r]),s=-1)}return t[i-1]&&i-s>=e&&n.push([s,i-1]),n}const vs=32;function Fv(t,e,n,{location:s=ne.location,distance:r=ne.distance,threshold:i=ne.threshold,findAllMatches:a=ne.findAllMatches,minMatchCharLength:o=ne.minMatchCharLength,includeMatches:l=ne.includeMatches,ignoreLocation:c=ne.ignoreLocation}={}){if(e.length>vs)throw new Error(_v(vs));const u=e.length,d=t.length,f=Math.max(0,Math.min(s,d));let h=i,m=f;const g=o>1||l,y=g?Array(d):[];let b;for(;(b=t.indexOf(e,m))>-1;){let A=Bi(e,{currentLocation:b,expectedLocation:f,distance:r,ignoreLocation:c});if(h=Math.min(A,h),m=b+u,g){let $=0;for(;$<u;)y[b+$]=1,$+=1}}m=-1;let v=[],w=1,k=u+d;const P=1<<u-1;for(let A=0;A<u;A+=1){let $=0,R=k;for(;$<R;)Bi(e,{errors:A,currentLocation:f+R,expectedLocation:f,distance:r,ignoreLocation:c})<=h?$=R:k=R,R=Math.floor((k-$)/2+$);k=R;let K=Math.max(1,f-R+1),Z=a?d:Math.min(f+R,d)+u,ee=Array(Z+2);ee[Z+1]=(1<<A)-1;for(let me=Z;me>=K;me-=1){let D=me-1,Y=n[t.charAt(D)];if(g&&(y[D]=+!!Y),ee[me]=(ee[me+1]<<1|1)&Y,A&&(ee[me]|=(v[me+1]|v[me])<<1|1|v[me+1]),ee[me]&P&&(w=Bi(e,{errors:A,currentLocation:D,expectedLocation:f,distance:r,ignoreLocation:c}),w<=h)){if(h=w,m=D,m<=f)break;K=Math.max(1,2*f-m)}}if(Bi(e,{errors:A+1,currentLocation:f,expectedLocation:f,distance:r,ignoreLocation:c})>h)break;v=ee}const S={isMatch:m>=0,score:Math.max(.001,w)};if(g){const A=Rv(y,o);A.length?l&&(S.indices=A):S.isMatch=!1}return S}function Mv(t){let e={};for(let n=0,s=t.length;n<s;n+=1){const r=t.charAt(n);e[r]=(e[r]||0)|1<<s-n-1}return e}const wa=String.prototype.normalize?(t=>t.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,"")):(t=>t);class Tf{constructor(e,{location:n=ne.location,threshold:s=ne.threshold,distance:r=ne.distance,includeMatches:i=ne.includeMatches,findAllMatches:a=ne.findAllMatches,minMatchCharLength:o=ne.minMatchCharLength,isCaseSensitive:l=ne.isCaseSensitive,ignoreDiacritics:c=ne.ignoreDiacritics,ignoreLocation:u=ne.ignoreLocation}={}){if(this.options={location:n,threshold:s,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:l,ignoreDiacritics:c,ignoreLocation:u},e=l?e:e.toLowerCase(),e=c?wa(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;const d=(h,m)=>{this.chunks.push({pattern:h,alphabet:Mv(h),startIndex:m})},f=this.pattern.length;if(f>vs){let h=0;const m=f%vs,g=f-m;for(;h<g;)d(this.pattern.substr(h,vs),h),h+=vs;if(m){const y=f-vs;d(this.pattern.substr(y),y)}}else d(this.pattern,0)}searchIn(e){const{isCaseSensitive:n,ignoreDiacritics:s,includeMatches:r}=this.options;if(e=n?e:e.toLowerCase(),e=s?wa(e):e,this.pattern===e){let g={isMatch:!0,score:0};return r&&(g.indices=[[0,e.length-1]]),g}const{location:i,distance:a,threshold:o,findAllMatches:l,minMatchCharLength:c,ignoreLocation:u}=this.options;let d=[],f=0,h=!1;this.chunks.forEach(({pattern:g,alphabet:y,startIndex:b})=>{const{isMatch:v,score:w,indices:k}=Fv(e,g,y,{location:i+b,distance:a,threshold:o,findAllMatches:l,minMatchCharLength:c,includeMatches:r,ignoreLocation:u});v&&(h=!0),f+=w,v&&k&&(d=[...d,...k])});let m={isMatch:h,score:h?f/this.chunks.length:1};return h&&r&&(m.indices=d),m}}class os{constructor(e){this.pattern=e}static isMultiMatch(e){return Su(e,this.multiRegex)}static isSingleMatch(e){return Su(e,this.singleRegex)}search(){}}function Su(t,e){const n=t.match(e);return n?n[1]:null}class Dv extends os{constructor(e){super(e)}static get type(){return"exact"}static get multiRegex(){return/^="(.*)"$/}static get singleRegex(){return/^=(.*)$/}search(e){const n=e===this.pattern;return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class Lv extends os{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 Ov extends os{constructor(e){super(e)}static get type(){return"prefix-exact"}static get multiRegex(){return/^\^"(.*)"$/}static get singleRegex(){return/^\^(.*)$/}search(e){const n=e.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,this.pattern.length-1]}}}class Bv extends os{constructor(e){super(e)}static get type(){return"inverse-prefix-exact"}static get multiRegex(){return/^!\^"(.*)"$/}static get singleRegex(){return/^!\^(.*)$/}search(e){const n=!e.startsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}}class Uv extends os{constructor(e){super(e)}static get type(){return"suffix-exact"}static get multiRegex(){return/^"(.*)"\$$/}static get singleRegex(){return/^(.*)\$$/}search(e){const n=e.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[e.length-this.pattern.length,e.length-1]}}}class jv extends os{constructor(e){super(e)}static get type(){return"inverse-suffix-exact"}static get multiRegex(){return/^!"(.*)"\$$/}static get singleRegex(){return/^!(.*)\$$/}search(e){const n=!e.endsWith(this.pattern);return{isMatch:n,score:n?0:1,indices:[0,e.length-1]}}}class Pf extends os{constructor(e,{location:n=ne.location,threshold:s=ne.threshold,distance:r=ne.distance,includeMatches:i=ne.includeMatches,findAllMatches:a=ne.findAllMatches,minMatchCharLength:o=ne.minMatchCharLength,isCaseSensitive:l=ne.isCaseSensitive,ignoreDiacritics:c=ne.ignoreDiacritics,ignoreLocation:u=ne.ignoreLocation}={}){super(e),this._bitapSearch=new Tf(e,{location:n,threshold:s,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:l,ignoreDiacritics:c,ignoreLocation:u})}static get type(){return"fuzzy"}static get multiRegex(){return/^"(.*)"$/}static get singleRegex(){return/^(.*)$/}search(e){return this._bitapSearch.searchIn(e)}}class $f extends os{constructor(e){super(e)}static get type(){return"include"}static get multiRegex(){return/^'"(.*)"$/}static get singleRegex(){return/^'(.*)$/}search(e){let n=0,s;const r=[],i=this.pattern.length;for(;(s=e.indexOf(this.pattern,n))>-1;)n=s+i,r.push([s,n-1]);const a=!!r.length;return{isMatch:a,score:a?0:1,indices:r}}}const ml=[Dv,$f,Ov,Bv,jv,Uv,Lv,Pf],Au=ml.length,zv=/ +(?=(?:[^\"]*\"[^\"]*\")*[^\"]*$)/,qv="|";function Hv(t,e={}){return t.split(qv).map(n=>{let s=n.trim().split(zv).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<Au;){const u=ml[c];let d=u.isMultiMatch(o);d&&(r.push(new u(d,e)),l=!0)}if(!l)for(c=-1;++c<Au;){const u=ml[c];let d=u.isSingleMatch(o);if(d){r.push(new u(d,e));break}}}return r})}const Vv=new Set([Pf.type,$f.type]);class Wv{constructor(e,{isCaseSensitive:n=ne.isCaseSensitive,ignoreDiacritics:s=ne.ignoreDiacritics,includeMatches:r=ne.includeMatches,minMatchCharLength:i=ne.minMatchCharLength,ignoreLocation:a=ne.ignoreLocation,findAllMatches:o=ne.findAllMatches,location:l=ne.location,threshold:c=ne.threshold,distance:u=ne.distance}={}){this.query=null,this.options={isCaseSensitive:n,ignoreDiacritics:s,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:a,location:l,threshold:c,distance:u},e=n?e:e.toLowerCase(),e=s?wa(e):e,this.pattern=e,this.query=Hv(this.pattern,this.options)}static condition(e,n){return n.useExtendedSearch}searchIn(e){const n=this.query;if(!n)return{isMatch:!1,score:1};const{includeMatches:s,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?wa(e):e;let a=0,o=[],l=0;for(let c=0,u=n.length;c<u;c+=1){const d=n[c];o.length=0,a=0;for(let f=0,h=d.length;f<h;f+=1){const m=d[f],{isMatch:g,indices:y,score:b}=m.search(e);if(g){if(a+=1,l+=b,s){const v=m.constructor.type;Vv.has(v)?o=[...o,...y]:o.push(y)}}else{l=0,a=0,o.length=0;break}}if(a){let f={isMatch:!0,score:l/a};return s&&(f.indices=o),f}}return{isMatch:!1,score:1}}}const gl=[];function Kv(...t){gl.push(...t)}function vl(t,e){for(let n=0,s=gl.length;n<s;n+=1){let r=gl[n];if(r.condition(t,e))return new r(t,e)}return new Tf(t,e)}const ba={AND:"$and",OR:"$or"},yl={PATH:"$path",PATTERN:"$val"},wl=t=>!!(t[ba.AND]||t[ba.OR]),Yv=t=>!!t[yl.PATH],Xv=t=>!Vn(t)&&Ef(t)&&!wl(t),Cu=t=>({[ba.AND]:Object.keys(t).map(e=>({[e]:t[e]}))});function If(t,e,{auto:n=!0}={}){const s=r=>{let i=Object.keys(r);const a=Yv(r);if(!a&&i.length>1&&!wl(r))return s(Cu(r));if(Xv(r)){const l=a?r[yl.PATH]:i[0],c=a?r[yl.PATTERN]:r[l];if(!bn(c))throw new Error(bv(l));const u={keyId:pl(l),pattern:c};return n&&(u.searcher=vl(c,e)),u}let o={children:[],operator:i[0]};return i.forEach(l=>{const c=r[l];Vn(c)&&c.forEach(u=>{o.children.push(s(u))})}),o};return wl(t)||(t=Cu(t)),s(t)}function Jv(t,{ignoreFieldNorm:e=ne.ignoreFieldNorm}){t.forEach(n=>{let s=1;n.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))}),n.score=s})}function Gv(t,e){const n=t.matches;e.matches=[],Rt(n)&&n.forEach(s=>{if(!Rt(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 Qv(t,e){e.score=t.score}function Zv(t,e,{includeMatches:n=ne.includeMatches,includeScore:s=ne.includeScore}={}){const r=[];return n&&r.push(Gv),s&&r.push(Qv),t.map(i=>{const{idx:a}=i,o={item:e[a],refIndex:a};return r.length&&r.forEach(l=>{l(i,o)}),o})}class js{constructor(e,n={},s){this.options={...ne,...n},this.options.useExtendedSearch,this._keyStore=new Ev(this.options.keys),this.setCollection(e,s)}setCollection(e,n){if(this._docs=e,n&&!(n instanceof tc))throw new Error(wv);this._myIndex=n||Cf(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight})}add(e){Rt(e)&&(this._docs.push(e),this._myIndex.add(e))}remove(e=()=>!1){const n=[];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,n.push(i))}return n}removeAt(e){this._docs.splice(e,1),this._myIndex.removeAt(e)}getIndex(){return this._myIndex}search(e,{limit:n=-1}={}){const{includeMatches:s,includeScore:r,shouldSort:i,sortFn:a,ignoreFieldNorm:o}=this.options;let l=bn(e)?bn(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e);return Jv(l,{ignoreFieldNorm:o}),i&&l.sort(a),kf(n)&&n>-1&&(l=l.slice(0,n)),Zv(l,this._docs,{includeMatches:s,includeScore:r})}_searchStringList(e){const n=vl(e,this.options),{records:s}=this._myIndex,r=[];return s.forEach(({v:i,i:a,n:o})=>{if(!Rt(i))return;const{isMatch:l,score:c,indices:u}=n.searchIn(i);l&&r.push({item:i,idx:a,matches:[{score:c,value:i,norm:o,indices:u}]})}),r}_searchLogical(e){const n=If(e,this.options),s=(o,l,c)=>{if(!o.children){const{keyId:d,searcher:f}=o,h=this._findMatches({key:this._keyStore.get(d),value:this._myIndex.getValueForItemAtKeyId(l,d),searcher:f});return h&&h.length?[{idx:c,item:l,matches:h}]:[]}const u=[];for(let d=0,f=o.children.length;d<f;d+=1){const h=o.children[d],m=s(h,l,c);if(m.length)u.push(...m);else if(o.operator===ba.AND)return[]}return u},r=this._myIndex.records,i={},a=[];return r.forEach(({$:o,i:l})=>{if(Rt(o)){let c=s(n,o,l);c.length&&(i[l]||(i[l]={idx:l,item:o,matches:[]},a.push(i[l])),c.forEach(({matches:u})=>{i[l].matches.push(...u)}))}}),a}_searchObjectList(e){const n=vl(e,this.options),{keys:s,records:r}=this._myIndex,i=[];return r.forEach(({$:a,i:o})=>{if(!Rt(a))return;let l=[];s.forEach((c,u)=>{l.push(...this._findMatches({key:c,value:a[u],searcher:n}))}),l.length&&i.push({idx:o,item:a,matches:l})}),i}_findMatches({key:e,value:n,searcher:s}){if(!Rt(n))return[];let r=[];if(Vn(n))n.forEach(({v:i,i:a,n:o})=>{if(!Rt(i))return;const{isMatch:l,score:c,indices:u}=s.searchIn(i);l&&r.push({score:c,key:e,value:i,idx:a,norm:o,indices:u})});else{const{v:i,n:a}=n,{isMatch:o,score:l,indices:c}=s.searchIn(i);o&&r.push({score:l,key:e,value:i,norm:a,indices:c})}return r}}js.version="7.1.0";js.createIndex=Cf;js.parseIndex=Nv;js.config=ne;js.parseQuery=If;Kv(Wv);function ls(t){const n=new RegExp(/\.([0-9a-z]+)(?:[?#]|$)/i).exec(t);if(!n)return"";const[,s]=n;return s}function xr(t,e){const n=t.getFullYear(),s=t.getMonth(),r=t.getDate(),i=t.getDay(),a=t.getHours(),o=t.getMinutes(),l=t.getSeconds(),c=S=>S.toString().padStart(2,"0"),u=["January","February","March","April","May","June","July","August","September","October","November","December"],d=["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],f=["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],h=["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],m=S=>{const A=["th","st","nd","rd"],$=S%100;return S+(A[($-20)%10]||A[$]||A[0])},g=a%12||12,y=a>=12,b={YYYY:n.toString(),YY:n.toString().slice(-2),MMMM:u[s],MMM:d[s],MM:c(s+1),Mo:m(s+1),M:(s+1).toString(),dddd:f[i],ddd:h[i],Do:m(r),DD:c(r),D:r.toString(),HH:c(a),H:a.toString(),hh:c(g),h:g.toString(),mm:c(o),m:o.toString(),ss:c(l),s:l.toString(),A:y?"PM":"AM",a:y?"pm":"am"},v=Object.keys(b).sort((S,A)=>A.length-S.length).map(S=>S.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")).join("|"),w=new RegExp(`\\[([^\\]]*)]|(${v})|.`,"g");let k="",P;for(;(P=w.exec(e))!==null;)P[1]!==void 0?k+=P[1]:P[2]!==void 0?k+=b[P[2]]:k+=P[0];return k}function ft(t,e){(!Number.isFinite(t)||t<0)&&(t=0);const n=Math.floor(t/3600),s=Math.floor(t%3600/60),r=Math.floor(t%60),i=n%12||12,a=n>=12,o=c=>c.toString().padStart(2,"0"),l={HH:o(n),hh:o(i),mm:o(s),ss:o(r),H:n.toString(),h:i.toString(),m:s.toString(),s:r.toString(),A:a?"PM":"AM",a:a?"pm":"am"};return e.replace(/\\(.)|HH|hh|mm|ss|H|h|m|s|A|a/g,(c,u)=>u!==void 0?u:l[c])}function nc(t,e){if(!e||!e.trim())return t>=3600?ft(t,"H:mm:ss"):ft(t,"m:ss");const n=e.trim().toLowerCase();return n==="seconds"?String(Math.floor(t)):n==="minutes"?String(Math.floor(t/60)):ft(t,e)}function Nf(t,e){if(t===void 0)return"";const n=String(t),s=e?.trim();return s&&/^0+$/.test(s)?n.padStart(s.length,"0"):n}function ey(t,e){const n=ty(t);return n!==void 0?n:Rf(e)}function ty(t){if(t==null)return;const e=t.trim();if(!/^\d+$/.test(e))return;const n=Number(e);return Number.isSafeInteger(n)?n:void 0}function Rf(t){const e=(t??"").trim();if(!e)return;const n=e.slice(0,64),s=n.match(/^(?:#\s*|ep(?:isode)?\.?\s*#?|e)(\d{1,6})\b(?!\.\d)/i);if(s)return Number(s[1]);const r=n.match(/^(\d{1,6})\s*(?:[-:)|]|\.(?!\d))/);if(r)return Number(r[1])}function bl(t,e,n,s){const r=new URL("obsidian://podnotes"),i=new URLSearchParams;return i.set("episodeName",t),i.set("url",e),n!==void 0&&(i.set("time",n.toString()),s!==void 0&&i.set("endTime",s.toString())),r.search=i.toString().replace(/\+/g,"%20"),r}function sc(t){return t.podcastName==="local file"}function ny(t){const e=()=>et.getEpisode(t)?.filePath,n=sc(t)?t.filePath??e():t.feedUrl??e();return!n||!t.title?"":bl(t.title,n).href}function rc(t,e){const n=e.startsWith(".")?e:`.${e}`;return t.endsWith(n)?t:`${t}${n}`}const Tu=255,ic="Untitled",sy=new TextEncoder;function ry(t){return sy.encode(t).length}function _a(t,e){return e==="bytes"?ry(t):t.length}function iy(){return _.Platform.isWin||_.Platform.isMacOS||_.Platform.isIosApp?{mode:"utf16",max:Tu}:{mode:"bytes",max:Tu}}function Ff(t,e,n){if(_a(t,n)<=e)return t;let s="",r=0;for(const i of t){const a=_a(i,n);if(r+a>e)break;s+=i,r+=a}return s}function Mf(t){return t.replace(/[\s.]+$/g,"").replace(/^\s+/,"")}function ay(t,e){const n=_a(t,e.mode)<=e.max?t:Ff(t,e.max,e.mode);return Mf(n)||ic}function oy(t,e,n){const r=t.toLowerCase().endsWith(e.toLowerCase())?t.slice(0,t.length-e.length):t,i=Math.max(1,n.max-_a(e,n.mode));return`${Mf(Ff(r,i,n.mode))||ic}${e}`}function ly(t){const e=t.split("/").pop()??"",n=e.lastIndexOf(".");if(n<=0)return"";const s=e.slice(n);return/^\.[A-Za-z0-9]{1,16}$/.test(s)?s:""}function $r(t,e=".md",n=iy()){const s=t.split("/").filter(i=>i.length>0);if(s.length===0)return`${ic}${e}`;const r=s.length-1;return s.map((i,a)=>a===r?oy(i,e,n):ay(i,n)).join("/")}const cy=500,uy=500;function Df(t){return t.filter(dy).map(e=>({...e,title:typeof e.title=="string"?e.title.slice(0,uy):""})).sort((e,n)=>e.startTime-n.startTime).slice(0,cy)}function dy(t){if(!t||typeof t!="object")return!1;const e=t;return e.toc!==!1&&(e.title===void 0||typeof e.title=="string")&&Number.isFinite(e.startTime)}const Lf=/\{\{(.*?)(:\s*.*?)?\}\}/g;function fy(t,e){return Array.from(t.matchAll(Lf)).some(([,n])=>n.toLowerCase()===e)}function zs(){const t={};function e(s,r){t[s]=r}function n(s){return s.replace(Lf,(r,i,a)=>{const o=t[i.toLowerCase()];if(o==null){const c=new js(Object.keys(t),{shouldSort:!0,findAllMatches:!1,threshold:.4,isCaseSensitive:!1}).search(i);return new _.Notice(`Tag ${i} is invalid.${c.length>0?` Did you mean ${c[0].item}?`:""}`),r}if(typeof o=="function"){const l=a?a.slice(1):"";return l===""?o():o(l)}return o})}return[n,e]}function Of(t){return t.episodeNumber??Rf(t.title)}function _l(t){return e=>{const n=Ds(t);return e?n.replace(/\s+/g,e):n}}function ac(t,e){t("title",_l(e.title)),t("podcast",_l(e.podcastName)),t("date",n=>e.episodeDate?xr(e.episodeDate,n??"YYYY-MM-DD"):""),t("currentdate",n=>xr(new Date,n??"YYYY-MM-DD")),t("episodenumber",n=>Nf(Of(e),n))}function hy(t){return t.replace(/\s+/g," ").trim()}function py(t){return t.replace(/\\/g,"\\\\").replace(/</g,"<").replace(/>/g,">").replace(/([`*_{}[\]()#+.!|-])/g,"\\$1")}function my(t,e){const n=Df(t??[]).map(s=>{const r=hy(s.title),i=r?` ${py(r)}`:"";return`- ${nc(s.startTime)}${i}`});return e?n.map(s=>`${e}${s}`).join(`
|
||
`):n.join(`
|
||
`)}function gy(t,e,n={}){const[s,r]=zs();r("title",e.title),r("description",a=>{const o=_.htmlToMarkdown(e.description).replace(/\n{3,}/g,`
|
||
|
||
`);return a?o.split(`
|
||
`).map(l=>`${a}${l}`).join(`
|
||
`):o}),r("content",a=>a?_.htmlToMarkdown(e.content).split(`
|
||
`).map(o=>`${a}${o}`).join(`
|
||
`):_.htmlToMarkdown(e.content)),r("safetitle",Ds(e.title)),r("stream",e.streamUrl),r("url",e.url),r("date",a=>e.episodeDate?xr(e.episodeDate,a??"YYYY-MM-DD"):""),r("currentdate",a=>xr(new Date,a??"YYYY-MM-DD")),r("episodenumber",a=>Nf(Of(e),a)),r("duration",a=>e.duration!==void 0?nc(e.duration,a):""),r("chapters",a=>my(n.chapters,a)),r("podcast",Ds(e.podcastName)),r("artwork",e.artworkUrl??""),r("episodeurl",e.url),r("episodeartwork",e.artworkUrl??""),r("feedurl",e.feedUrl??"");const i=T(re)?.settings?.savedFeeds?.[e.podcastName];return r("feedartwork",i?.artworkUrl??e.artworkUrl??""),r("podcastlink",wy(e.podcastName)),r("episodelink",ny(e)),s(t)}function xa(t,e={}){const[n,s]=zs(),{api:r,settings:i}=T(re),a=i.timestamp.offset??0;return s("time",o=>r.getPodcastTimeFormatted(o??"HH:mm:ss",!1,a)),s("linktime",o=>r.getPodcastTimeFormatted(o??"HH:mm:ss",!0,a)),s("segment",o=>e.segment?r.getPodcastSegmentFormatted(o??"HH:mm:ss",e.segment.startTime,e.segment.endTime,!1):r.getPodcastTimeFormatted(o??"HH:mm:ss",!1,a)),s("linksegment",o=>e.segment?r.getPodcastSegmentFormatted(o??"HH:mm:ss",e.segment.startTime,e.segment.endTime,!0):r.getPodcastTimeFormatted(o??"HH:mm:ss",!0,a)),n(t)}function ka(t,e){const[n,s]=zs();return ac(s,e),n(t)}function Bf(t,e){const n=ls(t),s=n?t.replace(new RegExp(`\\.${n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}$`,"i"),""):t,[r,i]=zs();return ac(i,e),r(s)}function vy(t,e,n){const[s,r]=zs();return ac(r,e),r("duration",i=>e.duration!==void 0?nc(e.duration,i):""),r("transcript",n),r("description",i=>i?_.htmlToMarkdown(e.description).split(`
|
||
`).map(a=>`${i}${a}`).join(`
|
||
`):_.htmlToMarkdown(e.description)),r("url",e.url),r("artwork",e.artworkUrl??""),s(t)}function yy(t,e){const[n,s]=zs(),r=Ds(e.title);return s("title",e.title),s("safetitle",r),s("podcast",r),s("url",Ui(e.link??"")),s("feedurl",Ui(e.url)),s("artwork",Ui(e.artworkUrl??"")),s("feedartwork",Ui(e.artworkUrl??"")),s("author",e.author??""),s("description",i=>{const a=_.htmlToMarkdown(e.description??"").replace(/\n{3,}/g,`
|
||
|
||
`);return i?a.split(`
|
||
`).map(o=>`${i}${o}`).join(`
|
||
`):a}),s("date",i=>xr(new Date,i??"YYYY-MM-DD")),n(t)}function oc(t,e){const[n,s]=zs(),r=_l(e.title);return s("title",r),s("podcast",r),s("date",i=>xr(new Date,i??"YYYY-MM-DD")),n(t)}function wy(t){const e=Ds(t),n=T(re)?.settings?.feedNote?.path?.trim();if(!n)return`[[${e}]]`;const s=oc(n,{title:t}),i=$r(rc(s,"md")).replace(/\.md$/i,"").trim(),a=i.split("/").pop()?.trim()||e;return i.includes("/")?`[[${i}|${a}]]`:`[[${a}]]`}function Ui(t){return t.replace(/["\\]/g,"")}function Ds(t){return t.replace(/[\\,#%&{}/*<>$'":@\u2023|?]/g,"").replace(/[\u0000-\u001f]/g," ").replace(/\s+/g," ").trim().replace(/^\.+/,"").replace(/\.+$/,"").trim()}function Uf(t){return t.replace(/^\s*(?:>\s?)+/,"")}function Eo(t){return Uf(t).includes("|")}function Pu(t){const e=Uf(t).trim();if(!e.includes("|"))return!1;const n=e.replace(/^\|/,"").replace(/\|$/,"").split("|");return n.length>0&&n.every(s=>/^\s*:?-+:?\s*$/.test(s))}function by(t,e,n){const s=t(n);if(!s||!Eo(s))return!1;for(let r=n;r>=0;r--){const i=t(r);if(!i||!Eo(i))break;if(Pu(i))return!0}for(let r=n;r<e;r++){const i=t(r);if(!i||!Eo(i))break;if(Pu(i))return!0}return!1}function _y(t){return t.replace(/\r\n?|\n/g," ").replace(/(?<!\\)\|/g,"\\|")}function jf(t,e){return by(e.getLine,e.lineCount,e.cursorLine)?_y(t):t}function zf(t,e){if(!Number.isFinite(t)||!Number.isFinite(e))return null;const n={startTime:Math.max(0,t),endTime:Math.max(0,e)};return n.endTime>n.startTime?n:null}function xy(t,e,n=0){if(!Number.isFinite(t)||!Number.isFinite(e)||e<=0)return null;const s=Math.max(0,t-n),r=Math.max(0,s-e);return zf(r,s)}function $u(t,e,n){return`${ft(Math.max(0,t),n)}-${ft(Math.max(0,e),n)}`}function ky(t){if(/\{\{(?:linksegment|segment)(?::\s*?.+?)?\}\}/i.test(t))return t;const n=t.replace(/\{\{linktime(:\s*?.+?)?\}\}/gi,"{{linksegment$1}}").replace(/\{\{time(:\s*?.+?)?\}\}/gi,"{{segment$1}}");return n===t?"- {{linksegment}}":n}async function Ei(t,e=T(re).app.vault){const n=t.split("/").filter(Boolean);let s="";for(const r of n)if(s=s?`${s}/${r}`:r,!e.getAbstractFileByPath(s))try{await e.createFolder(s)}catch(i){if(!(i instanceof Error&&/already exists/i.test(i.message))&&!e.getAbstractFileByPath(s))throw i}}const Ey=3e4;class ea extends Error{constructor(e,n,s){super(e),this.url=n,this.cause=s,this.name="NetworkError"}}class Sy extends ea{constructor(e,n){super(`Request timed out after ${n}ms`,e),this.name="TimeoutError"}}async function lc(t,e={}){const{timeoutMs:n=Ey,method:s,headers:r,body:i}=e;let a;const o=new Promise((l,c)=>{a=window.setTimeout(()=>{c(new Sy(t,n))},n)});try{const l=await Promise.race([_.requestUrl({url:t,method:s,headers:r,body:i,throw:!1}),o]);if(l.status>=400)throw new ea(`HTTP ${l.status}: ${l.text?.slice(0,100)||"Unknown error"}`,t);return l}catch(l){throw l instanceof ea?l:new ea(l instanceof Error?l.message:String(l),t,l)}finally{a&&window.clearTimeout(a)}}const Ay=1e6;async function qf(t){if(!t||!Cy(t))return[];try{const e=await lc(t,{timeoutMs:1e4});if(e.text.length>Ay)return[];const n=JSON.parse(e.text);return!n.chapters||!Array.isArray(n.chapters)?[]:Df(n.chapters)}catch{return[]}}function Cy(t){try{const e=new URL(t);return e.protocol==="https:"||e.protocol==="http:"}catch{return!1}}function cc(t){const e=T(re),n=ka(e.settings.note.path,t);return $r(rc(n,"md"))}async function Hf(t){try{const e=await Vf(t);T(re).app.workspace.getLeaf().openFile(e)}catch{new _.Notice(`Failed to create note: "${cc(t)}"`)}}async function Vf(t){const e=Si(t);if(e)return new _.Notice(`Note for "${t.title}" already exists`),e;const n=T(re),s=cc(t),r=n.settings.note.template,i=await Ty(r,t),a=gy(r,t,{chapters:i});return await $y(s,a,t)}async function Ty(t,e){if(!(!e.chaptersUrl||!fy(t,"chapters")))return await qf(e.chaptersUrl)}function Si(t){const e=cc(t),n=T(re).app.vault.getAbstractFileByPath(e);return!n||!(n instanceof _.TFile)?null:n}function Py(t){const e=Si(t);if(!e){new _.Notice(`Note for "${t.title}" does not exist`);return}T(re).app.workspace.getLeaf().openFile(e)}async function $y(t,e,n){const s=Si(n);if(s)return new _.Notice(`Note for "${n.title}" already exists`),s;const r=t.split("/").slice(0,-1).join("/");await Ei(r);const{app:i}=T(re);try{return await i.vault.create(t,e)}catch(a){const o=i.vault.getAbstractFileByPath(t);if(o instanceof _.TFile)return o;throw a}}const Iy=86400*366;function Ny(t){if(t==null)return;const e=t.trim();if(!e)return;let n;if(e.includes(":")){const s=e.split(":").map(r=>r.trim());if(s.length>3||s.some(r=>!/^\d+$/.test(r)))return;n=s.reduce((r,i)=>r*60+Number(i),0)}else{if(!/^\d+(\.\d+)?$/.test(e))return;n=Math.floor(Number(e))}if(!(!Number.isFinite(n)||n>Iy))return n}const Wf=new Set(["mp3","m4a","aac","ogg","wav","flac","wma","amr"]),Kf=new Set(["mp4","m4v","mov","webm","ogv"]);[...Wf,...Kf];function as(t){if(!t)return null;const e=t.toLowerCase();return Kf.has(e)?"video":Wf.has(e)?"audio":null}function Ry(t){return as(t)!==null}function fi(t){if(!t)return null;const e=t.split(";")[0].trim().toLowerCase();return e.startsWith("video/")?"video":e.startsWith("audio/")?"audio":null}function Ea(t){return t?as(ls(t)):null}function xl(t){if(!t)return null;const e=ls(t);return qs(e)?null:as(e)}function Ka(t){if(t.mediaType)return t.mediaType;const e=t.filePath,n=xl(e);return n||(xl(t.streamUrl)??"audio")}function qs(t){if(!t)return!1;const e=t.toLowerCase();return e==="mp4"||e==="webm"}function Yf(t,e){if(t.mediaType)return t.mediaType;const n=t.filePath,s=n?ls(n):null;return e&&qs(s)?e:Ka(t)}function Xf(t,e){if(t===e)return!0;if(!t||!e)return!1;try{const n=new URL(t),s=new URL(e);if(n.origin!==s.origin||n.pathname!==s.pathname)return!1;if(n.search===s.search)return!0;const r=Iu(n.searchParams),i=Iu(s.searchParams);return Fy(r,i)?!0:(Ea(n.pathname)!==null||Ea(s.pathname)!==null)&&r.length===0&&i.length===0}catch{return!1}}function Fy(t,e){return t.length===0||e.length===0||t.length!==e.length?!1:t.every((n,s)=>n===e[s])}function Iu(t){return Array.from(t.entries()).filter(([e])=>!My(e)).map(([e,n])=>`${e.toLowerCase()}=${n}`).sort()}function My(t){const e=t.toLowerCase();return e==="token"||e==="access_token"||e==="auth"||e==="authorization"||e==="signature"||e==="sig"||e==="expires"||e==="expiry"||e==="exp"||e==="policy"||e==="key-pair-id"||e.startsWith("x-amz-")}class Ai{constructor(e){this.feed=e}async getEpisodes(e){(!this.feed||this.feed.url!==e)&&await this.getFeed(e);const n=await this.parseFeed(e);return this.parsePage(n)}async getFeed(e){const n=await this.parseFeed(e),s=n.querySelector("title");if(!s)throw new Error("Invalid RSS feed");const r=n.querySelector("channel")??n,i=this.findChannelImageElement(r),a=s.textContent||"",o=i?.getAttribute("href")||i?.querySelector("url")?.textContent||"",l={title:a,url:e,artworkUrl:o},c=this.findFeedLink(r);c&&(l.link=c);const u=this.findDirectChildText(r,["description","itunes:summary"]);u&&(l.description=u);const d=this.findDirectChildText(r,["itunes:author","author","managingEditor"]);return d&&(l.author=d),this.feed=l,l}findImageElement(e){const n=e.getElementsByTagName("itunes:image")[0];return n||e.querySelector("image")}findChannelImageElement(e){const n=Array.from(e.children),s=n.find(r=>r.tagName.toLowerCase()==="itunes:image");return s||(n.find(r=>r.tagName.toLowerCase()==="image")??null)}findFeedLink(e){const n=Array.from(e.children).filter(s=>{const r=s.tagName.toLowerCase();return r==="link"||r==="atom:link"});for(const s of n){const r=s.textContent?.trim();if(r&&/^https?:\/\//i.test(r))return r}for(const s of n){const r=s.getAttribute("rel");if(r&&r!=="alternate")continue;const i=s.getAttribute("href")?.trim();if(i&&/^https?:\/\//i.test(i))return i}return""}findDirectChildText(e,n){const s=Array.from(e.children);for(const r of n){const i=r.toLowerCase();for(const a of s){if(a.tagName.toLowerCase()!==i)continue;const o=a.textContent?.trim()??"";if(o)return o}}return""}parsePage(e){const n=e.querySelectorAll("item");function s(r){return!!r}return Array.from(n).map(this.parseItem.bind(this)).filter(s)}parseItem(e){const n=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],u=e.getElementsByTagName("itunes:episode")[0],d=e.getElementsByTagName("itunes:duration")[0],f=e.getElementsByTagName("podcast:chapters")[0];if(!n||!s||!o)return null;const h=n.textContent||"",m=s.getAttribute("url")||"",g=s.getAttribute("type"),y=r?.textContent||"",b=i?.textContent||"",v=a?.textContent||"",w=new Date(o.textContent),k=l?.getAttribute("href")||this.feed?.artworkUrl,P=c?.textContent,S=ey(u?.textContent,h),A=Ny(d?.textContent),$=f?.getAttribute("url")||void 0;return{title:h,streamUrl:m,url:y||this.feed?.url||"",description:b,content:v,podcastName:this.feed?.title||"",artworkUrl:k,episodeDate:w,feedUrl:this.feed?.url||"",itunesTitle:P||"",episodeNumber:S,duration:A,chaptersUrl:$,mediaType:fi(g)??xl(m)??"audio"}}async parseFeed(e){const n=await lc(e,{timeoutMs:3e4});return new DOMParser().parseFromString(n.text,"text/xml")}}function Jf(t){const e=T(re),n=oc(e.settings.feedNote.path,t);return $r(rc(n,"md"))}function Ya(t){const e=Jf(t),n=T(re).app.vault.getAbstractFileByPath(e);return!n||!(n instanceof _.TFile)?null:n}function Dy(t){const e=Ya(t);if(!e){new _.Notice(`Note for "${t.title}" does not exist`);return}T(re).app.workspace.getLeaf().openFile(e)}async function Gf(t){const e=T(re),{path:n,template:s}=e.settings.feedNote;if(!n||!s){new _.Notice("Please set a podcast feed note path and template in the settings.");return}const r=Ya(t);if(r){new _.Notice(`Note for "${t.title}" already exists`),T(re).app.workspace.getLeaf().openFile(r);return}const i=Jf(t),a=await Ly(t),o=yy(s,a);try{const l=await Oy(i,o,t);T(re).app.workspace.getLeaf().openFile(l)}catch{new _.Notice(`Failed to create note: "${i}"`)}}async function Ly(t){if(!(!t.description||!t.link||!t.author)||!t.url)return t;try{const n=await new Ai(t).getFeed(t.url);return{...t,description:t.description||n.description,link:t.link||n.link,author:t.author||n.author}}catch{return t}}async function Oy(t,e,n){const s=Ya(n);if(s)return new _.Notice(`Note for "${n.title}" already exists`),s;const r=t.split("/").slice(0,-1).join("/");await Ei(r);const{app:i}=T(re);try{return await i.vault.create(t,e)}catch(a){const o=i.vault.getAbstractFileByPath(t);if(o instanceof _.TFile)return o;throw a}}function By(t,e){return e?[...t.filter(n=>n.title===e),...t.filter(n=>n.title!==e)]:t}class Uy extends _.FuzzySuggestModal{constructor(e,n,s){super(e),this.feeds=n,this.onChoose=s,this.setPlaceholder("Select a podcast to create or open its note")}getItems(){return this.feeds}getItemText(e){return e.title}onChooseItem(e){this.onChoose(e)}}const jy=/[()]/g,zy={"(":"%28",")":"%29"};function uc(t){const e=t.trim();if(!e)return e;let n;try{n=new URL(e).toString()}catch{n=qy(e)}return n.replace(jy,r=>zy[r]??r)}function qy(t){return t.replace(/\s/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,"0")}`)}const Hy=[{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"},{pattern:/audio\/webm/i,extension:"webm"},{pattern:/video\/mp4/i,extension:"mp4"},{pattern:/video\/x-m4v/i,extension:"m4v"},{pattern:/video\/quicktime/i,extension:"mov"},{pattern:/video\/webm/i,extension:"webm"},{pattern:/video\/ogg/i,extension:"ogv"}];function Vy(t){if(!t)return null;for(const{pattern:e,extension:n}of Hy)if(e.test(t))return n;return null}const Qf=4*1024*1024;function Xa(){return T(re).app.vault.adapter}function So(t,e){if(!t)return;const n=t[e]??t[e.toLowerCase()];if(n!==void 0)return n;const s=e.toLowerCase();for(const r of Object.keys(t))if(r.toLowerCase()===s)return t[r]}async function Wy(t,e=Qf){const n=uc(t),s=await _.requestUrl({url:n,method:"GET",headers:{Range:`bytes=0-${e-1}`},throw:!1});if(s.status!==200&&s.status!==206)throw new Error(`Could not download episode (HTTP ${s.status}).`);const r=So(s.headers,"content-type")??"",i=s.status===206;let a=null;if(i){const l=So(s.headers,"content-range")?.match(/\/(\d+)\s*$/);l&&(a=Number.parseInt(l[1],10))}else{const o=So(s.headers,"content-length");if(o){const l=Number.parseInt(o,10);Number.isFinite(l)&&(a=l)}}return{firstChunk:s.arrayBuffer,contentType:r,supportsRange:i,totalSize:a}}async function Ky(t,e,n,s,r=Qf){const i=Xa();await i.writeBinary(e,n.firstChunk);let a=n.firstChunk.byteLength;if(s?.(a,n.totalSize),!n.supportsRange||typeof i.appendBinary!="function")return a;const o=uc(t);for(;!(n.totalSize!==null&&a>=n.totalSize);){const l=n.totalSize!==null?Math.min(a+r,n.totalSize)-1:a+r-1,c=await _.requestUrl({url:o,method:"GET",headers:{Range:`bytes=${a}-${l}`},throw:!1});if(c.status===416)break;if(c.status!==206)throw new Error(`Range request failed (HTTP ${c.status}) at byte ${a}.`);const u=c.arrayBuffer;if(u.byteLength===0||(await i.appendBinary(e,u),a+=u.byteLength,s?.(a,n.totalSize),n.totalSize===null&&u.byteLength<r))break}return a}const kl=".podnotes-partial";let Yy=0;function Xy(t){const e=t.lastIndexOf("/"),n=e===-1?"":t.slice(0,e+1),s=e===-1?t:t.slice(e+1),r=`${Date.now().toString(36)}-${(Yy++).toString(36)}`;return $r(`${n}.${r}.${s}${kl}`,kl)}function Jy(t){const e=t.slice(t.lastIndexOf("/")+1);return e.startsWith(".")&&e.endsWith(kl)}async function Gy(t,e){await Xa().rename(t,e)}async function Qy(t,e){const n=Xa();try{const s=await n.list(t);for(const r of s.files)Jy(r)&&!e(r)&&await n.remove(r)}catch{}}function Zy(t){if(t.length<12||!(t[4]===102&&t[5]===116&&t[6]===121&&t[7]===112))return null;const n=String.fromCharCode(t[8],t[9],t[10],t[11]);if(n.startsWith("M4A"))return"m4a";if(n.startsWith("M4V"))return"m4v";if(n==="qt ")return"mov";switch(n){case"mp42":case"isom":case"iso2":case"mp41":case"dash":case"M4B ":case"M4P ":return"mp4";default:return"mp4"}}function ew(t){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:[48,38,178,117,142,102,207,17],fileExtension:"wma"},{signature:[35,33,65,77,82,10],fileExtension:"amr"}],n=Math.max(12,...e.map(i=>i.signature.length)),s=new Uint8Array(t,0,Math.min(n,t.byteLength)),r=Zy(s);if(r)return r;for(const{signature:i,mask:a,fileExtension:o}of e){if(i.length>s.length)continue;let l=!0;for(let c=0;c<i.length;c++)if(a){if((s[c]&a[c])!==(i[c]&a[c])){l=!1;break}}else if(s[c]!==i[c]){l=!1;break}if(l)return o}return null}function Ja(t){return t instanceof Error?t.message:String(t)}async function Zf(t){const e=uc(t);try{const n=await _.requestUrl({url:e,method:"GET"});if(n.status!==200)throw new Error("Could not download episode.");const s=n.arrayBuffer,r=n.headers["content-type"]??n.headers["Content-Type"]??"";return{data:s,contentType:r,byteLength:s.byteLength}}catch(n){throw new Error(`Failed to download ${t}:
|
||
|
||
${Ja(n)}`)}}function Nu(t){return t.split("/").slice(0,-1).join("/")}const Ao=new Map,Co=new Set;function Ru(t,e,n,s){const r=nh(t,n,s)??"mp3";if(!lw(s,r,t.mediaType))throw new Error("Not a playable media file");return{extension:r,filePath:dc(e,t,r)}}async function tw(t,e,n){const{app:s}=T(re),r=ls(t.streamUrl);if(r){const f=dc(e,t,r),h=s.vault.getAbstractFileByPath(f);if(h instanceof _.TFile)return et.addEpisode(t,f,h.stat.size),f}const i=Xa();if(!(typeof i.writeBinary=="function"&&typeof i.appendBinary=="function")){const{data:f,contentType:h}=await Zf(t.streamUrl),{extension:m,filePath:g}=Ru(t,e,f,h);return await rw({episode:t,downloadPathTemplate:e,data:f,extension:m}),g}const o=await Wy(t.streamUrl),{filePath:l}=Ru(t,e,o.firstChunk,o.contentType),c=s.vault.getAbstractFileByPath(l);if(c instanceof _.TFile)return et.addEpisode(t,l,c.stat.size),l;await Ei(Nu(l));const u=Xy(l);Co.add(u);let d=!1;try{await Qy(Nu(l),h=>Co.has(h));const f=await Ky(t.streamUrl,u,o,n);if(o.totalSize!==null&&f!==o.totalSize)throw new Error(`Incomplete download: got ${f} of ${o.totalSize} bytes.`);return await Gy(u,l),d=!0,et.addEpisode(t,l,f),l}finally{d||await th(u),Co.delete(u)}}async function eh(t,e){const{doc:n,update:s}=nw(`Download "${t.title}"`),r=999999999,i=new _.Notice(n,r),a=()=>s(o=>o.createEl("p",{text:`Successfully downloaded "${t.title}" from ${t.podcastName}.`}));try{const o=`${t.podcastName}\0${t.title}`,l=Ao.get(o);if(l){s(u=>u.createEl("p",{text:"Already downloading this episode..."})),await l,a();return}s(u=>u.createEl("p",{text:"Starting download..."}));const c=tw(t,e,(u,d)=>{const f=(u/1048576).toFixed(1),h=d&&d>0?` ${Math.round(u/d*100)}%`:"";s(m=>m.createEl("p",{text:`Downloading...${h} (${f} MB)`}))});Ao.set(o,c);try{await c}finally{Ao.delete(o)}a()}catch(o){throw s(l=>{l.createEl("p",{text:`Download failed: ${Ja(o)}`}).setCssStyles({fontStyle:"italic"})}),o}finally{window.setTimeout(()=>i.hide(),1e4)}}function nw(t){const e=new DocumentFragment,n=e.createDiv();n.setCssStyles({width:"100%",display:"flex"}),n.createEl("span",{text:t}).setCssStyles({textAlign:"center",fontWeight:"bold",marginBottom:"0.5em"});const r=e.createDiv();return r.setCssStyles({display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"}),{doc:e,update:(i,a=!0)=>{a&&r.empty(),i(r)}}}function sw(t,e){const s=Bf(t,e).split("/"),r=s.length-1;return s[r].trim()===""&&(s[r]=Ds(e.title)||"episode"),s.filter((i,a)=>a===r||i.trim()!=="").join("/")}function dc(t,e,n){const s=sw(t,e);return $r(`${s}.${n}`,`.${n}`)}async function rw({episode:t,downloadPathTemplate:e,data:n,extension:s}){const{app:r}=T(re),i=dc(e,t,s),a=i.split("/").slice(0,-1).join("/");await Ei(a);try{await r.vault.createBinary(i,n)}catch(o){throw new Error(`Failed to write file "${i}": ${Ja(o)}`)}et.addEpisode(t,i,n.byteLength)}async function iw(t){const e=et.removeEpisode(t);e&&await th(e)}async function th(t){if(!t)return;const{app:e}=T(re);try{const n=e.vault.getAbstractFileByPath(t);if(n instanceof _.TFile){await e.vault.delete(n);return}const{adapter:s}=e.vault;await s.exists(t)&&await s.remove(t)}catch{}}function aw(t){const{app:e}=T(re),n=et.getEpisode(t),s=[t.filePath,n?.filePath,ow(t.url)];for(const r of s){if(!r)continue;const i=e.vault.getAbstractFileByPath(r);if(i instanceof _.TFile)return i.path}return null}function ow(t){if(!t)return null;const{app:e}=T(re),n=t.trim();if(!n)return null;const s=n.match(/^\[\[(.*)\]\]$/)?.[1]??n,[r]=s.split("|"),i=r?.trim();if(!i)return null;const a=e.vault.getAbstractFileByPath(i);if(a instanceof _.TFile)return a.path;const o=e.metadataCache?.getFirstLinkpathDest(i,"");return o instanceof _.TFile?o.path:null}function nh(t,e,n){const s=Vy(n);if(fi(n)==="video"&&s)return s;const r=ls(t.streamUrl);if(as(r)==="video"&&!qs(r))return r;const i=ew(e);if(i){const a=fi(n)==="audio"||t.mediaType==="audio";return rh(i,a?"audio":void 0)??i}return s||r||null}function sh(t){const e=t.split(";")[0].trim().toLowerCase();return e?e.startsWith("text/")||e==="application/json"||e==="application/xml"||e.endsWith("+xml")||e.endsWith("+json"):!1}function lw(t,e,n){if(sh(t))return!1;const s=t.toLowerCase(),r=fi(s);return r==="video"||s===""&&n==="video"?as(e)==="video":s===""||r==="audio"||Ry(e)}function cw(t,e,n){if(sh(t))return!1;const s=fi(t);return s?s==="audio"||Fu(e,n):t.toLowerCase()===""||as(e)==="audio"||Fu(e,n)}function Fu(t,e){return e==="audio"&&qs(t)}function rh(t,e){return e==="audio"&&t?.toLowerCase()==="mp4"?"m4a":t}async function uw(t){const{app:e}=T(re),n=Ka(t);if(n!=="audio")throw new Error("Transcription supports audio episodes only.");const s=dw(t,n);if(sc(t)){const i=aw(t);if(!i)throw new Error(`Unable to locate the local audio file for "${t.title}". Try playing the file again.`);return Mu(i,n)}const r=et.getEpisode(t);if(r?.filePath&&Xf(r.streamUrl,t.streamUrl)){const i=Yf(r,s);if(i!=="audio")throw new Error("Transcription supports audio episodes only.");if(e.vault.getAbstractFileByPath(r.filePath)instanceof _.TFile)return Mu(r.filePath,i)}try{const{data:i,contentType:a}=await Zf(t.streamUrl),o=nh(t,i,a);if(!cw(a,o,s))throw new Error(`The downloaded file is not audio (received "${a}"). The episode may be unavailable or require re-authentication.`);return{buffer:i,extension:rh(o,s)??"mp3",basename:Ds(t.title)||"episode"}}catch(i){throw new Error(`Failed to fetch ${t.title}: ${Ja(i)}`)}}function dw(t,e){if(e==="audio")return t.mediaType==="audio"||qs(ls(t.streamUrl))?"audio":void 0}async function Mu(t,e){const{app:n}=T(re),s=n.vault.getAbstractFileByPath(t);if(!(s instanceof _.TFile))throw new Error(`Unable to read the audio file at "${t}".`);const r=s.extension||ls(s.path||t)||"";if((e==="audio"&&(r.toLowerCase()==="mp4"||r.toLowerCase()==="webm")?"audio":as(r)??Ea(s.path||t))!=="audio")throw new Error(`Unable to read the non-audio file at "${t}".`);return{buffer:await n.vault.readBinary(s),extension:e==="audio"&&r.toLowerCase()==="mp4"?"m4a":r,basename:s.basename||fw(s.path||t)}}function fw(t){const e=t.split("/").pop()??t,n=e.lastIndexOf(".");return n>0?e.slice(0,n):e}async function ih(t){const e=new URL("https://itunes.apple.com/search?");e.searchParams.append("term",t),e.searchParams.append("media","podcast"),e.searchParams.append("limit","3"),e.searchParams.append("kind","podcast");try{return((await lc(e.href,{timeoutMs:15e3})).json.results||[]).map(r=>({title:r.collectionName,url:r.feedUrl,artworkUrl:r.artworkUrl100,collectionId:r.collectionId}))}catch(n){const s=n instanceof Error?n.message:String(n);throw n instanceof Error?n:new Error(s)}}const To=t=>(t??"").trim().replace(/\/+$/,"").toLowerCase();async function hw(t,e){const n=T(Et),s=To(e),r=(s?Object.values(n).find(o=>To(o.url)===s):void 0)??n[t]??Object.values(n).find(o=>o.title===t);if(r?.collectionId)return r.collectionId;const i=await ih(t);return((s?i.find(o=>To(o.url)===s):void 0)??i.find(o=>o.title===t))?.collectionId}async function pw(t){const{title:e,itunesTitle:n,podcastName:s,feedUrl:r}=t.podcast;let i;try{const a=await hw(s,r);if(!a){new _.Notice(`Could not find "${s}" on Apple Podcasts to build a universal link.`);return}const o=`https://pod.link/${a}.json?limit=1000`,l=await _.requestUrl({url:o});if(l.status!==200)throw new Error(`Failed to get response from pod.link: ${o}`);const c=n??e,u=l.json.episodes.find(d=>d.title===c);if(!u){new _.Notice(`Could not find episode "${c}" on pod.link to build a universal link.`);return}i=`https://pod.link/${a}/episode/${u.episodeId}`}catch{new _.Notice("Could not get podcast link.");return}if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(i),new _.Notice("Universal episode link copied to clipboard.")}catch{new _.Notice(`Could not copy to clipboard. Episode link: ${i}`)}else new _.Notice(`Clipboard unavailable. Episode link: ${i}`)}function mw(t){const e=()=>!!t.api.podcast&&!!t.settings.timestamp.template,n=(r,i)=>{const a=r.getCursor("from"),o=jf(i,{getLine:l=>r.getLine(l),lineCount:r.lineCount(),cursorLine:a.line});r.replaceSelection(o)},s=(r,i)=>{const a=xy(t.api.currentTime,i,t.settings.timestamp.offset??0);if(!a){new _.Notice("Play more of the episode before capturing a segment");return}const o=xa(ky(t.settings.timestamp.template),{segment:a});n(r,o)};t.addCommand({id:"podnotes-show-leaf",name:"Show player",icon:"podcast",callback:()=>{t.activateView()}}),t.addCommand({id:"start-playing",name:"Play Podcast",icon:"play-circle",checkCallback:r=>{if(r)return!t.api.isPlaying&&!!t.api.podcast;t.api.start()}}),t.addCommand({id:"stop-playing",name:"Stop Podcast",icon:"stop-circle",checkCallback:r=>{if(r)return t.api.isPlaying&&!!t.api.podcast;t.api.stop()}}),t.addCommand({id:"skip-backward",name:"Skip Backward",icon:"skip-back",checkCallback:r=>{if(r)return!!t.api.podcast;t.api.skipBackward()}}),t.addCommand({id:"skip-forward",name:"Skip Forward",icon:"skip-forward",checkCallback:r=>{if(r)return!!t.api.podcast;t.api.skipForward()}}),t.addCommand({id:"download-playing-episode",name:"Download Playing Episode",icon:"download",checkCallback:r=>{if(r)return!!t.api.podcast;const i=t.api.podcast;eh(i,t.settings.download.path).catch(a=>{})}}),t.addCommand({id:"reorder-queue",name:"Reorder Queue",icon:"list-ordered",checkCallback:r=>{if(r)return T(pe).episodes.length>1;new pv(t.app).open()}}),t.addCommand({id:"capture-timestamp",name:"Capture Timestamp",icon:"clock",editorCallback:r=>{t.captureTimestamp(r)||new _.Notice("Play an episode and set a Capture timestamp format in settings to capture a timestamp.")}}),t.addCommand({id:"capture-segment-10s",name:"Capture Last 10 Seconds",icon:"scissors",editorCheckCallback:(r,i)=>{if(r)return e();s(i,10)}}),t.addCommand({id:"capture-segment-20s",name:"Capture Last 20 Seconds",icon:"scissors",editorCheckCallback:(r,i)=>{if(r)return e();s(i,20)}}),t.addCommand({id:"create-podcast-note",name:"Create episode note",icon:"file-plus",checkCallback:r=>{if(r)return!!t.api.podcast&&!!t.settings.note.path&&!!t.settings.note.template;Hf(t.api.podcast)}}),t.addCommand({id:"create-podcast-feed-note",name:"Create podcast feed note",icon:"file-plus",checkCallback:r=>{const i=Object.values(T(Et)),a=i.length>0&&!!t.settings.feedNote.path&&!!t.settings.feedNote.template;if(r)return a;if(!a)return;const o=By(i,t.api.podcast?.podcastName);new Uy(t.app,o,l=>{Gf(l)}).open()}}),t.addCommand({id:"get-share-link-episode",name:"Copy universal episode link to clipboard",icon:"share",checkCallback:r=>{if(r)return!!t.api.podcast;pw(t.api)}}),t.addCommand({id:"podnotes-toggle-playback",name:"Toggle playback",icon:"play",checkCallback:r=>{if(r)return!!t.api.podcast;t.api.togglePlayback()}}),t.addCommand({id:"increase-playback-rate",name:"Increase playback rate",icon:"gauge",checkCallback:r=>{if(r)return!!t.api.podcast;t.api.increasePlaybackRate()}}),t.addCommand({id:"decrease-playback-rate",name:"Decrease playback rate",icon:"gauge",checkCallback:r=>{if(r)return!!t.api.podcast;t.api.decreasePlaybackRate()}}),t.addCommand({id:"reset-playback-rate",name:"Reset playback rate",icon:"rotate-ccw",checkCallback:r=>{if(r)return!!t.api.podcast;t.api.resetPlaybackRate()}}),t.addCommand({id:"podnotes-transcribe",name:"Transcribe current episode",checkCallback:r=>{const i=!!t.api.podcast&&Ka(t.api.podcast)==="audio";if(r)return i;i&&t.getTranscriptionService().transcribeCurrentEpisode()}})}function ah(t,e){const n=ka(e,t);return $r(n,ly(n))}const gw=15,Du=t=>Number.isFinite(t)&&t>0?t:gw,vw=(t,e=1)=>{const n=Number.isFinite(e)?Math.min(1,Math.max(0,e)):1;return Number.isFinite(t)?Math.min(1,Math.max(0,t)):n};class yw{get podcast(){return T(vt)}get transcript(){return this.getTranscript()}get length(){return T(bs)}get currentTime(){return T(ut)}set currentTime(e){Gt.set(null),ut.update(n=>e)}get isPlaying(){return!T(rt)}get volume(){return T(zn)}set volume(e){zn.set(vw(e,T(zn)))}get playbackRate(){return T(Zn)}set playbackRate(e){Zn.set(Ms(e,this.defaultPlaybackRate))}getPodcastTimeFormatted(e,n=!1,s=0){if(!this.podcast)throw new Error("No podcast loaded");const r=Math.max(0,this.currentTime-s),i=ft(r,e);if(!n)return i;const a=this.getEpisodeLinkTarget();if(!a||a==="")return i;const o=bl(this.podcast.title,a,r);return`[${i}](${o.href})`}getPodcastSegmentFormatted(e,n,s,r=!1){if(!this.podcast)throw new Error("No podcast loaded");const i=zf(n,s),a=i?$u(i.startTime,i.endTime,e):$u(n,s,e);if(!r||!i)return a;const o=this.getEpisodeLinkTarget();if(!o||o==="")return a;const l=bl(this.podcast.title,o,i.startTime,i.endTime);return`[${a}](${l.href})`}async getTranscript(e=this.podcast){if(!e)return null;const n=T(re),s=ah(e,n.settings.transcript.path),r=n.app.vault.getAbstractFileByPath(s);return r instanceof _.TFile?await n.app.vault.read(r):null}getEpisodeLinkTarget(){return sc(this.podcast)?et.getEpisode(this.podcast)?.filePath:this.podcast.feedUrl}start(){rt.update(e=>!1)}stop(){rt.update(e=>!0)}togglePlayback(){rt.update(e=>!e)}skipBackward(){const e=Du(T(re).settings.skipBackwardLength);this.currentTime=Math.max(0,this.currentTime-e)}skipForward(){const e=Du(T(re).settings.skipForwardLength),n=this.currentTime+e,s=this.length;this.currentTime=s>0?Math.max(this.currentTime,Math.min(n,s-.25)):n}increasePlaybackRate(){Zn.update(e=>gu(e,cl))}decreasePlaybackRate(){Zn.update(e=>gu(e,-cl))}resetPlaybackRate(){this.playbackRate=this.defaultPlaybackRate}get defaultPlaybackRate(){return Ms(T(re).settings.defaultPlaybackRate)}}const ww=["openai","deepgram"],bw="gpt-4o-transcribe-diarize",_w="";function xw(t){return t==null||t===_w?ht.download.path:t}function kw(t){const e=t?.path??"",n=t?.template??"";return e===""&&n===""?{path:ht.note.path,template:ht.note.template}:{path:e,template:n}}function oh(t){const e=ht.transcript,n=t??{},s=n.diarization??{};return{path:typeof n.path=="string"?n.path:e.path,template:typeof n.template=="string"?n.template:e.template,diarization:{enabled:typeof s.enabled=="boolean"?s.enabled:e.diarization.enabled,provider:Ew(s.provider),speakerTemplate:typeof s.speakerTemplate=="string"?s.speakerTemplate:e.diarization.speakerTemplate}}}function Ew(t){return ww.includes(t)?t:ht.transcript.diarization.provider}function Sw(t){const e=t??{};return{path:typeof e.path=="string"?e.path:ht.feedNote.path,template:typeof e.template=="string"?e.template:ht.feedNote.template}}function Lu(t,e){const n=typeof t=="number"?t:Number(t);return Number.isFinite(n)&&n>0?Math.floor(n):e}function Aw(t){try{return new URL(t)}catch{return null}}var Cw=J("<span></span>");function fc(t,e){Te(e,!1);let n=B(e,"value",12,""),s=B(e,"disabled",8,!1),r=B(e,"placeholder",8,""),i=B(e,"type",8,"text"),a=B(e,"el",12,null),o=V();const l=it();let c=V(),u=B(e,"style",24,()=>({})),d=null,f=null,h=!1;An(()=>{E(c,new _.TextComponent(p(o)))}),Wa(()=>{p(c)?.inputEl&&d&&p(c).inputEl.removeEventListener("input",d)});function m(w){if(h)return;const P=w.target?.value??"";n(P),l("input",{value:P})}function g(w){h||(n(w),l("change",{value:w}))}function y(w){!w?.inputEl||d||(f=g,w.onChange(f),d=m,w.inputEl.addEventListener("input",d))}function b(w,k,P,S,A,$){const R=typeof w.getValue=="function"?w.getValue():w.inputEl?.value;k!==void 0&&R!==k&&(h=!0,w.setValue(k),h=!1),w?.inputEl&&(w.inputEl.disabled!==P&&w.setDisabled(P),S&&w.inputEl.placeholder!==S&&w.setPlaceholder(S),w.inputEl.type!==A&&(w.inputEl.type=A),$&&w.inputEl.setAttr("style",Pr($)),a(w.inputEl))}ge(()=>(p(c),L(n()),L(s()),L(r()),L(i()),L(u())),()=>{p(c)&&(y(p(c)),b(p(c),n(),s(),r(),i(),u()))}),yt(),Re();var v=Cw();an(v,w=>E(o,w),()=>p(o)),j(t,v),Pe()}var Tw=J("<span></span>");function hi(t,e){Te(e,!1);let n=B(e,"text",8,""),s=B(e,"tooltip",8,""),r=B(e,"ariaLabel",8,""),i=B(e,"icon",8,void 0),a=B(e,"disabled",8,!1),o=B(e,"warning",8,!1),l=B(e,"cta",8,!1),c=V(),u=B(e,"class",8),d=B(e,"style",8),f;const h=it();An(()=>m(p(c))),df(()=>g(f));function m(b){f=new _.ButtonComponent(b),g(f)}function g(b){n()&&b.setButtonText(n()),s()&&b.setTooltip(s()),i()&&b.setIcon(i()),a()&&b.setDisabled(a()),o()?b.setWarning():b.buttonEl.classList.remove("mod-warning"),u()&&b.setClass(u()),l()?b.setCta():b.removeCta(),b.onClick(v=>{h("click",{event:v})}),d()&&b.buttonEl.setAttr("style",Pr(d())),r()?b.buttonEl.setAttr("aria-label",r()):b.buttonEl.removeAttribute("aria-label")}Re();var y=Tw();an(y,b=>E(c,b),()=>p(c)),j(t,y),Pe()}const Pw=t=>t;function lh(t,{delay:e=0,duration:n=400,easing:s=Pw}={}){const r=+getComputedStyle(t).opacity;return{delay:e,duration:n,easing:s,css:i=>`opacity: ${i*r}`}}var $w=J('<div class="podcast-result-card svelte-bw0itx"><div class="podcast-artwork-container svelte-bw0itx"><img class="podcast-artwork svelte-bw0itx"/></div> <div class="podcast-info svelte-bw0itx"><h3 class="podcast-title svelte-bw0itx"> </h3></div> <div class="podcast-actions svelte-bw0itx"><!></div></div>');const Iw={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;}
|
||
|
||
/*
|
||
* The Add/Remove control uses Obsidian's native call-to-action / warning
|
||
* button styling with a text label. A label is always visible and is sized
|
||
* correctly per platform (Obsidian renders larger buttons on mobile/iPad),
|
||
* unlike the previous icon-only button whose glyph failed to render on iPad
|
||
* and left an empty, unrecognisable tap target — the root cause of #109.
|
||
*/.podcast-actions.svelte-bw0itx {display:flex;align-items:center;flex-shrink:0;}`};function Nw(t,e){Te(e,!1),Le(t,Iw);let n=B(e,"podcast",8),s=B(e,"isSaved",8,!1);const r=it();Re();var i=$w(),a=F(i),o=F(a),l=W(a,2),c=F(l),u=F(c),d=W(l,2),f=F(d);{var h=g=>{{let y=ke(()=>(L(n()),O(()=>`Remove ${n().title} podcast`)));hi(g,{text:"Remove",warning:!0,get ariaLabel(){return p(y)},$$events:{click:()=>r("removePodcast",{podcast:n()})}})}},m=g=>{{let y=ke(()=>(L(n()),O(()=>`Add ${n().title} podcast`)));hi(g,{text:"Add",cta:!0,get ariaLabel(){return p(y)},$$events:{click:()=>r("addPodcast",{podcast:n()})}})}};ue(f,g=>{s()?g(h):g(m,!1)})}we(()=>{le(o,"src",(L(n()),O(()=>n().artworkUrl))),le(o,"alt",(L(n()),O(()=>`Artwork for ${n().title}`))),Ae(u,(L(n()),O(()=>n().title)))}),uf(3,i,()=>lh,()=>({duration:300})),j(t,i),Pe()}var Rw=J('<div class="podcast-query-status svelte-8ek8i8" role="status" aria-live="polite">Searching...</div>'),Fw=J('<div class="podcast-query-status podcast-query-error svelte-8ek8i8" role="alert"> </div>'),Mw=J('<div class="podcast-query-status svelte-8ek8i8" role="status" aria-live="polite">No results.</div>'),Dw=J('<div role="listitem"><!></div>'),Lw=J('<div class="podcast-query-container svelte-8ek8i8"><!> <!> <div class="podcast-query-results svelte-8ek8i8" role="list" aria-label="Podcast search results"></div></div>');const Ow={hash:"svelte-8ek8i8",code:`.podcast-query-container.svelte-8ek8i8 {margin-bottom:1.5rem;}.podcast-query-status.svelte-8ek8i8 {margin-bottom:0.75rem;font-size:0.85rem;color:var(--text-muted);}.podcast-query-error.svelte-8ek8i8 {color:var(--text-error);}.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 Bw(t,e){Te(e,!1),Le(t,Ow);const n=()=>Ne(Et,"$savedFeeds",r),s=()=>Ne(Wg,"$podcastsUpdated",r),[r,i]=Tr();let a=V([]),o=V("grid-3"),l=V(""),c=V(!1),u=V(""),d=V();An(()=>{f(),p(d)&&p(d).focus()});function f(){p(l).trim()===""&&E(a,Object.values(n()))}const h=_.debounce(async({detail:{value:S}})=>{E(l,S),E(u,"");const A=Aw(S);if((A?.protocol==="http:"||A?.protocol==="https:")&&A){E(c,!0);try{const R=await new Ai().getFeed(A.href);E(a,[R])}catch(R){E(a,[]);const K=R instanceof Error?R.message:String(R);E(u,`Could not load feed: ${K}`),new _.Notice(p(u))}finally{E(c,!1)}}else if(S.trim()==="")f();else{E(c,!0);try{E(a,await ih(S))}catch{E(a,[]),E(u,"Could not search podcasts. Please try again.")}finally{E(c,!1)}}},300,!0);function m(S){const{podcast:A}=S.detail;Et.update($=>({...$,[A.title]:A})),f()}function g(S){const{podcast:A}=S.detail;Et.update($=>{const R={...$};return delete R[A.title],R}),f()}ge(()=>(p(l),n(),s()),()=>{p(l).trim()===""&&E(a,Object.values(n())),s()}),ge(()=>p(a),()=>{p(a).length%3===0||p(a).length>3?E(o,"grid-3"):p(a).length%2===0?E(o,"grid-2"):p(a).length%1===0&&E(o,"grid-1")}),yt(),Re();var y=Lw(),b=F(y);fc(b,{placeholder:"Search or enter feed URL...",style:{width:"100%","margin-bottom":"1rem"},get el(){return p(d)},set el(S){E(d,S)},$$events:{change:h},$$legacy:!0});var v=W(b,2);{var w=S=>{var A=Rw();j(S,A)},k=S=>{var A=pt(),$=Ve(A);{var R=Z=>{var ee=Fw(),be=F(ee);we(()=>Ae(be,p(u))),j(Z,ee)},K=Z=>{var ee=pt(),be=Ve(ee);{var me=D=>{var Y=Mw();j(D,Y)};ue(be,D=>{p(l),p(a),O(()=>p(l).trim()!==""&&p(a).length===0)&&D(me)},!0)}j(Z,ee)};ue($,Z=>{p(u)?Z(R):Z(K,!1)},!0)}j(S,A)};ue(v,S=>{p(c)?S(w):S(k,!1)})}var P=W(v,2);Rs(P,5,()=>p(a),S=>S.url,(S,A)=>{var $=Dw(),R=F($);{let K=ke(()=>(p(A),n(),O(()=>typeof p(A).url=="string"&&n()[p(A).title]?.url===p(A).url)));Nw(R,{get podcast(){return p(A)},get isSaved(){return p(K)},$$events:{addPodcast:m,removePodcast:g}})}j(S,$)}),uf(3,y,()=>lh,()=>({duration:300})),j(t,y),Pe(),i()}var Uw=J('<button type="button"><!></button>'),jw=J('<div class="playlist-item svelte-jzsw7l"><div class="playlist-item-left svelte-jzsw7l"><!> <span class="playlist-name svelte-jzsw7l"> </span> <span class="playlist-count svelte-jzsw7l"> </span></div> <div class="playlist-item-controls svelte-jzsw7l"><!></div></div>');const zw={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 Po(t,e){Te(e,!1),Le(t,zw);let n=B(e,"playlist",8),s=B(e,"showDeleteButton",8,!0),r=V(!1);const i=it();function a(){if(p(r)){i("delete",{value:n()});return}E(r,!0),setTimeout(()=>{E(r,!1)},2e3)}ge(()=>L(n()),()=>{n()&&E(r,!1)}),yt(),Re();var o=jw(),l=F(o),c=F(l);Ce(c,{get icon(){return L(n()),O(()=>n().icon)},clickable:!1,size:18});var u=W(c,2),d=F(u),f=W(u,2),h=F(f),m=W(l,2),g=F(m);{var y=b=>{var v=Uw();let w;var k=F(v);{let P=ke(()=>p(r)?"check":"trash");Ce(k,{get icon(){return p(P)},clickable:!1,size:16})}we(()=>{w=sn(v,1,"delete-button svelte-jzsw7l",null,w,{confirm:p(r)}),le(v,"aria-label",p(r)?"Confirm deletion":"Delete playlist")}),oe("click",v,a),j(b,v)};ue(g,b=>{s()&&b(y)})}we(()=>{Ae(d,(L(n()),O(()=>n().name))),Ae(h,`(${L(n()),O(()=>n().episodes.length)??""})`)}),j(t,o),Pe()}var qw=J("<span></span>");function Hw(t,e){Te(e,!1);let n=B(e,"value",8,""),s=B(e,"options",24,()=>({})),r=B(e,"disabled",8,!1),i=V(),a=V(),o=B(e,"style",8);const l=it();An(()=>{E(a,new _.DropdownComponent(p(i))),u(p(a))});function c(f){return typeof f.getValue=="function"?f.getValue():f.selectEl?.value}function u(f){s()&&f.addOptions(s()),n()&&f.setValue(n()),r()&&f.setDisabled(r()),f.onChange(h=>{l("change",{value:h})}),o()&&f.selectEl.setAttr("style",Pr(o()))}ge(()=>(p(a),L(n())),()=>{p(a)&&n()!==void 0&&c(p(a))!==n()&&p(a).setValue(n())}),yt(),Re();var d=qw();an(d,f=>E(i,f),()=>p(i)),j(t,d),Pe()}const $o=["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","lucide-clock","lucide-cloud","lucide-cross","lucide-folder","lucide-info","lucide-languages","lucide-link","lucide-pencil","lucide-pin","lucide-search","lucide-star","lucide-trash"];var Vw=J('<div class="playlist-manager-container svelte-w5in4v"><div class="playlist-list svelte-w5in4v"><!> <!> <!></div> <div class="add-playlist-container svelte-w5in4v"><!> <!> <!></div></div>');const Ww={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 Kw(t,e){Te(e,!1),Le(t,Ww);const n=()=>Ne(pe,"$queue",r),s=()=>Ne(Ft,"$favorites",r),[r,i]=Tr();let a=V([]),o=V(""),l=$o.reduce((S,A)=>(S[A]=A,S),{}),c=V($o[0]);An(()=>{const S=mt.subscribe(A=>{E(a,Object.values(A))});return()=>{S()}});function u(){const S=p(o).trim();if(!S){new _.Notice("Playlist name cannot be empty.");return}if(new Set([T(pe).name,T(Ft).name,T(Vt).name,Zi.name]).has(S)){new _.Notice(`"${S}" is a reserved playlist name.`);return}if(Object.prototype.hasOwnProperty.call(T(mt),S)){new _.Notice("A playlist with that name already exists.");return}mt.update($=>($[S]={name:S,icon:p(c),episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},$)),E(o,""),E(c,$o[0])}function d(S){E(c,S.detail.value)}function f(S){mt.update(A=>(delete A[S.detail.value.name],A))}Re();var h=Vw(),m=F(h),g=F(m);Po(g,{get playlist(){return n()},showDeleteButton:!1});var y=W(g,2);Po(y,{get playlist(){return s()},showDeleteButton:!1});var b=W(y,2);Rs(b,1,()=>p(a),S=>S.name,(S,A)=>{Po(S,{get playlist(){return p(A)},$$events:{delete:f}})});var v=W(m,2),w=F(v);Hw(w,{get options(){return l},get value(){return p(c)},set value(S){E(c,S)},$$events:{change:d},$$legacy:!0});var k=W(w,2);fc(k,{placeholder:"Playlist name",get value(){return p(o)},set value(S){E(o,S)},$$legacy:!0});var P=W(k,2);hi(P,{text:"Add",cta:!0,ariaLabel:"Add playlist",$$events:{click:u}}),j(t,h),Pe(),i()}function Yw(t,e){const n=e.toLowerCase();for(let s=0;s<t.attributes.length;s++){const r=t.attributes.item(s);if(r&&r.name.toLowerCase()===n){const i=r.value?.trim();return i||null}}return null}function Xw(t,e){let n=e;const s=Date.now();let r,i;const a=new _.Notice(e,0);function o(d){return`${t} (${c()}):
|
||
|
||
${d}`}function l(d){n=d,a.setMessage(o(n))}function c(){return Jw(r?r-s:Date.now()-s)}function u(){i!==void 0&&(window.clearInterval(i),i=void 0)}return i=window.setInterval(()=>{a.setMessage(o(n))},1e3),{update:l,hide:()=>{u(),a.hide()},stop:()=>{r=Date.now(),u()}}}function Jw(t){const e=Math.floor(t/1e3),n=Math.floor(e/60);return`${Math.floor(n/60).toString().padStart(2,"0")}:${(n%60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`}async function Gw(t){try{const n=new DOMParser().parseFromString(t,"application/xml");if(n.querySelector("parsererror"))throw new Error("Invalid XML format");const s=n.querySelectorAll("outline[text]"),r=[];for(let h=0;h<s.length;h++){const m=s.item(h),g=m.getAttribute("text"),y=Yw(m,"xmlUrl");!g||!y||r.push({title:g,url:y})}if(r.length===0)throw new Error("No valid podcast entries found in OPML");const i=T(Et),a=r.filter(h=>!Object.values(i).some(m=>m.url===h.url)),o=Xw("Importing podcasts","Preparing to import...");let l=0;const c=()=>{const h=(l/a.length*100).toFixed(1);o.update(`Importing... ${l}/${a.length} podcasts completed (${h}%)`)};c();const u=await Promise.all(a.map(async h=>{try{const m=await new Ai().getFeed(h.url);return l++,c(),m}catch{return l++,c(),null}}));o.stop();const d=u.filter(h=>h!==null);Et.update(h=>{for(const m of d)h[m.title]||(h[m.title]=structuredClone(m));return h});const f=r.length-a.length;if(o.update(`OPML import complete. Saved ${d.length} new podcasts. Skipped ${f} existing podcasts.`),d.length!==a.length){const h=a.length-d.length;new _.Notice(`Failed to import ${h} podcasts. Check console for details.`,1e4)}window.setTimeout(()=>o.hide(),5e3)}catch(e){new _.Notice(`Error importing OPML: ${e instanceof Error?e.message:"Unknown error"}`,1e4)}}async function Qw(t,e,n="PodNotes_Export.opml"){const s='<?xml version="1.0" encoding="utf-8" standalone="no"?>',r=f=>`<opml version="1.0">${f}</opml>`,i=f=>`<head>${f}</head>`,a="<title>PodNotes Feeds</title>",o=f=>`<body>${f}</body>`,l=f=>f.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,"""),c=f=>`<outline text="${l(f.title)}" type="rss" xmlUrl="${l(f.url)}" />`,u=f=>`<outline text="feeds">${e.map(c).join("")}</outline>`,d=s+r(`${i(a)}
|
||
${o(u())}`);try{await t.vault.create(n,d),new _.Notice(`Exported ${e.length} podcast feeds to file "${n}".`)}catch(f){f instanceof Error?f.message.includes("Folder does not exist")?new _.Notice("Unable to create export file: Folder does not exist."):new _.Notice(`Unable to create podcast export file:
|
||
|
||
${f.message}`):new _.Notice("An unexpected error occurred during export.")}}const ni="podnotes:feed-cache:v5",Zw=["podnotes:feed-cache:v1","podnotes:feed-cache:v2","podnotes:feed-cache:v3","podnotes:feed-cache:v4"],eb=1e3*60*60*6,tb=75,Ou=4*1024*1024;let Je=null;function ch(){let t;try{t=typeof window<"u"?window.localStorage:null}catch{t=null}if(t)for(const e of Zw)try{t.removeItem(e)}catch{}}function hc(){const t=T(re)?.app;if(t&&typeof t.loadLocalStorage=="function"&&typeof t.saveLocalStorage=="function")return{getItem:e=>{const n=t.loadLocalStorage(e);return typeof n=="string"?n:null},setItem:(e,n)=>t.saveLocalStorage(e,n),removeItem:e=>t.saveLocalStorage(e,null)};try{return typeof window<"u"&&window.localStorage?window.localStorage:null}catch{return null}}function uh(){if(Je)return Je;ch();const t=hc();if(!t)return Je={},Je;try{const e=t.getItem(ni);return e?(Je=JSON.parse(e),Je):(Je={},Je)}catch{return Je={},Je}}function nb(t,e){const n=Object.entries(t);n.sort((i,a)=>i[1].updatedAt-a[1].updatedAt);const s={};let r=0;for(let i=n.length-1;i>=0;i--){const[a,o]=n[i],l=JSON.stringify({[a]:o}).length;r+l<=e&&(s[a]=o,r+=l)}return s}function dh(){const t=hc();if(!(!t||!Je))try{let e=JSON.stringify(Je);e.length>Ou&&(Je=nb(Je,Ou*.8),e=JSON.stringify(Je)),t.setItem(ni,e)}catch(e){if(e instanceof DOMException&&(e.name==="QuotaExceededError"||e.name==="NS_ERROR_DOM_QUOTA_REACHED"))try{Je={},t.setItem(ni,"{}")}catch{t.removeItem(ni)}}}function sb(t){return{...t,episodeDate:t.episodeDate?.toISOString()}}function rb(t){if(!t.episodeDate)return 0;const e=new Date(t.episodeDate).getTime();return Number.isNaN(e)?0:e}function ib(t,e){if(t.length<=e)return t;const n=new Set(t.map((s,r)=>({index:r,time:rb(s)})).sort((s,r)=>r.time-s.time).slice(0,e).map(s=>s.index));return t.filter((s,r)=>n.has(r))}function ab(t){return{...t,episodeDate:t.episodeDate?new Date(t.episodeDate):void 0}}function fh(t){return t.url??t.title}function Io(t,e=eb){const n=uh(),s=fh(t),r=n[s];return r?Date.now()-r.updatedAt>e?(delete n[s],dh(),null):r.episodes.map(ab):null}function ob(t,e){if(!e.length)return;const n=uh(),s=fh(t);n[s]={updatedAt:Date.now(),episodes:ib(e,tb).map(sb)},dh()}function lb(){Je={};const t=hc();if(t)try{t.removeItem(ni)}catch{}ch()}const hh="podnotes-settings",ph=1,cb=["podNotes","playedEpisodes","downloadedEpisodes","currentEpisode"],Ga=new Set(["openAIApiKey","diarizationApiKey"]),ub={openAIApiKey:"OpenAI API key",diarizationApiKey:"Deepgram API key"};function Bu(t){return[...Ga].filter(e=>!!t[e]?.trim()).map(e=>ub[e])}const Qa=new Set(["__proto__","constructor","prototype"]),mh=new Set(Object.keys(ht).filter(t=>!cb.includes(t))),gh=["timestamp","note","feedNote","download","transcript","feedCache"];function db(t,e,n,s){const r={};for(const i of Object.keys(t))Qa.has(i)||mh.has(i)&&(Ga.has(i)&&!e.includeSecret||(r[i]=t[i]));return{type:hh,version:ph,pluginVersion:n,exportedAt:s,settings:r}}function fb(t){let e;try{e=JSON.parse(t)}catch{return{ok:!1,error:"File is not valid JSON."}}if(!Sa(e))return{ok:!1,error:"File does not contain a settings object."};let n=e,s=!1,r=null,i=null;if(e.type===hh){if(s=!0,typeof e.version!="number"||!Number.isInteger(e.version)||e.version<1)return{ok:!1,error:"Export file has an invalid version."};if(e.version>ph)return{ok:!1,error:`This file was exported by a newer version of PodNotes (format v${e.version}). Update PodNotes to import it.`};if(r=e.version,typeof e.pluginVersion=="string"&&(i=e.pluginVersion),!Sa(e.settings))return{ok:!1,error:"Export file is missing its settings payload."};n=e.settings}const a=pb(n);return Object.keys(a).length===0?{ok:!1,error:"No recognizable PodNotes settings were found in the file."}:{ok:!0,settings:a,meta:{fromEnvelope:s,version:r,pluginVersion:i,includesSecret:[...Ga].some(o=>o in a)}}}function hb(t,e){const n={...t,...e};for(const s of gh)n[s]={...ht[s],...t[s],...e[s]};return n.transcript=oh(n.transcript),n}function pb(t){const e={};for(const[n,s]of Object.entries(t)){if(Qa.has(n)||!mh.has(n))continue;const r=ht[n];vh(r,s)&&(Ga.has(n)&&s.trim()===""||(gh.includes(n)?e[n]=gb(r,s):n==="favorites"||n==="localFiles"?Array.isArray(s.episodes)&&(e[n]=s):n==="playlists"?e[n]=mb(s):e[n]=s))}return e}function mb(t){const e={};for(const[n,s]of Object.entries(t))Qa.has(n)||Sa(s)&&Array.isArray(s.episodes)&&(e[n]=s);return e}function gb(t,e){const n={};for(const[s,r]of Object.entries(e))Qa.has(s)||s in t&&vh(t[s],r)&&(n[s]=r);return n}function vh(t,e){return t==null?!1:Array.isArray(t)?Array.isArray(e):typeof t=="object"?Sa(e):typeof e==typeof t}function Sa(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}async function vb(t){const{getClient:e,chunkFiles:n,maxRetries:s,onProgress:r}=t,i=await e(),a=[];let o=0,l;for(let c=0;c<n.length;c++){r(`Diarizing with OpenAI... chunk ${c+1}/${n.length}`);const u=n[c];let d=0;for(;;)try{const f=await i.audio.transcriptions.create({model:bw,file:u,response_format:"diarized_json",chunking_strategy:"auto"});a.push(...Og(f));break}catch(f){if(d++,d>=s){o++,l=f,a.push({speaker:"?",text:`[Error diarizing chunk ${c+1}]`});break}await new Promise(h=>window.setTimeout(h,1e3*d))}}if(n.length>0&&o===n.length){const c=l instanceof Error?l.message:String(l);throw new Error(`OpenAI diarization failed for every chunk: ${c}`)}return a}const yb="https://api.deepgram.com/v1/listen",wb="model=nova-3&diarize=true&punctuate=true&smart_format=true&utterances=true";async function bb(t){const{audio:e,apiKey:n,onProgress:s}=t,r=t.request??_.requestUrl;s("Diarizing with Deepgram...");const i=await r({url:`${yb}?${wb}`,method:"POST",headers:{Authorization:`Token ${n}`},contentType:e.mimeType,body:e.buffer,throw:!1});if(i.status<200||i.status>=300){const a=_b(i);throw new Error(`Deepgram request failed (HTTP ${i.status})${a?`: ${a}`:""}`)}return Bg(i.json)}function _b(t){try{const e=t.json;if(e&&typeof e=="object"){const n=e,s=n.err_msg??n.message??n.reason;if(typeof s=="string")return s}}catch{}return typeof t.text=="string"?t.text.slice(0,200):""}function xb(t){const e=t.transcript?.diarization;return e?.enabled&&e.provider==="deepgram"?!!t.diarizationApiKey?.trim():!!t.openAIApiKey?.trim()}function ps(t){t.settingEl.setCssStyles({flexDirection:"column",alignItems:"unset",gap:"10px"})}function ji(t,e){e.empty(),_.MarkdownRenderer.renderMarkdown(t,e,"",new _.Component)}class kb extends _.PluginSettingTab{constructor(e,n){super(e,n),this.podcastQueryGrid=null,this.playlistManager=null,this.plugin=n,this.settingsTab=this}display(){const{containerEl:e}=this;e.empty(),new _.Setting(e).setName("PodNotes").setHeading();const n=e.createDiv();n.classList.add("settings-container"),new _.Setting(n).setName("Search Podcasts").setHeading().setDesc("Search for podcasts by name or custom feed URL.");const s=n.createDiv();this.podcastQueryGrid=va(Bw,{target:s}),new _.Setting(n).setName("Playlists").setHeading().setDesc("Add playlists to gather podcast episodes.");const r=n.createDiv();this.playlistManager=va(Kw,{target:r}),this.addQueueSettings(n),this.addEpisodeListSettings(n),this.addDefaultPlaybackRateSetting(n),this.addDefaultVolumeSetting(n),this.addSkipLengthSettings(n),this.addNoteSettings(n),this.addFeedNoteSettings(n),this.addDownloadSettings(n),this.addPerformanceSettings(n),this.addImportExportSettings(n),this.addTranscriptSettings(n)}hide(){this.podcastQueryGrid&&(ya(this.podcastQueryGrid),this.podcastQueryGrid=null),this.playlistManager&&(ya(this.playlistManager),this.playlistManager=null)}addQueueSettings(e){new _.Setting(e).setName("Keep a queue of episodes you switch away from").setDesc("When on, the episode you switch away from is kept at the top of the queue and playback automatically continues with the next queued episode when one ends. Turn this off to stop the queue from filling and advancing on its own — you can still add episodes to the queue manually.").addToggle(n=>n.setValue(this.plugin.settings.autoQueue).onChange(async s=>{this.plugin.settings.autoQueue=s,await this.plugin.saveSettings(),re.set(this.plugin)}))}addEpisodeListSettings(e){new _.Setting(e).setName("Latest episodes per podcast").setDesc(`How many of each podcast's most recent episodes appear in the Latest Episodes list, and how far back its search reaches. Raise this to find older episodes (1-${ll}; default ${ci}).`).addText(n=>{n.inputEl.type="number",n.inputEl.min="1",n.inputEl.max=`${ll}`,n.setValue(`${ws(this.plugin.settings.episodeListLimit)}`).setPlaceholder(`${ci}`).onChange(async s=>{const r=s.trim();if(r===""||!Number.isFinite(Number(r)))return;const i=ws(r);i!==this.plugin.settings.episodeListLimit&&(this.plugin.settings.episodeListLimit=i,ui.set(i),await this.plugin.saveSettings())}),n.inputEl.addEventListener("blur",()=>{n.setValue(`${ws(this.plugin.settings.episodeListLimit)}`)})})}addDefaultPlaybackRateSetting(e){new _.Setting(e).setName("Default Playback Rate").addSlider(n=>n.setLimits(.5,4,.1).setValue(this.plugin.settings.defaultPlaybackRate).onChange(s=>{this.plugin.settings.defaultPlaybackRate=s,this.plugin.saveSettings()}).setDynamicTooltip())}addDefaultVolumeSetting(e){new _.Setting(e).setName("Default Volume").setDesc("Set the default playback volume.").addSlider(n=>n.setLimits(0,1,.05).setValue(this.plugin.settings.defaultVolume).onChange(s=>{this.plugin.settings.defaultVolume=s,this.plugin.saveSettings()}).setDynamicTooltip())}addSkipLengthSettings(e){new _.Setting(e).setName("Skip backward length (s)").addText(n=>{n.inputEl.type="number",n.setValue(`${this.plugin.settings.skipBackwardLength}`).onChange(s=>{const r=Number.parseInt(s,10);!Number.isFinite(r)||r<=0||(this.plugin.settings.skipBackwardLength=r,this.plugin.saveSettings())}).setPlaceholder("seconds")}),new _.Setting(e).setName("Skip forward length (s)").addText(n=>{n.inputEl.type="number",n.setValue(`${this.plugin.settings.skipForwardLength}`).onChange(s=>{const r=Number.parseInt(s,10);!Number.isFinite(r)||r<=0||(this.plugin.settings.skipForwardLength=r,this.plugin.saveSettings())}).setPlaceholder("seconds")})}addNoteSettings(e){const n=e.createDiv();new _.Setting(n).setName("Note settings").setHeading();const s=new _.Setting(n).setName("Capture timestamp format").setHeading().addTextArea(u=>{u.setValue(this.plugin.settings.timestamp.template),u.setPlaceholder("- {{linktime}} "),u.onChange(d=>{this.plugin.settings.timestamp.template=d,this.plugin.saveSettings(),i(d)}),u.inputEl.setCssStyles({width:"100%"})});ps(s);const r=n.createDiv(),i=u=>{if(!this.plugin.api.podcast){r.setText("Play an episode to preview the timestamp format.");return}const d=xa(u);ji(d,r)};new _.Setting(n).setName("Timestamp offset (s)").setDesc("Subtract this many seconds when capturing a timestamp to compensate for reaction time.").addText(u=>{u.inputEl.type="number",u.setValue(`${this.plugin.settings.timestamp.offset}`).onChange(d=>{const f=Number.parseInt(d,10);this.plugin.settings.timestamp.offset=Number.isNaN(f)?0:Math.max(0,f),this.plugin.saveSettings(),i(this.plugin.settings.timestamp.template)}).setPlaceholder("e.g. 5")}),i(this.plugin.settings.timestamp.template);const a=No(),o=new _.Setting(n).setName("Note creation file path").setHeading().addText(u=>{u.setValue(this.plugin.settings.note.path),u.setPlaceholder("inputs/podcasts/{{podcast}} - {{title}}.md"),u.onChange(d=>{this.plugin.settings.note.path=d,this.plugin.saveSettings();const f=ka(d,a);ji(f,l)}),u.inputEl.setCssStyles({width:"100%"})});ps(o);const l=n.createDiv(),c=new _.Setting(n).setName("Note creation template").setHeading().addTextArea(u=>{u.setValue(this.plugin.settings.note.template),u.onChange(d=>{this.plugin.settings.note.template=d,this.plugin.saveSettings()}),u.inputEl.setCssStyles({width:"100%",height:"25vh"}),u.setPlaceholder(`---
|
||
type: podcastEpisode
|
||
podcast: "{{podcastlink}}"
|
||
url: "{{url}}"
|
||
date: {{date:YYYY-MM-DD}}
|
||
tags:
|
||
- podcastEpisode
|
||
---
|
||
# {{title}}
|
||
|
||

|
||
|
||
{{description}}`)});ps(c)}addFeedNoteSettings(e){const n=e.createDiv();new _.Setting(n).setName("Podcast feed note settings").setHeading(),n.createEl("p",{text:'Create a note for a whole podcast (the feed), not a single episode. Run the "Create podcast feed note" command to pick a saved podcast. Available tags: {{title}}, {{podcast}}, {{url}} (website), {{feedurl}} (RSS), {{artwork}}, {{author}}, {{description}}, {{date}}.'}).setCssStyles({fontSize:"var(--font-ui-smaller)",color:"var(--text-muted)"});const r=Eb(),i=new _.Setting(n).setName("Feed note file path").setHeading().addText(c=>{c.setValue(this.plugin.settings.feedNote.path),c.setPlaceholder("PodNotes/Podcasts/{{podcast}}.md"),c.onChange(u=>{this.plugin.settings.feedNote.path=u,this.plugin.saveSettings(),o(u)}),c.inputEl.setCssStyles({width:"100%"})});ps(i);const a=n.createDiv(),o=c=>{const u=oc(c,r);ji(u,a)};o(this.plugin.settings.feedNote.path);const l=new _.Setting(n).setName("Feed note template").setHeading().addTextArea(c=>{c.setValue(this.plugin.settings.feedNote.template),c.onChange(u=>{this.plugin.settings.feedNote.template=u,this.plugin.saveSettings()}),c.inputEl.setCssStyles({width:"100%",height:"25vh"})});ps(l)}addDownloadSettings(e){new _.Setting(e).setName("Download settings").setHeading();const n=No(),s=new _.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(o=>{o.setValue(this.plugin.settings.download.path),o.setPlaceholder("inputs/podcasts/{{podcast}} - {{title}}"),o.onChange(l=>{this.plugin.settings.download.path=l,this.plugin.saveSettings(),a(l)}),o.inputEl.setCssStyles({width:"100%"})});ps(s);const r=e.createDiv(),i=e.createDiv();i.setCssStyles({color:"var(--text-error)"});const a=o=>{const l=Bf(o,n);ji(`${l}.mp3`,r),i.toggle(!/\{\{title(:[^}]*)?\}\}/i.test(o)),i.setText("⚠ This path has no {{title}}, so multiple episodes can resolve to the same file — downloads will overwrite each other or fail. Add {{title}}, e.g. PodNotes/{{podcast}}/{{title}}.")};a(this.plugin.settings.download.path)}addPerformanceSettings(e){new _.Setting(e).setName("Performance").setHeading(),new _.Setting(e).setName("Cache podcast feeds").setDesc("Store recently downloaded feeds locally for faster startup.").addToggle(n=>n.setValue(this.plugin.settings.feedCache.enabled).onChange(async s=>{this.plugin.settings.feedCache.enabled=s,await this.plugin.saveSettings()})),new _.Setting(e).setName("Cache duration (hours)").setDesc("Choose how long to reuse cached feeds before fetching again.").addSlider(n=>n.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 _.Setting(e).setName("Clear cached feeds").setDesc("Remove stored feed data. PodNotes will refetch feeds as needed.").addButton(n=>n.setButtonText("Clear cache").onClick(()=>{lb(),en.set({}),new _.Notice("Cleared cached podcast feeds.")}))}addImportExportSettings(e){new _.Setting(e).setName("Import/Export").setHeading(),new _.Setting(e).setName("Import OPML").setDesc("Import podcasts from an OPML file.").addButton(s=>s.setButtonText("Import").onClick(()=>{this.pickFile(".opml",async r=>{try{await Gw(r)}catch(i){new _.Notice(`Error importing OPML: ${i instanceof Error?i.message:"Unknown error"}`,1e4)}},{tooLargeMessage:"That file is too large to be an OPML file."})}));let n="PodNotes_Export.opml";new _.Setting(e).setName("Export OPML").setDesc("Export saved podcast feeds to an OPML file.").addText(s=>s.setPlaceholder("Export file name").setValue(n).onChange(r=>{n=r})).addButton(s=>s.setButtonText("Export").onClick(()=>{const r=Object.values(T(Et));if(r.length===0){new _.Notice("No podcasts to export.");return}Qw(this.app,r,n.endsWith(".opml")?n:`${n}.opml`)})),this.addSettingsTransferControls(e)}addSettingsTransferControls(e){new _.Setting(e).setName("Settings & templates").setHeading(),new _.Setting(e).setName("Import settings").setDesc("Import PodNotes preferences, templates, feeds, and playlists from a settings file. Playback progress and downloads are not affected.").addButton(r=>r.setButtonText("Import").onClick(()=>{this.pickFile(".json",i=>this.handleSettingsImport(i))}));let n="PodNotes_Settings.json",s=!1;new _.Setting(e).setName("Include API keys").setDesc("When enabled, the export file contains your OpenAI and Deepgram API keys in plaintext (whichever you have set). The file is stored in your vault, so it may sync to other devices and be read by other plugins.").addToggle(r=>r.setValue(s).onChange(i=>{s=i})),new _.Setting(e).setName("Export settings").setDesc("Export PodNotes preferences, templates, feeds, and playlists.").addText(r=>r.setPlaceholder("Export file name").setValue(n).onChange(i=>{n=i})).addButton(r=>r.setButtonText("Export").onClick(()=>{const i=n.trim()||"PodNotes_Settings.json",a=i.endsWith(".json")?i:`${i}.json`;this.handleSettingsExport(a,s)}))}pickFile(e,n,s={}){const r=s.maxBytes??5242880,i=s.tooLargeMessage??"That file is too large to be a PodNotes settings file.",a=activeDocument.createElement("input");a.type="file",a.accept=e,a.setCssStyles({display:"none"}),activeDocument.body.appendChild(a),a.oncancel=()=>a.remove(),a.onchange=o=>{const c=o.target.files?.[0];if(a.remove(),!c){new _.Notice("No file selected.");return}if(c.size>r){new _.Notice(i);return}const u=new FileReader;u.onload=d=>{const f=d.target?.result;typeof f=="string"?n(f):new _.Notice("Could not read the selected file.")},u.onerror=()=>new _.Notice("Could not read the selected file."),u.readAsText(c)},a.click()}async handleSettingsExport(e,n){try{const s=db(this.plugin.settings,{includeSecret:n},this.plugin.manifest.version,new Date().toISOString()),r=JSON.stringify(s,null,2);if(this.app.vault.getAbstractFileByPath(e)){new _.Notice(`A file named "${e}" already exists. Choose a different name.`);return}await this.app.vault.create(e,r);const i=n?Bu(this.plugin.settings):[];new _.Notice(i.length?`Exported PodNotes settings to "${e}" (includes your ${i.join(" and ")}).`:`Exported PodNotes settings to "${e}".`)}catch(s){s instanceof Error&&s.message.includes("Folder does not exist")?new _.Notice("Unable to create export file: folder does not exist."):new _.Notice(`Unable to export settings:
|
||
|
||
${s instanceof Error?s.message:"Unknown error"}`)}}handleSettingsImport(e){const n=fb(e);if(!n.ok){new _.Notice(`Could not import settings: ${n.error}`,1e4);return}const s=(a,o)=>Object.prototype.hasOwnProperty.call(n.settings,a)&&Object.keys(o??{}).length>0,r=[];s("savedFeeds",this.plugin.settings.savedFeeds)&&r.push("podcast feeds"),s("playlists",this.plugin.settings.playlists)&&r.push("playlists"),r.push(...Bu(n.settings));const i=r.length?` This also replaces your ${r.join(", ")}.`:"";new Sb(this.app,"Import PodNotes settings?",`This overwrites your current PodNotes preferences and templates with the imported values.${i} Your playback progress and downloads are kept.`,"Import",()=>{this.applyImportedSettings(n.settings)}).open()}async applyImportedSettings(e){const n=hb(this.plugin.settings,e);this.plugin.settings=n,Et.set(n.savedFeeds),mt.set(n.playlists),Ft.set(n.favorites),pe.set(n.queue),Vt.set(n.localFiles),di.set(n.hidePlayedEpisodes);const s=ws(n.episodeListLimit);n.episodeListLimit=s,ui.set(s);const r=Number.isFinite(n.defaultVolume)?n.defaultVolume:1;zn.set(Math.min(1,Math.max(0,r))),Zn.set(Ms(n.defaultPlaybackRate)),await this.plugin.saveSettings(),re.set(this.plugin),this.display(),new _.Notice("Imported PodNotes settings.")}addTranscriptSettings(e){new _.Setting(e).setName("Transcript settings").setHeading();const n=No();new _.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 _.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=ka(a,n);s.empty(),s.createEl("p",{text:`Example: ${o}`})};r(this.plugin.settings.transcript.path);const i=new _.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.setCssStyles({width:"100%",height:"25vh"})});ps(i),this.addDiarizationSettings(e)}addDiarizationSettings(e){const n=e.createDiv(),s=()=>{n.empty();const r=this.plugin.settings.transcript.diarization;new _.Setting(n).setName("Speaker diarization").setDesc("Label transcript segments by speaker. Routes the episode audio to a diarization-capable provider instead of plain Whisper.").addToggle(i=>i.setValue(r.enabled).onChange(async a=>{this.plugin.settings.transcript.diarization.enabled=a,await this.plugin.saveSettings(),s()})),r.enabled&&(new _.Setting(n).setName("Diarization provider").setDesc("OpenAI reuses your OpenAI API key above (long episodes are chunked, so speaker labels can reset across chunks). Deepgram needs its own key and keeps speaker labels consistent across the whole episode.").addDropdown(i=>i.addOption("openai","OpenAI (gpt-4o-transcribe-diarize)").addOption("deepgram","Deepgram").setValue(r.provider).onChange(async a=>{this.plugin.settings.transcript.diarization.provider=a,await this.plugin.saveSettings(),s()})),r.provider==="deepgram"&&new _.Setting(n).setName("Deepgram API key").setDesc("Used only for Deepgram diarization. Create one at deepgram.com.").addText(i=>{i.setPlaceholder("Enter your Deepgram API key").setValue(this.plugin.settings.diarizationApiKey).onChange(async a=>{this.plugin.settings.diarizationApiKey=a,await this.plugin.saveSettings()}),i.inputEl.type="password"}),new _.Setting(n).setName("Speaker label format").setDesc("Prefix added before each speaker's turn. Use {{speaker}} for the speaker label (OpenAI labels speakers A, B, …; Deepgram labels them 1, 2, …).").addText(i=>i.setPlaceholder(Ql).setValue(r.speakerTemplate).onChange(async a=>{this.plugin.settings.transcript.diarization.speakerTemplate=a,await this.plugin.saveSettings()})))};s()}}function No(){const t={description:"demo",content:"demo",podcastName:"demo",title:"demo",url:"demo",artworkUrl:"demo",streamUrl:"demo",episodeDate:new Date,feedUrl:"demo"},e=Object.values(T(en));if(!e.length)return t;const n=e[Math.floor(Math.random()*e.length)];return n.length?n[Math.floor(Math.random()*n.length)]:t}function Eb(){const t={title:"Demo Podcast",url:"https://example.com/feed.xml",artworkUrl:"https://example.com/artwork.jpg",description:"A demo podcast feed.",link:"https://example.com",author:"Demo Author"},e=Object.values(T(Et));return e.length?e[Math.floor(Math.random()*e.length)]:t}class Sb extends _.Modal{constructor(e,n,s,r,i){super(e),this.title=n,this.body=s,this.confirmText=r,this.onConfirm=i}onOpen(){const{contentEl:e}=this;e.createEl("h3",{text:this.title}),e.createEl("p",{text:this.body}),new _.Setting(e).addButton(n=>n.setButtonText("Cancel").onClick(()=>this.close())).addButton(n=>n.setButtonText(this.confirmText).setWarning().onClick(()=>{this.close(),this.onConfirm()}))}onClose(){this.contentEl.empty()}}var Ab=J('<button type="button" class="playlist-card svelte-5dhk44"><!> <span class="playlist-card-name svelte-5dhk44"> </span> <span class="playlist-card-count svelte-5dhk44"> </span></button>');const Cb={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;
|
||
/* \`min-height\` is a floor, not a cap: the card must grow to fit icon +
|
||
name + count. The grid uses min-content rows, so the row grows with it. */height:auto;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);}
|
||
|
||
/* Keep the icon, name, and count at their natural height so flexbox never
|
||
compresses/clips a label to fit the min-height (the bug where the name
|
||
overlapped the count). The card grows instead. */.playlist-card-name.svelte-5dhk44,
|
||
.playlist-card-count.svelte-5dhk44 {flex-shrink:0;}.playlist-card.svelte-5dhk44 .icon-static {flex-shrink:0;}.playlist-card-name.svelte-5dhk44 {max-width:100%;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-size:0.85rem;line-height:1.3;color:var(--text-normal);}.playlist-card-count.svelte-5dhk44 {font-size:0.8rem;line-height:1.3;color:var(--text-muted);}`};function Tb(t,e){Te(e,!1),Le(t,Cb);let n=B(e,"playlist",8);const s=it();function r(d){s("clickPlaylist",{playlist:n(),event:d})}Re();var i=Ab(),a=F(i);Ce(a,{get icon(){return L(n()),O(()=>n().icon)},size:32,clickable:!1});var o=W(a,2),l=F(o),c=W(o,2),u=F(c);we(()=>{le(i,"aria-label",(L(n()),O(()=>n().name))),le(i,"title",(L(n()),O(()=>n().name))),Ae(l,(L(n()),O(()=>n().name))),Ae(u,`(${L(n()),O(()=>n().episodes.length)??""})`)}),oe("click",i,r),j(t,i),Pe()}var Pb=J('<button type="button" class="pn_image_container svelte-ds4mor"><img draggable="false"/></button>'),$b=J('<div class="pn_image_container pn_image_container--static svelte-ds4mor"><img draggable="false"/></div>');const Ib={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 pc(t,e){Te(e,!1),Le(t,Ib);let n=B(e,"src",8),s=B(e,"alt",8),r=B(e,"fadeIn",8,!1),i=B(e,"opacity",8,0),a=B(e,"interactive",8,!1),o=B(e,"loading",8,"lazy"),l=B(e,"class",8,""),c=V(!1),u=V(!0),d=V(!1);const f=it();function h(v){f("click",{event:v})}Re();var m=pt(),g=Ve(m);{var y=v=>{var w=pt(),k=Ve(w);{var P=A=>{var $=Pb(),R=F($);let K;we(()=>{le(R,"src",n()),le(R,"alt",s()),le(R,"loading",o()),sn(R,1,ru(l()),"svelte-ds4mor"),K=br(R,"",K,{opacity:i()?i():r()?p(c)?1:0:1,transition:r()?"opacity 0.5s ease-out":""})}),oe("load",R,()=>{E(c,!0),E(u,!1)}),oe("error",R,()=>{E(d,!0),E(u,!1)}),oe("click",$,h),j(A,$)},S=A=>{var $=$b(),R=F($);let K;we(()=>{le(R,"src",n()),le(R,"alt",s()),le(R,"loading",o()),sn(R,1,ru(l()),"svelte-ds4mor"),K=br(R,"",K,{opacity:i()?i():r()?p(c)?1:0:1,transition:r()?"opacity 0.5s ease-out":""})}),oe("load",R,()=>{E(c,!0),E(u,!1)}),oe("error",R,()=>{E(d,!0),E(u,!1)}),j(A,$)};ue(k,A=>{a()?A(P):A(S,!1)})}j(v,w)},b=v=>{var w=pt(),k=Ve(w);{var P=S=>{var A=pt(),$=Ve(A);of($,e,"fallback",{},null),j(S,A)};ue(k,S=>{p(d)&&S(P)},!0)}j(v,w)};ue(g,v=>{p(u)||p(c)?v(y):v(b,!1)})}j(t,m),Pe()}const Nb={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 Rb(t,e){Te(e,!1),Le(t,Nb);let n=B(e,"feed",8);const s=it();function r(a){s("clickPodcast",{feed:a})}Re();var i=ts(()=>r.bind(null,n()));pc(t,{get src(){return L(n()),O(()=>n().artworkUrl)},get alt(){return L(n()),O(()=>n().title)},interactive:!0,class:"podcast-image",$$events:{click(...a){p(i)?.apply(this,a)}}}),Pe()}var Fb=J("<div><p>No saved podcasts.</p></div>"),Mb=J('<div class="podcast-grid svelte-1x0bcng"><!> <!></div>');const Db={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 Lb(t,e){Te(e,!1),Le(t,Db);let n=B(e,"feeds",24,()=>[]),s=B(e,"playlists",24,()=>[]);const r=it();function i({detail:{playlist:f,event:h}}){r("clickPlaylist",{playlist:f,event:h})}Re();var a=Mb(),o=F(a);{var l=f=>{var h=pt(),m=Ve(h);Rs(m,1,s,g=>g.name,(g,y)=>{Tb(g,{get playlist(){return p(y)},$$events:{clickPlaylist:i}})}),j(f,h)};ue(o,f=>{L(s()),O(()=>s().length>0)&&f(l)})}var c=W(o,2);{var u=f=>{var h=pt(),m=Ve(h);Rs(m,1,n,g=>g.url,(g,y)=>{Rb(g,{get feed(){return p(y)},$$events:{clickPodcast(b){il.call(this,e,b)}}})}),j(f,h)},d=f=>{var h=Fb();j(f,h)};ue(c,f=>{L(n()),O(()=>n().length>0)?f(u):f(d,!1)})}j(t,a),Pe()}var Ob=J("<span></span>");function Uu(t,e){Te(e,!1);let n=B(e,"value",8),s=B(e,"limits",8),r=V();const i=it();let a=V(),o=B(e,"style",24,()=>({})),l=null,c=!1;An(()=>{E(a,new _.SliderComponent(p(r))),l=f=>{if(c)return;const h=Number(f.target.value);i("change",{value:h})},p(a).sliderEl.addEventListener("input",l)}),Wa(()=>{p(a)?.sliderEl&&l&&p(a).sliderEl.removeEventListener("input",l)});function u(f,h,m,g){const y=typeof f.getValue=="function"?f.getValue():Number(f.sliderEl?.value);h!==void 0&&y!==h&&(c=!0,f.setValue(h),c=!1),m&&(m.length===2?f.setLimits(m[0],m[1],1):f.setLimits(m[0],m[1],m[2])),g&&f.sliderEl.setAttr("style",Pr(g))}ge(()=>(p(a),L(n()),L(s()),L(o())),()=>{p(a)&&u(p(a),n(),s(),o())}),yt(),Re();var d=Ob();an(d,f=>E(r,f),()=>p(r)),j(t,d),Pe()}var Bb=J('<div class="la-line-scale svelte-k6ycv0"><div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div> <div class="svelte-k6ycv0"></div></div>');const Ub={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 El(t){Le(t,Ub);var e=Bb();j(t,e)}var jb=J('<div class="image-loader svelte-jp8vu"><!></div>');const zb={hash:"svelte-jp8vu",code:".image-loader.svelte-jp8vu {position:relative;width:100%;}"};function qb(t,e){Te(e,!1),Le(t,zb);const n=V(),s=V(),r=V();let i=B(e,"src",8),a=B(e,"alt",8),o=B(e,"fadeIn",8,!1),l=B(e,"interactive",8,!1),c=B(e,"width",8),u=B(e,"height",8),d=B(e,"aspectRatio",8,"1 / 1"),f=B(e,"loading",8,"lazy"),h=B(e,"class",8,"");const m=it(),g=w=>typeof w=="number"?`${w}px`:w;ge(()=>L(c()),()=>{E(n,g(c()))}),ge(()=>L(u()),()=>{E(s,g(u()))}),ge(()=>(p(s),L(d())),()=>{E(r,p(s)?void 0:d())}),yt(),Re();var y=jb();let b;var v=F(y);pc(v,{get alt(){return a()},get src(){return i()},get fadeIn(){return o()},get interactive(){return l()},get loading(){return f()},get class(){return h()},$$events:{click:w=>m("click",{event:w})}}),we(()=>b=br(y,"",b,{width:p(n),height:p(s),"aspect-ratio":p(r)})),j(t,y),Pe()}var Hb=J('<div class="podcast-episode-thumbnail-container svelte-dmhmse"><!></div>'),Vb=J('<div class="podcast-episode-thumbnail-container svelte-dmhmse"></div>'),Wb=J('<span class="episode-item-status svelte-dmhmse"> </span>'),Kb=J('<div class="podcast-episode-row svelte-dmhmse"><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> <div class="podcast-episode-overflow svelte-dmhmse"><!></div></div>');const Yb={hash:"svelte-dmhmse",code:`.podcast-episode-row.svelte-dmhmse {position:relative;display:flex;align-items:stretch;border-bottom:1px solid var(--background-modifier-border);}.podcast-episode-row.svelte-dmhmse:last-child {border-bottom:none;}.podcast-episode-item.svelte-dmhmse {display:flex;flex-direction:row;justify-content:flex-start;align-items:center;padding:0.625rem 2.5rem 0.625rem 0.75rem;min-height:4.5rem;width:100%;border:none;gap:0.75rem;background:transparent;text-align:left;cursor:pointer;transition:background-color 120ms ease;}.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);}.podcast-episode-overflow.svelte-dmhmse {position:absolute;top:50%;right:0.25rem;transform:translateY(-50%);display:flex;align-items:center;}.podcast-episode-overflow.svelte-dmhmse .icon-button {padding:0.35rem;border-radius:0.375rem;color:var(--text-muted);transition:background-color 120ms ease, color 120ms ease;}.podcast-episode-overflow.svelte-dmhmse .icon-button:hover {background-color:var(--background-modifier-hover);color:var(--text-normal);}.podcast-episode-overflow.svelte-dmhmse .icon-button:focus-visible {outline:2px solid var(--interactive-accent);outline-offset:-2px;}.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 Xb(t,e){Te(e,!1),Le(t,Yb);let n=B(e,"episode",8),s=B(e,"episodeFinished",8,!1),r=B(e,"showEpisodeImage",8,!1),i=B(e,"unavailableReason",8,void 0);const a=it(),o=new Intl.DateTimeFormat("en-GB",{day:"2-digit",month:"long",year:"numeric"}),l=new Map;let c=V();function u(){a("clickEpisode",{episode:n()})}function d(D){a("contextMenu",{episode:n(),event:D})}function f(){if(!p(c))return;const D=p(c).getBoundingClientRect();a("contextMenu",{episode:n(),event:{x:D.left,y:D.bottom}})}function h(D){if(!D)return null;const Y=new Date(D);return Number.isNaN(Y.getTime())?null:Y}function m(D,Y){return`${D.url??D.streamUrl??D.title??"episode"}|${Y.getTime()}`}function g(D){const Y=h(D?.episodeDate);if(!Y)return"";const _e=m(D,Y),at=l.get(_e);if(at)return at;const Oe=o.format(Y).toUpperCase();return l.set(_e,Oe),Oe}let y=V("");ge(()=>L(n()),()=>{E(y,g(n()))}),yt(),Re();var b=Kb(),v=F(b),w=F(v);{var k=D=>{var Y=Hb(),_e=F(Y);qb(_e,{get src(){return L(n()),O(()=>n().artworkUrl)},get alt(){return L(n()),O(()=>n().title)},fadeIn:!0,width:"100%",height:"100%",class:"podcast-episode-thumbnail"}),j(D,Y)},P=D=>{var Y=pt(),_e=Ve(Y);{var at=Oe=>{var wt=Vb();j(Oe,wt)};ue(_e,Oe=>{r()&&Oe(at)},!0)}j(D,Y)};ue(w,D=>{L(r()),L(n()),O(()=>r()&&n()?.artworkUrl)?D(k):D(P,!1)})}var S=W(w,2),A=F(S),$=F(A),R=W(A,2),K=F(R),Z=W(R,2);{var ee=D=>{var Y=Wb(),_e=F(Y);we(()=>Ae(_e,i())),j(D,Y)};ue(Z,D=>{i()&&D(ee)})}var be=W(v,2),me=F(be);{let D=ke(()=>(L(n()),O(()=>`More options for ${n().title}`)));Ce(me,{icon:"more-vertical",size:20,get label(){return p(D)},$$events:{click:f}})}an(be,D=>E(c,D),()=>p(c)),we(()=>{le(v,"title",(L(i()),L(n()),O(()=>i()??n().title))),Ae($,p(y)),sn(R,1,`episode-item-title ${s()&&"strikeout"}`,"svelte-dmhmse"),Ae(K,(L(n()),O(()=>n().title)))}),oe("click",v,u),oe("contextmenu",v,d),j(t,b),Pe()}function Jb(t){return{episode:t,isAvailable:!0}}function Gb(t){return t.map(Jb)}function Qb(t,e){const n=t_(e.flat());return fl(t).map(({key:s,episode:r})=>Zb(s,r,n)).sort(n_)}function Zb(t,e,n){const s=e_(t,e,n);return s?{episode:s,isAvailable:!0,playedEpisode:e,playedEpisodeKey:t}:{episode:yh(e),isAvailable:!1,unavailableReason:"Unavailable in current feeds",playedEpisode:e,playedEpisodeKey:t}}function e_(t,e,n){const s=[t,ec(e),e.title];for(const r of s){const i=n.get(r);if(i)return i}}function t_(t){const e=new Map;for(const n of t){const s=[gt(n),n.podcastName?`${n.podcastName}::${n.title}`:"",n.title].filter(Boolean);for(const r of s)e.has(r)||e.set(r,n)}return e}function yh(t){return{title:t.title,podcastName:t.podcastName,streamUrl:"",url:"",description:"",content:""}}function n_(t,e){if(t.isAvailable!==e.isAvailable)return t.isAvailable?-1:1;const n=ju(t.episode),s=ju(e.episode);return n!==s?s-n:t.episode.title.localeCompare(e.episode.title)}function ju(t){if(!t.episodeDate)return 0;const e=Number(new Date(t.episodeDate));return Number.isNaN(e)?0:e}var s_=J('<div class="episode-list-menu svelte-ozfrsd"><div class="episode-list-search svelte-ozfrsd"><!></div> <!> <!></div>'),r_=J('<div class="episode-list-loading svelte-ozfrsd" role="status" aria-live="polite"><!> <span>Fetching episodes...</span></div>'),i_=J('<p class="svelte-ozfrsd">No episodes found.</p>'),a_=J('<div class="episode-list-view-container svelte-ozfrsd"><!> <!> <div class="podcast-episode-list svelte-ozfrsd"><!> <!> <!></div></div>');const o_={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 wh(t,e){Te(e,!1),Le(t,o_);const n=()=>Ne(di,"$hidePlayedEpisodes",r),s=()=>Ne(We,"$playedEpisodes",r),[r,i]=Tr(),a=V(),o=V(),l=V();let c=B(e,"episodes",24,()=>[]),u=B(e,"episodeEntries",8,null),d=B(e,"showThumbnails",8,!1),f=B(e,"showListMenu",8,!0),h=B(e,"showPlayedToggle",8,!0),m=B(e,"alwaysShowPlayedEpisodes",8,!1),g=B(e,"isLoading",8,!1),y=V("");const b=it();function v(D,Y){b("clickEpisode",{episode:Y.detail.episode,entry:D})}function w(D,Y){b("contextMenuEpisode",{episode:Y.detail.episode,entry:D,event:Y.detail.event})}function k(D){b("search",{query:D.detail.value})}ge(()=>(L(u()),L(c())),()=>{E(a,u()??Gb(c()))}),ge(()=>(n(),L(m())),()=>{E(o,n()&&!m())}),ge(()=>(p(a),p(o),s()),()=>{E(l,p(a).filter(D=>!p(o)||!ei(D.episode,s())))}),yt(),Re();var P=a_(),S=F(P);of(S,e,"header",{},D=>{var Y=bg("Fallback");j(D,Y)});var A=W(S,2);{var $=D=>{var Y=s_(),_e=F(Y),at=F(_e);fc(at,{placeholder:"Search episodes",style:{width:"100%"},get value(){return p(y)},set value(Ie){E(y,Ie)},$$events:{input:k},$$legacy:!0});var Oe=W(_e,2);{var wt=Ie=>{{let At=ke(()=>n()?"eye-off":"eye"),Kt=ke(()=>n()?"Show played episodes":"Hide played episodes");Ce(Ie,{get icon(){return p(At)},size:25,get label(){return p(Kt)},get pressed(){return n()},$$events:{click:()=>di.update(Rr=>!Rr)}})}};ue(Oe,Ie=>{h()&&Ie(wt)})}var Wt=W(Oe,2);Ce(Wt,{icon:"refresh-cw",size:25,label:"Refresh episodes",$$events:{click:()=>b("clickRefresh")}}),j(D,Y)};ue(A,D=>{f()&&D($)})}var R=W(A,2),K=F(R);{var Z=D=>{var Y=r_(),_e=F(Y);El(_e),j(D,Y)};ue(K,D=>{g()&&D(Z)})}var ee=W(K,2);{var be=D=>{var Y=i_();j(D,Y)};ue(ee,D=>{p(l),L(g()),O(()=>p(l).length===0&&!g())&&D(be)})}var me=W(ee,2);Rs(me,3,()=>p(l),(D,Y)=>gt(D.episode)??`${D.episode.title}-${D.episode.episodeDate??""}-${Y}`,(D,Y)=>{var _e=ts(()=>v.bind(null,p(Y))),at=ts(()=>w.bind(null,p(Y)));{let Oe=ke(()=>(L(ei),p(Y),s(),O(()=>ei(p(Y).episode,s()))));Xb(D,{get episode(){return p(Y),O(()=>p(Y).episode)},get episodeFinished(){return p(Oe)},get showEpisodeImage(){return d()},get unavailableReason(){return p(Y),O(()=>p(Y).unavailableReason)},$$events:{clickEpisode(...wt){p(_e)?.apply(this,wt)},contextMenu(...wt){p(at)?.apply(this,wt)}}})}}),j(t,P),Pe(),i()}var l_=J('<li><button type="button" class="chapter-item svelte-1vxfdxx"><span class="chapter-time svelte-1vxfdxx"> </span> <span class="chapter-title svelte-1vxfdxx"> </span></button></li>'),c_=J('<ul class="chapters svelte-1vxfdxx"></ul>'),u_=J('<div class="chapter-list svelte-1vxfdxx"><button type="button" class="chapter-header svelte-1vxfdxx"><!> <h3 class="svelte-1vxfdxx"> </h3></button> <!></div>');const d_={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 f_(t,e){Te(e,!1),Le(t,d_);const n=V();let s=B(e,"chapters",24,()=>[]),r=B(e,"currentTime",8,0);const i=it();let a=V(!0);const o="chapter-list-"+Math.random().toString(36).slice(2);function l(h,m){for(let g=h.length-1;g>=0;g--)if(m>=h[g].startTime)return g;return-1}function c(h){i("seek",{time:h.startTime})}ge(()=>(L(s()),L(r())),()=>{E(n,l(s(),r()))}),yt(),Re();var u=pt(),d=Ve(u);{var f=h=>{var m=u_(),g=F(m),y=F(g);{let P=ke(()=>p(a)?"chevron-down":"chevron-right");Ce(y,{get icon(){return p(P)},size:16})}var b=W(y,2),v=F(b),w=W(g,2);{var k=P=>{var S=c_();Rs(S,5,s,Xm,(A,$,R)=>{var K=l_();let Z;var ee=F(K),be=F(ee),me=F(be),D=W(be,2),Y=F(D);we(_e=>{Z=sn(K,1,"svelte-1vxfdxx",null,Z,{active:R===p(n)}),le(ee,"aria-label",(p($),O(()=>`Jump to ${p($).title}`))),Ae(me,_e),Ae(Y,(p($),O(()=>p($).title)))},[()=>(L(ft),p($),O(()=>ft(p($).startTime,"H:mm:ss")))]),oe("click",ee,()=>c(p($))),j(A,K)}),we(()=>le(S,"id",o)),j(P,S)};ue(w,P=>{p(a)&&P(k)})}we(()=>{le(g,"aria-expanded",p(a)),le(g,"aria-controls",p(a)?o:void 0),Ae(v,`Chapters (${L(s()),O(()=>s().length)??""})`)}),oe("click",g,()=>E(a,!p(a))),j(h,m)};ue(d,h=>{L(s()),O(()=>s().length>0)&&h(f)})}j(t,u),Pe()}var h_=J('<div class="progress svelte-aac6sw" role="slider" tabindex="0" aria-valuemin="0"><div class="progress__bar svelte-aac6sw"></div></div>');const p_={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 m_(t,e){Te(e,!1),Le(t,p_);let n=B(e,"max",8),s=B(e,"value",8),r=B(e,"ariaLabel",8,"Seek"),i=B(e,"valueText",8,void 0),a=!1,o=B(e,"style",24,()=>({})),l=V(),c=V();const u=it();function d(v,w){u("click",{event:v,percent:w})}function f(){a=!0}function h(){a=!1}function m(v){a&&d(v)}function g(v){if(!p(l)||!n())return;const w=n()*.05;let k=s();switch(v.key){case"ArrowRight":case"ArrowUp":k=Math.min(n(),s()+w);break;case"ArrowLeft":case"ArrowDown":k=Math.max(0,s()-w);break;case"Home":k=0;break;case"End":k=n();break;case"Enter":case" ":k=s();break;default:return}v.preventDefault();const P=n()?k/n():0;d(v,P)}ge(()=>L(o()),()=>{E(c,Pr(o()))}),yt(),Re();var y=h_(),b=F(y);an(y,v=>E(l,v),()=>p(l)),we(v=>{le(y,"aria-label",r()),le(y,"aria-valuemax",n()),le(y,"aria-valuenow",s()),le(y,"aria-valuetext",i()),br(y,p(c)),br(b,v)},[()=>(L(n()),L(s()),O(()=>`width: ${n()?Math.min(100,s()/n()*100):0}%;`))]),oe("click",y,d),oe("mousedown",y,f),oe("mouseup",y,h),oe("mousemove",y,m),oe("keydown",y,g),j(t,y),Pe()}function g_(t,e,n){if(t!==ie.Player)return[];const s=e.findIndex(o=>o.title===n.title);if(s===-1||e.length<=1)return[];const r=[],i=s===0,a=s===e.length-1;return i||(r.push({icon:"chevrons-up",title:"Move to top of queue",kind:"top",index:s}),r.push({icon:"chevron-up",title:"Move up in queue",kind:"up",index:s})),a||(r.push({icon:"chevron-down",title:"Move down in queue",kind:"down",index:s}),r.push({icon:"chevrons-down",title:"Move to bottom of queue",kind:"bottom",index:s})),r}function Sl(t,e,n,s){const r=new _.Menu;if(n?.play||r.addItem(i=>i.setIcon("play").setTitle("Play").onClick(()=>{vt.set(t),He.set(ie.Player)})),!n?.markPlayed){const i=T(We),a=s?i[s]?.finished??ei(t,i):ei(t,i);r.addItem(o=>o.setIcon(a?"x":"check").setTitle(`Mark as ${a?"Unplayed":"Played"}`).onClick(()=>{a?s?We.markKeyAsUnplayed(s):We.markAsUnplayed(t):We.markAsPlayed(t)}))}if(!n?.download){const i=et.isEpisodeDownloaded(t);r.addItem(a=>a.setIcon(i?"cross":"download").setTitle(i?"Remove file":"Download").onClick(()=>{i?iw(t):eh(t,T(re).settings.download.path).catch(o=>{})}))}if(!n?.createNote){const i=!!Si(t);r.addItem(l=>l.setIcon("pencil").setTitle(`${i?"Open":"Create"} Note`).onClick(async()=>{if(i)Py(t);else{const{path:c,template:u}=T(re).settings.note;if(!!!(c&&u)){new _.Notice("Please set a note path and template in the settings.");return}await Hf(t)}}));const a=v_(t),o=!!Ya(a);r.addItem(l=>l.setIcon("rss").setTitle(`${o?"Open":"Create"} feed note`).onClick(async()=>{if(o)Dy(a);else{const{path:c,template:u}=T(re).settings.feedNote;if(!c||!u){new _.Notice("Please set a podcast feed note path and template in the settings.");return}await Gf(a)}}))}if(!n?.favorite){const i=T(Ft).episodes.find(a=>Hr(a,t));r.addItem(a=>a.setIcon("lucide-star").setTitle(`${i?"Remove from":"Add to"} Favorites`).onClick(()=>{i?Ft.update(o=>(o.episodes=o.episodes.filter(l=>!Hr(l,t)),o)):Ft.update(o=>{const l=[...o.episodes,t];return o.episodes=l,o})}))}if(!n?.queue){const i=T(pe).episodes.find(o=>o.title===t.title);r.addItem(o=>o.setIcon("list-ordered").setTitle(`${i?"Remove from":"Add to"} Queue`).onClick(()=>{i?pe.remove(t):pe.add(t)}));const a=g_(T(He),T(pe).episodes,t);if(a.length>0){r.addSeparator();for(const o of a)r.addItem(l=>l.setIcon(o.icon).setTitle(o.title).onClick(()=>{const c=T(pe).episodes.findIndex(u=>u.title===t.title);if(c!==-1)switch(o.kind){case"top":pe.moveToTop(c);break;case"up":pe.moveUp(c);break;case"down":pe.moveDown(c);break;case"bottom":pe.moveToBottom(c);break}}))}}if(!n?.playlists){const i=T(mt),a=Object.values(i);if(a.length>0){r.addSeparator();for(const o of a){const l=o.episodes.find(c=>Hr(c,t));r.addItem(c=>c.setIcon(o.icon).setTitle(`${l?"Remove from":"Add to"} ${o.name}`).onClick(()=>{l?mt.update(u=>(u[o.name].episodes=u[o.name].episodes.filter(d=>!Hr(d,t)),u)):mt.update(u=>{const d=[...u[o.name].episodes,t];return u[o.name].episodes=d,u})}))}}}e instanceof MouseEvent?r.showAtMouseEvent(e):r.showAtPosition(e)}function v_(t){const e=T(Et)[t.podcastName];return e||{title:t.podcastName,url:t.feedUrl??"",artworkUrl:t.artworkUrl??""}}function bh(t,e){const n=t.getAbstractFileByPath(e);return!n||!(n instanceof _.TFile)?"":t.getResourcePath(n)}var y_=J('<div class="podcast-artwork-isloading-overlay svelte-vlhi04"><!></div>'),w_=J('<button type="button" aria-label="Toggle playback"><!></button>'),b_=J('<div class="episode-video-container svelte-vlhi04"><video class="podcast-video svelte-vlhi04" playsinline=""></video> <!> <button type="button" class="podcast-video-fullscreen svelte-vlhi04" aria-label="Enter fullscreen"><!></button></div>',2),__=J("<div><!></div>"),x_=J('<div class="podcast-artwork-isloading-overlay svelte-vlhi04"><!></div>'),k_=J("<div><!></div>"),E_=J('<div class="episode-image-container svelte-vlhi04"><button type="button" class="hover-container svelte-vlhi04" aria-label="Toggle playback"><!> <!></button></div>'),S_=J("<audio></audio>"),A_=J("<h3>Queue</h3>"),C_=J('<div class="episode-player svelte-vlhi04"><!> <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 T_={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;}.episode-video-container.svelte-vlhi04 {width:100%;max-width:32rem;aspect-ratio:16 / 9;position:relative;margin:0 auto 0.5rem;background:#000;border-radius:0.75rem;overflow:hidden;box-shadow:0 4px 20px rgba(0, 0, 0, 0.2);}.podcast-video.svelte-vlhi04 {width:100%;height:100%;display:block;object-fit:contain;background:#000;}.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-video-overlay.svelte-vlhi04 {position:absolute;inset:0;display:flex;align-items:center;justify-content:center;opacity:0;border:none;background:rgba(0, 0, 0, 0.1);color:var(--text-on-accent);cursor:pointer;transition:opacity 200ms ease;}.episode-video-container.svelte-vlhi04:hover .podcast-video-overlay:where(.svelte-vlhi04),
|
||
.podcast-video-overlay.svelte-vlhi04:focus-visible,
|
||
.podcast-artwork-overlay.visible.svelte-vlhi04,
|
||
.podcast-video-overlay.visible.svelte-vlhi04 {opacity:1;}.podcast-video-overlay.svelte-vlhi04:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:-4px;}.podcast-video-fullscreen.svelte-vlhi04 {position:absolute;right:0.5rem;bottom:0.5rem;display:flex;align-items:center;justify-content:center;padding:0.35rem;border:none;border-radius:0.375rem;background:rgba(0, 0, 0, 0.45);color:var(--text-on-accent);cursor:pointer;opacity:0;transition:opacity 200ms ease, background-color 120ms ease;}.episode-video-container.svelte-vlhi04:hover .podcast-video-fullscreen:where(.svelte-vlhi04),
|
||
.podcast-video-fullscreen.svelte-vlhi04:focus-visible {opacity:1;}.podcast-video-fullscreen.svelte-vlhi04:hover {background:rgba(0, 0, 0, 0.65);}.podcast-video-fullscreen.svelte-vlhi04:focus-visible {outline:2px solid var(--background-modifier-border-focus);outline-offset:2px;}.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 {
|
||
/*
|
||
* Scale the title down as it gets longer (issue #81) so a long episode
|
||
* title no longer renders at one large fixed size. Titles up to ~40
|
||
* characters render at the 1rem base; beyond that the size eases down
|
||
* (0.0025rem per extra character) toward a readable 0.875rem floor,
|
||
* reached around ~90 characters. --title-char-count is an approximate
|
||
* length signal (UTF-16 code units, set from the title in the markup), so
|
||
* it only loosely tracks rendered width for non-Latin scripts;
|
||
* word-break: break-word below is what actually keeps any title contained.
|
||
*/font-size:clamp(
|
||
0.875rem,
|
||
calc(1rem - (var(--title-char-count, 0) - 40) * 0.0025rem),
|
||
1rem
|
||
);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 P_(t,e){Te(e,!1),Le(t,T_);const n=()=>Ne(re,"$plugin",h),s=()=>Ne(pe,"$queue",h),r=()=>Ne(vt,"$currentEpisode",h),i=()=>Ne(et,"$downloadedEpisodes",h),a=()=>Ne(bs,"$duration",h),o=()=>Ne(Gt,"$activePlaybackSegment",h),l=()=>Ne(ut,"$currentTime",h),c=()=>Ne(We,"$playedEpisodes",h),u=()=>Ne(ti,"$requestedPlaybackTime",h),d=()=>Ne(Zn,"$playbackRate",h),f=()=>Ne(rt,"$isPaused",h),[h,m]=Tr(),g=V(),y=V(),b=V(),v=V(),w=N=>Math.min(1,Math.max(0,N));let k=V(Mi(r())),P=V(!1),S=V(!0),A=V(1),$=V(null),R=!1,K=V([]),Z,ee=null;function be(){rt.update(N=>!N)}function me({detail:{event:N,percent:U}}){if(typeof U=="number"){Wt(U*a());return}if(N instanceof MouseEvent){const q=N.currentTarget,Fe=q.offsetWidth?N.offsetX/q.offsetWidth:0;Wt(Fe*a())}}function D(){mt.update(N=>(Object.values(N).forEach(U=>{U.episodes=U.episodes.filter(q=>!Hr(q,r()))}),N)),pe.remove(r())}function Y(){const N=o();if(N&&qr(r(),N.episodeKey)){const U=Number.isFinite(a())&&a()>0?Math.min(N.endTime,a()):l();ut.set(U),ee=U,Gt.set(null),rt.set(!0);return}We.markAsPlayed(r()),D(),pe.playNext()}function _e(N){Zn.set(Ms(N.detail.value))}function at(N){const U=w(N.detail.value);zn.set(U)}function Oe(N){Wt(N.detail.time)}function wt(){const N=p($)?.closest(".episode-video-container");if(N?.requestFullscreen){N.requestFullscreen();return}const U=p($);U?.requestFullscreen?U.requestFullscreen():U?.webkitEnterFullscreen&&U.webkitEnterFullscreen()}function Wt(N){Gt.set(null),ee=null,ut.set(N)}function Ie(){E(S,!1),At()}function At(){const N=c(),U=r(),q=u();if(!U){ut.set(0),rt.set(!1);return}if(q!==null){if(ti.set(null),Gt.set(null),ee=null,!qr(U,q.episodeKey)){Kt(U,N);return}ut.set(q.time),Gt.set(q.endTime===void 0?null:{episodeKey:q.episodeKey,startTime:q.time,endTime:q.endTime}),rt.set(!1);return}Gt.set(null),ee=null,Kt(U,N)}function Kt(N,U){const q=gt(N),Fe=U[N.title],Jt=!!Fe&&(!Fe.podcastName||!N.podcastName||Fe.podcastName===N.podcastName),Pn=q&&U[q]||(Jt?Fe:void 0);Pn?.time?ut.set(Pn.time):ut.set(0),rt.set(!1)}const Rr=5e3;let Fr=Number.NEGATIVE_INFINITY;function Hs(){p(S)||!r()||lo()||We.setEpisodeTime(r(),l(),a(),a()>0&&l()===a())}function Ni(N){if(co(N))return;const U=Date.now();U-Fr<Rr||(Fr=U,Hs())}function lo(){const N=o();return N&&qr(r(),N.episodeKey)?!0:ee===null?!1:l()===ee?!0:(ee=null,!1)}function co(N){const U=o();if(!U)return!1;if(!qr(r(),U.episodeKey))return Gt.set(null),!1;if(l()<U.endTime)return!1;const q=N.currentTarget;return q&&(q.currentTime=U.endTime),ut.set(U.endTime),ee=U.endTime,Gt.set(null),rt.set(!0),!0}function Vs(){Hs()}An(()=>{const N=vt.subscribe(Fe=>{E(S,!0),Fr=Number.NEGATIVE_INFINITY,ee=null,R&&(ut.set(0),bs.set(0)),R=!0;const Jt=Fe?.chaptersUrl;if(Jt&&Jt!==Z){Z=Jt,E(K,[]);const Pn=Jt;qf(Pn).then(Js=>{Pn===Z&&E(K,Js)})}else Jt||(Z=void 0,E(K,[]))}),U=zn.subscribe(Fe=>{E(A,w(Fe))}),q=()=>{document.visibilityState==="hidden"&&Hs()};return document.addEventListener("visibilitychange",q),()=>{N(),U(),document.removeEventListener("visibilitychange",q)}}),Wa(()=>{Hs(),rt.set(!0)});function Ri({detail:{event:N,episode:U}}){Sl(U,N)}function Fi(N){Sl(r(),N,{play:!0,markPlayed:!0})}function uo(N){const{episode:U}=N.detail;vt.set(U),He.set(ie.Player)}function Mi(N,U={}){if(!N)return{src:"",mediaType:"audio"};const q=M(N,U);return z(N,q)?{src:bh(n().app.vault,q.filePath),mediaType:de(N,q)}:{src:N.streamUrl,mediaType:Ka(N)}}function M(N,U){return U[N.podcastName]?.find(q=>q.title===N.title)}function z(N,U){if(!U?.filePath)return!1;const q=de(N,U);if(N.mediaType&&q!==N.mediaType)return!1;if(N.podcastName==="local file"){const Fe=N.filePath;return!Fe||U.filePath===Fe}return Xf(U.streamUrl,N.streamUrl)}function de(N,U){return Yf(U,N.mediaType)}ge(()=>(n(),s()),()=>{E(g,n()?.settings?.autoQueue!==!1||s().episodes.length>0)}),ge(()=>r(),()=>{E(y,r()?.title?.length??0)}),ge(()=>(r(),i()),()=>{E(k,Mi(r(),i()))}),ge(()=>p(k),()=>{E(b,p(k).mediaType)}),ge(()=>p(b),()=>{E(v,p(b)==="video")}),ge(()=>(p($),d()),()=>{p($)&&p($).playbackRate!==d()&&Qi($,p($).playbackRate=d())}),yt(),Re();var Ee=C_(),Ct=F(Ee);{var Yt=N=>{var U=b_(),q=F(U);q.autoplay=!0,an(q,xe=>E($,xe),()=>p($));var Fe=W(q,2);{var Jt=xe=>{var lt=y_(),ds=F(lt);El(ds),j(xe,lt)},Pn=xe=>{var lt=w_();let ds;var fs=F(lt);{let mo=ke(()=>f()?"play":"pause");Ce(fs,{get icon(){return p(mo)},clickable:!1})}we(()=>ds=sn(lt,1,"podcast-video-overlay svelte-vlhi04",null,ds,{visible:f()})),oe("click",lt,be),oe("contextmenu",lt,Fi),j(xe,lt)};ue(Fe,xe=>{p(S)?xe(Jt):xe(Pn,!1)})}var Js=W(Fe,2),ln=F(Js);Ce(ln,{icon:"maximize",clickable:!1}),we(()=>{le(q,"src",(p(k),O(()=>p(k).src))),le(q,"aria-label",(r(),O(()=>r().title)))}),hu("duration","durationchange",q,xe=>Jn(bs,xe)),cu(q,l,xe=>Jn(ut,xe)),uu(q,f,xe=>Jn(rt,xe)),du(q,()=>p(A),xe=>E(A,xe)),oe("ended",q,Y),oe("loadedmetadata",q,Ie),oe("timeupdate",q,Ni),oe("pause",q,Vs),oe("play",q,pu(function(xe){il.call(this,e,xe)})),oe("click",Js,wt),j(N,U)},ot=N=>{var U=E_(),q=F(U),Fe=F(q);{let ln=ke(()=>(r(),O(()=>r().artworkUrl??""))),xe=ke(()=>p(P)||f()?.5:1);pc(Fe,{class:"podcast-artwork",get src(){return p(ln)},get alt(){return r(),O(()=>r().title)},get opacity(){return p(xe)},$$slots:{fallback:(lt,ds)=>{var fs=__(),mo=F(fs);Ce(mo,{icon:"image",size:150,clickable:!1}),we(()=>sn(fs,1,"podcast-artwork-placeholder"+(p(P)||f()?" opacity-50":""),"svelte-vlhi04")),j(lt,fs)}}})}var Jt=W(Fe,2);{var Pn=ln=>{var xe=x_(),lt=F(xe);El(lt),j(ln,xe)},Js=ln=>{var xe=k_();let lt;var ds=F(xe);{let fs=ke(()=>f()?"play":"pause");Ce(ds,{get icon(){return p(fs)},clickable:!1})}we(()=>lt=sn(xe,1,"podcast-artwork-overlay svelte-vlhi04",null,lt,{visible:p(P)||f()})),j(ln,xe)};ue(Jt,ln=>{p(S)?ln(Pn):ln(Js,!1)})}oe("click",q,be),oe("contextmenu",q,Fi),oe("mouseenter",q,()=>E(P,!0)),oe("mouseleave",q,()=>E(P,!1)),j(N,U)};ue(Ct,N=>{p(v)?N(Yt):N(ot,!1)})}var ye=W(Ct,2),ze=F(ye),nt=W(ye,2);{var Lt=N=>{var U=S_();U.autoplay=!0,an(U,q=>E($,q),()=>p($)),we(()=>le(U,"src",(p(k),O(()=>p(k).src)))),hu("duration","durationchange",U,q=>Jn(bs,q)),cu(U,l,q=>Jn(ut,q)),uu(U,f,q=>Jn(rt,q)),du(U,()=>p(A),q=>E(A,q)),oe("ended",U,Y),oe("loadedmetadata",U,Ie),oe("timeupdate",U,Ni),oe("pause",U,Vs),oe("play",U,pu(function(q){il.call(this,e,q)})),j(N,U)};ue(nt,N=>{p(v)||N(Lt)})}var Xt=W(nt,2),cs=F(Xt),Mr=F(cs),Dr=W(cs,2);{let N=ke(()=>(L(ft),l(),a(),O(()=>`${ft(l(),"HH:mm:ss")} of ${ft(a(),"HH:mm:ss")}`)));m_(Dr,{get value(){return l()},get max(){return a()},ariaLabel:"Seek within episode",get valueText(){return p(N)},$$events:{click:me}})}var us=W(Dr,2),Lr=F(us),Ws=W(Xt,2),Ks=F(Ws),Ot=ts(()=>n().api.skipBackward.bind(n().api));hi(Ks,{icon:"skip-back",tooltip:"Skip backward",class:"player-control-button",$$events:{click(...N){p(Ot)?.apply(this,N)}}});var on=W(Ks,2),Cn=ts(()=>n().api.skipForward.bind(n().api));hi(on,{icon:"skip-forward",tooltip:"Skip forward",class:"player-control-button",$$events:{click(...N){p(Cn)?.apply(this,N)}}});var Ys=W(Ws,2),Xs=F(Ys),Tn=F(Xs),Di=F(Tn),Or=W(Tn,2);Uu(Or,{get value(){return p(A)},limits:[0,1,.05],$$events:{change:at}});var fo=W(Xs,2),Br=F(fo),ho=F(Br),po=W(Br,2);{let N=ke(()=>[yf,wf,cl]);Uu(po,{get value(){return d()},get limits(){return p(N)},$$events:{change:_e}})}var Kp=W(Ys,2),Vc=F(Kp);f_(Vc,{get chapters(){return p(K)},get currentTime(){return l()},$$events:{seek:Oe}});var Yp=W(Vc,2);{var Xp=N=>{wh(N,{get episodes(){return s(),O(()=>s().episodes)},showListMenu:!1,showThumbnails:!0,$$events:{contextMenuEpisode:Ri,clickEpisode:uo},$$slots:{header:(U,q)=>{var Fe=A_();j(U,Fe)}}})};ue(Yp,N=>{p(g)&&N(Xp)})}we((N,U,q)=>{br(ye,`--title-char-count: ${p(y)??""}`),Ae(ze,(r(),O(()=>r().title))),Ae(Mr,N),Ae(Lr,U),Ae(Di,`Volume: ${q??""}%`),Ae(ho,`${d()??""}x`)},[()=>(L(ft),l(),O(()=>ft(l(),"HH:mm:ss"))),()=>(L(ft),a(),l(),O(()=>ft(a()-l(),"HH:mm:ss"))),()=>(p(A),O(()=>Math.round(p(A)*100)))]),j(t,Ee),Pe(),m()}var $_=J('<div class="topbar-container svelte-1uvslqs"><button type="button" aria-label="Podcast grid"><!></button> <button type="button"><!></button> <button type="button"><!></button></div>');const I_={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 N_(t,e){Te(e,!1),Le(t,I_);const n=V(),s=V();let r=B(e,"viewState",28,()=>ie.PodcastGrid),i=B(e,"canShowEpisodeList",8,!1),a=B(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 u(P){r()!==P&&(P===ie.EpisodeList&&!i()||P===ie.Player&&!a()||r(P))}ge(()=>L(i()),()=>{E(n,i()?"View episode list":l)}),ge(()=>L(a()),()=>{E(s,a()?"Open player":c)}),yt(),Re();var d=$_(),f=F(d),h=ts(()=>u.bind(null,ie.PodcastGrid));le(f,"title",o);var m=F(f);Ce(m,{icon:"grid",size:20,clickable:!1});var g=W(f,2),y=ts(()=>u.bind(null,ie.EpisodeList)),b=F(g);Ce(b,{icon:"list-minus",size:20,clickable:!1});var v=W(g,2),w=ts(()=>u.bind(null,ie.Player)),k=F(v);Ce(k,{icon:"play",size:20,clickable:!1}),we(()=>{sn(f,1,(L(r()),L(ie),O(()=>`
|
||
topbar-menu-button
|
||
topbar-selectable
|
||
${r()===ie.PodcastGrid?"topbar-selected":""}
|
||
`)),"svelte-1uvslqs"),le(f,"aria-pressed",(L(r()),L(ie),O(()=>r()===ie.PodcastGrid))),sn(g,1,(L(r()),L(ie),L(i()),O(()=>`
|
||
topbar-menu-button
|
||
${r()===ie.EpisodeList?"topbar-selected":""}
|
||
${i()?"topbar-selectable":"topbar-disabled"}
|
||
`)),"svelte-1uvslqs"),le(g,"aria-label",i()?"Episode list":"Episode list (select a podcast or playlist first)"),le(g,"aria-pressed",(L(r()),L(ie),O(()=>r()===ie.EpisodeList))),g.disabled=!i(),le(g,"title",p(n)),sn(v,1,(L(r()),L(ie),L(a()),O(()=>`
|
||
topbar-menu-button
|
||
${r()===ie.Player?"topbar-selected":""}
|
||
${a()?"topbar-selectable":"topbar-disabled"}
|
||
`)),"svelte-1uvslqs"),le(v,"aria-label",a()?"Player":"Player (start playing an episode to open the player)"),le(v,"aria-pressed",(L(r()),L(ie),O(()=>r()===ie.Player))),v.disabled=!a(),le(v,"title",p(s))}),oe("click",f,function(...P){p(h)?.apply(this,P)}),oe("click",g,function(...P){p(y)?.apply(this,P)}),oe("click",v,function(...P){p(w)?.apply(this,P)}),j(t,d),Pe()}var R_=J('<img id="podcast-artwork" class="svelte-4w31cc"/>'),F_=J('<div class="podcast-header svelte-4w31cc"><!> <h2 class="podcast-heading svelte-4w31cc"> </h2></div>');const M_={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 Ro(t,e){Le(t,M_);let n=B(e,"text",8,""),s=B(e,"artworkUrl",8,"");var r=F_(),i=F(r);{var a=c=>{var u=R_();we(()=>{le(u,"src",s()),le(u,"alt",n())}),j(c,u)};ue(i,c=>{s()&&c(a)})}var o=W(i,2),l=F(o);we(()=>Ae(l,n())),j(t,r)}const D_={shouldSort:!0,findAllMatches:!0,threshold:.4,isCaseSensitive:!1,keys:["title"]},zu=new WeakMap;function L_(t){const e=zu.get(t);if(e&&e.size===t.length)return e.fuse;const n=new js(t,D_);return zu.set(t,{fuse:n,size:t.length}),n}function In(t,e){return e.length===0?[]:t.trim().length===0?e:L_(e).search(t).map(r=>r.item)}var O_=J('<span class="feed-loading-names svelte-14kt8yt"> </span>'),B_=J('<div class="feed-loading-banner svelte-14kt8yt"><div class="feed-loading-spinner svelte-14kt8yt"><!></div> <div class="feed-loading-text svelte-14kt8yt"><span> </span> <!></div></div>'),U_=J('<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <!>',1),j_=J('<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <div class="playlist-header-icon svelte-14kt8yt"><!></div> <!>',1),z_=J("<!> <!>",1),q_=J('<div class="podcast-view svelte-14kt8yt"><!> <!></div>');const H_={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 V_(t,e){Te(e,!1),Le(t,H_);const n=()=>Ne(pe,"$queue",a),s=()=>Ne(vt,"$currentEpisode",a),r=()=>Ne(hl,"$podcastView",a),i=()=>Ne(He,"$viewState",a),[a,o]=Tr(),l=V();let c=V([]),u=V(null),d=V(null),f=V(!1),h=V([]),m=V(null),g=V([]),y=[],b=V(!1),v=V(new Set),w="",k=V([]),P=V(""),S=!0;Wa(()=>{S=!1}),An(()=>{const M=()=>{const ye=Object.values(T(mt)),ze=T(pe),nt=T(re)?.settings?.autoQueue!==!1||ze.episodes.length>0;E(g,[...nt?[ze]:[],T(Ft),T(Vt),me(),...ye])},z=()=>{M(),wt()},de=[mt.subscribe(z),pe.subscribe(M),Ft.subscribe(z),Vt.subscribe(z),re.subscribe(M),We.subscribe(()=>{M(),p(f)&&_e()})],Ee=Et.subscribe(ye=>{const ze=Object.values(ye),nt=new Set(p(c).map(Xt=>Xt.title));E(c,ze);const Lt=ze.filter(Xt=>!nt.has(Xt.title));Lt.length>0&&Kt(Lt)});let Ct=T(He);const Yt=He.subscribe(ye=>{Ct=ye}),ot=Xg.subscribe(ye=>{y=ye,Ct===ie.EpisodeList&&!p(u)&&!p(d)&&!p(f)&&E(h,w?In(w,ye):ye)});return()=>{ot(),Yt(),Ee(),de.forEach(ye=>ye())}});function A(){const M=T(re)?.settings?.feedCache;return Math.max(1,M?.ttlHours??6)*60*60*1e3}function $(){return T(re)?.settings?.feedCache?.enabled!==!1}function R(M,z){return M?.length?z?.length?M.length>z.length:!0:!1}async function K(M,z=!0,de=!1){const Ee=$(),Ct=A(),ot=T(en)[M.title];if(z&&ot&&ot.length>0)return ot;if(z&&Ee){const ye=Io(M,Ct);if(ye?.length)return en.update(ze=>({...ze,[M.title]:ye})),ye}try{const ye=await new Ai(M).getEpisodes(M.url);return en.update(ze=>({...ze,[M.title]:ye})),Ee&&ob(M,ye),ye}catch{const ze=T(et);if(ze[M.title]?.length)return ze[M.title];if(!z){if(ot?.length)return ot;if(Ee){const nt=Io(M,Ct);if(nt?.length)return en.update(Lt=>({...Lt,[M.title]:nt})),nt}}return de&&new _.Notice(`Could not load episodes for ${M.title}. Check your connection and try again.`),[]}}function Z(){const M=new Set(fl(T(We)).map(({episode:z})=>z.podcastName));return p(c).filter(z=>M.has(z.title))}async function ee(M,z=!1){const Ee=$()?Io(M,A()):null,Ct=T(en)[M.title];return R(Ct,Ee)?Ct:K(M,!1,z)}async function be(M,z="cached",de=!1){return z==="network"?K(M,!1,de):z==="full"?ee(M,de):K(M,!0,de)}function me(){return{...Zi,episodes:fl(T(We)).map(({episode:M})=>yh(M)),isVirtual:!0}}function D(){const M=Object.values(T(en)),z=Object.values(T(et)),de=Object.values(T(mt)).map(Ee=>Ee.episodes);return[...M,...z,T(pe).episodes,T(Ft).episodes,T(Vt).episodes,...de]}function Y(M,z){if(!z)return M;const de=new Map(M.map(Ee=>[Ee.episode,Ee]));return In(z,M.map(Ee=>Ee.episode)).map(Ee=>de.get(Ee)).filter(Ee=>!!Ee)}function _e(){const M=Qb(T(We),D());E(m,Y(M,w)),E(h,p(m).map(z=>z.episode))}function at(){return p(f)&&p(d)?.isVirtual&&p(d).name===Zi.name}function Oe(){at()&&_e()}function wt(){if(!p(d)||p(d).isVirtual)return;const M=p(d).name;if(M===T(pe).name)return;let z;if(M===T(Ft).name)z=T(Ft);else if(M===T(Vt).name)z=T(Vt);else if(z=T(mt)[M],!z){Wt();return}z&&(E(d,z),E(h,w?In(w,z.episodes):z.episodes))}function Wt(){E(u,null),E(d,null),E(f,!1),E(m,null),E(h,w?In(w,y):y),He.set(ie.EpisodeList)}function Ie(M){if("playedEpisodeKey"in M)return typeof M.playedEpisodeKey=="string"?M.playedEpisodeKey:void 0}function At(M,z){if(!S)return;const de=new Set(p(v));z?de.add(M):de.delete(M),E(v,de)}function Kt(M,z="cached"){return M.length?Promise.all(M.map(async de=>{At(de.title,!0);try{await be(de,z)}finally{At(de.title,!1)}})).then(()=>{}):Promise.resolve()}async function Rr(M){const{feed:z}=M.detail;E(u,z),E(d,null),E(f,!1),E(m,null),E(h,[]),He.set(ie.EpisodeList),At(z.title,!0);try{const de=await ee(z,!0);E(h,w?In(w,de):de)}finally{At(z.title,!1)}}function Fr(M){const{episode:z,entry:de}=M.detail;if(!de.isAvailable){new _.Notice("This played episode is no longer available in current feeds.");return}vt.set(z),He.set(ie.Player)}function Hs({detail:{event:M,episode:z,entry:de}}){Sl(z,M,de.isAvailable?void 0:{play:!0,download:!0,createNote:!0,favorite:!0,queue:!0,playlists:!0},Ie(de))}async function Ni(){if(p(f)){await Kt(Z(),"network"),Oe();return}if(!p(u)&&!p(d)){await Kt(p(c),"network");return}if(p(u)){At(p(u).title,!0);try{const M=await be(p(u),"network",!0);E(m,null),E(h,w?In(w,M):M)}finally{At(p(u).title,!1)}}}const lo=_.debounce(M=>{const{query:z}=M.detail;if(w=z,p(f)){_e();return}if(p(u)){const Ee=T(en)[p(u).title]??[];E(m,null),E(h,In(z,Ee));return}if(p(d)){E(m,null),E(h,In(z,p(d).episodes));return}E(m,null),E(h,In(z,y))},250);function co(M){const{playlist:z}=M.detail;if(z.isVirtual&&z.name===Zi.name){E(u,null),E(d,z),E(f,!0),E(h,[]),E(m,[]),He.set(ie.EpisodeList),Kt(Z(),"full").then(()=>{Oe()});return}z.name===n().name&&n().episodes.length>0?(E(u,null),E(d,null),E(f,!1),E(m,null),s()||vt.set(n().episodes[0]),He.set(ie.Player)):(E(u,null),E(d,z),E(f,!1),E(m,null),E(h,z.episodes),He.set(ie.EpisodeList))}ge(()=>p(v),()=>{E(k,Array.from(p(v)))}),ge(()=>(p(k),p(u)),()=>{E(l,p(k).filter(M=>M!==p(u)?.title))}),ge(()=>p(l),()=>{E(P,p(l).length>3?`${p(l).slice(0,3).join(", ")} +${p(l).length-3} more`:p(l).join(", "))}),ge(()=>p(k),()=>{E(b,p(k).length>0)}),yt(),Re();var Vs=q_(),Ri=F(Vs);{let M=ke(()=>!!s());N_(Ri,{canShowEpisodeList:!0,get canShowPlayer(){return p(M)},get viewState(){return Fg(),i()},set viewState(z){Jn(He,z)},$$legacy:!0})}var Fi=W(Ri,2);{var uo=M=>{P_(M,{})},Mi=M=>{var z=pt(),de=Ve(z);{var Ee=Yt=>{var ot=z_(),ye=Ve(ot);{var ze=Lt=>{var Xt=B_(),cs=F(Xt),Mr=F(cs);Ce(Mr,{icon:"loader-2",size:18,clickable:!1});var Dr=W(cs,2),us=F(Dr),Lr=F(us),Ws=W(us,2);{var Ks=Ot=>{var on=O_(),Cn=F(on);we(()=>Ae(Cn,p(P))),j(Ot,on)};ue(Ws,Ot=>{p(P)&&Ot(Ks)})}we(()=>Ae(Lr,`Updating ${p(l),O(()=>p(l).length)??""} feed${p(l),O(()=>p(l).length===1?"":"s")??""}`)),j(Lt,Xt)};ue(ye,Lt=>{p(l),O(()=>p(l).length>0)&&Lt(ze)})}var nt=W(ye,2);{let Lt=ke(()=>!p(d)||p(f)),Xt=ke(()=>!p(f)),cs=ke(()=>(p(u),p(v),p(b),O(()=>p(u)?p(v).has(p(u).title):p(b))));wh(nt,{get episodes(){return p(h)},get episodeEntries(){return p(m)},get showThumbnails(){return p(Lt)},get showPlayedToggle(){return p(Xt)},get alwaysShowPlayedEpisodes(){return p(f)},get isLoading(){return p(cs)},$$events:{clickEpisode:Fr,contextMenuEpisode:Hs,clickRefresh:Ni,search:lo},$$slots:{header:(Mr,Dr)=>{var us=pt(),Lr=Ve(us);{var Ws=Ot=>{var on=U_(),Cn=Ve(on),Ys=F(Cn);Ce(Ys,{icon:"arrow-left",size:20,clickable:!1});var Xs=W(Cn,2);Ro(Xs,{get text(){return p(u),O(()=>p(u).title)},get artworkUrl(){return p(u),O(()=>p(u).artworkUrl)}}),oe("click",Cn,Wt),j(Ot,on)},Ks=Ot=>{var on=pt(),Cn=Ve(on);{var Ys=Tn=>{var Di=j_(),Or=Ve(Di),fo=F(Or);Ce(fo,{icon:"arrow-left",size:20,clickable:!1});var Br=W(Or,2),ho=F(Br);Ce(ho,{get icon(){return p(d),O(()=>p(d).icon)},size:40,clickable:!1});var po=W(Br,2);Ro(po,{get text(){return p(d),O(()=>p(d).name)}}),oe("click",Or,Wt),j(Tn,Di)},Xs=Tn=>{Ro(Tn,{text:"Latest Episodes"})};ue(Cn,Tn=>{p(d)?Tn(Ys):Tn(Xs,!1)},!0)}j(Ot,on)};ue(Lr,Ot=>{p(u)?Ot(Ws):Ot(Ks,!1)})}j(Mr,us)}}})}j(Yt,ot)},Ct=Yt=>{var ot=pt(),ye=Ve(ot);{var ze=nt=>{Lb(nt,{get feeds(){return p(c)},get playlists(){return p(g)},$$events:{clickPodcast:Rr,clickPlaylist:co}})};ue(ye,nt=>{i(),L(ie),O(()=>i()===ie.PodcastGrid)&&nt(ze)},!0)}j(Yt,ot)};ue(de,Yt=>{i(),L(ie),O(()=>i()===ie.EpisodeList)?Yt(Ee):Yt(Ct,!1)},!0)}j(M,z)};ue(Fi,M=>{i(),L(ie),O(()=>i()===ie.Player)?M(uo):M(Mi,!1)})}an(Vs,M=>Jn(hl,M),()=>r()),j(t,Vs),Pe(),o()}class W_ extends _.ItemView{constructor(e,n){super(e),this.plugin=n,this.podcastView=null}getViewType(){return Mn}getDisplayText(){return"Podcast Player"}getIcon(){return"play-circle"}async onOpen(){this.plugin.shouldMountPodcastView()&&this.mountPodcastView()}mountPodcastView(){this.podcastView||(this.podcastView=va(V_,{target:this.contentEl}))}async onClose(){this.podcastView&&(await ya(this.podcastView),this.podcastView=null),this.contentEl.empty(),this.plugin.unregisterPodcastView(this)}}function Fo(t){const e=t.replace(/\+/g," ");return t===e?[t]:[t,e]}function K_(t,e){for(const n of e){const s=n.trim().toLowerCase(),r=t.find(i=>i.title.trim().toLowerCase()===s);if(r)return r}}function qu(t){const e=We.get(t);return e?e.finished||e.duration>0&&e.time>=e.duration?0:e.time:0}async function Y_({url:t,episodeName:e,time:n,endTime:s,end:r,to:i},a,o){if(!t||!e){new _.Notice("URL and episode name are required to play an episode");return}const l=n!==void 0&&n!=="";let c=0;if(l){if(c=parseFloat(n),!Number.isFinite(c)){new _.Notice("Timestamp must be a valid number");return}if(c<0){new _.Notice("Timestamp must be zero or greater");return}}const u=X_(s??r??i,l,c);if(u===null)return;const d=Fo(e),f=T(vt),h=!!f&&d.includes(f.title),m=T(He)===ie.Player;if(h){if(l){const k=gt(f);ti.set({episodeKey:k,time:c,endTime:u}),He.set(ie.Player),a.currentTime=c,Hu(k,c,u),rt.set(!1),m&&ti.set(null),await o?.();return}Gt.set(null),He.set(ie.Player);const v=T(ut),w=T(bs);w>0&&v>=w&&(a.currentTime=0),rt.set(!1),await o?.();return}const{vault:g}=T(re).app,y=Fo(t).map(v=>g.getAbstractFileByPath(v)).find(v=>v!==null);let b;if(y)b=d.map(v=>Vt.getLocalEpisode(v)).find(v=>v!==void 0);else if(!Fo(t).some(v=>/^https?:\/\//i.test(v)))b=d.map(v=>Vt.getLocalEpisode(v)).find(v=>v!==void 0);else try{const w=await new Ai().getEpisodes(t);b=K_(w,d)}catch{new _.Notice("Could not load the podcast feed");return}if(!b){new _.Notice("Episode not found");return}ti.set({episodeKey:gt(b),time:l?c:qu(b),endTime:l?u:void 0}),Hu(gt(b),l?c:qu(b),l?u:void 0),vt.set(b),He.set(ie.Player),await o?.()}function X_(t,e,n){if(t===void 0||t==="")return;if(!e)return new _.Notice("Segment links require a start timestamp"),null;if(n<0)return new _.Notice("Segment start time must be zero or greater"),null;const s=parseFloat(t);return Number.isFinite(s)?s<=n?(new _.Notice("Segment end time must be after the start time"),null):s:(new _.Notice("Segment end time must be a valid number"),null)}function Hu(t,e,n){Gt.set(n===void 0?null:{episodeKey:t,startTime:e,endTime:n})}function J_(t){return t.workspace.on("file-menu",(e,n)=>{if(!(n instanceof _.TFile))return;const s=Ea(n.path),r=qs(n.extension);if(!(!s&&!r)){if(r){Mo(e,t,n,"audio"),Mo(e,t,n,"video");return}s&&Mo(e,t,n,s)}})}function Mo(t,e,n,s){const i=qs(n.extension)?`Play as ${s} with PodNotes`:"Play with PodNotes";t.addItem(a=>a.setIcon("play").setTitle(i).onClick(async()=>{const o={title:n.basename,description:"",content:"",podcastName:"local file",url:e.fileManager.generateMarkdownLink(n,""),streamUrl:bh(e.vault,n.path),filePath:n.path,episodeDate:new Date(n.stat.ctime),mediaType:s},l=et.addEpisode(o,n.path,n.stat.size);l&&new _.Notice(`A local file named "${n.basename}" was already tracked at "${l}". It has been replaced by "${n.path}".`),We.get(o)?.finished&&We.markAsUnplayed(o),vt.set(o),He.set(ie.Player),T(re)?.enablePodcastViewMount(),await G_(e)}))}async function G_(t){const{workspace:e}=t;let n=e.getLeavesOfType(Mn)[0]??null;if(!n){if(n=e.getRightLeaf(!1),!n)return;await n.setViewState({type:Mn,active:!0})}await e.revealLeaf(n)}const si=20*1024*1024,Al=44,pi=2;function Q_(t){switch(t.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";case"webm":return"audio/webm";default:return"audio/mpeg"}}function Z_(t,e){return t.toLowerCase()==="m4a"||e==="audio/mp4"}async function Vu({buffer:t,basename:e,extension:n,mimeType:s}){if(t.byteLength<=si)return[new File([t],`${e}.${n}`,{type:s})];if(Z_(n,s)){const r=await t0(t,e);if(r.length>0)return r}return e0(t,e,n,s)}function e0(t,e,n,s){if(t.byteLength<=si)return[new File([t],`${e}.${n}`,{type:s})];const r=[];for(let i=0,a=0;i<t.byteLength;i+=si,a++){const o=t.slice(i,i+si);r.push(new File([o],`${e}.part${a}.${n}`,{type:s}))}return r}async function t0(t,e){const n=n0();if(!n)return[];try{const s=await n.decodeAudioData(t.slice(0));return s0(s,e)}catch{return[]}finally{try{await n.close()}catch{}}}function n0(){if(typeof window>"u")return null;const t=window.AudioContext||window.webkitAudioContext;return t?new t:null}function s0(t,e){const n=t.numberOfChannels,s=n*pi,r=si-Al,i=Math.max(1,Math.floor(r/s)),a=Array.from({length:n},(c,u)=>t.getChannelData(u)),o=[];let l=0;for(let c=0;c<t.length;c+=i){const u=Math.min(t.length,c+i),d=r0(a,t.sampleRate,c,u);o.push(new File([d],`${e}.part${l}.wav`,{type:"audio/wav"})),l++}return o}function r0(t,e,n,s){const r=t.length,i=Math.max(0,s-n),a=r*pi,o=new ArrayBuffer(Al+i*a),l=new DataView(o);i0(l,e,r,i);let c=Al;for(let u=0;u<i;u++)for(let d=0;d<r;d++){const f=t[d][n+u]??0,h=Math.max(-1,Math.min(1,f)),m=h<0?h*32768:h*32767;l.setInt16(c,Math.round(m),!0),c+=pi}return o}function i0(t,e,n,s){const r=n*pi,i=e*r,a=s*r;zi(t,0,"RIFF"),t.setUint32(4,36+a,!0),zi(t,8,"WAVE"),zi(t,12,"fmt "),t.setUint32(16,16,!0),t.setUint16(20,1,!0),t.setUint16(22,n,!0),t.setUint32(24,e,!0),t.setUint32(28,i,!0),t.setUint16(32,r,!0),t.setUint16(34,pi*8,!0),zi(t,36,"data"),t.setUint32(40,a,!0)}function zi(t,e,n){for(let s=0;s<n.length;s++)t.setUint8(e+s,n.charCodeAt(s))}function a0(t,e){let n=e;const s=Date.now();let r;const i=new _.Notice(e,0);function a(u){return`${t} (${c()}):
|
||
|
||
${u}`}function o(u){n=u,i.setMessage(a(n))}const l=window.setInterval(()=>{i.setMessage(a(n))},1e3);function c(){return o0(r?r-s:Date.now()-s)}return{update:o,hide:()=>i.hide(),stop:()=>{r=Date.now(),window.clearInterval(l)}}}function o0(t){const e=Math.floor(t/1e3),n=Math.floor(e/60);return`${Math.floor(n/60).toString().padStart(2,"0")}:${(n%60).toString().padStart(2,"0")}:${(e%60).toString().padStart(2,"0")}`}class l0{constructor(e){this.client=null,this.cachedApiKey=null,this.MAX_RETRIES=3,this.MAX_CONCURRENT_TRANSCRIPTIONS=2,this.MAX_CONCURRENT_CHUNK_TRANSCRIPTIONS=3,this.pendingEpisodes=[],this.activeTranscriptions=new Set,this.plugin=e}async transcribeCurrentEpisode(){if(!xb(this.plugin.settings)){const a=this.plugin.settings.transcript.diarization,o=a?.enabled&&a.provider==="deepgram";new _.Notice(o?"Please add your Deepgram API key in the transcript settings to use Deepgram diarization.":"Please add your OpenAI API key in the transcript settings first.");return}const e=this.plugin.api.podcast;if(!e){new _.Notice("No episode is currently playing.");return}const n=this.getTranscriptPath(e);if(this.plugin.app.vault.getAbstractFileByPath(n)instanceof _.TFile){new _.Notice(`You've already transcribed this episode - found ${n}.`);return}const r=this.getEpisodeKey(e);if(this.pendingEpisodes.some(a=>this.getEpisodeKey(a)===r)||this.activeTranscriptions.has(r)){new _.Notice("This episode is already queued or transcribing.");return}this.pendingEpisodes.push(e),new _.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 n=this.getEpisodeKey(e);this.activeTranscriptions.add(n),this.transcribeEpisode(e).finally(()=>{this.activeTranscriptions.delete(n),this.drainQueue()})}}getEpisodeKey(e){return`${e.podcastName}:${e.title}`}async transcribeEpisode(e){const n=a0(`Transcription: ${e.title}`,"Preparing to transcribe...");try{const s=this.getTranscriptPath(e);if(this.plugin.app.vault.getAbstractFileByPath(s)instanceof _.TFile){n.stop(),n.update(`Transcript already exists - skipped (${s}).`);return}n.update("Fetching episode audio...");const{buffer:i,extension:a,basename:o}=await uw(e),l=Q_(a),c=await this.buildTranscriptBody({buffer:i,mimeType:l,extension:a,basename:o},n.update);n.update("Saving transcription..."),await this.saveTranscription(e,c),n.stop(),n.update("Transcription completed and saved.")}catch(s){const r=s instanceof Error?s.message:String(s);n.stop(),n.update(`Transcription failed: ${r}`)}finally{n.stop(),window.setTimeout(()=>n.hide(),5e3)}}async buildTranscriptBody(e,n){const s=this.plugin.settings.transcript.diarization;if(s?.enabled){const o=await this.diarize(e,s.provider,n);if(o.length===0)throw new Error("Diarization returned no speech segments.");return zg(o,s.speakerTemplate)}n("Creating audio chunks...");const r=await Vu(e);n("Starting transcription...");const a=(await this.transcribeChunks(r,n)).trim().replace(/\.\s+/g,`.
|
||
|
||
`);if(a.length===0)throw new Error("Transcription returned no text.");return a}async diarize(e,n,s){if(n==="deepgram"){const i=this.plugin.settings.diarizationApiKey?.trim();if(!i)throw new Error("Missing Deepgram API key for diarization.");return bb({audio:e,apiKey:i,onProgress:s})}s("Creating audio chunks...");const r=await Vu(e);return vb({getClient:()=>this.getClient(),chunkFiles:r,maxRetries:this.MAX_RETRIES,onProgress:s})}async transcribeChunks(e,n){const s=await this.getClient(),r=new Array(e.length);let i=0,a=0;const o=()=>{const d=(i/e.length*100).toFixed(1);n(`Transcribing... ${i}/${e.length} chunks completed (${d}%)`)};o();const l=async()=>{for(;;){const d=a++;if(d>=e.length)return;const f=e[d];let h=0;for(;h<this.MAX_RETRIES;)try{const m=await s.audio.transcriptions.create({model:"whisper-1",file:f});r[d]=m.text,i++,o();break}catch{h++,h>=this.MAX_RETRIES?(r[d]=`[Error transcribing chunk ${d}]`,i++,o()):await new Promise(g=>window.setTimeout(g,1e3*h))}}},c=Math.min(this.MAX_CONCURRENT_CHUNK_TRANSCRIPTIONS,e.length),u=Array.from({length:c},()=>l());return await Promise.all(u),r.join(" ")}getTranscriptPath(e){return ah(e,this.plugin.settings.transcript.path)}async saveTranscription(e,n){const s=this.getTranscriptPath(e),r=vy(this.plugin.settings.transcript.template,e,n),i=this.plugin.app.vault,a=s.substring(0,s.lastIndexOf("/"));await Ei(a,i);const o=i.getAbstractFileByPath(s);if(o)if(o instanceof _.TFile)await this.plugin.app.workspace.getLeaf().openFile(o);else throw new Error("Expected a file but found a folder at transcript path.");else{const l=await i.create(s,r);await this.plugin.app.workspace.getLeaf().openFile(l)}}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:n}=await Promise.resolve().then(()=>hx);return this.client=new n({apiKey:e,dangerouslyAllowBrowser:!0}),this.cachedApiKey=e,this.client}}class c0 extends _.Plugin{constructor(){super(...arguments),this.views=new Set,this.storeUnsubscribers=[],this.maxLayoutReadyAttempts=10,this.layoutReadyAttempts=0,this.layoutReadyRetry=null,this.isUnloaded=!1,this.podcastViewMountEnabled=!0,this.isReady=!1,this.pendingSave=null,this.saveScheduled=!1,this.saveChain=Promise.resolve(),this.mediaSessionActions=[]}async onload(){this.isUnloaded=!1,this.podcastViewMountEnabled=!this.isMobileRuntime(),re.set(this),await this.loadSettings(),We.set(this.settings.playedEpisodes),Et.set(this.settings.savedFeeds),mt.set(this.settings.playlists),pe.set(this.settings.queue),Ft.set(this.settings.favorites),Vt.set(this.settings.localFiles),et.set(this.settings.downloadedEpisodes),this.settings.currentEpisode&&vt.set(this.settings.currentEpisode),di.set(this.settings.hidePlayedEpisodes),ui.set(this.settings.episodeListLimit),zn.set(Math.min(1,Math.max(0,this.settings.defaultVolume??1))),Zn.set(Ms(this.settings.defaultPlaybackRate)),this.storeUnsubscribers.push(nv(this),Zg()),this.localFilesMirrorUnsubscribe=et.subscribe(e=>Vt.syncWithDownloaded(e)),this.api=new yw,this.volumeUnsubscribe=zn.subscribe(e=>{const n=Math.min(1,Math.max(0,e));if(n!==e){zn.set(n);return}n!==this.settings.defaultVolume&&(this.settings.defaultVolume=n,this.saveSettings())}),mw(this),this.addSettingTab(new kb(this.app,this)),this.registerView(Mn,e=>{const n=new W_(e,this);return this.views.add(n),n}),this.registerEvent(this.app.workspace.on("layout-change",()=>this.dedupePlayerLeaves())),this.addRibbonIcon("podcast","Show PodNotes",()=>{this.activateView()}),this.app.workspace.onLayoutReady(this.onLayoutReady.bind(this)),this.registerObsidianProtocolHandler("podnotes",e=>Y_(e,this.api,()=>this.activateView())),this.registerEvent(J_(this.app)),this.registerMediaSessionHandlers(),this.isReady=!0}onLayoutReady(){if(this.isUnloaded)return;if(this.isMobileRuntime()){this.clearLayoutReadyRetry(),this.layoutReadyAttempts=0;return}if(!this.app.workspace||!this.app.workspace.layoutReady){this.layoutReadyAttempts++,this.layoutReadyAttempts>=this.maxLayoutReadyAttempts||this.layoutReadyRetry||(this.layoutReadyRetry=window.setTimeout(()=>{this.layoutReadyRetry=null,this.onLayoutReady()},100));return}if(this.clearLayoutReadyRetry(),this.layoutReadyAttempts=0,this.app.workspace.getLeavesOfType(Mn).length)return;const e=this.app.workspace.getRightLeaf(!1);e&&e.setViewState({type:Mn}).catch(n=>{})}async activateView(){this.enablePodcastViewMount();const{workspace:e}=this.app;let s=e.getLeavesOfType(Mn)[0]??null;s||(s=e.getRightLeaf(!1),await s?.setViewState({type:Mn,active:!0})),s&&await e.revealLeaf(s)}shouldMountPodcastView(){return this.podcastViewMountEnabled}enablePodcastViewMount(){this.podcastViewMountEnabled=!0;for(const e of this.views)e.mountPodcastView()}unregisterPodcastView(e){this.views.delete(e)}dedupePlayerLeaves(){const e=this.app.workspace.getLeavesOfType(Mn);for(const n of e.slice(1))n.detach()}isMobileRuntime(){return _.Platform.isMobileApp||this.app.isMobile===!0}getTranscriptionService(){return this.transcriptionService||(this.transcriptionService=new l0(this)),this.transcriptionService}captureTimestamp(e){if(!e||!this.api.podcast||!this.settings.timestamp.template)return!1;const n=xa(this.settings.timestamp.template),s=e.getCursor("from"),r=jf(n,{getLine:i=>e.getLine(i),lineCount:e.lineCount(),cursorLine:s.line});return e.replaceSelection(r),!0}captureTimestampInActiveEditor(){return this.captureTimestamp(this.app.workspace.activeEditor?.editor)}async appendTimestampToEpisodeNote(){if(!this.api.podcast||!this.settings.timestamp.template||!this.settings.note.path||!this.settings.note.template)return!1;try{const e=xa(this.settings.timestamp.template),n=e.endsWith(`
|
||
`)?e:`${e}
|
||
`,s=Si(this.api.podcast)??await Vf(this.api.podcast),r=await this.app.vault.read(s),i=r.length>0&&!r.endsWith(`
|
||
`)?`
|
||
`:"";return await this.app.vault.modify(s,`${r}${i}${n}`),!0}catch{return new _.Notice("Failed to capture timestamp into episode note"),!1}}async captureTimestampFromMediaSession(){return this.captureTimestampInActiveEditor()?!0:await this.appendTimestampToEpisodeNote()}registerMediaSessionHandlers(){this.registerMediaSessionAction("previoustrack",()=>{this.captureTimestampFromMediaSession()})}registerMediaSessionAction(e,n){const s=window.navigator?.mediaSession;if(s?.setActionHandler)try{s.setActionHandler(e,n),this.mediaSessionActions.push(e)}catch{}}clearMediaSessionHandlers(){const e=window.navigator?.mediaSession;if(e?.setActionHandler){for(const n of this.mediaSessionActions)try{e.setActionHandler(n,null)}catch{}this.mediaSessionActions=[]}}onunload(){this.isUnloaded=!0,this.clearLayoutReadyRetry(),this.clearMediaSessionHandlers();for(const e of this.storeUnsubscribers)e();this.storeUnsubscribers=[],this.volumeUnsubscribe?.(),this.localFilesMirrorUnsubscribe?.(),this.views.clear()}clearLayoutReadyRetry(){this.layoutReadyRetry&&(window.clearTimeout(this.layoutReadyRetry),this.layoutReadyRetry=null)}async loadSettings(){const e=await this.loadData();this.settings=Object.assign({},ht,e),this.settings.timestamp={...ht.timestamp,...e?.timestamp??{}},this.settings.download={...ht.download,...e?.download??{}},this.settings.download.path=xw(this.settings.download.path),this.settings.episodeListLimit=ws(this.settings.episodeListLimit),this.settings.skipBackwardLength=Lu(this.settings.skipBackwardLength,ht.skipBackwardLength),this.settings.skipForwardLength=Lu(this.settings.skipForwardLength,ht.skipForwardLength),this.settings.defaultPlaybackRate=Ms(this.settings.defaultPlaybackRate),this.settings.note=kw(e?.note),this.settings.transcript=oh(e?.transcript),this.settings.feedNote=Sw(e?.feedNote)}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 te(t,e,n,s,r){if(typeof e=="function"?t!==e||!0:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return e.set(t,n),n}function x(t,e,n,s){if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return n==="m"?s:n==="a"?s.call(t):s?s.value:e.get(t)}let _h=function(){const{crypto:t}=globalThis;if(t?.randomUUID)return _h=t.randomUUID.bind(t),t.randomUUID();const e=new Uint8Array(1),n=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,s=>(+s^n()&15>>+s/4).toString(16))};function Cl(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}const Tl=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){const e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch{}try{return new Error(JSON.stringify(t))}catch{}}return new Error(t)};class Q extends Error{}class Ye extends Q{constructor(e,n,s,r){super(`${Ye.makeMessage(e,n,s)}`),this.status=e,this.headers=r,this.requestID=r?.get("x-request-id"),this.error=n;const i=n;this.code=i?.code,this.param=i?.param,this.type=i?.type}static makeMessage(e,n,s){const r=n?.message?typeof n.message=="string"?n.message:JSON.stringify(n.message):n?JSON.stringify(n):s;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||"(no status code or body)"}static generate(e,n,s,r){if(!e||!r)return new Ci({message:s,cause:Tl(n)});const i=n?.error;return e===400?new mc(e,i,s,r):e===401?new gc(e,i,s,r):e===403?new vc(e,i,s,r):e===404?new yc(e,i,s,r):e===409?new wc(e,i,s,r):e===422?new bc(e,i,s,r):e===429?new _c(e,i,s,r):e>=500?new xc(e,i,s,r):new Ye(e,i,s,r)}}class Mt extends Ye{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}}class Ci extends Ye{constructor({message:e,cause:n}){super(void 0,void 0,e||"Connection error.",void 0),n&&(this.cause=n)}}class Za extends Ci{constructor({message:e}={}){super({message:e??"Request timed out."})}}class mc extends Ye{}class gc extends Ye{}class vc extends Ye{}class yc extends Ye{}class wc extends Ye{}class bc extends Ye{}class _c extends Ye{}class xc extends Ye{}class xh extends Q{constructor(){super("Could not parse response content as the length limit was reached")}}class kh extends Q{constructor(){super("Could not parse response content as the request was rejected by the content filter")}}class lr extends Error{constructor(e){super(e)}}const u0=/^[a-z][a-z0-9+.-]*:/i,d0=t=>u0.test(t);let _t=t=>(_t=Array.isArray,_t(t)),Wu=_t;function Eh(t){return typeof t!="object"?{}:t??{}}function f0(t){if(!t)return!0;for(const e in t)return!1;return!0}function h0(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function Do(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}const p0=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new Q(`${t} must be an integer`);if(e<0)throw new Q(`${t} must be a positive integer`);return e},m0=t=>{try{return JSON.parse(t)}catch{return}},Ti=t=>new Promise(e=>setTimeout(e,t)),nr="6.9.1",g0=()=>typeof window<"u"&&typeof window.document<"u"&&typeof navigator<"u";function v0(){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 y0=()=>{const t=v0();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nr,"X-Stainless-OS":Yu(Deno.build.os),"X-Stainless-Arch":Ku(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":nr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nr,"X-Stainless-OS":Yu(globalThis.process.platform??"unknown"),"X-Stainless-Arch":Ku(globalThis.process.arch??"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":globalThis.process.version??"unknown"};const e=w0();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":nr,"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":nr,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function w0(){if(typeof navigator>"u"||!navigator)return null;const t=[{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:n}of t){const s=n.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 Ku=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",Yu=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown");let Xu;const b0=()=>Xu??(Xu=y0());function _0(){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 Sh(...t){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(...t)}function Ah(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Sh({start(){},async pull(n){const{done:s,value:r}=await e.next();s?n.close():n.enqueue(r)},async cancel(){await e.return?.()}})}function Ch(t){if(t[Symbol.asyncIterator])return t;const e=t.getReader();return{async next(){try{const n=await e.read();return n?.done&&e.releaseLock(),n}catch(n){throw e.releaseLock(),n}},async return(){const n=e.cancel();return e.releaseLock(),await n,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function x0(t){if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await t[Symbol.asyncIterator]().return?.();return}const e=t.getReader(),n=e.cancel();e.releaseLock(),await n}const k0=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)}),Th="RFC3986",Ph=t=>String(t),Ju={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:Ph},E0="RFC1738";let Pl=(t,e)=>(Pl=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),Pl(t,e));const un=(()=>{const t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})(),Lo=1024,S0=(t,e,n,s,r)=>{if(t.length===0)return t;let i=t;if(typeof t=="symbol"?i=Symbol.prototype.toString.call(t):typeof t!="string"&&(i=String(t)),n==="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+=Lo){const l=i.length>=Lo?i.slice(o,o+Lo):i,c=[];for(let u=0;u<l.length;++u){let d=l.charCodeAt(u);if(d===45||d===46||d===95||d===126||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||r===E0&&(d===40||d===41)){c[c.length]=l.charAt(u);continue}if(d<128){c[c.length]=un[d];continue}if(d<2048){c[c.length]=un[192|d>>6]+un[128|d&63];continue}if(d<55296||d>=57344){c[c.length]=un[224|d>>12]+un[128|d>>6&63]+un[128|d&63];continue}u+=1,d=65536+((d&1023)<<10|l.charCodeAt(u)&1023),c[c.length]=un[240|d>>18]+un[128|d>>12&63]+un[128|d>>6&63]+un[128|d&63]}a+=c.join("")}return a};function A0(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Gu(t,e){if(_t(t)){const n=[];for(let s=0;s<t.length;s+=1)n.push(e(t[s]));return n}return e(t)}const $h={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Ih=function(t,e){Array.prototype.push.apply(t,_t(e)?e:[e])};let Qu;const Ue={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:S0,encodeValuesOnly:!1,format:Th,formatter:Ph,indices:!1,serializeDate(t){return(Qu??(Qu=Function.prototype.call.bind(Date.prototype.toISOString)))(t)},skipNulls:!1,strictNullHandling:!1};function C0(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}const Oo={};function Nh(t,e,n,s,r,i,a,o,l,c,u,d,f,h,m,g,y,b){let v=t,w=b,k=0,P=!1;for(;(w=w.get(Oo))!==void 0&&!P;){const K=w.get(t);if(k+=1,typeof K<"u"){if(K===k)throw new RangeError("Cyclic object value");P=!0}typeof w.get(Oo)>"u"&&(k=0)}if(typeof c=="function"?v=c(e,v):v instanceof Date?v=f?.(v):n==="comma"&&_t(v)&&(v=Gu(v,function(K){return K instanceof Date?f?.(K):K})),v===null){if(i)return l&&!g?l(e,Ue.encoder,y,"key",h):e;v=""}if(C0(v)||A0(v)){if(l){const K=g?e:l(e,Ue.encoder,y,"key",h);return[m?.(K)+"="+m?.(l(v,Ue.encoder,y,"value",h))]}return[m?.(e)+"="+m?.(String(v))]}const S=[];if(typeof v>"u")return S;let A;if(n==="comma"&&_t(v))g&&l&&(v=Gu(v,l)),A=[{value:v.length>0?v.join(",")||null:void 0}];else if(_t(c))A=c;else{const K=Object.keys(v);A=u?K.sort(u):K}const $=o?String(e).replace(/\./g,"%2E"):String(e),R=s&&_t(v)&&v.length===1?$+"[]":$;if(r&&_t(v)&&v.length===0)return R+"[]";for(let K=0;K<A.length;++K){const Z=A[K],ee=typeof Z=="object"&&typeof Z.value<"u"?Z.value:v[Z];if(a&&ee===null)continue;const be=d&&o?Z.replace(/\./g,"%2E"):Z,me=_t(v)?typeof n=="function"?n(R,be):R:R+(d?"."+be:"["+be+"]");b.set(t,k);const D=new WeakMap;D.set(Oo,b),Ih(S,Nh(ee,me,n,s,r,i,a,o,n==="comma"&&g&&_t(v)?null:l,c,u,d,f,h,m,g,y,D))}return S}function T0(t=Ue){if(typeof t.allowEmptyArrays<"u"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys<"u"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder<"u"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");const e=t.charset||Ue.charset;if(typeof t.charset<"u"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let n=Th;if(typeof t.format<"u"){if(!Pl(Ju,t.format))throw new TypeError("Unknown format option provided.");n=t.format}const s=Ju[n];let r=Ue.filter;(typeof t.filter=="function"||_t(t.filter))&&(r=t.filter);let i;if(t.arrayFormat&&t.arrayFormat in $h?i=t.arrayFormat:"indices"in t?i=t.indices?"indices":"repeat":i=Ue.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");const a=typeof t.allowDots>"u"?t.encodeDotInKeys?!0:Ue.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:Ue.addQueryPrefix,allowDots:a,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:Ue.allowEmptyArrays,arrayFormat:i,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:Ue.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter>"u"?Ue.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:Ue.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:Ue.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:Ue.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:Ue.encodeValuesOnly,filter:r,format:n,formatter:s,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:Ue.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:Ue.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:Ue.strictNullHandling}}function P0(t,e={}){let n=t;const s=T0(e);let r,i;typeof s.filter=="function"?(i=s.filter,n=i("",n)):_t(s.filter)&&(i=s.filter,r=i);const a=[];if(typeof n!="object"||n===null)return"";const o=$h[s.arrayFormat],l=o==="comma"&&s.commaRoundTrip;r||(r=Object.keys(n)),s.sort&&r.sort(s.sort);const c=new WeakMap;for(let f=0;f<r.length;++f){const h=r[f];s.skipNulls&&n[h]===null||Ih(a,Nh(n[h],h,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 u=a.join(s.delimiter);let d=s.addQueryPrefix===!0?"?":"";return s.charsetSentinel&&(s.charset==="iso-8859-1"?d+="utf8=%26%2310003%3B&":d+="utf8=%E2%9C%93&"),u.length>0?d+u:""}function $0(t){let e=0;for(const r of t)e+=r.length;const n=new Uint8Array(e);let s=0;for(const r of t)n.set(r,s),s+=r.length;return n}let Zu;function kc(t){let e;return(Zu??(e=new globalThis.TextEncoder,Zu=e.encode.bind(e)))(t)}let ed;function td(t){let e;return(ed??(e=new globalThis.TextDecoder,ed=e.decode.bind(e)))(t)}var Tt,Pt;class eo{constructor(){Tt.set(this,void 0),Pt.set(this,void 0),te(this,Tt,new Uint8Array),te(this,Pt,null)}decode(e){if(e==null)return[];const n=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?kc(e):e;te(this,Tt,$0([x(this,Tt,"f"),n]));const s=[];let r;for(;(r=I0(x(this,Tt,"f"),x(this,Pt,"f")))!=null;){if(r.carriage&&x(this,Pt,"f")==null){te(this,Pt,r.index);continue}if(x(this,Pt,"f")!=null&&(r.index!==x(this,Pt,"f")+1||r.carriage)){s.push(td(x(this,Tt,"f").subarray(0,x(this,Pt,"f")-1))),te(this,Tt,x(this,Tt,"f").subarray(x(this,Pt,"f"))),te(this,Pt,null);continue}const i=x(this,Pt,"f")!==null?r.preceding-1:r.preceding,a=td(x(this,Tt,"f").subarray(0,i));s.push(a),te(this,Tt,x(this,Tt,"f").subarray(r.index)),te(this,Pt,null)}return s}flush(){return x(this,Tt,"f").length?this.decode(`
|
||
`):[]}}Tt=new WeakMap,Pt=new WeakMap;eo.NEWLINE_CHARS=new Set([`
|
||
`,"\r"]);eo.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function I0(t,e){for(let r=e??0;r<t.length;r++){if(t[r]===10)return{preceding:r,index:r+1,carriage:!1};if(t[r]===13)return{preceding:r,index:r+1,carriage:!0}}return null}function N0(t){for(let s=0;s<t.length-1;s++){if(t[s]===10&&t[s+1]===10||t[s]===13&&t[s+1]===13)return s+2;if(t[s]===13&&t[s+1]===10&&s+3<t.length&&t[s+2]===13&&t[s+3]===10)return s+4}return-1}const Aa={off:0,error:200,warn:300,info:400,debug:500},nd=(t,e,n)=>{if(t){if(h0(Aa,t))return t;Xe(n).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Aa))}`)}};function Vr(){}function qi(t,e,n){return!e||Aa[t]>Aa[n]?Vr:e[t].bind(e)}const R0={error:Vr,warn:Vr,info:Vr,debug:Vr};let sd=new WeakMap;function Xe(t){const e=t.logger,n=t.logLevel??"off";if(!e)return R0;const s=sd.get(e);if(s&&s[0]===n)return s[1];const r={error:qi("error",e,n),warn:qi("warn",e,n),info:qi("info",e,n),debug:qi("debug",e,n)};return sd.set(e,[n,r]),r}const gs=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,n])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":n]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Ur;class _n{constructor(e,n,s){this.iterator=e,Ur.set(this,void 0),this.controller=n,te(this,Ur,s)}static fromSSEResponse(e,n,s){let r=!1;const i=s?Xe(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 F0(e,n))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(u){throw i.error("Could not parse message into JSON:",l.data),i.error("From chunk:",l.raw),u}if(c&&c.error)throw new Ye(void 0,c.error,void 0,e.headers);yield c}else{let c;try{c=JSON.parse(l.data)}catch(u){throw u}if(l.event=="error")throw new Ye(void 0,c.error,c.message,void 0);yield{event:l.event,data:c}}}o=!0}catch(l){if(Cl(l))return;throw l}finally{o||n.abort()}}return new _n(a,n,s)}static fromReadableStream(e,n,s){let r=!1;async function*i(){const o=new eo,l=Ch(e);for await(const c of l)for(const u of o.decode(c))yield u;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(Cl(l))return;throw l}finally{o||n.abort()}}return new _n(a,n,s)}[(Ur=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){const e=[],n=[],s=this.iterator(),r=i=>({next:()=>{if(i.length===0){const a=s.next();e.push(a),n.push(a)}return i.shift()}});return[new _n(()=>r(e),this.controller,x(this,Ur,"f")),new _n(()=>r(n),this.controller,x(this,Ur,"f"))]}toReadableStream(){const e=this;let n;return Sh({async start(){n=e[Symbol.asyncIterator]()},async pull(s){try{const{value:r,done:i}=await n.next();if(i)return s.close();const a=kc(JSON.stringify(r)+`
|
||
`);s.enqueue(a)}catch(r){s.error(r)}},async cancel(){await n.return?.()}})}}async function*F0(t,e){if(!t.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 n=new D0,s=new eo,r=Ch(t.body);for await(const i of M0(r))for(const a of s.decode(i)){const o=n.decode(a);o&&(yield o)}for(const i of s.flush()){const a=n.decode(i);a&&(yield a)}}async function*M0(t){let e=new Uint8Array;for await(const n of t){if(n==null)continue;const s=n instanceof ArrayBuffer?new Uint8Array(n):typeof n=="string"?kc(n):n;let r=new Uint8Array(e.length+s.length);r.set(e),r.set(s,e.length),e=r;let i;for(;(i=N0(e))!==-1;)yield e.slice(0,i),e=e.slice(i)}e.length>0&&(yield e)}class D0{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[n,s,r]=L0(e,":");return r.startsWith(" ")&&(r=r.substring(1)),n==="event"?this.event=r:n==="data"&&this.data.push(r),null}}function L0(t,e){const n=t.indexOf(e);return n!==-1?[t.substring(0,n),e,t.substring(n+e.length)]:[t,"",""]}async function Rh(t,e){const{response:n,requestLogID:s,retryOfRequestLogID:r,startTime:i}=e,a=await(async()=>{if(e.options.stream)return Xe(t).debug("response",n.status,n.url,n.headers,n.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(n,e.controller,t):_n.fromSSEResponse(n,e.controller,t);if(n.status===204)return null;if(e.options.__binaryResponse)return n;const l=n.headers.get("content-type")?.split(";")[0]?.trim();if(l?.includes("application/json")||l?.endsWith("+json")){const d=await n.json();return Fh(d,n)}return await n.text()})();return Xe(t).debug(`[${s}] response parsed`,gs({retryOfRequestLogID:r,url:n.url,status:n.status,body:a,durationMs:Date.now()-i})),a}function Fh(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var Wr;class Pi extends Promise{constructor(e,n,s=Rh){super(r=>{r(null)}),this.responsePromise=n,this.parseResponse=s,Wr.set(this,void 0),te(this,Wr,e)}_thenUnwrap(e){return new Pi(x(this,Wr,"f"),this.responsePromise,async(n,s)=>Fh(e(await this.parseResponse(n,s),s),s.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){const[e,n]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:n,request_id:n.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(x(this,Wr,"f"),e))),this.parsedPromise}then(e,n){return this.parse().then(e,n)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}}Wr=new WeakMap;var Hi;class Ec{constructor(e,n,s,r){Hi.set(this,void 0),te(this,Hi,e),this.options=r,this.response=n,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 x(this,Hi,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Hi=new WeakMap,Symbol.asyncIterator)](){for await(const e of this.iterPages())for(const n of e.getPaginatedItems())yield n}}class Mh extends Pi{constructor(e,n,s){super(e,n,async(r,i)=>new s(r,i.response,await Rh(r,i),i.options))}async*[Symbol.asyncIterator](){const e=await this;for await(const n of e)yield n}}class to extends Ec{constructor(e,n,s,r){super(e,n,s,r),this.data=s.data||[],this.object=s.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}}class De extends Ec{constructor(e,n,s,r){super(e,n,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(),n=e[e.length-1]?.id;return n?{...this.options,query:{...Eh(this.options.query),after:n}}:null}}class Ca extends Ec{constructor(e,n,s,r){super(e,n,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:{...Eh(this.options.query),after:e}}:null}}const Dh=()=>{if(typeof File>"u"){const{process:t}=globalThis,e=typeof t?.versions?.node=="string"&&parseInt(t.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 ri(t,e,n){return Dh(),new File(t,e??"unknown_file",n)}function ta(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}const Sc=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function",rd=async(t,e)=>$l(t.body)?{...t,body:await Lh(t.body,e)}:t,Ls=async(t,e)=>({...t,body:await Lh(t.body,e)}),id=new WeakMap;function O0(t){const e=typeof t=="function"?t:t.fetch,n=id.get(e);if(n)return n;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 id.set(e,s),s}const Lh=async(t,e)=>{if(!await O0(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");const n=new FormData;return await Promise.all(Object.entries(t||{}).map(([s,r])=>Il(n,s,r))),n},Oh=t=>t instanceof Blob&&"name"in t,B0=t=>typeof t=="object"&&t!==null&&(t instanceof Response||Sc(t)||Oh(t)),$l=t=>{if(B0(t))return!0;if(Array.isArray(t))return t.some($l);if(t&&typeof t=="object"){for(const e in t)if($l(t[e]))return!0}return!1},Il=async(t,e,n)=>{if(n!==void 0){if(n==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")t.append(e,String(n));else if(n instanceof Response)t.append(e,ri([await n.blob()],ta(n)));else if(Sc(n))t.append(e,ri([await new Response(Ah(n)).blob()],ta(n)));else if(Oh(n))t.append(e,n,ta(n));else if(Array.isArray(n))await Promise.all(n.map(s=>Il(t,e+"[]",s)));else if(typeof n=="object")await Promise.all(Object.entries(n).map(([s,r])=>Il(t,`${e}[${s}]`,r)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}},Bh=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",U0=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Bh(t),j0=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function Uh(t,e,n){if(Dh(),t=await t,U0(t))return t instanceof File?t:ri([await t.arrayBuffer()],t.name);if(j0(t)){const r=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),ri(await Nl(r),e,n)}const s=await Nl(t);if(e||(e=ta(t)),!n?.type){const r=s.find(i=>typeof i=="object"&&"type"in i&&i.type);typeof r=="string"&&(n={...n,type:r})}return ri(s,e,n)}async function Nl(t){let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Bh(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Sc(t))for await(const n of t)e.push(...await Nl(n));else{const n=t?.constructor?.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${z0(t)}`)}return e}function z0(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(n=>`"${n}"`).join(", ")}]`}class G{constructor(e){this._client=e}}function jh(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}const ad=Object.freeze(Object.create(null)),q0=(t=jh)=>function(n,...s){if(n.length===1)return n[0];let r=!1;const i=[],a=n.reduce((u,d,f)=>{/[?#]/.test(d)&&(r=!0);const h=s[f];let m=(r?encodeURIComponent:t)(""+h);return f!==s.length&&(h==null||typeof h=="object"&&h.toString===Object.getPrototypeOf(Object.getPrototypeOf(h.hasOwnProperty??ad)??ad)?.toString)&&(m=h+"",i.push({start:u.length+d.length,length:m.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),u+d+(f===s.length?"":m)},""),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((u,d)=>u.start-d.start),i.length>0){let u=0;const d=i.reduce((f,h)=>{const m=" ".repeat(h.start-u),g="^".repeat(h.length);return u=h.start+h.length,f+m+g},"");throw new Q(`Path parameters result in path with invalid segments:
|
||
${i.map(f=>f.error).join(`
|
||
`)}
|
||
${a}
|
||
${d}`)}return a},I=q0(jh);let zh=class extends G{list(e,n={},s){return this._client.getAPIList(I`/chat/completions/${e}/messages`,De,{query:n,...s})}};function Ta(t){return t!==void 0&&"function"in t&&t.function!==void 0}function Ac(t){return t?.$brand==="auto-parseable-response-format"}function $i(t){return t?.$brand==="auto-parseable-tool"}function H0(t,e){return!e||!qh(e)?{...t,choices:t.choices.map(n=>(Hh(n.message.tool_calls),{...n,message:{...n.message,parsed:null,...n.message.tool_calls?{tool_calls:n.message.tool_calls}:void 0}}))}:Cc(t,e)}function Cc(t,e){const n=t.choices.map(s=>{if(s.finish_reason==="length")throw new xh;if(s.finish_reason==="content_filter")throw new kh;return Hh(s.message.tool_calls),{...s,message:{...s.message,...s.message.tool_calls?{tool_calls:s.message.tool_calls?.map(r=>W0(e,r))??void 0}:void 0,parsed:s.message.content&&!s.message.refusal?V0(e,s.message.content):null}}});return{...t,choices:n}}function V0(t,e){return t.response_format?.type!=="json_schema"?null:t.response_format?.type==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function W0(t,e){const n=t.tools?.find(s=>Ta(s)&&s.function?.name===e.function.name);return{...e,function:{...e.function,parsed_arguments:$i(n)?n.$parseRaw(e.function.arguments):n?.function.strict?JSON.parse(e.function.arguments):null}}}function K0(t,e){if(!t||!("tools"in t)||!t.tools)return!1;const n=t.tools?.find(s=>Ta(s)&&s.function?.name===e.function.name);return Ta(n)&&($i(n)||n?.function.strict||!1)}function qh(t){return Ac(t.response_format)?!0:t.tools?.some(e=>$i(e)||e.type==="function"&&e.function.strict===!0)??!1}function Hh(t){for(const e of t||[])if(e.type!=="function")throw new Q(`Currently only \`function\` tool calls are supported; Received \`${e.type}\``)}function Y0(t){for(const e of t??[]){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 Pa=t=>t?.role==="assistant",Vh=t=>t?.role==="tool";var Rl,na,sa,Kr,Yr,ra,Xr,Rn,Jr,$a,Ia,sr,Wh;class Tc{constructor(){Rl.add(this),this.controller=new AbortController,na.set(this,void 0),sa.set(this,()=>{}),Kr.set(this,()=>{}),Yr.set(this,void 0),ra.set(this,()=>{}),Xr.set(this,()=>{}),Rn.set(this,{}),Jr.set(this,!1),$a.set(this,!1),Ia.set(this,!1),sr.set(this,!1),te(this,na,new Promise((e,n)=>{te(this,sa,e,"f"),te(this,Kr,n,"f")})),te(this,Yr,new Promise((e,n)=>{te(this,ra,e,"f"),te(this,Xr,n,"f")})),x(this,na,"f").catch(()=>{}),x(this,Yr,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},x(this,Rl,"m",Wh).bind(this))},0)}_connected(){this.ended||(x(this,sa,"f").call(this),this._emit("connect"))}get ended(){return x(this,Jr,"f")}get errored(){return x(this,$a,"f")}get aborted(){return x(this,Ia,"f")}abort(){this.controller.abort()}on(e,n){return(x(this,Rn,"f")[e]||(x(this,Rn,"f")[e]=[])).push({listener:n}),this}off(e,n){const s=x(this,Rn,"f")[e];if(!s)return this;const r=s.findIndex(i=>i.listener===n);return r>=0&&s.splice(r,1),this}once(e,n){return(x(this,Rn,"f")[e]||(x(this,Rn,"f")[e]=[])).push({listener:n,once:!0}),this}emitted(e){return new Promise((n,s)=>{te(this,sr,!0),e!=="error"&&this.once("error",s),this.once(e,n)})}async done(){te(this,sr,!0),await x(this,Yr,"f")}_emit(e,...n){if(x(this,Jr,"f"))return;e==="end"&&(te(this,Jr,!0),x(this,ra,"f").call(this));const s=x(this,Rn,"f")[e];if(s&&(x(this,Rn,"f")[e]=s.filter(r=>!r.once),s.forEach(({listener:r})=>r(...n))),e==="abort"){const r=n[0];!x(this,sr,"f")&&!s?.length&&Promise.reject(r),x(this,Kr,"f").call(this,r),x(this,Xr,"f").call(this,r),this._emit("end");return}if(e==="error"){const r=n[0];!x(this,sr,"f")&&!s?.length&&Promise.reject(r),x(this,Kr,"f").call(this,r),x(this,Xr,"f").call(this,r),this._emit("end")}}_emitFinal(){}}na=new WeakMap,sa=new WeakMap,Kr=new WeakMap,Yr=new WeakMap,ra=new WeakMap,Xr=new WeakMap,Rn=new WeakMap,Jr=new WeakMap,$a=new WeakMap,Ia=new WeakMap,sr=new WeakMap,Rl=new WeakSet,Wh=function(e){if(te(this,$a,!0),e instanceof Error&&e.name==="AbortError"&&(e=new Mt),e instanceof Mt)return te(this,Ia,!0),this._emit("abort",e);if(e instanceof Q)return this._emit("error",e);if(e instanceof Error){const n=new Q(e.message);return n.cause=e,this._emit("error",n)}return this._emit("error",new Q(String(e)))};function X0(t){return typeof t.parse=="function"}var ct,Fl,Na,Ml,Dl,Ll,Kh,Yh;const J0=10;class Xh extends Tc{constructor(){super(...arguments),ct.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){this._chatCompletions.push(e),this._emit("chatCompletion",e);const n=e.choices[0]?.message;return n&&this._addMessage(n),e}_addMessage(e,n=!0){if("content"in e||(e.content=null),this.messages.push(e),n){if(this._emit("message",e),Vh(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(Pa(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(),x(this,ct,"m",Fl).call(this)}async finalMessage(){return await this.done(),x(this,ct,"m",Na).call(this)}async finalFunctionToolCall(){return await this.done(),x(this,ct,"m",Ml).call(this)}async finalFunctionToolCallResult(){return await this.done(),x(this,ct,"m",Dl).call(this)}async totalUsage(){return await this.done(),x(this,ct,"m",Ll).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){const e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);const n=x(this,ct,"m",Na).call(this);n&&this._emit("finalMessage",n);const s=x(this,ct,"m",Fl).call(this);s&&this._emit("finalContent",s);const r=x(this,ct,"m",Ml).call(this);r&&this._emit("finalFunctionToolCall",r);const i=x(this,ct,"m",Dl).call(this);i!=null&&this._emit("finalFunctionToolCallResult",i),this._chatCompletions.some(a=>a.usage)&&this._emit("totalUsage",x(this,ct,"m",Ll).call(this))}async _createChatCompletion(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),x(this,ct,"m",Kh).call(this,n);const i=await e.chat.completions.create({...n,stream:!1},{...s,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Cc(i,n))}async _runChatCompletion(e,n,s){for(const r of n.messages)this._addMessage(r,!1);return await this._createChatCompletion(e,n,s)}async _runTools(e,n,s){const r="tool",{tool_choice:i="auto",stream:a,...o}=n,l=typeof i!="string"&&i.type==="function"&&i?.function?.name,{maxChatCompletions:c=J0}=s||{},u=n.tools.map(h=>{if($i(h)){if(!h.$callback)throw new Q("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:h.$callback,name:h.function.name,description:h.function.description||"",parameters:h.function.parameters,parse:h.$parseRaw,strict:!0}}}return h}),d={};for(const h of u)h.type==="function"&&(d[h.function.name||h.function.function.name]=h.function);const f="tools"in n?u.map(h=>h.type==="function"?{type:"function",function:{name:h.function.name||h.function.function.name,parameters:h.function.parameters,description:h.function.description,strict:h.function.strict}}:h):void 0;for(const h of n.messages)this._addMessage(h,!1);for(let h=0;h<c;++h){const g=(await this._createChatCompletion(e,{...o,tool_choice:i,tools:f,messages:[...this.messages]},s)).choices[0]?.message;if(!g)throw new Q("missing message in ChatCompletion response");if(!g.tool_calls?.length)return;for(const y of g.tool_calls){if(y.type!=="function")continue;const b=y.id,{name:v,arguments:w}=y.function,k=d[v];if(k){if(l&&l!==v){const $=`Invalid tool_call: ${JSON.stringify(v)}. ${JSON.stringify(l)} requested. Please try again`;this._addMessage({role:r,tool_call_id:b,content:$});continue}}else{const $=`Invalid tool_call: ${JSON.stringify(v)}. Available options are: ${Object.keys(d).map(R=>JSON.stringify(R)).join(", ")}. Please try again`;this._addMessage({role:r,tool_call_id:b,content:$});continue}let P;try{P=X0(k)?await k.parse(w):w}catch($){const R=$ instanceof Error?$.message:String($);this._addMessage({role:r,tool_call_id:b,content:R});continue}const S=await k.function(P,this),A=x(this,ct,"m",Yh).call(this,S);if(this._addMessage({role:r,tool_call_id:b,content:A}),l)return}}}}ct=new WeakSet,Fl=function(){return x(this,ct,"m",Na).call(this).content??null},Na=function(){let e=this.messages.length;for(;e-- >0;){const n=this.messages[e];if(Pa(n))return{...n,content:n.content??null,refusal:n.refusal??null}}throw new Q("stream ended without producing a ChatCompletionMessage with role=assistant")},Ml=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(Pa(n)&&n?.tool_calls?.length)return n.tool_calls.filter(s=>s.type==="function").at(-1)?.function}},Dl=function(){for(let e=this.messages.length-1;e>=0;e--){const n=this.messages[e];if(Vh(n)&&n.content!=null&&typeof n.content=="string"&&this.messages.some(s=>s.role==="assistant"&&s.tool_calls?.some(r=>r.type==="function"&&r.id===n.tool_call_id)))return n.content}},Ll=function(){const e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(const{usage:n}of this._chatCompletions)n&&(e.completion_tokens+=n.completion_tokens,e.prompt_tokens+=n.prompt_tokens,e.total_tokens+=n.total_tokens);return e},Kh=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.")},Yh=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};class Pc extends Xh{static runTools(e,n,s){const r=new Pc,i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,i)),r}_addMessage(e,n=!0){super._addMessage(e,n),Pa(e)&&e.content&&this._emit("content",e.content)}}const Jh=1,Gh=2,Qh=4,Zh=8,ep=16,tp=32,np=64,sp=128,rp=256,ip=sp|rp,ap=ep|tp|ip|np,op=Jh|Gh|ap,lp=Qh|Zh,G0=op|lp,qe={STR:Jh,NUM:Gh,ARR:Qh,OBJ:Zh,NULL:ep,BOOL:tp,NAN:np,INFINITY:sp,MINUS_INFINITY:rp,INF:ip,SPECIAL:ap,ATOM:op,COLLECTION:lp,ALL:G0};class Q0 extends Error{}class Z0 extends Error{}function ex(t,e=qe.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return tx(t.trim(),e)}const tx=(t,e)=>{const n=t.length;let s=0;const r=f=>{throw new Q0(`${f} at position ${s}`)},i=f=>{throw new Z0(`${f} at position ${s}`)},a=()=>(d(),s>=n&&r("Unexpected end of input"),t[s]==='"'?o():t[s]==="{"?l():t[s]==="["?c():t.substring(s,s+4)==="null"||qe.NULL&e&&n-s<4&&"null".startsWith(t.substring(s))?(s+=4,null):t.substring(s,s+4)==="true"||qe.BOOL&e&&n-s<4&&"true".startsWith(t.substring(s))?(s+=4,!0):t.substring(s,s+5)==="false"||qe.BOOL&e&&n-s<5&&"false".startsWith(t.substring(s))?(s+=5,!1):t.substring(s,s+8)==="Infinity"||qe.INFINITY&e&&n-s<8&&"Infinity".startsWith(t.substring(s))?(s+=8,1/0):t.substring(s,s+9)==="-Infinity"||qe.MINUS_INFINITY&e&&1<n-s&&n-s<9&&"-Infinity".startsWith(t.substring(s))?(s+=9,-1/0):t.substring(s,s+3)==="NaN"||qe.NAN&e&&n-s<3&&"NaN".startsWith(t.substring(s))?(s+=3,NaN):u()),o=()=>{const f=s;let h=!1;for(s++;s<n&&(t[s]!=='"'||h&&t[s-1]==="\\");)h=t[s]==="\\"?!h:!1,s++;if(t.charAt(s)=='"')try{return JSON.parse(t.substring(f,++s-Number(h)))}catch(m){i(String(m))}else if(qe.STR&e)try{return JSON.parse(t.substring(f,s-Number(h))+'"')}catch{return JSON.parse(t.substring(f,t.lastIndexOf("\\"))+'"')}r("Unterminated string literal")},l=()=>{s++,d();const f={};try{for(;t[s]!=="}";){if(d(),s>=n&&qe.OBJ&e)return f;const h=o();d(),s++;try{const m=a();Object.defineProperty(f,h,{value:m,writable:!0,enumerable:!0,configurable:!0})}catch(m){if(qe.OBJ&e)return f;throw m}d(),t[s]===","&&s++}}catch{if(qe.OBJ&e)return f;r("Expected '}' at end of object")}return s++,f},c=()=>{s++;const f=[];try{for(;t[s]!=="]";)f.push(a()),d(),t[s]===","&&s++}catch{if(qe.ARR&e)return f;r("Expected ']' at end of array")}return s++,f},u=()=>{if(s===0){t==="-"&&qe.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(qe.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch{}i(String(h))}}const f=s;for(t[s]==="-"&&s++;t[s]&&!",]}".includes(t[s]);)s++;s==n&&!(qe.NUM&e)&&r("Unterminated number literal");try{return JSON.parse(t.substring(f,s))}catch{t.substring(f,s)==="-"&&qe.NUM&e&&r("Not sure what '-' is");try{return JSON.parse(t.substring(f,t.lastIndexOf("e")))}catch(m){i(String(m))}}},d=()=>{for(;s<n&&`
|
||
\r `.includes(t[s]);)s++};return a()},od=t=>ex(t,qe.ALL^qe.NUM);var Be,Nn,Zs,Yn,Bo,Vi,Uo,jo,zo,Wi,qo,ld;class mi extends Xh{constructor(e){super(),Be.add(this),Nn.set(this,void 0),Zs.set(this,void 0),Yn.set(this,void 0),te(this,Nn,e),te(this,Zs,[])}get currentChatCompletionSnapshot(){return x(this,Yn,"f")}static fromReadableStream(e){const n=new mi(null);return n._run(()=>n._fromReadableStream(e)),n}static createChatCompletion(e,n,s){const r=new mi(n);return r._run(()=>r._runChatCompletion(e,{...n,stream:!0},{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createChatCompletion(e,n,s){super._createChatCompletion;const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),x(this,Be,"m",Bo).call(this);const i=await e.chat.completions.create({...n,stream:!0},{...s,signal:this.controller.signal});this._connected();for await(const a of i)x(this,Be,"m",Uo).call(this,a);if(i.controller.signal?.aborted)throw new Mt;return this._addChatCompletion(x(this,Be,"m",Wi).call(this))}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),x(this,Be,"m",Bo).call(this),this._connected();const r=_n.fromReadableStream(e,this.controller);let i;for await(const a of r)i&&i!==a.id&&this._addChatCompletion(x(this,Be,"m",Wi).call(this)),x(this,Be,"m",Uo).call(this,a),i=a.id;if(r.controller.signal?.aborted)throw new Mt;return this._addChatCompletion(x(this,Be,"m",Wi).call(this))}[(Nn=new WeakMap,Zs=new WeakMap,Yn=new WeakMap,Be=new WeakSet,Bo=function(){this.ended||te(this,Yn,void 0)},Vi=function(n){let s=x(this,Zs,"f")[n.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},x(this,Zs,"f")[n.index]=s,s)},Uo=function(n){if(this.ended)return;const s=x(this,Be,"m",ld).call(this,n);this._emit("chunk",n,s);for(const r of n.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=x(this,Be,"m",Vi).call(this,i);i.finish_reason&&(x(this,Be,"m",zo).call(this,i),a.current_tool_call_index!=null&&x(this,Be,"m",jo).call(this,i,a.current_tool_call_index));for(const o of r.delta.tool_calls??[])a.current_tool_call_index!==o.index&&(x(this,Be,"m",zo).call(this,i),a.current_tool_call_index!=null&&x(this,Be,"m",jo).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))}}},jo=function(n,s){if(x(this,Be,"m",Vi).call(this,n).done_tool_calls.has(s))return;const i=n.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=x(this,Nn,"f")?.tools?.find(o=>Ta(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:$i(a)?a.$parseRaw(i.function.arguments):a?.function.strict?JSON.parse(i.function.arguments):null})}else i.type},zo=function(n){const s=x(this,Be,"m",Vi).call(this,n);if(n.message.content&&!s.content_done){s.content_done=!0;const r=x(this,Be,"m",qo).call(this);this._emit("content.done",{content:n.message.content,parsed:r?r.$parseRaw(n.message.content):null})}n.message.refusal&&!s.refusal_done&&(s.refusal_done=!0,this._emit("refusal.done",{refusal:n.message.refusal})),n.logprobs?.content&&!s.logprobs_content_done&&(s.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:n.logprobs.content})),n.logprobs?.refusal&&!s.logprobs_refusal_done&&(s.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:n.logprobs.refusal}))},Wi=function(){if(this.ended)throw new Q("stream has ended, this shouldn't happen");const n=x(this,Yn,"f");if(!n)throw new Q("request ended without sending any chunks");return te(this,Yn,void 0),te(this,Zs,[]),nx(n,x(this,Nn,"f"))},qo=function(){const n=x(this,Nn,"f")?.response_format;return Ac(n)?n:null},ld=function(n){var s,r,i,a;let o=x(this,Yn,"f");const{choices:l,...c}=n;o?Object.assign(o,c):o=te(this,Yn,{...c,choices:[]});for(const{delta:u,finish_reason:d,index:f,logprobs:h=null,...m}of n.choices){let g=o.choices[f];if(g||(g=o.choices[f]={finish_reason:d,index:f,message:{},logprobs:h,...m}),h)if(!g.logprobs)g.logprobs=Object.assign({},h);else{const{content:S,refusal:A,...$}=h;Object.assign(g.logprobs,$),S&&((s=g.logprobs).content??(s.content=[]),g.logprobs.content.push(...S)),A&&((r=g.logprobs).refusal??(r.refusal=[]),g.logprobs.refusal.push(...A))}if(d&&(g.finish_reason=d,x(this,Nn,"f")&&qh(x(this,Nn,"f")))){if(d==="length")throw new xh;if(d==="content_filter")throw new kh}if(Object.assign(g,m),!u)continue;const{content:y,refusal:b,function_call:v,role:w,tool_calls:k,...P}=u;if(Object.assign(g.message,P),b&&(g.message.refusal=(g.message.refusal||"")+b),w&&(g.message.role=w),v&&(g.message.function_call?(v.name&&(g.message.function_call.name=v.name),v.arguments&&((i=g.message.function_call).arguments??(i.arguments=""),g.message.function_call.arguments+=v.arguments)):g.message.function_call=v),y&&(g.message.content=(g.message.content||"")+y,!g.message.refusal&&x(this,Be,"m",qo).call(this)&&(g.message.parsed=od(g.message.content))),k){g.message.tool_calls||(g.message.tool_calls=[]);for(const{index:S,id:A,type:$,function:R,...K}of k){const Z=(a=g.message.tool_calls)[S]??(a[S]={});Object.assign(Z,K),A&&(Z.id=A),$&&(Z.type=$),R&&(Z.function??(Z.function={name:R.name??"",arguments:""})),R?.name&&(Z.function.name=R.name),R?.arguments&&(Z.function.arguments+=R.arguments,K0(x(this,Nn,"f"),Z)&&(Z.function.parsed_arguments=od(Z.function.arguments)))}}}return o},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("chunk",r=>{const i=n.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>n.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 _n(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}function nx(t,e){const{id:n,choices:s,created:r,model:i,system_fingerprint:a,...o}=t,l={...o,id:n,choices:s.map(({message:c,finish_reason:u,index:d,logprobs:f,...h})=>{if(!u)throw new Q(`missing finish_reason for choice ${d}`);const{content:m=null,function_call:g,tool_calls:y,...b}=c,v=c.role;if(!v)throw new Q(`missing role for choice ${d}`);if(g){const{arguments:w,name:k}=g;if(w==null)throw new Q(`missing function_call.arguments for choice ${d}`);if(!k)throw new Q(`missing function_call.name for choice ${d}`);return{...h,message:{content:m,function_call:{arguments:w,name:k},role:v,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:f}}return y?{...h,index:d,finish_reason:u,logprobs:f,message:{...b,role:v,content:m,refusal:c.refusal??null,tool_calls:y.map((w,k)=>{const{function:P,type:S,id:A,...$}=w,{arguments:R,name:K,...Z}=P||{};if(A==null)throw new Q(`missing choices[${d}].tool_calls[${k}].id
|
||
${Ki(t)}`);if(S==null)throw new Q(`missing choices[${d}].tool_calls[${k}].type
|
||
${Ki(t)}`);if(K==null)throw new Q(`missing choices[${d}].tool_calls[${k}].function.name
|
||
${Ki(t)}`);if(R==null)throw new Q(`missing choices[${d}].tool_calls[${k}].function.arguments
|
||
${Ki(t)}`);return{...$,id:A,type:S,function:{...Z,name:K,arguments:R}}})}}:{...h,message:{...b,content:m,role:v,refusal:c.refusal??null},finish_reason:u,index:d,logprobs:f}}),created:r,model:i,object:"chat.completion",...a?{system_fingerprint:a}:{}};return H0(l,e)}function Ki(t){return JSON.stringify(t)}class Ra extends mi{static fromReadableStream(e){const n=new Ra(null);return n._run(()=>n._fromReadableStream(e)),n}static runTools(e,n,s){const r=new Ra(n),i={...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"runTools"}};return r._run(()=>r._runTools(e,n,i)),r}}let $c=class extends G{constructor(){super(...arguments),this.messages=new zh(this._client)}create(e,n){return this._client.post("/chat/completions",{body:e,...n,stream:e.stream??!1})}retrieve(e,n){return this._client.get(I`/chat/completions/${e}`,n)}update(e,n,s){return this._client.post(I`/chat/completions/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/chat/completions",De,{query:e,...n})}delete(e,n){return this._client.delete(I`/chat/completions/${e}`,n)}parse(e,n){return Y0(e.tools),this._client.chat.completions.create(e,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(s=>Cc(s,e))}runTools(e,n){return e.stream?Ra.runTools(this._client,e,n):Pc.runTools(this._client,e,n)}stream(e,n){return mi.createChatCompletion(this._client,e,n)}};$c.Messages=zh;class Ic extends G{constructor(){super(...arguments),this.completions=new $c(this._client)}}Ic.Completions=$c;const cp=Symbol("brand.privateNullableHeaders");function*sx(t){if(!t)return;if(cp in t){const{values:s,nulls:r}=t;yield*s.entries();for(const i of r)yield[i,null];return}let e=!1,n;t instanceof Headers?n=t.entries():Wu(t)?n=t:(e=!0,n=Object.entries(t??{}));for(let s of n){const r=s[0];if(typeof r!="string")throw new TypeError("expected header name to be a string");const i=Wu(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 H=t=>{const e=new Headers,n=new Set;for(const s of t){const r=new Set;for(const[i,a]of sx(s)){const o=i.toLowerCase();r.has(o)||(e.delete(i),r.add(o)),a===null?(e.delete(i),n.add(o)):(e.append(i,a),n.delete(o))}}return{[cp]:!0,values:e,nulls:n}};class up extends G{create(e,n){return this._client.post("/audio/speech",{body:e,...n,headers:H([{Accept:"application/octet-stream"},n?.headers]),__binaryResponse:!0})}}class dp extends G{create(e,n){return this._client.post("/audio/transcriptions",Ls({body:e,...n,stream:e.stream??!1,__metadata:{model:e.model}},this._client))}}class fp extends G{create(e,n){return this._client.post("/audio/translations",Ls({body:e,...n,__metadata:{model:e.model}},this._client))}}class Ii extends G{constructor(){super(...arguments),this.transcriptions=new dp(this._client),this.translations=new fp(this._client),this.speech=new up(this._client)}}Ii.Transcriptions=dp;Ii.Translations=fp;Ii.Speech=up;class hp extends G{create(e,n){return this._client.post("/batches",{body:e,...n})}retrieve(e,n){return this._client.get(I`/batches/${e}`,n)}list(e={},n){return this._client.getAPIList("/batches",De,{query:e,...n})}cancel(e,n){return this._client.post(I`/batches/${e}/cancel`,n)}}class pp extends G{create(e,n){return this._client.post("/assistants",{body:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(I`/assistants/${e}`,{...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(I`/assistants/${e}`,{body:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/assistants",De,{query:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(I`/assistants/${e}`,{...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let mp=class extends G{create(e,n){return this._client.post("/realtime/sessions",{body:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}};class gp extends G{create(e,n){return this._client.post("/realtime/transcription_sessions",{body:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}}let no=class extends G{constructor(){super(...arguments),this.sessions=new mp(this._client),this.transcriptionSessions=new gp(this._client)}};no.Sessions=mp;no.TranscriptionSessions=gp;class vp extends G{create(e,n){return this._client.post("/chatkit/sessions",{body:e,...n,headers:H([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}cancel(e,n){return this._client.post(I`/chatkit/sessions/${e}/cancel`,{...n,headers:H([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}}let yp=class extends G{retrieve(e,n){return this._client.get(I`/chatkit/threads/${e}`,{...n,headers:H([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}list(e={},n){return this._client.getAPIList("/chatkit/threads",Ca,{query:e,...n,headers:H([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}delete(e,n){return this._client.delete(I`/chatkit/threads/${e}`,{...n,headers:H([{"OpenAI-Beta":"chatkit_beta=v1"},n?.headers])})}listItems(e,n={},s){return this._client.getAPIList(I`/chatkit/threads/${e}/items`,Ca,{query:n,...s,headers:H([{"OpenAI-Beta":"chatkit_beta=v1"},s?.headers])})}};class so extends G{constructor(){super(...arguments),this.sessions=new vp(this._client),this.threads=new yp(this._client)}}so.Sessions=vp;so.Threads=yp;class wp extends G{create(e,n,s){return this._client.post(I`/threads/${e}/messages`,{body:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(I`/threads/${r}/messages/${e}`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...i}=n;return this._client.post(I`/threads/${r}/messages/${e}`,{body:i,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(I`/threads/${e}/messages`,De,{query:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{thread_id:r}=n;return this._client.delete(I`/threads/${r}/messages/${e}`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class bp extends G{retrieve(e,n,s){const{thread_id:r,run_id:i,...a}=n;return this._client.get(I`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n,s){const{thread_id:r,...i}=n;return this._client.getAPIList(I`/threads/${r}/runs/${e}/steps`,De,{query:i,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}const rx=t=>{if(typeof Buffer<"u"){const e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{const e=atob(t),n=e.length,s=new Uint8Array(n);for(let r=0;r<n;r++)s[r]=e.charCodeAt(r);return Array.from(new Float32Array(s.buffer))}},er=t=>{if(typeof globalThis.process<"u")return globalThis.process.env?.[t]?.trim()??void 0;if(typeof globalThis.Deno<"u")return globalThis.Deno.env?.get?.(t)?.trim()};var Ge,_s,Ol,pn,ia,Qt,xs,cr,ys,Fa,It,aa,oa,ii,Gr,Qr,cd,ud,dd,fd,hd,pd,md;class ai extends Tc{constructor(){super(...arguments),Ge.add(this),Ol.set(this,[]),pn.set(this,{}),ia.set(this,{}),Qt.set(this,void 0),xs.set(this,void 0),cr.set(this,void 0),ys.set(this,void 0),Fa.set(this,void 0),It.set(this,void 0),aa.set(this,void 0),oa.set(this,void 0),ii.set(this,void 0)}[(Ol=new WeakMap,pn=new WeakMap,ia=new WeakMap,Qt=new WeakMap,xs=new WeakMap,cr=new WeakMap,ys=new WeakMap,Fa=new WeakMap,It=new WeakMap,aa=new WeakMap,oa=new WeakMap,ii=new WeakMap,Ge=new WeakSet,Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const i=n.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>n.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 n=new _s;return n._run(()=>n._fromReadableStream(e)),n}async _fromReadableStream(e,n){const s=n?.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),this._connected();const r=_n.fromReadableStream(e,this.controller);for await(const i of r)x(this,Ge,"m",Gr).call(this,i);if(r.controller.signal?.aborted)throw new Mt;return this._addRun(x(this,Ge,"m",Qr).call(this))}toReadableStream(){return new _n(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,n,s,r){const i=new _s;return i._run(()=>i._runToolAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}async _createToolAssistantStream(e,n,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(n,a,{...r,signal:this.controller.signal});this._connected();for await(const l of o)x(this,Ge,"m",Gr).call(this,l);if(o.controller.signal?.aborted)throw new Mt;return this._addRun(x(this,Ge,"m",Qr).call(this))}static createThreadAssistantStream(e,n,s){const r=new _s;return r._run(()=>r._threadAssistantStream(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}static createAssistantStream(e,n,s,r){const i=new _s;return i._run(()=>i._runAssistantStream(e,n,s,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":"stream"}})),i}currentEvent(){return x(this,aa,"f")}currentRun(){return x(this,oa,"f")}currentMessageSnapshot(){return x(this,Qt,"f")}currentRunStepSnapshot(){return x(this,ii,"f")}async finalRunSteps(){return await this.done(),Object.values(x(this,pn,"f"))}async finalMessages(){return await this.done(),Object.values(x(this,ia,"f"))}async finalRun(){if(await this.done(),!x(this,xs,"f"))throw Error("Final run was not received.");return x(this,xs,"f")}async _createThreadAssistantStream(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort()));const i={...n,stream:!0},a=await e.createAndRun(i,{...s,signal:this.controller.signal});this._connected();for await(const o of a)x(this,Ge,"m",Gr).call(this,o);if(a.controller.signal?.aborted)throw new Mt;return this._addRun(x(this,Ge,"m",Qr).call(this))}async _createAssistantStream(e,n,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(n,a,{...r,signal:this.controller.signal});this._connected();for await(const l of o)x(this,Ge,"m",Gr).call(this,l);if(o.controller.signal?.aborted)throw new Mt;return this._addRun(x(this,Ge,"m",Qr).call(this))}static accumulateDelta(e,n){for(const[s,r]of Object.entries(n)){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(Do(i)&&Do(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(!Do(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,n,s){return await this._createThreadAssistantStream(n,e,s)}async _runAssistantStream(e,n,s,r){return await this._createAssistantStream(n,e,s,r)}async _runToolAssistantStream(e,n,s,r){return await this._createToolAssistantStream(n,e,s,r)}}_s=ai,Gr=function(e){if(!this.ended)switch(te(this,aa,e),x(this,Ge,"m",dd).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":x(this,Ge,"m",md).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":x(this,Ge,"m",ud).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":x(this,Ge,"m",cd).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier")}},Qr=function(){if(this.ended)throw new Q("stream has ended, this shouldn't happen");if(!x(this,xs,"f"))throw Error("Final run has not been received");return x(this,xs,"f")},cd=function(e){const[n,s]=x(this,Ge,"m",hd).call(this,e,x(this,Qt,"f"));te(this,Qt,n),x(this,ia,"f")[n.id]=n;for(const r of s){const i=n.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,n),e.data.delta.content)for(const r of e.data.delta.content){if(r.type=="text"&&r.text){let i=r.text,a=n.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!=x(this,cr,"f")){if(x(this,ys,"f"))switch(x(this,ys,"f").type){case"text":this._emit("textDone",x(this,ys,"f").text,x(this,Qt,"f"));break;case"image_file":this._emit("imageFileDone",x(this,ys,"f").image_file,x(this,Qt,"f"));break}te(this,cr,r.index)}te(this,ys,n.content[r.index])}break;case"thread.message.completed":case"thread.message.incomplete":if(x(this,cr,"f")!==void 0){const r=e.data.content[x(this,cr,"f")];if(r)switch(r.type){case"image_file":this._emit("imageFileDone",r.image_file,x(this,Qt,"f"));break;case"text":this._emit("textDone",r.text,x(this,Qt,"f"));break}}x(this,Qt,"f")&&this._emit("messageDone",e.data),te(this,Qt,void 0)}},ud=function(e){const n=x(this,Ge,"m",fd).call(this,e);switch(te(this,ii,n),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&&n.step_details.type=="tool_calls")for(const i of s.step_details.tool_calls)i.index==x(this,Fa,"f")?this._emit("toolCallDelta",i,n.step_details.tool_calls[i.index]):(x(this,It,"f")&&this._emit("toolCallDone",x(this,It,"f")),te(this,Fa,i.index),te(this,It,n.step_details.tool_calls[i.index]),x(this,It,"f")&&this._emit("toolCallCreated",x(this,It,"f")));this._emit("runStepDelta",e.data.delta,n);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":te(this,ii,void 0),e.data.step_details.type=="tool_calls"&&x(this,It,"f")&&(this._emit("toolCallDone",x(this,It,"f")),te(this,It,void 0)),this._emit("runStepDone",e.data,n);break}},dd=function(e){x(this,Ol,"f").push(e),this._emit("event",e)},fd=function(e){switch(e.event){case"thread.run.step.created":return x(this,pn,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let n=x(this,pn,"f")[e.data.id];if(!n)throw Error("Received a RunStepDelta before creation of a snapshot");let s=e.data;if(s.delta){const r=_s.accumulateDelta(n,s.delta);x(this,pn,"f")[e.data.id]=r}return x(this,pn,"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":x(this,pn,"f")[e.data.id]=e.data;break}if(x(this,pn,"f")[e.data.id])return x(this,pn,"f")[e.data.id];throw new Error("No snapshot available")},hd=function(e,n){let s=[];switch(e.event){case"thread.message.created":return[e.data,s];case"thread.message.delta":if(!n)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 n.content){let a=n.content[i.index];n.content[i.index]=x(this,Ge,"m",pd).call(this,i,a)}else n.content[i.index]=i,s.push(i);return[n,s];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(n)return[n,s];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},pd=function(e,n){return _s.accumulateDelta(n,e)},md=function(e){switch(te(this,oa,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":te(this,xs,e.data),x(this,It,"f")&&(this._emit("toolCallDone",x(this,It,"f")),te(this,It,void 0));break}};let Nc=class extends G{constructor(){super(...arguments),this.steps=new bp(this._client)}create(e,n,s){const{include:r,...i}=n;return this._client.post(I`/threads/${e}/runs`,{query:{include:r},body:i,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}retrieve(e,n,s){const{thread_id:r}=n;return this._client.get(I`/threads/${r}/runs/${e}`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{thread_id:r,...i}=n;return this._client.post(I`/threads/${r}/runs/${e}`,{body:i,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(I`/threads/${e}/runs`,De,{query:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{thread_id:r}=n;return this._client.post(I`/threads/${r}/runs/${e}/cancel`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(r.id,{thread_id:e},s)}createAndStream(e,n,s){return ai.createAssistantStream(e,this._client.beta.threads.runs,n,s)}async poll(e,n,s){const r=H([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,n,{...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 Ti(o);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return i}}}stream(e,n,s){return ai.createAssistantStream(e,this._client.beta.threads.runs,n,s)}submitToolOutputs(e,n,s){const{thread_id:r,...i}=n;return this._client.post(I`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers]),stream:n.stream??!1})}async submitToolOutputsAndPoll(e,n,s){const r=await this.submitToolOutputs(e,n,s);return await this.poll(r.id,n,s)}submitToolOutputsStream(e,n,s){return ai.createToolAssistantStream(e,this._client.beta.threads.runs,n,s)}};Nc.Steps=bp;class ro extends G{constructor(){super(...arguments),this.runs=new Nc(this._client),this.messages=new wp(this._client)}create(e={},n){return this._client.post("/threads",{body:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(I`/threads/${e}`,{...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(I`/threads/${e}`,{body:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n){return this._client.delete(I`/threads/${e}`,{...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}createAndRun(e,n){return this._client.post("/threads/runs",{body:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers]),stream:e.stream??!1})}async createAndRunPoll(e,n){const s=await this.createAndRun(e,n);return await this.runs.poll(s.id,{thread_id:s.thread_id},n)}createAndRunStream(e,n){return ai.createThreadAssistantStream(e,this._client.beta.threads,n)}}ro.Runs=Nc;ro.Messages=wp;class Ir extends G{constructor(){super(...arguments),this.realtime=new no(this._client),this.chatkit=new so(this._client),this.assistants=new pp(this._client),this.threads=new ro(this._client)}}Ir.Realtime=no;Ir.ChatKit=so;Ir.Assistants=pp;Ir.Threads=ro;class _p extends G{create(e,n){return this._client.post("/completions",{body:e,...n,stream:e.stream??!1})}}class xp extends G{retrieve(e,n,s){const{container_id:r}=n;return this._client.get(I`/containers/${r}/files/${e}/content`,{...s,headers:H([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}}let Rc=class extends G{constructor(){super(...arguments),this.content=new xp(this._client)}create(e,n,s){return this._client.post(I`/containers/${e}/files`,Ls({body:n,...s},this._client))}retrieve(e,n,s){const{container_id:r}=n;return this._client.get(I`/containers/${r}/files/${e}`,s)}list(e,n={},s){return this._client.getAPIList(I`/containers/${e}/files`,De,{query:n,...s})}delete(e,n,s){const{container_id:r}=n;return this._client.delete(I`/containers/${r}/files/${e}`,{...s,headers:H([{Accept:"*/*"},s?.headers])})}};Rc.Content=xp;class Fc extends G{constructor(){super(...arguments),this.files=new Rc(this._client)}create(e,n){return this._client.post("/containers",{body:e,...n})}retrieve(e,n){return this._client.get(I`/containers/${e}`,n)}list(e={},n){return this._client.getAPIList("/containers",De,{query:e,...n})}delete(e,n){return this._client.delete(I`/containers/${e}`,{...n,headers:H([{Accept:"*/*"},n?.headers])})}}Fc.Files=Rc;class kp extends G{create(e,n,s){const{include:r,...i}=n;return this._client.post(I`/conversations/${e}/items`,{query:{include:r},body:i,...s})}retrieve(e,n,s){const{conversation_id:r,...i}=n;return this._client.get(I`/conversations/${r}/items/${e}`,{query:i,...s})}list(e,n={},s){return this._client.getAPIList(I`/conversations/${e}/items`,Ca,{query:n,...s})}delete(e,n,s){const{conversation_id:r}=n;return this._client.delete(I`/conversations/${r}/items/${e}`,s)}}class Mc extends G{constructor(){super(...arguments),this.items=new kp(this._client)}create(e={},n){return this._client.post("/conversations",{body:e,...n})}retrieve(e,n){return this._client.get(I`/conversations/${e}`,n)}update(e,n,s){return this._client.post(I`/conversations/${e}`,{body:n,...s})}delete(e,n){return this._client.delete(I`/conversations/${e}`,n)}}Mc.Items=kp;class Ep extends G{create(e,n){const s=!!e.encoding_format;let r=s?e.encoding_format:"base64";s&&Xe(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);const i=this._client.post("/embeddings",{body:{...e,encoding_format:r},...n});return s?i:(Xe(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=rx(l)}),a)))}}class Sp extends G{retrieve(e,n,s){const{eval_id:r,run_id:i}=n;return this._client.get(I`/evals/${r}/runs/${i}/output_items/${e}`,s)}list(e,n,s){const{eval_id:r,...i}=n;return this._client.getAPIList(I`/evals/${r}/runs/${e}/output_items`,De,{query:i,...s})}}class Dc extends G{constructor(){super(...arguments),this.outputItems=new Sp(this._client)}create(e,n,s){return this._client.post(I`/evals/${e}/runs`,{body:n,...s})}retrieve(e,n,s){const{eval_id:r}=n;return this._client.get(I`/evals/${r}/runs/${e}`,s)}list(e,n={},s){return this._client.getAPIList(I`/evals/${e}/runs`,De,{query:n,...s})}delete(e,n,s){const{eval_id:r}=n;return this._client.delete(I`/evals/${r}/runs/${e}`,s)}cancel(e,n,s){const{eval_id:r}=n;return this._client.post(I`/evals/${r}/runs/${e}`,s)}}Dc.OutputItems=Sp;class Lc extends G{constructor(){super(...arguments),this.runs=new Dc(this._client)}create(e,n){return this._client.post("/evals",{body:e,...n})}retrieve(e,n){return this._client.get(I`/evals/${e}`,n)}update(e,n,s){return this._client.post(I`/evals/${e}`,{body:n,...s})}list(e={},n){return this._client.getAPIList("/evals",De,{query:e,...n})}delete(e,n){return this._client.delete(I`/evals/${e}`,n)}}Lc.Runs=Dc;let Ap=class extends G{create(e,n){return this._client.post("/files",Ls({body:e,...n},this._client))}retrieve(e,n){return this._client.get(I`/files/${e}`,n)}list(e={},n){return this._client.getAPIList("/files",De,{query:e,...n})}delete(e,n){return this._client.delete(I`/files/${e}`,n)}content(e,n){return this._client.get(I`/files/${e}/content`,{...n,headers:H([{Accept:"application/binary"},n?.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:n=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 Ti(n),a=await this.retrieve(e),Date.now()-i>s)throw new Za({message:`Giving up on waiting for file ${e} to finish processing after ${s} milliseconds.`});return a}};class Cp extends G{}let Tp=class extends G{run(e,n){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...n})}validate(e,n){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...n})}};class Oc extends G{constructor(){super(...arguments),this.graders=new Tp(this._client)}}Oc.Graders=Tp;class Pp extends G{create(e,n,s){return this._client.getAPIList(I`/fine_tuning/checkpoints/${e}/permissions`,to,{body:n,method:"post",...s})}retrieve(e,n={},s){return this._client.get(I`/fine_tuning/checkpoints/${e}/permissions`,{query:n,...s})}delete(e,n,s){const{fine_tuned_model_checkpoint:r}=n;return this._client.delete(I`/fine_tuning/checkpoints/${r}/permissions/${e}`,s)}}let Bc=class extends G{constructor(){super(...arguments),this.permissions=new Pp(this._client)}};Bc.Permissions=Pp;class $p extends G{list(e,n={},s){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/checkpoints`,De,{query:n,...s})}}class Uc extends G{constructor(){super(...arguments),this.checkpoints=new $p(this._client)}create(e,n){return this._client.post("/fine_tuning/jobs",{body:e,...n})}retrieve(e,n){return this._client.get(I`/fine_tuning/jobs/${e}`,n)}list(e={},n){return this._client.getAPIList("/fine_tuning/jobs",De,{query:e,...n})}cancel(e,n){return this._client.post(I`/fine_tuning/jobs/${e}/cancel`,n)}listEvents(e,n={},s){return this._client.getAPIList(I`/fine_tuning/jobs/${e}/events`,De,{query:n,...s})}pause(e,n){return this._client.post(I`/fine_tuning/jobs/${e}/pause`,n)}resume(e,n){return this._client.post(I`/fine_tuning/jobs/${e}/resume`,n)}}Uc.Checkpoints=$p;class Nr extends G{constructor(){super(...arguments),this.methods=new Cp(this._client),this.jobs=new Uc(this._client),this.checkpoints=new Bc(this._client),this.alpha=new Oc(this._client)}}Nr.Methods=Cp;Nr.Jobs=Uc;Nr.Checkpoints=Bc;Nr.Alpha=Oc;class Ip extends G{}class jc extends G{constructor(){super(...arguments),this.graderModels=new Ip(this._client)}}jc.GraderModels=Ip;class Np extends G{createVariation(e,n){return this._client.post("/images/variations",Ls({body:e,...n},this._client))}edit(e,n){return this._client.post("/images/edits",Ls({body:e,...n,stream:e.stream??!1},this._client))}generate(e,n){return this._client.post("/images/generations",{body:e,...n,stream:e.stream??!1})}}class Rp extends G{retrieve(e,n){return this._client.get(I`/models/${e}`,n)}list(e){return this._client.getAPIList("/models",to,e)}delete(e,n){return this._client.delete(I`/models/${e}`,n)}}class Fp extends G{create(e,n){return this._client.post("/moderations",{body:e,...n})}}class Mp extends G{accept(e,n,s){return this._client.post(I`/realtime/calls/${e}/accept`,{body:n,...s,headers:H([{Accept:"*/*"},s?.headers])})}hangup(e,n){return this._client.post(I`/realtime/calls/${e}/hangup`,{...n,headers:H([{Accept:"*/*"},n?.headers])})}refer(e,n,s){return this._client.post(I`/realtime/calls/${e}/refer`,{body:n,...s,headers:H([{Accept:"*/*"},s?.headers])})}reject(e,n={},s){return this._client.post(I`/realtime/calls/${e}/reject`,{body:n,...s,headers:H([{Accept:"*/*"},s?.headers])})}}class Dp extends G{create(e,n){return this._client.post("/realtime/client_secrets",{body:e,...n})}}class io extends G{constructor(){super(...arguments),this.clientSecrets=new Dp(this._client),this.calls=new Mp(this._client)}}io.ClientSecrets=Dp;io.Calls=Mp;function ix(t,e){return!e||!ox(e)?{...t,output_parsed:null,output:t.output.map(n=>n.type==="function_call"?{...n,parsed_arguments:null}:n.type==="message"?{...n,content:n.content.map(s=>({...s,parsed:null}))}:n)}:Lp(t,e)}function Lp(t,e){const n=t.output.map(r=>{if(r.type==="function_call")return{...r,parsed_arguments:ux(e,r)};if(r.type==="message"){const i=r.content.map(a=>a.type==="output_text"?{...a,parsed:ax(e,a.text)}:a);return{...r,content:i}}return r}),s=Object.assign({},t,{output:n});return Object.getOwnPropertyDescriptor(t,"output_text")||Bl(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 ax(t,e){return t.text?.format?.type!=="json_schema"?null:"$parseRaw"in t.text?.format?(t.text?.format).$parseRaw(e):JSON.parse(e)}function ox(t){return!!Ac(t.text?.format)}function lx(t){return t?.$brand==="auto-parseable-tool"}function cx(t,e){return t.find(n=>n.type==="function"&&n.name===e)}function ux(t,e){const n=cx(t.tools??[],e.name);return{...e,...e,parsed_arguments:lx(n)?n.$parseRaw(e.arguments):n?.strict?JSON.parse(e.arguments):null}}function Bl(t){const e=[];for(const n of t.output)if(n.type==="message")for(const s of n.content)s.type==="output_text"&&e.push(s.text);t.output_text=e.join("")}var tr,Yi,Xn,Xi,gd,vd,yd,wd;class zc extends Tc{constructor(e){super(),tr.add(this),Yi.set(this,void 0),Xn.set(this,void 0),Xi.set(this,void 0),te(this,Yi,e)}static createResponse(e,n,s){const r=new zc(n);return r._run(()=>r._createOrRetrieveResponse(e,n,{...s,headers:{...s?.headers,"X-Stainless-Helper-Method":"stream"}})),r}async _createOrRetrieveResponse(e,n,s){const r=s?.signal;r&&(r.aborted&&this.controller.abort(),r.addEventListener("abort",()=>this.controller.abort())),x(this,tr,"m",gd).call(this);let i,a=null;"response_id"in n?(i=await e.responses.retrieve(n.response_id,{stream:!0},{...s,signal:this.controller.signal,stream:!0}),a=n.starting_after??null):i=await e.responses.create({...n,stream:!0},{...s,signal:this.controller.signal}),this._connected();for await(const o of i)x(this,tr,"m",vd).call(this,o,a);if(i.controller.signal?.aborted)throw new Mt;return x(this,tr,"m",yd).call(this)}[(Yi=new WeakMap,Xn=new WeakMap,Xi=new WeakMap,tr=new WeakSet,gd=function(){this.ended||te(this,Xn,void 0)},vd=function(n,s){if(this.ended)return;const r=(a,o)=>{(s==null||o.sequence_number>s)&&this._emit(a,o)},i=x(this,tr,"m",wd).call(this,n);switch(r("event",n),n.type){case"response.output_text.delta":{const a=i.output[n.output_index];if(!a)throw new Q(`missing output at index ${n.output_index}`);if(a.type==="message"){const o=a.content[n.content_index];if(!o)throw new Q(`missing content at index ${n.content_index}`);if(o.type!=="output_text")throw new Q(`expected content to be 'output_text', got ${o.type}`);r("response.output_text.delta",{...n,snapshot:o.text})}break}case"response.function_call_arguments.delta":{const a=i.output[n.output_index];if(!a)throw new Q(`missing output at index ${n.output_index}`);a.type==="function_call"&&r("response.function_call_arguments.delta",{...n,snapshot:a.arguments});break}default:r(n.type,n);break}},yd=function(){if(this.ended)throw new Q("stream has ended, this shouldn't happen");const n=x(this,Xn,"f");if(!n)throw new Q("request ended without sending any events");te(this,Xn,void 0);const s=dx(n,x(this,Yi,"f"));return te(this,Xi,s),s},wd=function(n){let s=x(this,Xn,"f");if(!s){if(n.type!=="response.created")throw new Q(`When snapshot hasn't been set yet, expected 'response.created' event, got ${n.type}`);return s=te(this,Xn,n.response),s}switch(n.type){case"response.output_item.added":{s.output.push(n.item);break}case"response.content_part.added":{const r=s.output[n.output_index];if(!r)throw new Q(`missing output at index ${n.output_index}`);const i=r.type,a=n.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[n.output_index];if(!r)throw new Q(`missing output at index ${n.output_index}`);if(r.type==="message"){const i=r.content[n.content_index];if(!i)throw new Q(`missing content at index ${n.content_index}`);if(i.type!=="output_text")throw new Q(`expected content to be 'output_text', got ${i.type}`);i.text+=n.delta}break}case"response.function_call_arguments.delta":{const r=s.output[n.output_index];if(!r)throw new Q(`missing output at index ${n.output_index}`);r.type==="function_call"&&(r.arguments+=n.delta);break}case"response.reasoning_text.delta":{const r=s.output[n.output_index];if(!r)throw new Q(`missing output at index ${n.output_index}`);if(r.type==="reasoning"){const i=r.content?.[n.content_index];if(!i)throw new Q(`missing content at index ${n.content_index}`);if(i.type!=="reasoning_text")throw new Q(`expected content to be 'reasoning_text', got ${i.type}`);i.text+=n.delta}break}case"response.completed":{te(this,Xn,n.response);break}}return s},Symbol.asyncIterator)](){const e=[],n=[];let s=!1;return this.on("event",r=>{const i=n.shift();i?i.resolve(r):e.push(r)}),this.on("end",()=>{s=!0;for(const r of n)r.resolve(void 0);n.length=0}),this.on("abort",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),this.on("error",r=>{s=!0;for(const i of n)i.reject(r);n.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:s?{value:void 0,done:!0}:new Promise((i,a)=>n.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=x(this,Xi,"f");if(!e)throw new Q("stream ended without producing a ChatCompletion");return e}}function dx(t,e){return ix(t,e)}class Op extends G{list(e,n={},s){return this._client.getAPIList(I`/responses/${e}/input_items`,De,{query:n,...s})}}class Bp extends G{count(e={},n){return this._client.post("/responses/input_tokens",{body:e,...n})}}class ao extends G{constructor(){super(...arguments),this.inputItems=new Op(this._client),this.inputTokens=new Bp(this._client)}create(e,n){return this._client.post("/responses",{body:e,...n,stream:e.stream??!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&Bl(s),s))}retrieve(e,n={},s){return this._client.get(I`/responses/${e}`,{query:n,...s,stream:n?.stream??!1})._thenUnwrap(r=>("object"in r&&r.object==="response"&&Bl(r),r))}delete(e,n){return this._client.delete(I`/responses/${e}`,{...n,headers:H([{Accept:"*/*"},n?.headers])})}parse(e,n){return this._client.responses.create(e,n)._thenUnwrap(s=>Lp(s,e))}stream(e,n){return zc.createResponse(this._client,e,n)}cancel(e,n){return this._client.post(I`/responses/${e}/cancel`,n)}}ao.InputItems=Op;ao.InputTokens=Bp;class Up extends G{create(e,n,s){return this._client.post(I`/uploads/${e}/parts`,Ls({body:n,...s},this._client))}}class qc extends G{constructor(){super(...arguments),this.parts=new Up(this._client)}create(e,n){return this._client.post("/uploads",{body:e,...n})}cancel(e,n){return this._client.post(I`/uploads/${e}/cancel`,n)}complete(e,n,s){return this._client.post(I`/uploads/${e}/complete`,{body:n,...s})}}qc.Parts=Up;const fx=async t=>{const e=await Promise.allSettled(t),n=e.filter(r=>r.status==="rejected");if(n.length){for(const r of n);throw new Error(`${n.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 jp extends G{create(e,n,s){return this._client.post(I`/vector_stores/${e}/file_batches`,{body:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(I`/vector_stores/${r}/file_batches/${e}`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}cancel(e,n,s){const{vector_store_id:r}=n;return this._client.post(I`/vector_stores/${r}/file_batches/${e}/cancel`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n);return await this.poll(e,r.id,s)}listFiles(e,n,s){const{vector_store_id:r,...i}=n;return this._client.getAPIList(I`/vector_stores/${r}/file_batches/${e}/files`,De,{query:i,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async poll(e,n,s){const r=H([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(n,{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 Ti(o);break;case"failed":case"cancelled":case"completed":return i}}}async uploadAndPoll(e,{files:n,fileIds:s=[]},r){if(n==null||n.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,n.length),o=this._client,l=n.values(),c=[...s];async function u(f){for(let h of f){const m=await o.files.create({file:h,purpose:"assistants"},r);c.push(m.id)}}const d=Array(a).fill(l).map(u);return await fx(d),await this.createAndPoll(e,{file_ids:c})}}class zp extends G{create(e,n,s){return this._client.post(I`/vector_stores/${e}/files`,{body:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}retrieve(e,n,s){const{vector_store_id:r}=n;return this._client.get(I`/vector_stores/${r}/files/${e}`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}update(e,n,s){const{vector_store_id:r,...i}=n;return this._client.post(I`/vector_stores/${r}/files/${e}`,{body:i,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e,n={},s){return this._client.getAPIList(I`/vector_stores/${e}/files`,De,{query:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}delete(e,n,s){const{vector_store_id:r}=n;return this._client.delete(I`/vector_stores/${r}/files/${e}`,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}async createAndPoll(e,n,s){const r=await this.create(e,n,s);return await this.poll(e,r.id,s)}async poll(e,n,s){const r=H([s?.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":s?.pollIntervalMs?.toString()??void 0}]);for(;;){const i=await this.retrieve(n,{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 Ti(o);break;case"failed":case"completed":return a}}}async upload(e,n,s){const r=await this._client.files.create({file:n,purpose:"assistants"},s);return this.create(e,{file_id:r.id},s)}async uploadAndPoll(e,n,s){const r=await this.upload(e,n,s);return await this.poll(e,r.id,s)}content(e,n,s){const{vector_store_id:r}=n;return this._client.getAPIList(I`/vector_stores/${r}/files/${e}/content`,to,{...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}class oo extends G{constructor(){super(...arguments),this.files=new zp(this._client),this.fileBatches=new jp(this._client)}create(e,n){return this._client.post("/vector_stores",{body:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}retrieve(e,n){return this._client.get(I`/vector_stores/${e}`,{...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}update(e,n,s){return this._client.post(I`/vector_stores/${e}`,{body:n,...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}list(e={},n){return this._client.getAPIList("/vector_stores",De,{query:e,...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}delete(e,n){return this._client.delete(I`/vector_stores/${e}`,{...n,headers:H([{"OpenAI-Beta":"assistants=v2"},n?.headers])})}search(e,n,s){return this._client.getAPIList(I`/vector_stores/${e}/search`,to,{body:n,method:"post",...s,headers:H([{"OpenAI-Beta":"assistants=v2"},s?.headers])})}}oo.Files=zp;oo.FileBatches=jp;class qp extends G{create(e,n){return this._client.post("/videos",rd({body:e,...n},this._client))}retrieve(e,n){return this._client.get(I`/videos/${e}`,n)}list(e={},n){return this._client.getAPIList("/videos",Ca,{query:e,...n})}delete(e,n){return this._client.delete(I`/videos/${e}`,n)}downloadContent(e,n={},s){return this._client.get(I`/videos/${e}/content`,{query:n,...s,headers:H([{Accept:"application/binary"},s?.headers]),__binaryResponse:!0})}remix(e,n,s){return this._client.post(I`/videos/${e}/remix`,rd({body:n,...s},this._client))}}var rr,Hp,la;class Vp extends G{constructor(){super(...arguments),rr.add(this)}async unwrap(e,n,s=this._client.webhookSecret,r=300){return await this.verifySignature(e,n,s,r),JSON.parse(e)}async verifySignature(e,n,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");x(this,rr,"m",Hp).call(this,s);const i=H([n]).values,a=x(this,rr,"m",la).call(this,i,"webhook-signature"),o=x(this,rr,"m",la).call(this,i,"webhook-timestamp"),l=x(this,rr,"m",la).call(this,i,"webhook-id"),c=parseInt(o,10);if(isNaN(c))throw new lr("Invalid webhook timestamp format");const u=Math.floor(Date.now()/1e3);if(u-c>r)throw new lr("Webhook timestamp is too old");if(c>u+r)throw new lr("Webhook timestamp is too new");const d=a.split(" ").map(g=>g.startsWith("v1,")?g.substring(3):g),f=s.startsWith("whsec_")?Buffer.from(s.replace("whsec_",""),"base64"):Buffer.from(s,"utf-8"),h=l?`${l}.${o}.${e}`:`${o}.${e}`,m=await crypto.subtle.importKey("raw",f,{name:"HMAC",hash:"SHA-256"},!1,["verify"]);for(const g of d)try{const y=Buffer.from(g,"base64");if(await crypto.subtle.verify("HMAC",m,y,new TextEncoder().encode(h)))return}catch{continue}throw new lr("The given webhook signature does not match the expected signature")}}rr=new WeakSet,Hp=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")},la=function(e,n){if(!e)throw new Error("Headers are required");const s=e.get(n);if(s==null)throw new Error(`Missing required header: ${n}`);return s};var Ul,Hc,ca,Wp;class ae{constructor({baseURL:e=er("OPENAI_BASE_URL"),apiKey:n=er("OPENAI_API_KEY"),organization:s=er("OPENAI_ORG_ID")??null,project:r=er("OPENAI_PROJECT_ID")??null,webhookSecret:i=er("OPENAI_WEBHOOK_SECRET")??null,...a}={}){if(Ul.add(this),ca.set(this,void 0),this.completions=new _p(this),this.chat=new Ic(this),this.embeddings=new Ep(this),this.files=new Ap(this),this.images=new Np(this),this.audio=new Ii(this),this.moderations=new Fp(this),this.models=new Rp(this),this.fineTuning=new Nr(this),this.graders=new jc(this),this.vectorStores=new oo(this),this.webhooks=new Vp(this),this.beta=new Ir(this),this.batches=new hp(this),this.uploads=new qc(this),this.responses=new ao(this),this.realtime=new io(this),this.conversations=new Mc(this),this.evals=new Lc(this),this.containers=new Fc(this),this.videos=new qp(this),n===void 0)throw new Q("Missing credentials. Please pass an `apiKey`, or set the `OPENAI_API_KEY` environment variable.");const o={apiKey:n,organization:s,project:r,webhookSecret:i,...a,baseURL:e||"https://api.openai.com/v1"};if(!o.dangerouslyAllowBrowser&&g0())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??Hc.DEFAULT_TIMEOUT,this.logger=o.logger??console;const l="warn";this.logLevel=l,this.logLevel=nd(o.logLevel,"ClientOptions.logLevel",this)??nd(er("OPENAI_LOG"),"process.env['OPENAI_LOG']",this)??l,this.fetchOptions=o.fetchOptions,this.maxRetries=o.maxRetries??2,this.fetch=o.fetch??_0(),te(this,ca,k0),this._options=o,this.apiKey=typeof n=="string"?n:"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:n}){}async authHeaders(e){return H([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return P0(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${nr}`}defaultIdempotencyKey(){return`stainless-node-retry-${_h()}`}makeStatusError(e,n,s,r){return Ye.generate(e,n,s,r)}async _callApiKey(){const e=this._options.apiKey;if(typeof e!="function")return!1;let n;try{n=await e()}catch(s){throw s instanceof Q?s:new Q(`Failed to get token from 'apiKey' function: ${s.message}`,{cause:s})}if(typeof n!="string"||!n)throw new Q(`Expected 'apiKey' function argument to return a string but it returned ${n}`);return this.apiKey=n,!0}buildURL(e,n,s){const r=!x(this,Ul,"m",Wp).call(this)&&s||this.baseURL,i=d0(e)?new URL(e):new URL(r+(r.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),a=this.defaultQuery();return f0(a)||(n={...a,...n}),typeof n=="object"&&n&&!Array.isArray(n)&&(i.search=this.stringifyQuery(n)),i.toString()}async prepareOptions(e){await this._callApiKey()}async prepareRequest(e,{url:n,options:s}){}get(e,n){return this.methodRequest("get",e,n)}post(e,n){return this.methodRequest("post",e,n)}patch(e,n){return this.methodRequest("patch",e,n)}put(e,n){return this.methodRequest("put",e,n)}delete(e,n){return this.methodRequest("delete",e,n)}methodRequest(e,n,s){return this.request(Promise.resolve(s).then(r=>({method:e,path:n,...r})))}request(e,n=null){return new Pi(this,this.makeRequest(e,n,void 0))}async makeRequest(e,n,s){const r=await e,i=r.maxRetries??this.maxRetries;n==null&&(n=i),await this.prepareOptions(r);const{req:a,url:o,timeout:l}=await this.buildRequest(r,{retryCount:i-n});await this.prepareRequest(a,{url:o,options:r});const c="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),u=s===void 0?"":`, retryOf: ${s}`,d=Date.now();if(Xe(this).debug(`[${c}] sending request`,gs({retryOfRequestLogID:s,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new Mt;const f=new AbortController,h=await this.fetchWithTimeout(o,a,l,f).catch(Tl),m=Date.now();if(h instanceof globalThis.Error){const b=`retrying, ${n} attempts remaining`;if(r.signal?.aborted)throw new Mt;const v=Cl(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(n)return Xe(this).info(`[${c}] connection ${v?"timed out":"failed"} - ${b}`),Xe(this).debug(`[${c}] connection ${v?"timed out":"failed"} (${b})`,gs({retryOfRequestLogID:s,url:o,durationMs:m-d,message:h.message})),this.retryRequest(r,n,s??c);throw Xe(this).info(`[${c}] connection ${v?"timed out":"failed"} - error; no more retries left`),Xe(this).debug(`[${c}] connection ${v?"timed out":"failed"} (error; no more retries left)`,gs({retryOfRequestLogID:s,url:o,durationMs:m-d,message:h.message})),v?new Za:new Ci({cause:h})}const g=[...h.headers.entries()].filter(([b])=>b==="x-request-id").map(([b,v])=>", "+b+": "+JSON.stringify(v)).join(""),y=`[${c}${u}${g}] ${a.method} ${o} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${m-d}ms`;if(!h.ok){const b=await this.shouldRetry(h);if(n&&b){const A=`retrying, ${n} attempts remaining`;return await x0(h.body),Xe(this).info(`${y} - ${A}`),Xe(this).debug(`[${c}] response error (${A})`,gs({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),this.retryRequest(r,n,s??c,h.headers)}const v=b?"error; no more retries left":"error; not retryable";Xe(this).info(`${y} - ${v}`);const w=await h.text().catch(A=>Tl(A).message),k=m0(w),P=k?void 0:w;throw Xe(this).debug(`[${c}] response error (${v})`,gs({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,message:P,durationMs:Date.now()-d})),this.makeStatusError(h.status,k,P,h.headers)}return Xe(this).info(y),Xe(this).debug(`[${c}] response start`,gs({retryOfRequestLogID:s,url:h.url,status:h.status,headers:h.headers,durationMs:m-d})),{response:h,options:r,controller:f,requestLogID:c,retryOfRequestLogID:s,startTime:d}}getAPIList(e,n,s){return this.requestAPIList(n,{method:"get",path:e,...s})}requestAPIList(e,n){const s=this.makeRequest(n,null,void 0);return new Mh(this,s,e)}async fetchWithTimeout(e,n,s,r){const{signal:i,method:a,...o}=n||{};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,u={signal:r.signal,...c?{duplex:"half"}:{},method:"GET",...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(l)}}async shouldRetry(e){const n=e.headers.get("x-should-retry");return n==="true"?!0:n==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,n,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(n,l)}return await Ti(i),this.makeRequest(e,n-1,s)}calculateDefaultRetryTimeoutMillis(e,n){const i=n-e,a=Math.min(.5*Math.pow(2,i),8),o=1-Math.random()*.25;return a*o*1e3}async buildRequest(e,{retryCount:n=0}={}){const s={...e},{method:r,path:i,query:a,defaultBaseURL:o}=s,l=this.buildURL(i,a,o);"timeout"in s&&p0("timeout",s.timeout),s.timeout=s.timeout??this.timeout;const{bodyHeaders:c,body:u}=this.buildBody({options:s}),d=await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:n});return{req:{method:r,headers:d,...s.signal&&{signal:s.signal},...globalThis.ReadableStream&&u instanceof globalThis.ReadableStream&&{duplex:"half"},...u&&{body:u},...this.fetchOptions??{},...s.fetchOptions??{}},url:l,timeout:s.timeout}}async buildHeaders({options:e,method:n,bodyHeaders:s,retryCount:r}){let i={};this.idempotencyHeader&&n!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);const a=H([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))}:{},...b0(),"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:n}}){if(!e)return{bodyHeaders:void 0,body:void 0};const s=H([n]);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:Ah(e)}:x(this,ca,"f").call(this,{body:e,headers:s})}}Hc=ae,ca=new WeakMap,Ul=new WeakSet,Wp=function(){return this.baseURL!=="https://api.openai.com/v1"};ae.OpenAI=Hc;ae.DEFAULT_TIMEOUT=6e5;ae.OpenAIError=Q;ae.APIError=Ye;ae.APIConnectionError=Ci;ae.APIConnectionTimeoutError=Za;ae.APIUserAbortError=Mt;ae.NotFoundError=yc;ae.ConflictError=wc;ae.RateLimitError=_c;ae.BadRequestError=mc;ae.AuthenticationError=gc;ae.InternalServerError=xc;ae.PermissionDeniedError=vc;ae.UnprocessableEntityError=bc;ae.InvalidWebhookSignatureError=lr;ae.toFile=Uh;ae.Completions=_p;ae.Chat=Ic;ae.Embeddings=Ep;ae.Files=Ap;ae.Images=Np;ae.Audio=Ii;ae.Moderations=Fp;ae.Models=Rp;ae.FineTuning=Nr;ae.Graders=jc;ae.VectorStores=oo;ae.Webhooks=Vp;ae.Beta=Ir;ae.Batches=hp;ae.Uploads=qc;ae.Responses=ao;ae.Realtime=io;ae.Conversations=Mc;ae.Evals=Lc;ae.Containers=Fc;ae.Videos=qp;const hx=Object.freeze(Object.defineProperty({__proto__:null,APIConnectionError:Ci,APIConnectionTimeoutError:Za,APIError:Ye,APIPromise:Pi,APIUserAbortError:Mt,AuthenticationError:gc,BadRequestError:mc,ConflictError:wc,InternalServerError:xc,InvalidWebhookSignatureError:lr,NotFoundError:yc,OpenAI:ae,OpenAIError:Q,PagePromise:Mh,PermissionDeniedError:vc,RateLimitError:_c,UnprocessableEntityError:bc,default:ae,toFile:Uh},Symbol.toStringTag,{value:"Module"}));module.exports=c0;
|
||
|
||
/* nosourcemap */ |