315 lines
455 KiB
JavaScript
Executable File
315 lines
455 KiB
JavaScript
Executable File
var e=Object.defineProperty,t=(e,t,n)=>()=>{if(n)throw n[0];try{return e&&(t=e(e=0)),t}catch(e){throw n=[e],e}},n=(t,n)=>{let r={};for(var i in t)e(r,i,{get:t[i],enumerable:!0});return n||e(r,Symbol.toStringTag,{value:`Module`}),r};let r=require("obsidian");var i=globalThis.process?.env?.NODE_ENV,a=i&&!i.toLowerCase().startsWith(`prod`),o=Array.isArray,s=Array.prototype.indexOf,c=Array.prototype.includes,l=Array.from,u=Object.defineProperty,d=Object.getOwnPropertyDescriptor,f=Object.getOwnPropertyDescriptors,p=Object.prototype,m=Array.prototype,h=Object.getPrototypeOf,g=Object.isExtensible;function _(e){return typeof e==`function`}var v=()=>{};function y(e){return e()}function b(e){for(var t=0;t<e.length;t++)e[t]()}function x(){var e,t;return{promise:new Promise((n,r)=>{e=n,t=r}),resolve:e,reject:t}}function S(e){"@babel/helpers - typeof";return S=typeof Symbol==`function`&&typeof Symbol.iterator==`symbol`?function(e){return typeof e}:function(e){return e&&typeof Symbol==`function`&&e.constructor===Symbol&&e!==Symbol.prototype?`symbol`:typeof e},S(e)}function ee(e,t){if(S(e)!=`object`||!e)return e;var n=e[Symbol.toPrimitive];if(n!==void 0){var r=n.call(e,t||`default`);if(S(r)!=`object`)return r;throw TypeError(`@@toPrimitive must return a primitive value.`)}return(t===`string`?String:Number)(e)}function te(e){var t=ee(e,`string`);return S(t)==`symbol`?t:t+``}function ne(e,t,n){return(t=te(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var re=1024,ie=2048,ae=4096,oe=8192,se=16384,ce=32768,le=1<<25,ue=65536,de=1<<19,fe=1<<20,pe=1<<25,me=65536,he=1<<21,ge=1<<22,_e=1<<23,ve=Symbol(`$state`),ye=Symbol(`legacy props`),be=Symbol(``),xe=Symbol(`proxy path`),Se=Symbol(`attributes`),Ce=Symbol(`class`),we=Symbol(`style`),Te=Symbol(`text`),Ee=Symbol(`hmr anchor`),De=new class extends Error{constructor(...e){super(...e),ne(this,`name`,`StaleReactionError`),ne(this,`message`,"The reaction that called `getAbortSignal()` was re-run or destroyed")}},Oe=!!globalThis.document?.contentType&&globalThis.document.contentType.includes(`xml`);function ke(e){return e===this.v}function Ae(e,t){return e==e?e!==t||typeof e==`object`&&!!e||typeof e==`function`:t==t}function je(e){return!Ae(e,this.v)}function Me(e){if(a){let t=Error(`lifecycle_outside_component\n\`${e}(...)\` can only be used during component initialisation\nhttps://svelte.dev/e/lifecycle_outside_component`);throw t.name=`Svelte error`,t}throw Error(`https://svelte.dev/e/lifecycle_outside_component`)}function Ne(){if(a){let e=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 e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/async_derived_orphan`)}function Pe(){if(a){let e=Error(`derived_references_self
|
||
A derived value cannot reference itself recursively
|
||
https://svelte.dev/e/derived_references_self`);throw e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/derived_references_self`)}function Fe(e,t,n){if(a){let r=Error(`each_key_duplicate\n${n?`Keyed each block has duplicate key \`${n}\` at indexes ${e} and ${t}`:`Keyed each block has duplicate key at indexes ${e} and ${t}`}\nhttps://svelte.dev/e/each_key_duplicate`);throw r.name=`Svelte error`,r}throw Error(`https://svelte.dev/e/each_key_duplicate`)}function Ie(e,t,n){if(a){let r=Error(`each_key_volatile\nKeyed each block has key that is not idempotent — the key for item at index ${e} was \`${t}\` but is now \`${n}\`. Keys must be the same each time for a given item\nhttps://svelte.dev/e/each_key_volatile`);throw r.name=`Svelte error`,r}throw Error(`https://svelte.dev/e/each_key_volatile`)}function Le(e){if(a){let t=Error(`effect_in_teardown\n\`${e}\` cannot be used inside an effect cleanup function\nhttps://svelte.dev/e/effect_in_teardown`);throw t.name=`Svelte error`,t}throw Error(`https://svelte.dev/e/effect_in_teardown`)}function Re(){if(a){let e=Error(`effect_in_unowned_derived
|
||
Effect cannot be created inside a \`$derived\` value that was not itself created inside an effect
|
||
https://svelte.dev/e/effect_in_unowned_derived`);throw e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/effect_in_unowned_derived`)}function ze(e){if(a){let t=Error(`effect_orphan\n\`${e}\` can only be used inside an effect (e.g. during component initialisation)\nhttps://svelte.dev/e/effect_orphan`);throw t.name=`Svelte error`,t}throw Error(`https://svelte.dev/e/effect_orphan`)}function Be(){if(a){let e=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 e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/effect_update_depth_exceeded`)}function Ve(e){if(a){let t=Error(`lifecycle_legacy_only\n\`${e}(...)\` cannot be used in runes mode\nhttps://svelte.dev/e/lifecycle_legacy_only`);throw t.name=`Svelte error`,t}throw Error(`https://svelte.dev/e/lifecycle_legacy_only`)}function He(e){if(a){let t=Error(`props_invalid_value\nCannot do \`bind:${e}={undefined}\` when \`${e}\` has a fallback value\nhttps://svelte.dev/e/props_invalid_value`);throw t.name=`Svelte error`,t}throw Error(`https://svelte.dev/e/props_invalid_value`)}function Ue(e){if(a){let t=Error(`rune_outside_svelte\nThe \`${e}\` rune is only available inside \`.svelte\` and \`.svelte.js/ts\` files\nhttps://svelte.dev/e/rune_outside_svelte`);throw t.name=`Svelte error`,t}throw Error(`https://svelte.dev/e/rune_outside_svelte`)}function We(){if(a){let e=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 e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/state_descriptors_fixed`)}function Ge(){if(a){let e=Error(`state_prototype_fixed
|
||
Cannot set prototype of \`$state\` object
|
||
https://svelte.dev/e/state_prototype_fixed`);throw e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/state_prototype_fixed`)}function Ke(){if(a){let e=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 e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/state_unsafe_mutation`)}function qe(){if(a){let e=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 e.name=`Svelte error`,e}throw Error(`https://svelte.dev/e/svelte_boundary_reset_onerror`)}var Je=!1;function Ye(){Je=!0}var Xe={},Ze=Symbol(`uninitialized`),Qe=Symbol(`filename`);function $e(e,t){return e.label=t,et(e.v,t),e}function et(e,t){return e?.[xe]?.(t),e}function tt(e){let t=Error(),n=nt();return n.length===0?null:(n.unshift(`
|
||
`),u(t,`stack`,{value:n.join(`
|
||
`)}),u(t,`name`,{value:e}),t)}function nt(){let e=Error.stackTraceLimit;Error.stackTraceLimit=1/0;let t=Error().stack;if(Error.stackTraceLimit=e,!t)return[];let n=t.split(`
|
||
`),r=[];for(let e=0;e<n.length;e++){let t=n[e],i=t.replaceAll(`\\`,`/`);if(t.trim()!==`Error`){if(t.includes(`validate_each_keys`))return[];i.includes(`svelte/src/internal`)||i.includes(`node_modules/.vite`)||r.push(t)}}return r}var rt=null;function it(e){rt=e}var at=null;function ot(e){at=e}var st=null;function ct(e){st=e}function lt(e,t=!1,n){rt={p:rt,i:!1,c:null,e:null,s:e,x:null,r:M,l:Je&&!t?{s:null,u:null,$:[]}:null},a&&(rt.function=n,st=n)}function ut(e){var t=rt,n=t.e;if(n!==null){t.e=null;for(var r of n)qi(r)}return e!==void 0&&(t.x=e),t.i=!0,rt=t.p,a&&(st=rt?.function??null),e??{}}function dt(){return!Je||rt!==null&&rt.l===null}var ft=[];function pt(){var e=ft;ft=[],b(e)}function mt(e){if(ft.length===0&&!vr){var t=ft;queueMicrotask(()=>{t===ft&&pt()})}ft.push(e)}var ht=!1;function gt(e){ht=e}var _t;function vt(e){if(e===null)throw Xe;return _t=e}function yt(){return vt(Lt(_t))}function C(e){if(ht){if(Lt(_t)!==null)throw Xe;_t=e}}function bt(e=1){if(ht){for(var t=e,n=_t;t--;)n=Lt(n);_t=n}}function xt(e=!0){for(var t=0,n=_t;;){if(n.nodeType===8){var r=n.data;if(r===`]`){if(t===0)return n;--t}else(r===`[`||r===`[!`||r[0]===`[`&&!isNaN(Number(r.slice(1))))&&(t+=1)}var i=Lt(n);e&&n.remove(),n=i}}function St(e){if(!e||e.nodeType!==8)throw Xe;return e.data}var Ct=/^[a-zA-Z_$][a-zA-Z_$0-9]*$/;function wt(e){if(typeof e!=`object`||!e||ve in e)return e;let t=h(e);if(t!==p&&t!==m)return e;var n=new Map,r=o(e),i=si(0),s=null,c=ki,l=e=>{if(ki===c)return e();var t=_i,n=ki;yi(null),Ai(c);var r=e();return yi(t),Ai(n),r};r&&(n.set(`length`,si(e.length,s)),a&&(e=Ot(e)));var u=``;let f=!1;function g(e){if(!f){f=!0,u=e,$e(i,`${u} version`);for(let[e,t]of n)$e(t,Tt(u,e));f=!1}}return new Proxy(e,{defineProperty(e,t,r){(!(`value`in r)||r.configurable===!1||r.enumerable===!1||r.writable===!1)&&We();var i=n.get(t);return i===void 0?l(()=>{var e=si(r.value,s);return n.set(t,e),a&&typeof t==`string`&&$e(e,Tt(u,t)),e}):j(i,r.value,!0),!0},deleteProperty(e,t){var r=n.get(t);if(r===void 0){if(t in e){let e=l(()=>si(Ze,s));n.set(t,e),di(i),a&&$e(e,Tt(u,t))}}else j(r,Ze),di(i);return!0},get(t,r,i){if(r===ve)return e;if(a&&r===xe)return g;var o=n.get(r),c=r in t;if(o===void 0&&(!c||d(t,r)?.writable)&&(o=l(()=>{var e=si(wt(c?t[r]:Ze),s);return a&&$e(e,Tt(u,r)),e}),n.set(r,o)),o!==void 0){var f=N(o);return f===Ze?void 0:f}return Reflect.get(t,r,i)},getOwnPropertyDescriptor(e,t){var r=Reflect.getOwnPropertyDescriptor(e,t);if(r&&`value`in r){var i=n.get(t);i&&(r.value=N(i))}else if(r===void 0){var a=n.get(t),o=a?.v;if(a!==void 0&&o!==Ze)return{enumerable:!0,configurable:!0,value:o,writable:!0}}return r},has(e,t){if(t===ve)return!0;var r=n.get(t),i=r!==void 0&&r.v!==Ze||Reflect.has(e,t);return(r!==void 0||M!==null&&(!i||d(e,t)?.writable))&&(r===void 0&&(r=l(()=>{var n=si(i?wt(e[t]):Ze,s);return a&&$e(n,Tt(u,t)),n}),n.set(t,r)),N(r)===Ze)?!1:i},set(e,t,o,c){var f=n.get(t),p=t in e;if(r&&t===`length`)for(var m=o;m<f.v;m+=1){var h=n.get(m+``);h===void 0?m in e&&(h=l(()=>si(Ze,s)),n.set(m+``,h),a&&$e(h,Tt(u,m))):j(h,Ze)}if(f===void 0)(!p||d(e,t)?.writable)&&(f=l(()=>si(void 0,s)),a&&$e(f,Tt(u,t)),j(f,wt(o)),n.set(t,f));else{p=f.v!==Ze;var g=l(()=>wt(o));j(f,g)}var _=Reflect.getOwnPropertyDescriptor(e,t);if(_?.set&&_.set.call(c,o),!p){if(r&&typeof t==`string`){var v=n.get(`length`),y=Number(t);Number.isInteger(y)&&y>=v.v&&j(v,y+1)}di(i)}return!0},ownKeys(e){N(i);var t=Reflect.ownKeys(e).filter(e=>{var t=n.get(e);return t===void 0||t.v!==Ze});for(var[r,a]of n)a.v!==Ze&&!(r in e)&&t.push(r);return t},setPrototypeOf(){Ge()}})}function Tt(e,t){return typeof t==`symbol`?`${e}[Symbol(${t.description??``})]`:Ct.test(t)?`${e}.${t}`:/^\d+$/.test(t)?`${e}[${t}]`:`${e}['${t}']`}function Et(e){try{if(typeof e==`object`&&e&&ve in e)return e[ve]}catch{}return e}var Dt=new Set([`copyWithin`,`fill`,`pop`,`push`,`reverse`,`shift`,`sort`,`splice`,`unshift`]);function Ot(e){return new Proxy(e,{get(e,t,n){var r=Reflect.get(e,t,n);return Dt.has(t)?function(...e){ai();var t=r.apply(this,e);return ui(),t}:r}})}function kt(){let e=Array.prototype,t=Array.__svelte_cleanup;t&&t();let{indexOf:n,lastIndexOf:r,includes:i}=e;e.indexOf=function(e,t){let r=n.call(this,e,t);if(r===-1)for(let n=t??0;n<this.length&&Et(this[n])!==e;n+=1);return r},e.lastIndexOf=function(e,t){let n=r.call(this,e,t??this.length-1);if(n===-1)for(let n=0;n<=(t??this.length-1)&&Et(this[n])!==e;n+=1);return n},e.includes=function(e,t){let n=i.call(this,e,t);if(!n)for(let t=0;t<this.length&&Et(this[t])!==e;t+=1);return n},Array.__svelte_cleanup=()=>{e.indexOf=n,e.lastIndexOf=r,e.includes=i}}var At,jt,Mt,Nt;function Pt(){if(At===void 0){At=window,jt=/Firefox/.test(navigator.userAgent);var e=Element.prototype,t=Node.prototype,n=Text.prototype;Mt=d(t,`firstChild`).get,Nt=d(t,`nextSibling`).get,g(e)&&(e[Ce]=void 0,e[Se]=null,e[we]=void 0,e.__e=void 0),g(n)&&(n[Te]=void 0),a&&(e.__svelte_meta=null,kt())}}function Ft(e=``){return document.createTextNode(e)}function It(e){return Mt.call(e)}function Lt(e){return Nt.call(e)}function w(e,t){if(!ht)return It(e);var n=It(_t);if(n===null)n=_t.appendChild(Ft());else if(t&&n.nodeType!==3){var r=Ft();return n?.before(r),vt(r),r}return t&&Ht(n),vt(n),n}function Rt(e,t=!1){if(!ht){var n=It(e);return n instanceof Comment&&n.data===``?Lt(n):n}if(t){if(_t?.nodeType!==3){var r=Ft();return _t?.before(r),vt(r),r}Ht(_t)}return _t}function T(e,t=1,n=!1){let r=ht?_t:e;for(var i;t--;)i=r,r=Lt(r);if(!ht)return r;if(n){if(r?.nodeType!==3){var a=Ft();return r===null?i?.after(a):r.before(a),vt(a),a}Ht(r)}return vt(r),r}function zt(e){e.textContent=``}function Bt(){return!1}function Vt(e,t,n){return t==null||t===`http://www.w3.org/1999/xhtml`?n?document.createElement(e,{is:n}):document.createElement(e):n?document.createElementNS(t,e,{is:n}):document.createElementNS(t,e)}function Ht(e){if(e.nodeValue.length<65536)return;let t=e.nextSibling;for(;t!==null&&t.nodeType===3;)t.remove(),e.nodeValue+=t.nodeValue,t=e.nextSibling}var Ut=new WeakMap;function Wt(e){var t=M;if(t===null)return _i.f|=_e,e;if(a&&e instanceof Error&&!Ut.has(e)&&Ut.set(e,Kt(e,t)),!(t.f&32768)&&!(t.f&4))throw a&&!t.parent&&e instanceof Error&&qt(e),e;Gt(e,t)}function Gt(e,t){if(!(t!==null&&t.f&16384)){for(;t!==null;){if(t.f&128){if(!(t.f&32768))throw e;try{t.b.error(e);return}catch(t){e=t}}t=t.parent}throw a&&e instanceof Error&&qt(e),e}}function Kt(e,t){let n=d(e,`message`);if(!(n&&!n.configurable)){for(var r=jt?` `:` `,i=`\n${r}in ${t.fn?.name||`<unknown>`}`,a=t.ctx;a!==null;)i+=`\n${r}in ${a.function?.[Qe].split(`/`).pop()}`,a=a.p;return{message:e.message+`\n${i}\n`,stack:e.stack?.split(`
|
||
`).filter(e=>!e.includes(`svelte/src/internal`)).join(`
|
||
`)}}}function qt(e){let t=Ut.get(e);t&&(u(e,`message`,{value:t.message}),u(e,`stack`,{value:t.stack}))}var Jt=~(ie|ae|re);function Yt(e,t){e.f=e.f&Jt|t}function Xt(e){e.f&512||e.deps===null?Yt(e,re):Yt(e,ae)}function Zt(e){if(e!==null)for(let t of e)!(t.f&2)||!(t.f&65536)||(t.f^=me,Zt(t.deps))}function Qt(e,t,n){e.f&2048?t.add(e):e.f&4096&&n.add(e),Zt(e.deps),Yt(e,re)}function $t(e,t,n){if(e==null)return t(void 0),n&&n(void 0),v;let r=P(()=>e.subscribe(t,n));return r.unsubscribe?()=>r.unsubscribe():r}var en=[];function tn(e,t){return{subscribe:nn(e,t).subscribe}}function nn(e,t=v){let n=null,r=new Set;function i(t){if(Ae(e,t)&&(e=t,n)){let t=!en.length;for(let t of r)t[1](),en.push(t,e);if(t){for(let e=0;e<en.length;e+=2)en[e][0](en[e+1]);en.length=0}}}function a(t){i(t(e))}function o(o,s=v){let c=[o,s];return r.add(c),r.size===1&&(n=t(i,a)||v),o(e),()=>{r.delete(c),r.size===0&&n&&(n(),n=null)}}return{set:i,update:a,subscribe:o}}function E(e){let t;return $t(e,e=>t=e)(),t}var rn=!1,an=!1,on=Symbol(`unmounted`);function sn(e,t,n){let r=n[t]??(n[t]={store:null,source:A(void 0),unsubscribe:v});if(a&&(r.source.label=t),r.store!==e&&!(on in n)){if(r.unsubscribe(),r.store=e??null,e==null)r.source.v=void 0,r.unsubscribe=v;else{var i=!0;r.unsubscribe=$t(e,e=>{i?r.source.v=e:j(r.source,e)}),i=!1}}return e&&on in n?E(e):N(r.source)}function cn(e,t){return un(e,t),t}function ln(){let e={};function t(){Gi(()=>{for(var t in e)e[t].unsubscribe();u(e,on,{enumerable:!1,value:!0})})}return[e,t]}function un(e,t){rn=!0;try{e.set(t)}finally{rn=!1}}function dn(){an=!0}function fn(e){var t=an;try{return an=!1,[e(),an]}finally{an=t}}function pn(e,t,n,r=!0){r&&n();for(var i of t)e.addEventListener(i,n);Gi(()=>{for(var r of t)e.removeEventListener(r,n)})}function mn(e){var t=_i,n=M;yi(null),bi(null);try{return e()}finally{yi(t),bi(n)}}function hn(e){let t=0,n=oi(0),r;return a&&$e(n,`createSubscriber version`),()=>{Wi()&&(N(n),ea(()=>(t===0&&(r=P(()=>e(()=>di(n)))),t+=1,()=>{mt(()=>{--t,t===0&&(r?.(),r=void 0,di(n))})})))}}function gn(e,t){if(t.has(e))throw TypeError(`Cannot initialize the same private elements twice on an object`)}function _n(e,t){gn(e,t),t.add(e)}function D(e,t,n){gn(e,t),t.set(e,n)}function vn(e,t,n){if(typeof e==`function`?e===t:e.has(t))return arguments.length<3?t:n;throw TypeError(`Private element is not present on this object`)}function O(e,t,n){return e.set(vn(e,t),n),n}function k(e,t){return e.get(vn(e,t))}var yn=ue|de;function bn(e,t,n,r){new Rn(e,t,n,r)}var xn=new WeakMap,Sn=new WeakMap,Cn=new WeakMap,wn=new WeakMap,Tn=new WeakMap,En=new WeakMap,Dn=new WeakMap,On=new WeakMap,kn=new WeakMap,An=new WeakMap,jn=new WeakMap,Mn=new WeakMap,Nn=new WeakMap,Pn=new WeakMap,Fn=new WeakMap,In=new WeakMap,Ln=new WeakSet,Rn=class{constructor(e,t,n,r){_n(this,Ln),ne(this,`parent`,void 0),ne(this,`is_pending`,!1),ne(this,`transform_error`,void 0),D(this,xn,void 0),D(this,Sn,ht?_t:null),D(this,Cn,void 0),D(this,wn,void 0),D(this,Tn,void 0),D(this,En,null),D(this,Dn,null),D(this,On,null),D(this,kn,null),D(this,An,0),D(this,jn,0),D(this,Mn,!1),D(this,Nn,new Set),D(this,Pn,new Set),D(this,Fn,null),D(this,In,hn(()=>(O(Fn,this,oi(k(An,this))),a&&$e(k(Fn,this),`$effect.pending()`),()=>{O(Fn,this,null)}))),O(xn,this,e),O(Cn,this,t),O(wn,this,e=>{var t=M;t.b=this,t.f|=128,n(e)}),this.parent=M.b,this.transform_error=r??this.parent?.transform_error??(e=>e),O(Tn,this,na(()=>{if(ht){let e=k(Sn,this);yt();let t=e.data===`[!`;if(e.data.startsWith(`[?`)){let t=JSON.parse(e.data.slice(2));vn(Ln,this,Bn).call(this,t)}else t?vn(Ln,this,Hn).call(this):vn(Ln,this,zn).call(this)}else vn(Ln,this,Un).call(this)},yn)),ht&&O(xn,this,_t)}defer_effect(e){Qt(e,k(Nn,this),k(Pn,this))}is_rendered(){return!this.is_pending&&(!this.parent||this.parent.is_rendered())}has_pending_snippet(){return!!k(Cn,this).pending}update_pending_count(e,t){vn(Ln,this,Kn).call(this,e,t),O(An,this,k(An,this)+e),!(!k(Fn,this)||k(Mn,this))&&(O(Mn,this,!0),mt(()=>{O(Mn,this,!1),k(Fn,this)&&li(k(Fn,this),k(An,this))}))}get_effect_pending(){return k(In,this).call(this),N(k(Fn,this))}error(e){if(!k(Cn,this).onerror&&!k(Cn,this).failed)throw e;mr?.is_fork?(k(En,this)&&mr.skip_effect(k(En,this)),k(Dn,this)&&mr.skip_effect(k(Dn,this)),k(On,this)&&mr.skip_effect(k(On,this)),mr.oncommit(()=>{vn(Ln,this,qn).call(this,e)})):vn(Ln,this,qn).call(this,e)}};function zn(){try{O(En,this,ra(()=>k(wn,this).call(this,k(xn,this))))}catch(e){this.error(e)}}function Bn(e){let t=k(Cn,this).failed,{reset:n,invoke_onerror:r}=vn(Ln,this,Vn).call(this,e);mt(r),t&&O(On,this,ra(()=>{t(k(xn,this),()=>e,()=>n)}))}function Vn(e){var t=!1,n=!1;let r=()=>{t||(t=!0,n&&qe(),k(On,this)!==null&&ua(k(On,this),()=>{O(On,this,null)}),vn(Ln,this,Gn).call(this,()=>{vn(Ln,this,Un).call(this)}))};return{reset:r,invoke_onerror:()=>{try{n=!0,k(Cn,this).onerror?.(e,r),n=!1}catch(e){Gt(e,k(Tn,this)&&k(Tn,this).parent)}}}}function Hn(){let e=k(Cn,this).pending;e&&(this.is_pending=!0,O(Dn,this,ra(()=>e(k(xn,this)))),mt(()=>{var e=O(kn,this,document.createDocumentFragment()),t=Ft();e.append(t),O(En,this,vn(Ln,this,Gn).call(this,()=>ra(()=>k(wn,this).call(this,t)))),k(jn,this)===0&&(k(xn,this).before(e),O(kn,this,null),ua(k(Dn,this),()=>{O(Dn,this,null)}),vn(Ln,this,Wn).call(this,mr))}))}function Un(){try{if(this.is_pending=this.has_pending_snippet(),O(jn,this,0),O(An,this,0),O(En,this,ra(()=>{k(wn,this).call(this,k(xn,this))})),k(jn,this)>0){var e=O(kn,this,document.createDocumentFragment());ma(k(En,this),e);let t=k(Cn,this).pending;O(Dn,this,ra(()=>t(k(xn,this))))}else vn(Ln,this,Wn).call(this,mr)}catch(e){this.error(e)}}function Wn(e){this.is_pending=!1,e.transfer_effects(k(Nn,this),k(Pn,this))}function Gn(e){var t=M,n=_i,r=rt;bi(k(Tn,this)),yi(k(Tn,this)),it(k(Tn,this).ctx);try{return Vr.ensure(),e()}catch(e){return Wt(e),null}finally{bi(t),yi(n),it(r)}}function Kn(e,t){if(!this.has_pending_snippet()){if(this.parent){var n;vn(Ln,n=this.parent,Kn).call(n,e,t)}return}O(jn,this,k(jn,this)+e),k(jn,this)===0&&(vn(Ln,this,Wn).call(this,t),k(Dn,this)&&ua(k(Dn,this),()=>{O(Dn,this,null)}),k(kn,this)&&(k(xn,this).before(k(kn,this)),O(kn,this,null)))}function qn(e){k(En,this)&&(sa(k(En,this)),O(En,this,null)),k(Dn,this)&&(sa(k(Dn,this)),O(Dn,this,null)),k(On,this)&&(sa(k(On,this)),O(On,this,null)),ht&&(vt(k(Sn,this)),bt(),vt(xt()));let t=k(Cn,this).failed,n=e=>{let{reset:n,invoke_onerror:r}=vn(Ln,this,Vn).call(this,e);r(),t&&O(On,this,vn(Ln,this,Gn).call(this,()=>{try{return ra(()=>{var r=M;r.b=this,r.f|=128,t(k(xn,this),()=>e,()=>n)})}catch(e){return Gt(e,k(Tn,this).parent),null}}))};mt(()=>{var t;try{t=this.transform_error(e)}catch(e){Gt(e,k(Tn,this)&&k(Tn,this).parent);return}typeof t==`object`&&t&&typeof t.then==`function`?t.then(n,e=>Gt(e,k(Tn,this)&&k(Tn,this).parent)):n(t)})}function Jn(e,t,n,r){let i=dt()?tr:ar;var o=e.filter(e=>!e.settled),s=t.map(i);if(a&&s.forEach((e,n)=>{e.label=t[n].toString().replace(`() => `,``).replaceAll(`$.eager(() => `,`$state.eager(`).replace(/\$\.get\((.+?)\)/g,(e,t)=>t)}),n.length===0&&o.length===0){r(s);return}var c=M,l=Yn(),u=o.length===1?o[0].promise:o.length>1?Promise.all(o.map(e=>e.promise)):null;function d(e){if(!(c.f&16384)){l();try{r([...s,...e])}catch(e){Gt(e,c)}Xn()}}var f=Zn();if(n.length===0){u.then(()=>d([])).finally(f);return}function p(){Promise.all(n.map(e=>rr(e))).then(d).catch(e=>Gt(e,c)).finally(f)}u?u.then(()=>{l(),p(),Xn()}):p()}function Yn(){var e=M,t=_i,n=rt,r=mr;if(a)var i=at;return function(o=!0){bi(e),yi(t),it(n),o&&!(e.f&16384)&&(r?.activate(),r?.apply()),a&&($n(null),ot(i))}}function Xn(e=!0){bi(null),yi(null),it(null),e&&mr?.deactivate(),a&&($n(null),ot(null))}function Zn(){var e=M,t=e.b,n=mr,r=!!t?.is_rendered();return t?.update_pending_count(1,n),n.increment(r,e),()=>{t?.update_pending_count(-1,n),n.decrement(r,e)}}var Qn=null;function $n(e){Qn=e}var er=new Set;function tr(e){var t=2|ie;return M!==null&&(M.f|=de),{ctx:rt,deps:null,effects:null,equals:ke,f:t,fn:e,reactions:null,rv:0,v:Ze,wv:0,parent:M,ac:null}}var nr=Symbol(`obsolete`);function rr(e,t,n){let r=M;r===null&&Ne();var i=void 0,o=oi(Ze);a&&(o.label=t??e.toString());var s=!_i,c=new Set;return $i(()=>{var t=M;a&&(Qn={effect:t,effect_deps:new Set,warned:!1});var l=x();i=l.promise;try{Promise.resolve(e()).then(l.resolve,e=>{e!==De&&l.reject(e)}).finally(Xn)}catch(e){l.reject(e),Xn()}if(a){if(Qn){if(t.deps!==null)for(let e=0;e<wi;e+=1)Qn.effect_deps.add(t.deps[e]);if(Ci!==null)for(let e=0;e<Ci.length;e+=1)Qn.effect_deps.add(Ci[e])}Qn=null}var u=mr;if(s){if(t.f&32768)var d=Zn();if(r.b?.is_rendered())u.async_deriveds.get(t)?.reject(nr);else for(let e of c.values())e.reject(nr);c.add(l),u.async_deriveds.set(t,l)}let f=(e,r=void 0)=>{a&&(Qn=null),d?.(),c.delete(l),r!==nr&&(u.activate(),r?(o.f|=_e,li(o,r)):(o.f&8388608&&(o.f^=_e),a&&n!==void 0&&!o.equals(e)&&(er.add(o),setTimeout(()=>{er.has(o)&&!(t.f&16384)&&(o.label,er.delete(o))})),li(o,e)),u.deactivate())};l.promise.then(f,e=>f(null,e||`unknown`))}),Gi(()=>{for(let e of c)e.reject(nr)}),a&&(o.f|=ge),new Promise(e=>{function t(n){function r(){n===i?e(o):t(i)}n.then(r,r)}t(i)})}function ir(e){let t=tr(e);return Si(t),t}function ar(e){let t=tr(e);return t.equals=je,t}function or(e){var t=e.effects;if(t!==null){e.effects=null;for(var n=0;n<t.length;n+=1)sa(t[n])}}var sr=[];function cr(e){var t,n=M,r=e.parent;if(!hi&&r!==null&&e.v!==Ze&&r.f&24576)return e.v;if(bi(r),a){let r=ti;ri(new Set);try{c.call(sr,e)&&Pe(),sr.push(e),e.f&=~me,or(e),t=Pi(e)}finally{bi(n),ri(r),sr.pop()}}else try{e.f&=~me,or(e),t=Pi(e)}finally{bi(n)}return t}function lr(e){var t=cr(e);if(!e.equals(t)&&(e.wv=ji(),(!mr?.is_fork||e.deps===null)&&(mr===null?e.v=t:(mr.capture(e,t,!0),hr?.capture(e,t,!0)),e.deps===null))){Yt(e,re);return}hi||(gr===null?Xt(e):(Wi()||mr?.is_fork)&&gr.set(e,t))}function ur(e){if(e.effects!==null)for(let t of e.effects)(t.teardown||t.ac)&&(t.teardown?.(),t.ac!==null&&mn(()=>{t.ac.abort(De),t.ac=null}),t.fn!==null&&(t.teardown=v),Ii(t,0),aa(t))}function dr(e){if(e.effects!==null)for(let t of e.effects)t.teardown&&t.fn!==null&&Li(t)}var fr,pr=null,mr=null,hr=null,gr=null,_r=null,vr=!1,yr=!1,br=null,xr=null,Sr=0,Cr=new Set,wr=1,Tr=new WeakMap,Er=new WeakMap,Dr=new WeakMap,Or=new WeakMap,kr=new WeakMap,Ar=new WeakMap,jr=new WeakMap,Mr=new WeakMap,Nr=new WeakMap,Pr=new WeakMap,Fr=new WeakMap,Ir=new WeakMap,Lr=new WeakMap,Rr=new WeakMap,zr=new WeakMap,Br=new WeakSet,Vr=class e{constructor(){_n(this,Br),ne(this,`id`,wr++),D(this,Tr,!1),ne(this,`linked`,!0),D(this,Er,null),D(this,Dr,null),ne(this,`async_deriveds`,new Map),ne(this,`current`,new Map),ne(this,`previous`,new Map),D(this,Or,new Set),D(this,kr,new Set),D(this,Ar,0),D(this,jr,new Map),D(this,Mr,null),D(this,Nr,[]),D(this,Pr,[]),D(this,Fr,new Set),D(this,Ir,new Set),D(this,Lr,new Map),D(this,Rr,new Set),ne(this,`is_fork`,!1),D(this,zr,!1),pr===null?pr=this:(O(Dr,pr,this),O(Er,this,pr)),pr=this}skip_effect(e){k(Lr,this).has(e)||k(Lr,this).set(e,{d:[],m:[]}),k(Rr,this).delete(e)}unskip_effect(e,t=e=>this.schedule(e)){var n=k(Lr,this).get(e);if(n){k(Lr,this).delete(e);for(var r of n.d)Yt(r,ie),t(r);for(r of n.m)Yt(r,ae),t(r)}k(Rr,this).add(e)}capture(e,t,n=!1){e.v!==Ze&&!this.previous.has(e)&&this.previous.set(e,e.v),e.f&8388608||(this.current.set(e,[t,n]),gr?.set(e,t)),this.is_fork||(e.v=t)}activate(){mr=this}deactivate(){mr=null,gr=null}flush(){try{a&&Cr.clear(),yr=!0,mr=this,vn(Br,this,Ur).call(this)}finally{if(Sr=0,_r=null,br=null,xr=null,yr=!1,mr=null,gr=null,ni.clear(),a)for(let e of Cr)e.updated=null}}discard(){for(let e of k(kr,this))e(this);k(kr,this).clear();for(let e of this.async_deriveds.values())e.reject(nr);vn(Br,this,Jr).call(this),k(Mr,this)?.resolve()}register_created_effect(e){k(Pr,this).push(e)}increment(e,t){if(O(Ar,this,k(Ar,this)+1),e){let e=k(jr,this).get(t)??0;k(jr,this).set(t,e+1)}}decrement(e,t){if(O(Ar,this,k(Ar,this)-1),e){let e=k(jr,this).get(t)??0;e===1?k(jr,this).delete(t):k(jr,this).set(t,e-1)}k(zr,this)||(O(zr,this,!0),mt(()=>{O(zr,this,!1),this.linked&&this.flush()}))}transfer_effects(e,t){for(let t of e)k(Fr,this).add(t);for(let e of t)k(Ir,this).add(e);e.clear(),t.clear()}oncommit(e){k(Or,this).add(e)}ondiscard(e){k(kr,this).add(e)}settled(){return(k(Mr,this)??O(Mr,this,x())).promise}static ensure(){if(mr===null){let t=mr=new e;!yr&&mt(()=>{k(Tr,t)||t.flush()})}return mr}apply(){gr=null}schedule(e){if(_r=e,e.b?.is_pending&&e.f&16777228&&!(e.f&32768)){e.b.defer_effect(e);return}for(var t=e;t.parent!==null;){t=t.parent;var n=t.f;if(br!==null&&t===M&&(_i===null||!(_i.f&2))&&!rn)return;if(n&96){if(!(n&1024))return;t.f^=re}}k(Nr,this).push(t)}};fr=Vr;function Hr(){if(this.is_fork)return!0;for(let n of k(jr,this).keys()){for(var e=n,t=!1;e.parent!==null;){if(k(Lr,this).has(e)){t=!0;break}e=e.parent}if(!t)return!0}return!1}function Ur(){if(O(Tr,this,!0),Sr++>1e3&&(vn(Br,this,Jr).call(this),Yr()),a)for(let e of this.current.keys())Cr.add(e);for(let e of k(Fr,this))k(Ir,this).delete(e),Yt(e,ie),this.schedule(e);for(let e of k(Ir,this))Yt(e,ae),this.schedule(e);let e=k(Nr,this);O(Nr,this,[]),this.apply();var t=br=[],n=[],r=xr=[];for(let r of e)try{vn(Br,this,Wr).call(this,r,t,n)}catch(e){throw ei(r),vn(Br,this,Hr).call(this)||this.discard(),e}if(mr=null,r.length>0){var i=fr.ensure();for(let e of r)i.schedule(e)}if(br=null,xr=null,vn(Br,this,Hr).call(this)){vn(Br,this,qr).call(this,n),vn(Br,this,qr).call(this,t);for(let[e,t]of k(Lr,this))$r(e,t);r.length>0&&vn(Br,mr,Ur).call(mr);return}let o=vn(Br,this,Gr).call(this);if(o){vn(Br,this,qr).call(this,n),vn(Br,this,qr).call(this,t),vn(Br,o,Kr).call(o,this);return}k(Fr,this).clear(),k(Ir,this).clear();for(let e of k(Or,this))e(this);k(Or,this).clear(),hr=this,Zr(n),Zr(t),hr=null,k(Mr,this)?.resolve();var s=mr;if(k(Ar,this)===0&&(k(Nr,this).length===0||s!==null)&&vn(Br,this,Jr).call(this),k(Nr,this).length>0){if(s!==null){let e=s;k(Nr,e).push(...k(Nr,this).filter(t=>!k(Nr,e).includes(t)))}else s=this}s!==null&&vn(Br,s,Ur).call(s)}function Wr(e,t,n){e.f^=re;for(var r=e.first;r!==null;){var i=r.f,a=!!(i&96);if(!(a&&i&1024||i&8192||k(Lr,this).has(r))&&r.fn!==null){a?r.f^=re:i&4?t.push(r):Mi(r)&&(i&16&&k(Ir,this).add(r),Li(r));var o=r.first;if(o!==null){r=o;continue}}for(;r!==null;){var s=r.next;if(s!==null){r=s;break}r=r.parent}}}function Gr(){for(var e=k(Er,this);e!==null;){if(!e.is_fork){for(let[t,[,n]]of this.current)if(e.current.has(t)&&!n)return e}e=k(Er,e)}return null}function Kr(e){for(let[t,n]of e.current)!this.previous.has(t)&&e.previous.has(t)&&this.previous.set(t,e.previous.get(t)),this.current.set(t,n);for(let[t,n]of e.async_deriveds){let e=this.async_deriveds.get(t);e&&n.promise.then(e.resolve).catch(e.reject)}e.async_deriveds.clear(),this.transfer_effects(k(Fr,e),k(Ir,e));let t=e=>{var n=e.reactions;if(n!==null&&!(e.f&2&&!(e.f&6144)))for(let e of n){var r=e.f;if(r&2)t(e);else{var i=e;r&4194320&&!this.async_deriveds.has(i)&&(k(Ir,this).delete(i),Yt(i,ie),this.schedule(i))}}};for(let e of this.current.keys())t(e);this.oncommit(()=>e.discard()),vn(Br,e,Jr).call(e),mr=this,vn(Br,this,Ur).call(this)}function qr(e){for(var t=0;t<e.length;t+=1)Qt(e[t],k(Fr,this),k(Ir,this))}function Jr(){if(this.linked){var e=k(Er,this),t=k(Dr,this);e===null||O(Dr,e,t),t===null?pr=e:O(Er,t,e),this.linked=!1}}function Yr(){if(a){var e=new Map;for(let n of mr.current.keys())for(let[r,i]of n.updated??[]){var t=e.get(r);t||(t={error:i.error,count:0},e.set(r,t)),t.count+=i.count}for(let t of e.values())t.error}try{Be()}catch(e){a&&u(e,`stack`,{value:``}),Gt(e,_r)}}var Xr=null;function Zr(e){var t=e.length;if(t!==0){for(var n=0;n<t;){var r=e[n++];if(!(r.f&24576)&&Mi(r)&&(Xr=new Set,Li(r),r.deps===null&&r.first===null&&r.nodes===null&&r.teardown===null&&r.ac===null&&la(r),Xr?.size>0)){ni.clear();for(let e of Xr){if(e.f&24576)continue;let t=[e],n=e.parent;for(;n!==null;)Xr.has(n)&&(Xr.delete(n),t.push(n)),n=n.parent;for(let e=t.length-1;e>=0;e--){let n=t[e];n.f&24576||Li(n)}}Xr.clear()}}Xr=null}}function Qr(e){mr.schedule(e)}function $r(e,t){if(!(e.f&32&&e.f&1024)){e.f&2048?t.d.push(e):e.f&4096&&t.m.push(e),Yt(e,re);for(var n=e.first;n!==null;)$r(n,t),n=n.next}}function ei(e){Yt(e,re);for(var t=e.first;t!==null;)ei(t),t=t.next}var ti=new Set,ni=new Map;function ri(e){ti=e}var ii=!1;function ai(){ii=!0}function oi(e,t){return{f:0,v:e,reactions:null,equals:ke,rv:0,wv:0}}function si(e,t){let n=oi(e,t);return Si(n),n}function A(e,t=!1,n=!0){let r=oi(e);if(t||(r.equals=je),Je&&n&&rt!==null&&rt.l!==null){var i;((i=rt.l).s??(i.s=[])).push(r)}return r}function ci(e,t){return j(e,P(()=>N(e))),t}function j(e,t,n=!1){_i!==null&&(!vi||_i.f&131072)&&dt()&&_i.f&4325394&&(xi===null||!xi.has(e))&&Ke();let r=n?wt(t):t;return a&&et(r,e.label),li(e,r,xr)}function li(e,t,n=null){if(!e.equals(t)){ni.set(e,hi?t:e.v);var r=Vr.ensure();if(r.capture(e,t),a){if(M!==null){e.updated??(e.updated=new Map);let t=(e.updated.get(``)?.count??0)+1;if(e.updated.set(``,{error:null,count:t}),t>5){let t=tt(`updated at`);if(t!==null){let n=e.updated.get(t.stack);n||(n={error:t,count:0},e.updated.set(t.stack,n)),n.count++}}}M!==null&&(e.set_during_effect=!0)}if(e.f&2){let t=e;e.f&2048&&cr(t),gr===null&&Xt(t)}e.wv=ji(),fi(e,ie,n),dt()&&M!==null&&M.f&1024&&!(M.f&96)&&(Ti===null?Ei([e]):Ti.push(e)),!r.is_fork&&ti.size>0&&!ii&&ui()}return t}function ui(){ii=!1;for(let e of ti){e.f&1024&&Yt(e,ae);let t;try{t=Mi(e)}catch{t=!0}t&&Li(e)}ti.clear()}function di(e){j(e,e.v+1)}function fi(e,t,n){var r=e.reactions;if(r!==null)for(var i=dt(),a=r.length,o=0;o<a;o++){var s=r[o],c=s.f;if(!(!i&&s===M)){var l=(c&ie)===0;if(l&&Yt(s,t),c&131072)ti.add(s);else if(c&2){var u=s;gr?.delete(u),c&65536||(c&512&&(M===null||!(M.f&2097152))&&(s.f|=me),fi(u,ae,n))}else if(l){var d=s;c&16&&Xr!==null&&Xr.add(d),n===null?Qr(d):n.push(d)}}}}var pi=null,mi=!1,hi=!1;function gi(e){hi=e}var _i=null,vi=!1;function yi(e){_i=e}var M=null;function bi(e){M=e}var xi=null;function Si(e){_i!==null&&(xi??(xi=new Set)).add(e)}var Ci=null,wi=0,Ti=null;function Ei(e){Ti=e}var Di=1,Oi=0,ki=Oi;function Ai(e){ki=e}function ji(){return++Di}function Mi(e){var t=e.f;if(t&2048)return!0;if(t&2&&(e.f&=~me),t&4096){for(var n=e.deps,r=n.length,i=0;i<r;i++){var a=n[i];if(Mi(a)&&lr(a),a.wv>e.wv)return!0}t&512&&gr===null&&Yt(e,re)}return!1}function Ni(e,t,n=!0){var r=e.reactions;if(r!==null&&!(xi!==null&&xi.has(e)))for(var i=0;i<r.length;i++){var a=r[i];a.f&2?Ni(a,t,!1):t===a&&(n?Yt(a,ie):a.f&1024&&Yt(a,ae),Qr(a))}}function Pi(e){var t=Ci,n=wi,r=Ti,i=_i,a=xi,o=rt,s=vi,c=ki,l=e.f;Ci=null,wi=0,Ti=null,_i=l&96?null:e,xi=null,it(e.ctx),vi=!1,ki=++Oi,e.ac!==null&&(mn(()=>{e.ac.abort(De)}),e.ac=null);try{e.f|=he;var u=e.fn,d=u();e.f|=ce;var f=e.deps,p=mr?.is_fork;if(Ci!==null){var m;if(p||Ii(e,wi),f!==null&&wi>0)for(f.length=wi+Ci.length,m=0;m<Ci.length;m++)f[wi+m]=Ci[m];else e.deps=f=Ci;if(Wi()&&e.f&512)for(m=wi;m<f.length;m++){var h;((h=f[m]).reactions??(h.reactions=[])).push(e)}}else!p&&f!==null&&wi<f.length&&(Ii(e,wi),f.length=wi);if(dt()&&Ti!==null&&!vi&&f!==null&&!(e.f&6146))for(m=0;m<Ti.length;m++)Ni(Ti[m],e);if(i!==null&&i!==e){if(Oi++,i.deps!==null)for(let e=0;e<n;e+=1)i.deps[e].rv=Oi;if(t!==null)for(let e of t)e.rv=Oi;Ti!==null&&(r===null?r=Ti:r.push(...Ti))}return e.f&8388608&&(e.f^=_e),d}catch(e){return Wt(e)}finally{e.f^=he,Ci=t,wi=n,Ti=r,_i=i,xi=a,it(o),vi=s,ki=c}}function Fi(e,t){let n=t.reactions;if(n!==null){var r=s.call(n,e);if(r!==-1){var i=n.length-1;i===0?n=t.reactions=null:(n[r]=n[i],n.pop())}}if(n===null&&t.f&2&&(Ci===null||!c.call(Ci,t))){var a=t;a.f&512&&(a.f^=512,a.f&=~me),a.v!==Ze&&Xt(a),a.ac!==null&&mn(()=>{a.ac.abort(De),a.ac=null,Yt(a,ie)}),ur(a),Ii(a,0)}}function Ii(e,t){var n=e.deps;if(n!==null)for(var r=t;r<n.length;r++)Fi(e,n[r])}function Li(e){var t=e.f;if(!(t&16384)){Yt(e,re);var n=M,r=mi;if(M=e,mi=!(t&96),a){var i=st;ct(e.component_function);var o=at;ot(e.dev_stack??at)}try{t&16777232?oa(e):aa(e),ia(e);var s=Pi(e);e.teardown=typeof s==`function`?s:null,e.wv=Di}finally{mi=r,M=n,a&&(ct(i),ot(o))}}}function N(e){var t=!!(e.f&2);if(pi?.add(e),_i!==null&&!vi&&!(M!==null&&M.f&16384)&&(xi===null||!xi.has(e))){var n=_i.deps;if(_i.f&2097152)e.rv<Oi&&(e.rv=Oi,Ci===null&&n!==null&&n[wi]===e?wi++:Ci===null?Ci=[e]:Ci.push(e));else{var r;(r=_i).deps??(r.deps=[]),c.call(_i.deps,e)||_i.deps.push(e);var i=e.reactions;i===null?e.reactions=[_i]:c.call(i,_i)||i.push(_i)}}if(a&&(!vi&&Qn&&mr===null&&hr===null&&!Qn.warned&&!(Qn.effect.f&2097152)&&!Qn.effect_deps.has(e)&&(Qn.warned=!0,e.label,tt(`traced at`)),er.delete(e)),hi&&ni.has(e))return ni.get(e);if(t){var o=e;if(hi){var s=o.v;return(!(o.f&1024)&&o.reactions!==null||zi(o))&&(s=cr(o)),ni.set(o,s),s}var l=!(o.f&512)&&!vi&&_i!==null&&(mi||!!(_i.f&512)),u=(o.f&ce)===0;Mi(o)&&(l&&(o.f|=512),lr(o)),l&&!u&&(dr(o),Ri(o))}if(gr?.has(e))return gr.get(e);if(e.f&8388608)throw e.v;return e.v}function Ri(e){if(e.f|=512,e.deps!==null)for(let t of e.deps)(t.reactions??(t.reactions=[])).push(e),t.f&2&&!(t.f&512)&&(dr(t),Ri(t))}function zi(e){if(e.v===Ze)return!0;if(e.deps===null)return!1;for(let t of e.deps)if(ni.has(t)||t.f&2&&zi(t))return!0;return!1}function P(e){var t=vi;try{return vi=!0,e()}finally{vi=t}}function F(e){if(!(typeof e!=`object`||!e||e instanceof EventTarget)){if(ve in e)Bi(e);else if(!Array.isArray(e))for(let t in e){let n=e[t];typeof n==`object`&&n&&ve in n&&Bi(n)}}}function Bi(e,t=new Set){if(typeof e==`object`&&e&&!(e instanceof EventTarget)&&!t.has(e)){t.add(e),e instanceof Date&&e.getTime();for(let n in e)try{Bi(e[n],t)}catch{}let n=h(e);if(n!==Object.prototype&&n!==Array.prototype&&n!==Map.prototype&&n!==Set.prototype&&n!==Date.prototype){let t=f(n);for(let n in t){let r=t[n].get;if(r)try{r.call(e)}catch{}}}}}function Vi(e){M===null&&(_i===null&&ze(e),Re()),hi&&Le(e)}function Hi(e,t){var n=t.last;n===null?t.last=t.first=e:(n.next=e,e.prev=n,t.last=e)}function Ui(e,t){var n=M;if(a)for(;n!==null&&n.f&131072;)n=n.parent;n!==null&&n.f&8192&&(e|=oe);var r={ctx:rt,deps:null,nodes:null,f:e|ie|512,first:null,fn:t,last:null,next:null,parent:n,b:n&&n.b,prev:null,teardown:null,wv:0,ac:null};a&&(r.component_function=st),mr?.register_created_effect(r);var i=r;if(e&4)br===null?Vr.ensure().schedule(r):br.push(r);else if(t!==null){try{Li(r)}catch(e){throw sa(r),e}i.deps===null&&i.teardown===null&&i.nodes===null&&i.first===i.last&&!(i.f&524288)&&(i=i.first,e&16&&e&65536&&i!==null&&(i.f|=ue))}if(i!==null&&(i.parent=n,n!==null&&Hi(i,n),_i!==null&&_i.f&2&&!(e&64))){var o=_i;(o.effects??(o.effects=[])).push(i)}return r}function Wi(){return _i!==null&&!vi}function Gi(e){let t=Ui(8,null);return Yt(t,re),t.teardown=e,t}function Ki(e){Vi(`$effect`),a&&u(e,`name`,{value:`$effect`});var t=M.f;if(!_i&&t&32&&rt!==null&&!rt.i){var n=rt;(n.e??(n.e=[])).push(e)}else return qi(e)}function qi(e){return Ui(4|fe,e)}function Ji(e){return Vi(`$effect.pre`),a&&u(e,`name`,{value:`$effect.pre`}),Ui(8|fe,e)}function Yi(e){Vr.ensure();let t=Ui(64|de,e);return(e={})=>new Promise(n=>{e.outro?ua(t,()=>{sa(t),n(void 0)}):(sa(t),n(void 0))})}function Xi(e){return Ui(4,e)}function Zi(e,t){var n=rt,r={effect:null,ran:!1,deps:e};n.l.$.push(r),r.effect=ea(()=>{if(e(),!r.ran){r.ran=!0;var n=M;try{bi(n.parent),P(t)}finally{bi(n)}}})}function Qi(){var e=rt;ea(()=>{for(var t of e.l.$){t.deps();var n=t.effect;n.f&1024&&n.deps!==null&&Yt(n,ae),Mi(n)&&Li(n),t.ran=!1}})}function $i(e){return Ui(ge|de,e)}function ea(e,t=0){return Ui(8|t,e)}function ta(e,t=[],n=[],r=[]){Jn(r,t,n,t=>{Ui(8,()=>{e(...t.map(N))})})}function na(e,t=0){var n=Ui(16|t,e);return a&&(n.dev_stack=at),n}function ra(e){return Ui(32|de,e)}function ia(e){var t=e.teardown;if(t!==null){let e=hi,n=_i;gi(!0),yi(null);try{t.call(null)}finally{gi(e),yi(n)}}}function aa(e,t=!1){var n=e.first;for(e.first=e.last=null;n!==null;){let e=n.ac;e!==null&&mn(()=>{e.abort(De)});var r=n.next;n.f&64?n.parent=null:sa(n,t),n=r}}function oa(e){for(var t=e.first;t!==null;){var n=t.next;t.f&32||sa(t),t=n}}function sa(e,t=!0){var n=!1;(t||e.f&262144)&&e.nodes!==null&&e.nodes.end!==null&&(ca(e.nodes.start,e.nodes.end),n=!0),e.f|=le,aa(e,t&&!n),Ii(e,0);var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)e.stop();ia(e),e.f^=le,e.f|=se;var i=e.parent;i!==null&&i.first!==null&&la(e),a&&(e.component_function=null),e.next=e.prev=e.teardown=e.ctx=e.deps=e.fn=e.nodes=e.ac=e.b=null}function ca(e,t){for(;e!==null;){var n=e===t?null:Lt(e);e.remove(),e=n}}function la(e){var t=e.parent,n=e.prev,r=e.next;n!==null&&(n.next=r),r!==null&&(r.prev=n),t!==null&&(t.first===e&&(t.first=r),t.last===e&&(t.last=n))}function ua(e,t,n=!0){var r=[];da(e,r,!0);var i=()=>{n&&sa(e),t&&t()},a=r.length;if(a>0){var o=()=>--a||i();for(var s of r)s.out(o)}else i()}function da(e,t,n){if(!(e.f&8192)){e.f^=oe;var r=e.nodes&&e.nodes.t;if(r!==null)for(let e of r)(e.is_global||n)&&t.push(e);for(var i=e.first;i!==null;){var a=i.next;if(!(i.f&64)){var o=!!(i.f&65536)||!!(i.f&32)&&!!(e.f&16);da(i,t,o?n:!1)}i=a}}}function fa(e){pa(e,!0)}function pa(e,t){if(e.f&8192){e.f^=oe,e.f&1024||(Yt(e,ie),Vr.ensure().schedule(e));for(var n=e.first;n!==null;){var r=n.next,i=!!(n.f&65536)||!!(n.f&32);pa(n,i?t:!1),n=r}var a=e.nodes&&e.nodes.t;if(a!==null)for(let e of a)(e.is_global||t)&&e.in()}}function ma(e,t){if(e.nodes)for(var n=e.nodes.start,r=e.nodes.end;n!==null;){var i=n===r?null:Lt(n);t.append(n),n=i}}var I=function(e){return e[e.PodcastGrid=0]=`PodcastGrid`,e[e.EpisodeList=1]=`EpisodeList`,e[e.Player=2]=`Player`,e}({}),ha=/\{\{\s*speaker\s*\}\}/gi,ga=`**{{speaker}}:** `;function _a(e){return typeof e==`object`&&!!e}function va(e){return typeof e==`string`?e.trim():``}function ya(e){if(!_a(e)||!Array.isArray(e.segments))return[];let t=[];for(let n of e.segments){if(!_a(n))continue;let e=va(n.text);if(!e)continue;let r=typeof n.speaker==`string`&&n.speaker.trim()?n.speaker.trim():`?`;t.push({speaker:r,text:e,start:typeof n.start==`number`?n.start:void 0,end:typeof n.end==`number`?n.end:void 0})}return Ca(t)}function ba(e){if(!_a(e)||!_a(e.results))return[];let t=e.results;if(Array.isArray(t.utterances)){let e=[];for(let n of t.utterances){if(!_a(n))continue;let t=va(n.transcript);t&&e.push({speaker:Sa(n.speaker),text:t,start:typeof n.start==`number`?n.start:void 0,end:typeof n.end==`number`?n.end:void 0})}return Ca(e)}return Ca(xa(t))}function xa(e){let t=e.channels;if(!Array.isArray(t)||!_a(t[0]))return[];let n=t[0].alternatives;if(!Array.isArray(n)||!_a(n[0]))return[];let r=n[0].words;if(!Array.isArray(r))return[];let i=[];for(let e of r){if(!_a(e))continue;let t=typeof e.punctuated_word==`string`?e.punctuated_word:typeof e.word==`string`?e.word:``;if(!t)continue;let n=Sa(e.speaker),r=i[i.length-1];r&&r.speaker===n?(r.text+=` ${t}`,typeof e.end==`number`&&(r.end=e.end)):i.push({speaker:n,text:t,start:typeof e.start==`number`?e.start:void 0,end:typeof e.end==`number`?e.end:void 0})}return i}function Sa(e){return typeof e==`number`&&Number.isFinite(e)?String(e+1):`?`}function Ca(e){let t=[];for(let n of e){let e=t[t.length-1];e&&e.speaker===n.speaker?(e.text=`${e.text} ${n.text}`.trim(),n.end!==void 0&&(e.end=n.end)):t.push({...n})}return t}function wa(e,t){return ha.test(e)?(ha.lastIndex=0,e.replace(ha,()=>t)):`${t}: ${e}`}function Ta(e,t){let n=t||`**{{speaker}}:** `;return e.map(e=>`${wa(n,e.speaker)}${e.text}`).join(`
|
||
|
||
`)}var Ea=`podcast_player_view`,Da={icon:`lucide-star`,name:`Favorites`,shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},Oa={icon:`list-ordered`,name:`Queue`,shouldEpisodeRemoveAfterPlay:!0,shouldRepeat:!1},ka={icon:`folder`,name:`Local Files`,shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},Aa={icon:`check-square`,name:`Played`,shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},ja={savedFeeds:{},podNotes:{},defaultPlaybackRate:1,defaultVolume:1,hidePlayedEpisodes:!1,episodeListLimit:10,playedEpisodes:{},favorites:{...Da,episodes:[]},queue:{...Oa,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:{...ka,episodes:[]},openAISecretId:``,deepgramSecretId:``,transcript:{path:`transcripts/{{podcast}}/{{title}}.md`,template:`# {{title}}
|
||
|
||
Podcast: {{podcast}}
|
||
Date: {{date}}
|
||
|
||
{{transcript}}`,diarization:{enabled:!1,provider:`openai`,speakerTemplate:ga}},feedCache:{enabled:!0,ttlHours:6}},Ma=.5,Na=.1;function Pa(e,t=1){let n=typeof e==`number`?e:Number(e),r=Number.isFinite(t)?t:1;return Ia(Number.isFinite(n)?n:r)}function Fa(e,t){return Pa(La(e+t))}function Ia(e){return Math.min(4,Math.max(Ma,La(e)))}function La(e){return Math.round(e*10)/10}var Ra=`::`;function za(e,t){return e.includes(Ra)||t.includes(Ra)||e.endsWith(`:`)||t.startsWith(`:`)}var Ba=`\0`;function Va(e){return e.replace(/\\/g,`\\\\`).replace(/:/g,`\\c`)}function Ha(e){if(!e||!e.title)return``;if(e.podcastName){let{podcastName:t,title:n}=e;return za(t,n)?`${Ba}${Va(t)}:${Va(n)}`:`${t}${Ra}${n}`}return e.title}function Ua(e,t){return!e||!t?!1:Ha(e)===t||e.title===t}function Wa(e,t){return!e||!t?!1:Ua(e,Ha(t))?!0:!e.podcastName&&!!t.title&&e.title===t.title}function Ga(e,t){if(!t)return;let n=Ha(t);if(n&&e[n])return e[n];if(t.title&&e[t.title])return e[t.title]}function Ka(e,t){return Ga(t,e)?.finished??!1}function qa(e){return e.podcastName?`${e.podcastName}::${e.title}`:e.title}function Ja(e,t,n){let r=new Set,i=qa(t);for(let[a,o]of Object.entries(e))(a===n||a===i||Za(o,t))&&r.add(a);return Array.from(r)}function Ya(e){let t=new Map;for(let[n,r]of Object.entries(e)){if(!r.finished)continue;let e=qa(r);(!t.get(e)||Xa(n))&&t.set(e,{key:n,episode:r})}return Array.from(t.values())}function Xa(e){return e.includes(`::`)}function Za(e,t){return e.title===t.title?!e.podcastName||!t.podcastName||e.podcastName===t.podcastName:!1}function Qa(e){let t;if(e instanceof Date)t=new Date(e.getTime());else if(typeof e==`string`&&e.trim()!==``)t=new Date(e);else return;return Number.isFinite(t.getTime())?t:void 0}function $a(e){return Qa(e)?.toISOString()}function eo(e){if(e instanceof Date){let t=e.getTime();return Number.isFinite(t)?t:void 0}return Qa(e)?.getTime()}function to(e){let t=typeof e==`number`?e:Number(e);return!Number.isFinite(t)||t<1?10:Math.min(Math.floor(t),75)}var no=nn(0),ro=nn({}),io=nn({}),ao=nn(10);function oo(e){return eo(e?.episodeDate)??0}function so(e,t){return e?.length?[...e].sort((e,t)=>oo(t)-oo(e)).slice(0,t):[]}function co(e,t){if(!e||!t||e.length!==t.length)return!1;for(let n=0;n<e.length;n+=1)if(e[n]!==t[n])return!1;return!0}var lo=e=>`${e.podcastName}::${e.title}`;function uo(e,t,n){let r=[...e],i=oo(t),a=0,o=r.length;for(;a<o;){let e=a+o>>1;i>oo(r[e])?o=e:a=e+1}return r.splice(a,0,t),r.length>n&&(r.length=n),r}function fo(e,t=[]){if(!t?.length)return e;let n=new Set(t.map(lo));return e.filter(e=>!n.has(lo(e)))}function po(e,t,n,r){let i=fo(e,t);if(!n?.length)return i;for(let e of n)i=uo(i,e,r);return i}var mo=tn([],e=>{let t=new Map,n=new Map,r=[],i=to(E(ao));function a(a){let o=Object.entries(a),s=o.length,c=Math.max(1,i*Math.max(s,1)),l=!1,u=r,d=new Map,f=new Map;for(let[e,r]of o){d.set(e,r);let a=n.get(e),o=t.get(e)||[],s=a===r&&o?o:so(r,i);f.set(e,s),co(o,s)||(l=!0,u=po(u,o,s,c))}for(let e of t.keys())d.has(e)||(l=!0,u=fo(u,t.get(e)));n=d,t=f,l&&(r=u,e(r))}function o(){let a=E(io),o=Object.entries(a),s=o.length,c=Math.max(1,i*Math.max(s,1)),l=new Map,u=new Map,d=[];for(let[e,t]of o){let n=so(t,i);l.set(e,t),u.set(e,n),d.push(...n)}let f=d.sort((e,t)=>oo(t)-oo(e)).slice(0,c);n=l,t=u,co(r,f)||(r=f,e(r))}let s=io.subscribe(a),c=ao.subscribe(e=>{let t=to(e);t!==i&&(i=t,o())});return()=>{t.clear(),n.clear(),r=[],c(),s()}}),ho=(()=>{let e=nn({}),{subscribe:t,update:n,set:r}=e;function i(t){return E(e)[t.podcastName]?.some(e=>e.title===t.title)}return{subscribe:t,set:r,update:n,isEpisodeDownloaded:i,addEpisode:(e,t,r)=>{let i;return n(n=>{let a=n[e.podcastName]||[],o=a.findIndex(t=>t.title===e.title);if(o!==-1){let n=a[o].filePath;n&&n!==t&&(i=n),a[o]={...e,filePath:t,size:r}}else a.push({...e,filePath:t,size:r});return n[e.podcastName]=a,n}),i},removeEpisode:e=>{let t;return n(n=>{let r=n[e.podcastName]||[],i=r.findIndex(t=>t.title===e.title);return i===-1?n:(t=r[i].filePath,r.splice(i,1),n[e.podcastName]=r,n)}),t},getEpisode:t=>E(e)[t.podcastName]?.find(e=>e.title===t.title)}})(),L=nn(),go=nn(0),_o=nn(null),vo=nn(null),yo=nn(0),bo=nn(1),xo=nn(1),So=nn(!1),Co=(()=>{let{subscribe:e,update:t}=nn();return{subscribe:e,update:t,set:(e,n=!0)=>{t(t=>{if(t){n&&zo(t);let e=E(go),r=E(yo),i=r>0&&e===r;To.setEpisodeTime(t,e,r,i)}return e})}}})(),wo=nn(!0),To=(()=>{let e=nn({}),{subscribe:t,update:n,set:r}=e;return{subscribe:t,set:r,update:n,get:t=>Ga(E(e),t),setEpisodeTime:(e,t,r,i)=>{e&&n(n=>{let a=Ha(e);return a&&(n[a]={title:e.title,podcastName:e.podcastName,time:t,duration:r,finished:i}),n})},markAsPlayed:e=>{e&&n(t=>{let n=Ha(e);if(!n)return t;let r=Ga(t,e)||{title:e.title,podcastName:e.podcastName,time:0,duration:0,finished:!1};return r.time=r.duration,r.finished=!0,t[n]=r,t})},markAsUnplayed:e=>{e&&n(t=>{let n=Ha(e);return n&&Eo(t,{title:e.title,podcastName:e.podcastName},n),t})},markKeyAsUnplayed:e=>{e&&n(t=>{let n=t[e];return n&&Eo(t,n,e),t})}}})();function Eo(e,t,n){let r=Ja(e,t,n),i=r.length>0?r:[n];for(let n of i)e[n]={...e[n]||{title:t.title,podcastName:t.podcastName,time:0,duration:0,finished:!1},time:0,finished:!1}}function Do(e,t,n){let r=e.length;if(t<0||t>=r||n<0||n>=r||t===n)return e;let i=[...e],[a]=i.splice(t,1);return i.splice(n,0,a),i}function Oo(e=[]){let t=new Set,n=[];for(let r of e)t.has(r.title)||(t.add(r.title),n.push(r));return n}var ko=(()=>{let e=nn({icon:`list-ordered`,name:`Queue`,episodes:[],shouldEpisodeRemoveAfterPlay:!0,shouldRepeat:!1}),{subscribe:t,update:n,set:r}=e,i=(e,t)=>e.some(e=>e.title===t.title);function a(t,r){let{episodes:i}=E(e),a=Do(i,t,r);a!==i&&n(e=>(e.episodes=a,e))}return{subscribe:t,update:n,set:e=>r({...e,episodes:Oo(e.episodes)}),add:e=>{n(t=>(i(t.episodes,e)||t.episodes.push(e),t))},remove:e=>{n(t=>(t.episodes=t.episodes.filter(t=>t.title!==e.title),t))},playNext:()=>{Lo()&&n(e=>{let t=e.episodes.shift();return t&&Co.set(t,!1),e})},move:a,moveUp:e=>a(e,e-1),moveDown:e=>a(e,e+1),moveToTop:e=>a(e,0),moveToBottom:t=>a(t,E(e).episodes.length-1)}})(),Ao=nn({icon:`lucide-star`,name:`Favorites`,episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1});function jo(e){return e.filePath}function Mo(e,t){if(e.length!==t.length)return!1;let n=new Map(e.map(e=>[Ha(e),e]));for(let e of t){let t=Ha(e),r=t?n.get(t):void 0;if(!r||r.streamUrl!==e.streamUrl||r.mediaType!==e.mediaType||jo(r)!==jo(e))return!1}return!0}var No=(()=>{let e=nn({icon:`folder`,name:`Local Files`,episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1}),{subscribe:t,update:n,set:r}=e;return{subscribe:t,update:n,set:r,syncWithDownloaded:t=>{let r=new Set,i=[];for(let e of Object.values(t).flat()){let t=Ha(e);!t||r.has(t)||(r.add(t),i.push(e))}Mo(E(e).episodes,i)||n(e=>({...e,...ka,episodes:i}))},getLocalEpisode:t=>{let{episodes:n}=E(e),r=t.trim().toLowerCase(),i=e=>e.title.trim().toLowerCase()===r;return n.find(e=>i(e)&&e.podcastName===`local file`)??n.find(i)},updateStreamUrl:(t,n)=>{e.update(e=>{let r=e.episodes.findIndex(e=>e.title===t);return r!==-1&&(e.episodes[r].streamUrl=n),e})}}})(),Po=nn({}),Fo=nn(),Io=(()=>{let{subscribe:e,set:t}=nn(I.PodcastGrid);return{subscribe:e,set:e=>{t(e),E(Fo)?.scrollIntoView()}}})();function Lo(){return E(L)?.settings?.autoQueue!==!1}function Ro(){return Co.subscribe(e=>{if(!e)return;let{episodes:t}=E(ko);t.some(t=>t.title===e.title)&&ko.update(t=>(t.episodes=t.episodes.filter(t=>t.title!==e.title),t))})}function zo(e){Lo()&&ko.update(t=>(t.episodes.some(t=>t.title===e.title)||(t.episodes=[e,...t.episodes]),t))}function Bo(e,t,n){return{subscribe:t=>e.subscribe(e=>t(e)),apply:(e,n)=>t(e,n),shouldPersist:n?(e,t)=>n(e,t):void 0}}var Vo=[Bo(To,(e,t)=>{e.playedEpisodes=t}),Bo(ro,(e,t)=>{e.savedFeeds=t}),Bo(Po,(e,t)=>{e.playlists=t}),Bo(ko,(e,t)=>{e.queue={...t,...Oa}}),Bo(Ao,(e,t)=>{e.favorites={...t,...Da}}),Bo(No,(e,t)=>{e.localFiles={...t,...ka}}),Bo(ho,(e,t)=>{e.downloadedEpisodes=t}),Bo(Co,(e,t)=>{e.currentEpisode=t}),Bo(So,(e,t)=>{e.hidePlayedEpisodes=t},(e,t)=>e.hidePlayedEpisodes!==t)],Ho=[...Vo,Bo(xo,(e,t)=>{Number.isFinite(t)&&(e.defaultVolume=Math.min(1,Math.max(0,t)))}),Bo(ao,(e,t)=>{e.episodeListLimit=to(t)})];function Uo(){let e=new Map,t=Ho.map(t=>{let n=!1;return t.subscribe(r=>{if(!n){n=!0;return}e.set(t,structuredClone(r))})}),n=!1;return{replayInto(t){for(let[n,r]of e)n.apply(t,structuredClone(r))},dispose(){if(!n){n=!0;for(let e of t)e();e.clear()}}}}function Wo(e){let t=Vo.map(t=>t.subscribe(n=>{t.shouldPersist&&!t.shouldPersist(e.settings,n)||(t.apply(e.settings,n),e.saveSettings())}));return()=>{for(let e of t)e()}}[...`allowfullscreen.async.autofocus.autoplay.checked.controls.default.disabled.formnovalidate.indeterminate.inert.ismap.loop.multiple.muted.nomodule.novalidate.open.playsinline.readonly.required.reversed.seamless.selected.webkitdirectory.defer.disablepictureinpicture.disableremoteplayback`.split(`.`)];var Go=[`touchstart`,`touchmove`];function Ko(e){return Go.includes(e)}var qo=new Map;function Jo(e,t){var n=qo.get(e);n||(n=new Set,qo.set(e,n)),n.add(t)}var Yo=Symbol(`events`),Xo=new Set,Zo=new Set;function Qo(e,t,n,r={}){function i(e){if(r.capture||es.call(t,e),!e.cancelBubble)return mn(()=>n?.call(this,e))}return e.startsWith(`pointer`)||e.startsWith(`touch`)||e===`wheel`?mt(()=>{t.addEventListener(e,i,r)}):t.addEventListener(e,i,r),i}function R(e,t,n,r,i){var a={capture:r,passive:i},o=Qo(e,t,n,a);(t===document.body||t===window||t===document||t instanceof HTMLMediaElement)&&Gi(()=>{t.removeEventListener(e,o,a)})}var $o=null;function es(e){var t=this,n=t.ownerDocument,r=e.type,i=e.composedPath?.()||[],a=i[0]||e.target;$o=e;var o=0,s=$o===e&&e[Yo];if(s){var c=i.indexOf(s);if(c!==-1&&(t===document||t===window)){e[Yo]=t;return}var l=i.indexOf(t);if(l===-1)return;c<=l&&(o=c)}if(a=i[o]||e.target,a!==t){u(e,`currentTarget`,{configurable:!0,get(){return a||n}});var d=_i,f=M;yi(null),bi(null);try{for(var p,m=[];a!==null&&a!==t;){try{var h=a[Yo]?.[r];h!=null&&(!a.disabled||e.target===a)&&h.call(a,e)}catch(e){p?m.push(e):p=e}if(e.cancelBubble)break;o++,a=o<i.length?i[o]:null}if(p){for(let e of m)queueMicrotask(()=>{throw e});throw p}}finally{e[Yo]=t,delete e.currentTarget,yi(d),bi(f)}}}var ts=globalThis?.window?.trustedTypes&&globalThis.window.trustedTypes.createPolicy(`svelte-trusted-html`,{createHTML:e=>e});function ns(e){return ts?.createHTML(e)??e}function rs(e){var t=Vt(`template`);return t.innerHTML=ns(e.replaceAll(`<!>`,`<!---->`)),t.content}function is(e,t){var n=M;n.nodes===null&&(n.nodes={start:e,end:t,a:null,t:null})}function z(e,t){var n=!!(t&1),r=!!(t&2),i,a=!e.startsWith(`<!>`);return()=>{if(ht)return is(_t,null),_t;i===void 0&&(i=rs(a?e:`<!>`+e),n||(i=It(i)));var t=r||jt?document.importNode(i,!0):i.cloneNode(!0);if(n){var o=It(t),s=t.lastChild;is(o,s)}else is(t,t);return t}}function as(e=``){if(!ht){var t=Ft(e+``);return is(t,t),t}var n=_t;return n.nodeType===3?Ht(n):(n.before(n=Ft()),vt(n)),is(n,n),n}function os(){if(ht)return is(_t,null),_t;var e=document.createDocumentFragment(),t=document.createComment(``),n=Ft();return e.append(t,n),is(t,n),e}function B(e,t){if(ht){var n=M;(!(n.f&32768)||n.nodes.end===null)&&(n.nodes.end=_t),yt();return}e!==null&&e.before(t)}var ss=!0;function cs(e,t){var n=t==null?``:typeof t==`object`?`${t}`:t;n!==(e[Te]??(e[Te]=e.nodeValue))&&(e[Te]=n,e.nodeValue=`${n}`)}function ls(e,t){return ds(e,t)}var us=new Map;function ds(e,{target:t,anchor:n,props:r={},events:i,context:a,intro:o=!0,transformError:s}){Pt();var c=void 0,u=Yi(()=>{var u=n??t.appendChild(Ft());bn(u,{pending:()=>{}},t=>{lt({});var n=rt;if(a&&(n.c=a),i&&(r.$$events=i),ht&&is(t,null),ss=o,c=e(t,r)||{},ss=!0,ht&&(M.nodes.end=_t,_t===null||_t.nodeType!==8||_t.data!==`]`))throw Xe;ut()},s);var d=new Set,f=e=>{for(var n=0;n<e.length;n++){var r=e[n];if(!d.has(r)){d.add(r);var i=Ko(r);for(let e of[t,document]){var a=us.get(e);a===void 0&&(a=new Map,us.set(e,a));var o=a.get(r);o===void 0?(e.addEventListener(r,es,{passive:i}),a.set(r,1)):a.set(r,o+1)}}}};return f(l(Xo)),Zo.add(f),()=>{for(var e of d)for(let n of[t,document]){var r=us.get(n),i=r.get(e);--i==0?(n.removeEventListener(e,es),r.delete(e),r.size===0&&us.delete(n)):r.set(e,i)}Zo.delete(f),u!==n&&u.parentNode?.removeChild(u)}});return fs.set(c,u),c}var fs=new WeakMap;function ps(e,t){let n=fs.get(e);return n?(fs.delete(e),n(t)):(a&&ve in e,Promise.resolve())}var ms=new WeakMap,hs=new WeakMap,gs=new WeakMap,_s=new WeakMap,vs=new WeakMap,ys=new WeakMap,bs=new WeakMap,xs=class{constructor(e,t=!0){ne(this,`anchor`,void 0),D(this,ms,new Map),D(this,hs,new Map),D(this,gs,new Map),D(this,_s,new Set),D(this,vs,!0),D(this,ys,e=>{if(k(ms,this).has(e)){var t=k(ms,this).get(e),n=k(hs,this).get(t);if(n)fa(n),k(_s,this).delete(t);else{var r=k(gs,this).get(t);r&&(fa(r.effect),k(hs,this).set(t,r.effect),k(gs,this).delete(t),a&&(r.fragment.lastChild[Ee]=this.anchor),r.fragment.lastChild.remove(),this.anchor.before(r.fragment),n=r.effect)}for(let[t,n]of k(ms,this)){if(k(ms,this).delete(t),t===e)break;let r=k(gs,this).get(n);r&&(sa(r.effect),k(gs,this).delete(n))}for(let[e,r]of k(hs,this)){if(e===t||k(_s,this).has(e))continue;let i=()=>{if(Array.from(k(ms,this).values()).includes(e)){var t=document.createDocumentFragment();ma(r,t),t.append(Ft()),k(gs,this).set(e,{effect:r,fragment:t})}else sa(r);k(_s,this).delete(e),k(hs,this).delete(e)};k(vs,this)||!n?(k(_s,this).add(e),ua(r,i,!1)):i()}}}),D(this,bs,e=>{k(ms,this).delete(e);let t=Array.from(k(ms,this).values());for(let[e,n]of k(gs,this))t.includes(e)||(sa(n.effect),k(gs,this).delete(e))}),this.anchor=e,O(vs,this,t)}ensure(e,t){var n=mr,r=Bt();if(t&&!k(hs,this).has(e)&&!k(gs,this).has(e)){if(r){var i=document.createDocumentFragment(),a=Ft();i.append(a),k(gs,this).set(e,{effect:ra(()=>t(a)),fragment:i})}else k(hs,this).set(e,ra(()=>t(this.anchor)))}if(k(ms,this).set(n,e),r){for(let[t,r]of k(hs,this))t===e?n.unskip_effect(r):n.skip_effect(r);for(let[t,r]of k(gs,this))t===e?n.unskip_effect(r.effect):n.skip_effect(r.effect);n.oncommit(k(ys,this)),n.ondiscard(k(bs,this))}else ht&&(this.anchor=_t),k(ys,this).call(this,n)}};function Ss(e,t,n=!1){var r;ht&&(r=_t,yt());var i=new xs(e),a=n?ue:0;function o(e,t){if(ht){var n=St(r);if(e!==parseInt(n.substring(1))){var a=xt();vt(a),i.anchor=a,gt(!1),i.ensure(e,t),gt(!0);return}}i.ensure(e,t)}na(()=>{var e=!1;t((t,n=0)=>{e=!0,o(n,t)}),e||o(-1,null)},a)}function Cs(e,t){return t}function ws(e,t,n){for(var r=[],i=t.length,a,o=t.length,s=0;s<i;s++){let n=t[s];ua(n,()=>{if(a){if(a.pending.delete(n),a.done.add(n),a.pending.size===0){var t=e.outrogroups;Ts(e,l(a.done)),t.delete(a),t.size===0&&(e.outrogroups=null)}}else--o},!1)}if(o===0){var c=r.length===0&&n!==null;if(c){var u=n,d=u.parentNode;zt(d),d.append(u),e.items.clear()}Ts(e,t,!c)}else a={pending:new Set(t),done:new Set},(e.outrogroups??(e.outrogroups=new Set)).add(a)}function Ts(e,t,n=!0){var r;if(e.pending.size>0){r=new Set;for(let t of e.pending.values())for(let n of t)r.add(e.items.get(n).e)}for(var i=0;i<t.length;i++){var a=t[i];r?.has(a)?(a.f|=pe,ma(a,document.createDocumentFragment())):sa(t[i],n)}}var Es;function Ds(e,t,n,r,i,s=null){var c=e,u=new Map;if(t&4){var d=e;c=ht?vt(It(d)):d.appendChild(Ft())}ht&&yt();var f=null,p=ar(()=>{var e=n();return o(e)?e:e==null?[]:l(e)});a&&$e(p,`{#each ...}`);var m,h=new Map,g=!0;function _(e){y.effect.f&16384||(y.pending.delete(e),y.fallback=f,ks(y,m,c,t,r),f!==null&&(m.length===0?f.f&33554432?(f.f^=pe,js(f,null,c)):fa(f):ua(f,()=>{f=null})))}function v(e){y.pending.delete(e)}var y={effect:na(()=>{m=N(p);var e=m.length;let o=!1;ht&&St(c)===`[!`!=(e===0)&&(c=xt(),vt(c),gt(!1),o=!0);for(var l=new Set,d=mr,y=Bt(),b=0;b<e;b+=1){ht&&_t.nodeType===8&&_t.data===`]`&&(c=_t,o=!0,gt(!1));var x=m[b],S=r(x,b);if(a){var ee=r(x,b);S!==ee&&Ie(String(b),String(S),String(ee))}var te=g?null:u.get(S);te?(te.v&&li(te.v,x),te.i&&li(te.i,b),y&&d.unskip_effect(te.e)):(te=As(u,g?c:Es??(Es=Ft()),x,S,b,i,t,n),g||(te.e.f|=pe),u.set(S,te)),l.add(S)}if(e===0&&s&&!f&&(g?f=ra(()=>s(c)):(f=ra(()=>s(Es??(Es=Ft()))),f.f|=pe)),e>l.size&&(a?Ns(m,r):Fe(``,``,``)),ht&&e>0&&vt(xt()),!g){if(h.set(d,l),y){for(let[e,t]of u)l.has(e)||d.skip_effect(t.e);d.oncommit(_),d.ondiscard(v)}else _(d)}o&>(!0),N(p)}),flags:t,items:u,pending:h,outrogroups:null,fallback:f};g=!1,ht&&(c=_t)}function Os(e){for(;e!==null&&!(e.f&32);)e=e.next;return e}function ks(e,t,n,r,i){var a=!!(r&8),o=t.length,s=e.items,c=Os(e.effect.first),u,d=null,f,p=[],m=[],h,g,_,v;if(a)for(v=0;v<o;v+=1)h=t[v],g=i(h,v),_=s.get(g).e,_.f&33554432||(_.nodes?.a?.measure(),(f??(f=new Set)).add(_));for(v=0;v<o;v+=1){if(h=t[v],g=i(h,v),_=s.get(g).e,e.outrogroups!==null)for(let t of e.outrogroups)t.pending.delete(_),t.done.delete(_);if(_.f&8192&&(fa(_),a&&(_.nodes?.a?.unfix(),(f??(f=new Set)).delete(_))),_.f&33554432){if(_.f^=pe,_===c)js(_,null,n);else{var y=d?d.next:c;_===e.effect.last&&(e.effect.last=_.prev),_.prev&&(_.prev.next=_.next),_.next&&(_.next.prev=_.prev),Ms(e,d,_),Ms(e,_,y),js(_,y,n),d=_,p=[],m=[],c=Os(d.next);continue}}if(_!==c){if(u!==void 0&&u.has(_)){if(p.length<m.length){var b=m[0],x;d=b.prev;var S=p[0],ee=p[p.length-1];for(x=0;x<p.length;x+=1)js(p[x],b,n);for(x=0;x<m.length;x+=1)u.delete(m[x]);Ms(e,S.prev,ee.next),Ms(e,d,S),Ms(e,ee,b),c=b,d=ee,--v,p=[],m=[]}else u.delete(_),js(_,c,n),Ms(e,_.prev,_.next),Ms(e,_,d===null?e.effect.first:d.next),Ms(e,d,_),d=_;continue}for(p=[],m=[];c!==null&&c!==_;)(u??(u=new Set)).add(c),m.push(c),c=Os(c.next);if(c===null)continue}_.f&33554432||p.push(_),d=_,c=Os(_.next)}if(e.outrogroups!==null){for(let t of e.outrogroups)t.pending.size===0&&(Ts(e,l(t.done)),e.outrogroups?.delete(t));e.outrogroups.size===0&&(e.outrogroups=null)}if(c!==null||u!==void 0){var te=[];if(u!==void 0)for(_ of u)_.f&8192||te.push(_);for(;c!==null;)!(c.f&8192)&&c!==e.fallback&&te.push(c),c=Os(c.next);var ne=te.length;if(ne>0){var re=r&4&&o===0?n:null;if(a){for(v=0;v<ne;v+=1)te[v].nodes?.a?.measure();for(v=0;v<ne;v+=1)te[v].nodes?.a?.fix()}ws(e,te,re)}}a&&mt(()=>{if(f!==void 0)for(_ of f)_.nodes?.a?.apply()})}function As(e,t,n,r,i,o,s,c){var l=s&1?s&16?oi(n):A(n,!1,!1):null,u=s&2?oi(i):null;return a&&l&&(l.trace=()=>{c()[u?.v??i]}),{v:l,i:u,e:ra(()=>(o(t,l??n,u??i,c),()=>{e.delete(r)}))}}function js(e,t,n){if(e.nodes)for(var r=e.nodes.start,i=e.nodes.end,a=t&&!(t.f&33554432)?t.nodes.start:n;r!==null;){var o=Lt(r);if(a.before(r),r===i)return;r=o}}function Ms(e,t,n){t===null?e.effect.first=n:t.next=n,n===null?e.effect.last=t:n.prev=t}function Ns(e,t){let n=new Map,r=e.length;for(let i=0;i<r;i++){let r=t(e[i],i);if(n.has(r)){let e=String(n.get(r)),t=String(i),a=String(r);a.startsWith(`[object `)&&(a=null),Fe(e,t,a)}n.set(r,i)}}function Ps(e,t,n,r,i){ht&&yt();var a=t.$$slots?.[n],o=!1;a===!0&&(a=t[n==="default"?`children`:n],o=!0),a===void 0?i!==null&&i(e):a(e,o?()=>r:r)}var Fs=()=>performance.now(),Is={tick:e=>requestAnimationFrame(e),now:()=>Fs(),tasks:new Set};function Ls(){let e=Is.now();Is.tasks.forEach(t=>{t.c(e)||(Is.tasks.delete(t),t.f())}),Is.tasks.size!==0&&Is.tick(Ls)}function Rs(e){let t;return Is.tasks.size===0&&Is.tick(Ls),{promise:new Promise(n=>{Is.tasks.add(t={c:e,f:n})}),abort(){Is.tasks.delete(t)}}}function zs(e,t){mn(()=>{e.dispatchEvent(new CustomEvent(t))})}function Bs(e){if(e===`float`)return`cssFloat`;if(e===`offset`)return`cssOffset`;if(e.startsWith(`--`))return e;let t=e.split(`-`);return t.length===1?t[0]:t[0]+t.slice(1).map(e=>e[0].toUpperCase()+e.slice(1)).join(``)}function Vs(e){let t={},n=e.split(`;`);for(let e of n){let[n,r]=e.split(`:`);if(!n||r===void 0)break;let i=Bs(n.trim());t[i]=r.trim()}return t}var Hs=e=>e;function Us(e,t,n,r){var i,a=!!(e&1),o=!!(e&2),s=a&&o,c=!!(e&4),l=s?`both`:a?`in`:`out`,u,d=t.inert,f=t.style.overflow,p,m;function h(){return mn(()=>u??(u=n()(t,r?.()??{},{direction:l})))}var g={is_global:c,in(){if(t.inert=d,!a){m?.abort(),m?.reset?.();return}o||p?.abort(),p=Ws(t,h(),m,1,()=>{zs(t,`introstart`)},()=>{zs(t,`introend`),p?.abort(),p=u=void 0,t.style.overflow=f})},out(e){if(!o){e?.(),u=void 0;return}t.inert=!0,m=Ws(t,h(),p,0,()=>{zs(t,`outrostart`)},()=>{zs(t,`outroend`),e?.()})},stop:()=>{p?.abort(),m?.abort()}},_=M;if(((i=_.nodes).t??(i.t=[])).push(g),a&&ss){var v=c;if(!v){for(var y=_.parent;y&&y.f&65536;)for(;(y=y.parent)&&!(y.f&16););v=!y||!!(y.f&32768)}v&&Xi(()=>{P(()=>g.in())})}}function Ws(e,t,n,r,i,a){var o=r===1;if(_(t)){var s,c=!1;return mt(()=>{c||(s=Ws(e,t({direction:o?`in`:`out`}),n,r,i,a))}),{abort:()=>{c=!0,s?.abort()},deactivate:()=>s.deactivate(),reset:()=>s.reset(),t:()=>s.t()}}if(n?.deactivate(),!t?.duration&&!t?.delay)return i(),a(),{abort:v,deactivate:v,reset:v,t:()=>r};let{delay:l=0,css:u,tick:d,easing:f=Hs}=t;var p=[];if(o&&n===void 0&&(d&&d(0,1),u)){var m=Vs(u(0,1));p.push(m,m)}var h=()=>1-r,g=e.animate(p,{duration:l,fill:`forwards`});return g.onfinish=()=>{g.cancel(),i();var o=n?.t()??1-r;n?.abort();var s=r-o,c=t.duration*Math.abs(s),l=[];if(c>0){var p=!1;if(u)for(var m=Math.ceil(c/(1e3/60)),_=0;_<=m;_+=1){var v=o+s*f(_/m),y=Vs(u(v,1-v));l.push(y),p||(p=y.overflow===`hidden`)}p&&(e.style.overflow=`hidden`),h=()=>{var e=g.currentTime;return o+s*f(e/c)},d&&Rs(()=>{if(g.playState!==`running`)return!1;var e=h();return d(e,1-e),!0})}g=e.animate(l,{duration:c,fill:`forwards`}),g.onfinish=()=>{h=()=>r,d?.(r,1-r),a()}},{abort:()=>{g&&(g.cancel(),g.effect=null,g.onfinish=v)},deactivate:()=>{a=v},reset:()=>{r===0&&d?.(1,0)},t:()=>h()}}function Gs(e,t){Xi(()=>{var n=e.getRootNode(),r=n.host?n:n.head??n.ownerDocument.head;if(!r.querySelector(`#`+t.hash)){let e=Vt(`style`);e.id=t.hash,e.textContent=t.code,r.appendChild(e),a&&Jo(t.hash,e)}})}function Ks(e){var t,n,r=``;if(typeof e==`string`||typeof e==`number`)r+=e;else if(typeof e==`object`){if(Array.isArray(e)){var i=e.length;for(t=0;t<i;t++)e[t]&&(n=Ks(e[t]))&&(r&&(r+=` `),r+=n)}else for(n in e)e[n]&&(r&&(r+=` `),r+=n)}return r}function qs(){for(var e,t,n=0,r=``,i=arguments.length;n<i;n++)(e=arguments[n])&&(t=Ks(e))&&(r&&(r+=` `),r+=t);return r}function Js(e){return typeof e==`object`?qs(e):e??``}var Ys=[...`
|
||
\r\f\xA0\v`];function Xs(e,t,n){var r=e==null?``:``+e;if(t&&(r=r?r+` `+t:t),n){for(var i of Object.keys(n))if(n[i])r=r?r+` `+i:i;else if(r.length)for(var a=i.length,o=0;(o=r.indexOf(i,o))>=0;){var s=o+a;(o===0||Ys.includes(r[o-1]))&&(s===r.length||Ys.includes(r[s]))?r=(o===0?``:r.substring(0,o))+r.substring(s+1):o=s}}return r===``?null:r}function Zs(e,t=!1){var n=t?` !important;`:`;`,r=``;for(var i of Object.keys(e)){var a=e[i];a!=null&&a!==``&&(r+=` `+i+`: `+a+n)}return r}function Qs(e){return e[0]!==`-`||e[1]!==`-`?e.toLowerCase():e}function $s(e,t){if(t){var n=``,r,i;if(Array.isArray(t)?(r=t[0],i=t[1]):r=t,e){e=String(e).replaceAll(/\s*\/\*.*?\*\/\s*/g,``).trim();var a=!1,o=0,s=!1,c=[];r&&c.push(...Object.keys(r).map(Qs)),i&&c.push(...Object.keys(i).map(Qs));var l=0,u=-1;let t=e.length;for(var d=0;d<t;d++){var f=e[d];if(s?f===`/`&&e[d-1]===`*`&&(s=!1):a?a===f&&(a=!1):f===`/`&&e[d+1]===`*`?s=!0:f===`"`||f===`'`?a=f:f===`(`?o++:f===`)`&&o--,!s&&a===!1&&o===0){if(f===`:`&&u===-1)u=d;else if(f===`;`||d===t-1){if(u!==-1){var p=Qs(e.substring(l,u).trim());if(!c.includes(p)){f!==`;`&&d++;var m=e.substring(l,d).trim();n+=` `+m+`;`}}l=d+1,u=-1}}}}return r&&(n+=Zs(r)),i&&(n+=Zs(i,!0)),n=n.trim(),n===``?null:n}return e==null?null:String(e)}function ec(e,t,n,r,i,a){var o=e[Ce];if(ht||o!==n||o===void 0){var s=Xs(n,r,a);(!ht||s!==e.getAttribute(`class`))&&(s==null?e.removeAttribute(`class`):t?e.className=s:e.setAttribute(`class`,s)),e[Ce]=n}else if(a&&i!==a)for(var c in a){var l=!!a[c];(i==null||l!==!!i[c])&&e.classList.toggle(c,l)}return a}function tc(e,t={},n,r){for(var i in n){var a=n[i];t[i]!==a&&(n[i]==null?e.style.removeProperty(i):e.style.setProperty(i,a,r))}}function nc(e,t,n,r){var i=e[we];if(ht||i!==t){var a=$s(t,r);(!ht||a!==e.getAttribute(`style`))&&(a==null?e.removeAttribute(`style`):e.style.cssText=a),e[we]=t}else r&&(Array.isArray(r)?(tc(e,n?.[0],r[0]),tc(e,n?.[1],r[1],`important`)):tc(e,n,r));return r}var rc=Symbol(`is custom element`),ic=Symbol(`is html`),ac=Oe?`link`:`LINK`;function oc(e,t,n,r){var i=sc(e);if(ht&&(i[t]=e.getAttribute(t),t===`src`||t===`srcset`||t===`href`&&e.nodeName===ac)){r||uc(e,t,n??``);return}i[t]!==(i[t]=n)&&(t===`loading`&&(e[be]=n),n==null?e.removeAttribute(t):typeof n!=`string`&&lc(e).includes(t)?e[t]=n:e.setAttribute(t,n))}function sc(e){return e[Se]??(e[Se]={[rc]:e.nodeName.includes(`-`),[ic]:e.namespaceURI===`http://www.w3.org/1999/xhtml`})}var cc=new Map;function lc(e){var t=e.getAttribute(`is`)||e.nodeName,n=cc.get(t);if(n)return n;cc.set(t,n=[]);for(var r,i=e,a=Element.prototype;a!==i;){for(var o in r=f(i),r)r[o].set&&o!==`innerHTML`&&o!==`textContent`&&o!==`innerText`&&n.push(o);i=h(i)}return n}function uc(e,t,n){a&&(t===`srcset`&&pc(e,n)||dc(e.getAttribute(t)??``,n)||e.outerHTML.replace(e.innerHTML,e.innerHTML&&`...`))}function dc(e,t){return e===t||new URL(e,document.baseURI).href===new URL(t,document.baseURI).href}function fc(e){return e.split(`,`).map(e=>e.trim().split(` `).filter(Boolean))}function pc(e,t){var n=fc(e.srcset),r=fc(t);return r.length===n.length&&r.every(([e,t],r)=>t===n[r][1]&&(dc(n[r][0],e)||dc(e,n[r][0])))}function mc(e,t,n=t){var r,i,a=()=>{cancelAnimationFrame(r),e.paused||(r=requestAnimationFrame(a));var t=e.currentTime;i!==t&&n(i=t)};r=requestAnimationFrame(a),e.addEventListener(`timeupdate`,a),ea(()=>{var n=Number(t());i!==n&&!isNaN(n)&&(e.currentTime=i=n)}),Gi(()=>{cancelAnimationFrame(r),e.removeEventListener(`timeupdate`,a)})}function hc(e,t,n=t){var r=t();pn(e,[`play`,`pause`,`canplay`],()=>{r!==e.paused&&n(r=e.paused)},r==null),Xi(()=>{(r=!!t())!==e.paused&&(r?e.pause():e.play().catch(e=>{throw n(r=!0),e}))})}function gc(e,t,n=t){var r=()=>{n(e.volume)};t()??r(),pn(e,[`volumechange`],r,!1),ea(()=>{var n=Number(t());n!==e.volume&&!isNaN(n)&&(e.volume=n)})}var _c,vc=new WeakMap,yc=new WeakMap,bc=new WeakMap,xc=new WeakSet,Sc=class{constructor(e){_n(this,xc),D(this,vc,new WeakMap),D(this,yc,void 0),D(this,bc,void 0),O(bc,this,e)}observe(e,t){var n=k(vc,this).get(e)||new Set;return n.add(t),k(vc,this).set(e,n),vn(xc,this,Cc).call(this).observe(e,k(bc,this)),()=>{var n=k(vc,this).get(e);n.delete(t),n.size===0&&(k(vc,this).delete(e),k(yc,this).unobserve(e))}}};_c=Sc;function Cc(){return k(yc,this)??O(yc,this,new ResizeObserver(e=>{for(var t of e){_c.entries.set(t.target,t);for(var n of k(vc,this).get(t.target)||[])n(t)}}))}ne(Sc,`entries`,new WeakMap);function wc(e,t){return e===t||e?.[ve]===t}function Tc(e={},t,n,r){var i=rt.r,a=M;return Xi(()=>{var o,s;return ea(()=>{o=s,s=r?.()||[],P(()=>{wc(n(...s),e)||(t(e,...s),o&&wc(n(...o),e)&&t(null,...o))})}),()=>{let r=a;for(;r!==i&&r.parent!==null&&r.parent.f&33554432;)r=r.parent;let o=()=>{s&&wc(n(...s),e)&&t(null,...s)},c=r.teardown;r.teardown=()=>{o(),c?.()}}}),e}function Ec(e,t,n,r,i){var a=()=>{r(n[e])};n.addEventListener(t,a),i?ea(()=>{n[e]=i()}):a(),(n===document.body||n===window||n===document)&&Gi(()=>{n.removeEventListener(t,a)})}function Dc(e){return function(...t){return t[0].preventDefault(),e?.apply(this,t)}}function Oc(e=!1){let t=rt,n=t.l.u;if(!n)return;let r=()=>F(t.s);if(e){let e=0,n={},i=tr(()=>{let r=!1,i=t.s;for(let e in i)i[e]!==n[e]&&(n[e]=i[e],r=!0);return r&&e++,e});r=()=>N(i)}n.b.length&&Ji(()=>{kc(t,r),b(n.b)}),Ki(()=>{let e=P(()=>n.m.map(y));return()=>{for(let t of e)typeof t==`function`&&t()}}),n.a.length&&Ki(()=>{kc(t,r),b(n.a)})}function kc(e,t){if(e.l.s)for(let t of e.l.s)N(t);t()}function Ac(e,t){var n=e.$$events?.[t.type];for(var r of o(n)?n.slice():n==null?[]:[n])r.call(this,t)}function V(e,t,n,r){var i=!Je||!!(n&2),o=!!(n&8),s=!!(n&16),c=r,l=!0,u=void 0,f=()=>s&&i?(u??(u=tr(r)),N(u)):(l&&(l=!1,c=s?P(r):r),c);let p;if(o){var m=ve in e||ye in e;p=d(e,t)?.set??(m&&t in e?n=>e[t]=n:void 0)}var h,g=!1;o?[h,g]=fn(()=>e[t]):h=e[t],h===void 0&&r!==void 0&&(h=f(),p&&(i&&He(t),p(h)));var _=i?()=>{var n=e[t];return n===void 0?f():(l=!0,n)}:()=>{var n=e[t];return n!==void 0&&(c=void 0),n===void 0?c:n};if(i&&!(n&4))return _;if(p){var v=e.$$legacy;return(function(e,t){return arguments.length>0?((!i||!t||v||g)&&p(t?_():e),e):_()})}var y=!1,b=(n&1?tr:ar)(()=>(y=!1,_()));a&&(b.label=t),o&&N(b);var x=M;return(function(e,t){if(arguments.length>0){let n=t?N(b):i&&o?wt(e):e;return j(b,n),y=!0,c!==void 0&&(c=n),e}return hi&&y||x.f&16384?b.v:N(b)})}if(a){function jc(e){if(!(e in globalThis)){let t;Object.defineProperty(globalThis,e,{configurable:!0,get:()=>{if(t!==void 0)return t;Ue(e)},set:e=>{t=e}})}}jc(`$state`),jc(`$effect`),jc(`$derived`),jc(`$inspect`),jc(`$props`),jc(`$bindable`)}function Mc(e){rt===null&&Me(`onMount`),Je&&rt.l!==null?Lc(rt).m.push(e):Ki(()=>{let t=P(e);if(typeof t==`function`)return t})}function Nc(e){rt===null&&Me(`onDestroy`),Mc(()=>()=>P(e))}function Pc(e,t,{bubbles:n=!1,cancelable:r=!1}={}){return new CustomEvent(e,{detail:t,bubbles:n,cancelable:r})}function Fc(){let e=rt;return e===null&&Me(`createEventDispatcher`),(t,n,r)=>{let i=e.s.$$events?.[t];if(i){let a=o(i)?i.slice():[i],s=Pc(t,n,r);for(let t of a)t.call(e.x,s);return!s.defaultPrevented}return!0}}function Ic(e){rt===null&&Me(`afterUpdate`),rt.l===null&&Ve(`afterUpdate`),Lc(rt).a.push(e)}function Lc(e){var t=e.l;return t.u??(t.u={a:[],b:[],m:[]})}if(typeof window<`u`){var Rc,zc;((Rc=(zc=window).__svelte??(zc.__svelte={})).v??(Rc.v=new Set)).add(`5`)}Ye();function Bc(e){return Object.entries(e).map(([e,t])=>`${e}: ${t}`).join(`; `)}var Vc=z(`<button type="button" class="icon-button svelte-11mdast"><span></span></button>`),Hc=z(`<span class="icon-static svelte-11mdast"></span>`),Uc={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 Wc(e,t){lt(t,!1),Gs(e,Uc);let n=V(t,`size`,8,16),i=V(t,`icon`,8),a=V(t,`clickable`,8,!0),o=V(t,`label`,8,``),s=V(t,`pressed`,8,void 0),c=V(t,`disabled`,8,!1),l=A(),u=V(t,`style`,24,()=>({})),d=A(),f=A(),p=Fc();Mc(()=>{(0,r.setIcon)(N(l),i()),m()}),Ic(()=>{(0,r.setIcon)(N(l),i()),m()});function m(){N(l)&&(ci(l,N(l).style.cssText=N(d)),n()&&(ci(l,N(l).style.width=`${n()}px`),ci(l,N(l).style.height=`${n()}px`)))}function h(e){!a()||c()||p(`click`,{event:e})}Zi(()=>F(u()),()=>{j(d,Bc(u()))}),Zi(()=>F(s()),()=>{j(f,s()===void 0?void 0:s()?`true`:`false`)}),Qi(),Oc();var g=os(),_=Rt(g),v=e=>{var t=Vc();Tc(w(t),e=>j(l,e),()=>N(l)),C(t),ta(()=>{oc(t,`aria-label`,o()),oc(t,`aria-pressed`,N(f)),t.disabled=c()}),R(`click`,t,h),B(e,t)},y=e=>{var t=Hc();Tc(t,e=>j(l,e),()=>N(l)),ta(()=>{oc(t,`aria-label`,o()||void 0),oc(t,`aria-hidden`,o()?void 0:`true`)}),B(e,t)};Ss(_,e=>{a()?e(v):e(y,-1)}),B(e,g),ut()}var Gc=z(`<p class="queue-reorder-empty svelte-ohpjsg">Your queue is empty.</p>`),Kc=z(`<span class="queue-reorder-podcast svelte-ohpjsg"> </span>`),qc=z(`<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>`),Jc=z(`<ol class="queue-reorder-list svelte-ohpjsg"></ol>`),Yc=z(`<div class="queue-reorder svelte-ohpjsg"><!> <div class="queue-reorder-footer svelte-ohpjsg"><button type="button" class="mod-cta">Done</button></div></div>`),Xc={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 Zc(e,t){lt(t,!1),Gs(e,Xc);let n=()=>sn(ko,`$queue`,r),[r,i]=ln(),a=A(),o=V(t,`close`,8,()=>{});function s(e){return n().episodes.findIndex(t=>t.title===e.title)}function c(e){let t=s(e);t>0&&ko.moveToTop(t)}function l(e){let t=s(e);t>0&&ko.moveUp(t)}function u(e){let t=s(e);t!==-1&&t<n().episodes.length-1&&ko.moveDown(t)}function d(e){let t=s(e);t!==-1&&t<n().episodes.length-1&&ko.moveToBottom(t)}function f(e){ko.remove(e)}Zi(()=>n(),()=>{j(a,n().episodes)}),Qi(),Oc();var p=Yc(),m=w(p),h=e=>{B(e,Gc())},g=e=>{var t=Jc();Ds(t,7,()=>N(a),e=>e.title,(e,t,n)=>{var r=qc(),i=w(r),o=w(i,!0);C(i);var s=T(i,2),p=w(s),m=w(p,!0);C(p);var h=T(p,2),g=e=>{var n=Kc(),r=w(n,!0);C(n),ta(()=>cs(r,(N(t),P(()=>N(t).podcastName)))),B(e,n)};Ss(h,e=>{N(t),P(()=>N(t).podcastName)&&e(g)}),C(s);var _=T(s,2),v=w(_);{let e=ar(()=>N(n)===0);Wc(v,{icon:`chevrons-up`,label:`Move to top`,size:20,get disabled(){return N(e)},$$events:{click:()=>c(N(t))}})}var y=T(v,2);{let e=ar(()=>N(n)===0);Wc(y,{icon:`chevron-up`,label:`Move up`,size:20,get disabled(){return N(e)},$$events:{click:()=>l(N(t))}})}var b=T(y,2);{let e=ar(()=>(F(N(n)),N(a),P(()=>N(n)===N(a).length-1)));Wc(b,{icon:`chevron-down`,label:`Move down`,size:20,get disabled(){return N(e)},$$events:{click:()=>u(N(t))}})}var x=T(b,2);{let e=ar(()=>(F(N(n)),N(a),P(()=>N(n)===N(a).length-1)));Wc(x,{icon:`chevrons-down`,label:`Move to bottom`,size:20,get disabled(){return N(e)},$$events:{click:()=>d(N(t))}})}Wc(T(x,2),{icon:`x`,label:`Remove from queue`,size:20,$$events:{click:()=>f(N(t))}}),C(_),C(r),ta(()=>{cs(o,N(n)+1),cs(m,(N(t),P(()=>N(t).title)))}),B(e,r)}),C(t),B(e,t)};Ss(m,e=>{N(a),P(()=>N(a).length===0)?e(h):e(g,-1)});var _=T(m,2),v=w(_);C(_),C(p),R(`click`,v,function(...e){o()?.apply(this,e)}),B(e,p),ut(),i()}var Qc=class extends r.Modal{constructor(e){super(e),this.component=null}onOpen(){this.titleEl.setText(`Reorder Queue`),this.component=ls(Zc,{target:this.contentEl,props:{close:()=>this.close()}})}onClose(){this.component&&(ps(this.component),this.component=null),this.contentEl.empty()}};function $c(e){return Array.isArray?Array.isArray(e):ll(e)===`[object Array]`}function el(e){if(typeof e==`string`)return e;if(typeof e==`bigint`)return e.toString();let t=e+``;return t==`0`&&1/e==-1/0?`-0`:t}function tl(e){return e==null?``:el(e)}function nl(e){return typeof e==`string`}function rl(e){return typeof e==`number`}function il(e){return e===!0||e===!1||ol(e)&&ll(e)==`[object Boolean]`}function al(e){return typeof e==`object`}function ol(e){return al(e)&&e!==null}function sl(e){return e!=null}function cl(e){return!e.trim().length}function ll(e){return e==null?e===void 0?`[object Undefined]`:`[object Null]`:Object.prototype.toString.call(e)}var ul=`Incorrect 'index' type`,dl=`Invalid doc index: must be a non-negative integer within the bounds of the docs array`,fl=e=>`Invalid value for key ${e}`,pl=e=>`Pattern length exceeds max of ${e}.`,ml=e=>`Missing ${e} property in key`,hl=e=>`Property 'weight' in key '${e}' must be a positive integer`,gl=`Fuse.match does not support useTokenSearch: token search requires corpus-level statistics (df, fieldCount) that a one-off string comparison does not have. Use new Fuse(...).search(...) instead.`,_l=Object.prototype.hasOwnProperty,vl=class{constructor(e){this._keys=[],this._keyMap={};let t=0;e.forEach(e=>{let n=yl(e);this._keys.push(n),this._keyMap[n.id]=n,t+=n.weight}),this._keys.forEach(e=>{e.weight/=t})}get(e){return this._keyMap[e]}keys(){return this._keys}toJSON(){return JSON.stringify(this._keys)}};function yl(e){let t=null,n=null,r=null,i=1,a=null;if(nl(e)||$c(e))r=e,t=bl(e),n=xl(e);else{if(!_l.call(e,`name`))throw Error(ml(`name`));let o=e.name;if(r=o,_l.call(e,`weight`)&&e.weight!==void 0&&(i=e.weight,i<=0))throw Error(hl(xl(o)));t=bl(o),n=xl(o),a=e.getFn??null}return{path:t,id:n,weight:i,src:r,getFn:a}}function bl(e){return $c(e)?e:e.split(`.`)}function xl(e){return $c(e)?e.join(`.`):e}function Sl(e,t){let n=[],r=!1,i=(e,t,a,o)=>{if(sl(e)){if(!t[a])n.push(o===void 0?e:{v:e,i:o});else{let s=e[t[a]];if(!sl(s))return;if(a===t.length-1&&(nl(s)||rl(s)||il(s)||typeof s==`bigint`))n.push(o===void 0?tl(s):{v:tl(s),i:o});else if($c(s)){r=!0;for(let e=0,n=s.length;e<n;e+=1)i(s[e],t,a+1,e)}else t.length&&i(s,t,a+1,o)}}};return i(e,nl(t)?t.split(`.`):t,0),r?n:n[0]}var Cl={includeMatches:!1,findAllMatches:!1,minMatchCharLength:1},wl={isCaseSensitive:!1,ignoreDiacritics:!1,includeScore:!1,keys:[],shouldSort:!0,sortFn:(e,t)=>e.score===t.score?e.idx<t.idx?-1:1:e.score<t.score?-1:1},Tl={location:0,threshold:.6,distance:100},El={useExtendedSearch:!1,useTokenSearch:!1,tokenize:void 0,tokenMatch:`any`,getFn:Sl,ignoreLocation:!1,ignoreFieldNorm:!1,fieldNormWeight:1},H=Object.freeze({...wl,...Cl,...Tl,...El});function Dl(e){return e>=9&&e<=13||e===32||e===160}function Ol(e=1,t=3){let n=new Map,r=10**t;return{get(t){let i=0,a=!1;for(let e=0;e<t.length;e++)Dl(t.charCodeAt(e))?a=!1:a||(i++,a=!0);if(i===0&&(i=1),n.has(i))return n.get(i);let o=Math.round(r/i**(.5*e))/r;return n.set(i,o),o},clear(){n.clear()}}}var kl=class{constructor({getFn:e=H.getFn,fieldNormWeight:t=H.fieldNormWeight}={}){this.norm=Ol(t,3),this.getFn=e,this.isCreated=!1,this.docs=[],this.keys=[],this._keysMap={},this.setIndexRecords()}setSources(e=[]){this.docs=e}setIndexRecords(e=[]){this.records=e}setKeys(e=[]){this.keys=e,this._keysMap={},e.forEach((e,t)=>{this._keysMap[e.id]=t})}create(){if(this.isCreated||!this.docs.length)return;this.isCreated=!0;let e=this.docs.length;this.records=Array(e);let t=0;if(nl(this.docs[0]))for(let n=0;n<e;n++){let e=this._createStringRecord(this.docs[n],n);e&&(this.records[t++]=e)}else for(let n=0;n<e;n++)this.records[t++]=this._createObjectRecord(this.docs[n],n);this.records.length=t,this.norm.clear()}add(e,t){if(!Number.isInteger(t)||t<0)throw Error(dl);if(nl(e)){let n=this._createStringRecord(e,t);return n&&this.records.push(n),n}let n=this._createObjectRecord(e,t);return this.records.push(n),n}removeAt(e){if(!Number.isInteger(e)||e<0)throw Error(dl);for(let t=0,n=this.records.length;t<n;t+=1)if(this.records[t].i===e){this.records.splice(t,1);break}for(let t=0,n=this.records.length;t<n;t+=1)this.records[t].i>e&&--this.records[t].i}removeAll(e){let t=new Set;for(let n of e)Number.isInteger(n)&&n>=0&&t.add(n);if(t.size===0)return;this.records=this.records.filter(e=>!t.has(e.i));let n=Array.from(t).sort((e,t)=>e-t);for(let e of this.records){let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e.i?t=i+1:r=i}e.i-=t}}getValueForItemAtKeyId(e,t){return e[this._keysMap[t]]}size(){return this.records.length}_createStringRecord(e,t){return!sl(e)||cl(e)?null:{v:e,i:t,n:this.norm.get(e)}}_createObjectRecord(e,t){let n={i:t,$:{}};for(let t=0,r=this.keys.length;t<r;t++){let r=this.keys[t],i=r.getFn?r.getFn(e):this.getFn(e,r.path);if(sl(i)){if($c(i)){let e=[];for(let t=0,n=i.length;t<n;t+=1){let n=i[t];if(sl(n)){if(nl(n)){if(!cl(n)){let r={v:n,i:t,n:this.norm.get(n)};e.push(r)}}else if(sl(n.v)){let t=nl(n.v)?n.v:tl(n.v);if(!cl(t)){let r={v:t,i:n.i,n:this.norm.get(t)};e.push(r)}}}}n.$[t]=e}else if(nl(i)&&!cl(i)){let e={v:i,n:this.norm.get(i)};n.$[t]=e}}}return n}toJSON(){return{keys:this.keys.map(({getFn:e,...t})=>t),records:this.records}}};function Al(e,t,{getFn:n=H.getFn,fieldNormWeight:r=H.fieldNormWeight}={}){let i=new kl({getFn:n,fieldNormWeight:r});return i.setKeys(e.map(yl)),i.setSources(t),i.create(),i}function jl(e,{getFn:t=H.getFn,fieldNormWeight:n=H.fieldNormWeight}={}){let{keys:r,records:i}=e,a=new kl({getFn:t,fieldNormWeight:n});return a.setKeys(r),a.setIndexRecords(i),a}function Ml(e=[],t=H.minMatchCharLength){let n=[],r=-1,i=-1,a=0;for(let o=e.length;a<o;a+=1){let o=e[a];o&&r===-1?r=a:!o&&r!==-1&&(i=a-1,i-r+1>=t&&n.push([r,i]),r=-1)}return e[a-1]&&a-r>=t&&n.push([r,a-1]),n}function Nl(e,t,n,{location:r=H.location,distance:i=H.distance,threshold:a=H.threshold,findAllMatches:o=H.findAllMatches,minMatchCharLength:s=H.minMatchCharLength,includeMatches:c=H.includeMatches,ignoreLocation:l=H.ignoreLocation}={}){if(t.length>32)throw Error(pl(32));let u=t.length,d=e.length,f=Math.max(0,Math.min(r,d)),p=a,m=f,h=(e,t)=>{let n=e/u;if(l)return n;let r=Math.abs(f-t);return i?n+r/i:r?1:n},g=s>1||c,_=g?Array(d):[],v;for(;(v=e.indexOf(t,m))>-1;){let e=h(0,v);if(p=Math.min(e,p),m=v+u,g){let e=0;for(;e<u;)_[v+e]=1,e+=1}}m=-1;let y=[],b=1,x=0,S=u+d,ee=1<<u-1;for(let t=0;t<u;t+=1){let r=0,i=S;for(;r<i;)h(t,f+i)<=p?r=i:S=i,i=Math.floor((S-r)/2+r);S=i;let a=Math.max(1,f-i+1),s=o?d:Math.min(f+i,d)+u,c=Array(s+2);c[s+1]=(1<<t)-1;for(let r=s;r>=a;--r){let i=r-1,o=n[e[i]];if(c[r]=(c[r+1]<<1|1)&o,t&&(c[r]|=(y[r+1]|y[r])<<1|1|y[r+1]),c[r]&ee&&(b=h(t,i),b<=p)){if(p=b,m=i,x=t,m<=f)break;a=Math.max(1,2*f-m)}}if(h(t+1,f)>p)break;y=c}if(g&&m>=0){let t=Math.min(d-1,m+u-1+x);for(let r=m;r<=t;r+=1)n[e[r]]&&(_[r]=1)}let te={isMatch:m>=0,score:Math.max(.001,b)};if(g){let e=Ml(_,s);e.length?c&&(te.indices=e):te.isMatch=!1}return te}function Pl(e){let t={};for(let n=0,r=e.length;n<r;n+=1){let i=e.charAt(n);t[i]=(t[i]||0)|1<<r-n-1}return t}function Fl(e){if(e.length<=1)return e;e.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let t=[e[0]];for(let n=1,r=e.length;n<r;n+=1){let r=t[t.length-1],i=e[n];i[0]<=r[1]+1?r[1]=Math.max(r[1],i[1]):t.push(i)}return t}var Il={ł:`l`,Ł:`L`,đ:`d`,Đ:`D`,ø:`o`,Ø:`O`,ħ:`h`,Ħ:`H`,ŧ:`t`,Ŧ:`T`,ı:`i`,ß:`ss`},Ll=RegExp(`[`+Object.keys(Il).join(``)+`]`,`g`),Rl=typeof String.prototype.normalize==`function`?e=>e.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,``).replace(Ll,e=>Il[e]):e=>e,zl=class{constructor(e,{location:t=H.location,threshold:n=H.threshold,distance:r=H.distance,includeMatches:i=H.includeMatches,findAllMatches:a=H.findAllMatches,minMatchCharLength:o=H.minMatchCharLength,isCaseSensitive:s=H.isCaseSensitive,ignoreDiacritics:c=H.ignoreDiacritics,ignoreLocation:l=H.ignoreLocation}={}){if(this.options={location:t,threshold:n,distance:r,includeMatches:i,findAllMatches:a,minMatchCharLength:o,isCaseSensitive:s,ignoreDiacritics:c,ignoreLocation:l},e=s?e:e.toLowerCase(),e=c?Rl(e):e,this.pattern=e,this.chunks=[],!this.pattern.length)return;let u=(e,t)=>{this.chunks.push({pattern:e,alphabet:Pl(e),startIndex:t})},d=this.pattern.length;if(d>32){let e=0,t=d%32,n=d-t;for(;e<n;)u(this.pattern.substr(e,32),e),e+=32;if(t){let e=d-32;u(this.pattern.substr(e),e)}}else u(this.pattern,0)}searchIn(e){let{isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r}=this.options;if(e=t?e:e.toLowerCase(),e=n?Rl(e):e,this.pattern===e){if(e.length<this.options.minMatchCharLength)return{isMatch:!1,score:1};let t={isMatch:!0,score:0};return r&&(t.indices=[[0,e.length-1]]),t}let{location:i,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,ignoreLocation:l}=this.options,u=[],d=0,f=!1;this.chunks.forEach(({pattern:t,alphabet:n,startIndex:p})=>{let{isMatch:m,score:h,indices:g}=Nl(e,t,n,{location:i+p,distance:a,threshold:o,findAllMatches:s,minMatchCharLength:c,includeMatches:r,ignoreLocation:l});m&&(f=!0),d+=h,m&&g&&u.push(...g)});let p={isMatch:f,score:f?d/this.chunks.length:1};return f&&r&&(p.indices=Fl(u)),p}},Bl=new Set([`fuzzy`,`include`]);function Vl(e){return e.startsWith(`inverse`)}var Hl=[{type:`exact`,multiRegex:/^="(.*)"$/,singleRegex:/^=(.*)$/,create:e=>({type:`exact`,search(t){let n=t===e;return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`include`,multiRegex:/^'"(.*)"$/,singleRegex:/^'(.*)$/,create:e=>({type:`include`,search(t){let n=0,r,i=[],a=e.length;for(;(r=t.indexOf(e,n))>-1;)n=r+a,i.push([r,n-1]);let o=!!i.length;return{isMatch:o,score:+!o,indices:i}}})},{type:`prefix-exact`,multiRegex:/^\^"(.*)"$/,singleRegex:/^\^(.*)$/,create:e=>({type:`prefix-exact`,search(t){let n=t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,e.length-1]}}})},{type:`inverse-prefix-exact`,multiRegex:/^!\^"(.*)"$/,singleRegex:/^!\^(.*)$/,create:e=>({type:`inverse-prefix-exact`,search(t){let n=!t.startsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`inverse-suffix-exact`,multiRegex:/^!"(.*)"\$$/,singleRegex:/^!(.*)\$$/,create:e=>({type:`inverse-suffix-exact`,search(t){let n=!t.endsWith(e);return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`suffix-exact`,multiRegex:/^"(.*)"\$$/,singleRegex:/^(.*)\$$/,create:e=>({type:`suffix-exact`,search(t){let n=t.endsWith(e);return{isMatch:n,score:+!n,indices:[t.length-e.length,t.length-1]}}})},{type:`inverse-exact`,multiRegex:/^!"(.*)"$/,singleRegex:/^!(.*)$/,create:e=>({type:`inverse-exact`,search(t){let n=t.indexOf(e)===-1;return{isMatch:n,score:+!n,indices:[0,t.length-1]}}})},{type:`fuzzy`,multiRegex:/^"(.*)"$/,singleRegex:/^(.*)$/,create:(e,t={})=>{let n=new zl(e,{location:t.location??H.location,threshold:t.threshold??H.threshold,distance:t.distance??H.distance,includeMatches:t.includeMatches??H.includeMatches,findAllMatches:t.findAllMatches??H.findAllMatches,minMatchCharLength:t.minMatchCharLength??H.minMatchCharLength,isCaseSensitive:t.isCaseSensitive??H.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics??H.ignoreDiacritics,ignoreLocation:t.ignoreLocation??H.ignoreLocation});return{type:`fuzzy`,search(e){return n.searchIn(e)}}}}],Ul=Hl.length,Wl=`\0`,Gl=`|`;function Kl(e){let t=[],n=e.length,r=0;for(;r<n;){for(;r<n&&e[r]===` `;)r++;if(r>=n)break;let i=r;for(;i<n&&e[i]!==` `&&e[i]!==`"`;)i++;if(i<n&&e[i]===`"`){for(i++;i<n;){if(e[i]===`"`){let t=i+1;if(t>=n||e[t]===` `){i++;break}if(e[t]===`$`&&(t+1>=n||e[t+1]===` `)){i+=2;break}}i++}t.push(e.substring(r,i)),r=i}else{for(;i<n&&e[i]!==` `;)i++;t.push(e.substring(r,i)),r=i}}return t}function ql(e,t){let n=e.match(t);return n?n[1]:null}function Jl(e,t={}){return e.replace(/\\\|/g,Wl).split(Gl).map(e=>{let n=Kl(e.replace(/\u0000/g,`|`).trim()).filter(e=>e&&!!e.trim()),r=[];for(let e=0,i=n.length;e<i;e+=1){let i=n[e],a=!1,o=-1;for(;!a&&++o<Ul;){let e=Hl[o],n=ql(i,e.multiRegex);n&&(r.push(e.create(n,t)),a=!0)}if(!a)for(o=-1;++o<Ul;){let e=Hl[o],n=ql(i,e.singleRegex);if(n){r.push(e.create(n,t));break}}}return r})}var Yl=class{constructor(e,{isCaseSensitive:t=H.isCaseSensitive,ignoreDiacritics:n=H.ignoreDiacritics,includeMatches:r=H.includeMatches,minMatchCharLength:i=H.minMatchCharLength,ignoreLocation:a=H.ignoreLocation,findAllMatches:o=H.findAllMatches,location:s=H.location,threshold:c=H.threshold,distance:l=H.distance}={}){this.query=null,this.options={isCaseSensitive:t,ignoreDiacritics:n,includeMatches:r,minMatchCharLength:i,findAllMatches:o,ignoreLocation:a,location:s,threshold:c,distance:l},e=t?e:e.toLowerCase(),e=n?Rl(e):e,this.pattern=e,this.query=Jl(this.pattern,this.options)}static condition(e,t){return t.useExtendedSearch}searchIn(e){let t=this.query;if(!t)return{isMatch:!1,score:1};let{includeMatches:n,isCaseSensitive:r,ignoreDiacritics:i}=this.options;e=r?e:e.toLowerCase(),e=i?Rl(e):e;let a=0,o=[],s=0,c=!1;for(let r=0,i=t.length;r<i;r+=1){let i=t[r];o.length=0,a=0,c=!1;for(let t=0,r=i.length;t<r;t+=1){let r=i[t],{isMatch:l,indices:u,score:d}=r.search(e);if(l)a+=1,s+=d,Vl(r.type)&&(c=!0),n&&(Bl.has(r.type)?o.push(...u):o.push(u));else{s=0,a=0,o.length=0,c=!1;break}}if(a){let e={isMatch:!0,score:s/a};return c&&(e.hasInverse=!0),n&&(e.indices=Fl(o)),e}}return{isMatch:!1,score:1}}},Xl=[];function Zl(...e){Xl.push(...e)}function Ql(e,t){for(let n=0,r=Xl.length;n<r;n+=1){let r=Xl[n];if(r.condition(e,t))return new r(e,t)}return new zl(e,t)}var $l={AND:`$and`,OR:`$or`},eu={PATH:`$path`,PATTERN:`$val`},tu=e=>!!(e[$l.AND]||e[$l.OR]),nu=e=>!!e[eu.PATH],ru=e=>!$c(e)&&al(e)&&!tu(e),iu=e=>({[$l.AND]:Object.keys(e).map(t=>({[t]:e[t]}))});function au(e,t,{auto:n=!0}={}){let r=e=>{if(nl(e)){let r={keyId:null,pattern:e};return n&&(r.searcher=Ql(e,t)),r}let i=Object.keys(e),a=nu(e);if(!a&&i.length>1&&!tu(e))return r(iu(e));if(ru(e)){let r=a?e[eu.PATH]:i[0],o=a?e[eu.PATTERN]:e[r];if(!nl(o))throw Error(fl(r));let s={keyId:xl(r),pattern:o};return n&&(s.searcher=Ql(o,t)),s}let o={children:[],operator:i[0]};return i.forEach(t=>{let n=e[t];$c(n)&&n.forEach(e=>{o.children.push(r(e))})}),o};return tu(e)||(e=iu(e)),r(e)}function ou(e,{ignoreFieldNorm:t=H.ignoreFieldNorm}){let n=1;return e.forEach(({key:e,norm:r,score:i})=>{let a=e?e.weight:null;n*=(i===0&&a?2**-52:i)**+((a||1)*(t?1:r))}),n}function su(e,{ignoreFieldNorm:t=H.ignoreFieldNorm}){e.forEach(e=>{e.score=ou(e.matches,{ignoreFieldNorm:t})})}var cu=class{constructor(e,t){this.limit=e,this.heap=[],this.comparator=t}get size(){return this.heap.length}insert(e){this.size<this.limit?(this.heap.push(e),this._bubbleUp(this.size-1)):this.comparator(e,this.heap[0])<0&&(this.heap[0]=e,this._sinkDown(0))}extractSorted(){return this.heap.sort(this.comparator)}_bubbleUp(e){let t=this.heap;for(;e>0;){let n=e-1>>1;if(this.comparator(t[e],t[n])<=0)break;let r=t[e];t[e]=t[n],t[n]=r,e=n}}_sinkDown(e){let t=this.heap,n=t.length,r=e;do{e=r;let i=2*e+1,a=2*e+2;if(i<n&&this.comparator(t[i],t[r])>0&&(r=i),a<n&&this.comparator(t[a],t[r])>0&&(r=a),r!==e){let n=t[e];t[e]=t[r],t[r]=n}}while(r!==e)}};function lu(e){let t=[];return e.matches.forEach(e=>{if(!sl(e.indices)||!e.indices.length)return;let n={indices:e.indices,value:e.value};e.key&&(n.key=e.key.id),e.idx>-1&&(n.refIndex=e.idx),t.push(n)}),t}function uu(e,t,{includeMatches:n=H.includeMatches,includeScore:r=H.includeScore}={}){return e.map(e=>{let{idx:i}=e,a={item:t[i],refIndex:i};return n&&(a.matches=lu(e)),r&&(a.score=e.score),a})}var du=/[\p{L}\p{M}\p{N}_]+/gu,fu=new WeakSet;function pu(e){fu.has(e)||fu.add(e)}function mu(e){if(typeof e==`function`){let t=!1;return n=>{let r=e(n);if(!t&&(t=!0,!Array.isArray(r)||r.some(e=>typeof e!=`string`)))throw Error(`[Fuse] tokenize function must return string[]; received ${Array.isArray(r)?`array containing non-strings`:typeof r}.`);return r}}return e instanceof RegExp?(e.global||pu(e),t=>t.match(e)||[]):e=>e.match(du)||[]}function hu({isCaseSensitive:e=!1,ignoreDiacritics:t=!1,tokenize:n}={}){let r=mu(n);return{tokenize(n){return e||(n=n.toLowerCase()),t&&(n=Rl(n)),r(n)}}}var gu=class{static condition(e,t){return t.useTokenSearch}constructor(e,t){this.options=t,this.analyzer=hu({isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,tokenize:t.tokenize});let n=this.analyzer.tokenize(e),{df:r,fieldCount:i}=t._invertedIndex;this.termSearchers=[],this.idfWeights=[];for(let e of n){this.termSearchers.push(new zl(e,{location:t.location,threshold:t.threshold,distance:t.distance,includeMatches:t.includeMatches,findAllMatches:t.findAllMatches,minMatchCharLength:t.minMatchCharLength,isCaseSensitive:t.isCaseSensitive,ignoreDiacritics:t.ignoreDiacritics,ignoreLocation:!0}));let n=r.get(e)||0,a=Math.log(1+(i-n+.5)/(n+.5));this.idfWeights.push(a)}this.combineAll=t.tokenMatch===`all`,this.numTerms=this.termSearchers.length,this.useMask=this.numTerms<=31}searchIn(e){if(!this.termSearchers.length)return{isMatch:!1,score:1};let t=[],n=0,r=0,i=0,a=0,o=this.combineAll&&!this.useMask?new Set:null;for(let s=0;s<this.termSearchers.length;s++){let c=this.termSearchers[s].searchIn(e),l=this.idfWeights[s];r+=l,c.isMatch&&(i++,n+=l*(1-c.score),c.indices&&t.push(...c.indices),this.combineAll&&(this.useMask?a|=1<<s:o.add(s)))}if(i===0)return{isMatch:!1,score:1};let s=r>0?1-n/r:0,c={isMatch:!0,score:Math.max(.001,s)};return this.options.includeMatches&&t.length&&(c.indices=Fl(t)),this.combineAll&&(this.useMask?c.matchedMask=a:c.matchedTerms=o,c.termCount=this.numTerms),c}};function _u(e,t,n,r){let i=r.tokenize(t);if(!i.length)return;e.fieldCount++,e.docFieldCount.set(n,(e.docFieldCount.get(n)||0)+1);let a=new Set(i),o=e.docTermFieldHits.get(n);o||(o=new Map,e.docTermFieldHits.set(n,o));for(let t of a)o.set(t,(o.get(t)||0)+1),e.df.set(t,(e.df.get(t)||0)+1)}function vu(e,t,n,r){let{i,v:a,$:o}=t;if(a!==void 0){_u(e,a,i,r);return}if(o)for(let t=0;t<n;t++){let n=o[t];if(n){if(Array.isArray(n))for(let t of n)_u(e,t.v,i,r);else _u(e,n.v,i,r)}}}function yu(e,t,n){let r={fieldCount:0,df:new Map,docFieldCount:new Map,docTermFieldHits:new Map};for(let i of e)vu(r,i,t,n);return r}function bu(e,t,n,r){vu(e,t,n,r)}function xu(e,t){let n=e.docFieldCount.get(t);if(n===void 0)return;e.fieldCount-=n,e.docFieldCount.delete(t);let r=e.docTermFieldHits.get(t);if(r){for(let[t,n]of r){let r=(e.df.get(t)||0)-n;r<=0?e.df.delete(t):e.df.set(t,r)}e.docTermFieldHits.delete(t)}}function Su(e,t){if(t.length===0)return;let n=Array.from(new Set(t)).sort((e,t)=>e-t);for(let t of n)xu(e,t);let r=e=>{let t=0,r=n.length;for(;t<r;){let i=t+r>>>1;n[i]<e?t=i+1:r=i}return e-t},i=n[0],a=new Map;for(let[t,n]of e.docFieldCount)a.set(t>i?r(t):t,n);e.docFieldCount=a;let o=new Map;for(let[t,n]of e.docTermFieldHits)o.set(t>i?r(t):t,n);e.docTermFieldHits=o}var Cu=class{constructor(e,t,n){this.options={...H,...t},this.options.useExtendedSearch,this.options.useTokenSearch,this._keyStore=new vl(this.options.keys),this._docs=e,this._myIndex=null,this._invertedIndex=null,this.setCollection(e,n),this._lastQuery=null,this._lastSearcher=null}_getSearcher(e){if(this._lastQuery===e)return this._lastSearcher;let t=Ql(e,this._invertedIndex?{...this.options,_invertedIndex:this._invertedIndex}:this.options);return this._lastQuery=e,this._lastSearcher=t,t}setCollection(e,t){if(this._docs=e,t&&!(t instanceof kl))throw Error(ul);if(this._myIndex=t||Al(this.options.keys,this._docs,{getFn:this.options.getFn,fieldNormWeight:this.options.fieldNormWeight}),this.options.useTokenSearch){let e=hu({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});this._invertedIndex=yu(this._myIndex.records,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}add(e){if(!sl(e))return;this._docs.push(e);let t=this._myIndex.add(e,this._docs.length-1);if(this._invertedIndex&&t){let e=hu({isCaseSensitive:this.options.isCaseSensitive,ignoreDiacritics:this.options.ignoreDiacritics,tokenize:this.options.tokenize});bu(this._invertedIndex,t,this._myIndex.keys.length,e)}this._invalidateSearcherCache()}remove(e=()=>!1){let t=[],n=[];for(let r=0,i=this._docs.length;r<i;r+=1)e(this._docs[r],r)&&(t.push(this._docs[r]),n.push(r));if(n.length){this._invertedIndex&&Su(this._invertedIndex,n);let e=new Set(n);this._docs=this._docs.filter((t,n)=>!e.has(n)),this._myIndex.removeAll(n),this._invalidateSearcherCache()}return t}removeAt(e){if(!Number.isInteger(e)||e<0||e>=this._docs.length)throw Error(dl);this._invertedIndex&&Su(this._invertedIndex,[e]);let t=this._docs.splice(e,1)[0];return this._myIndex.removeAt(e),this._invalidateSearcherCache(),t}_invalidateSearcherCache(){this._lastQuery=null,this._lastSearcher=null}getIndex(){return this._myIndex}_normalizedKeys(){return this._myIndex.keys.map(e=>this._keyStore.get(e.id)||e)}search(e,t){let{limit:n=-1}=t||{},{includeMatches:r,includeScore:i,shouldSort:a,sortFn:o,ignoreFieldNorm:s}=this.options;if(nl(e)&&!e.trim()){let e=this._docs.map((e,t)=>({item:e,refIndex:t}));return rl(n)&&n>-1&&(e=e.slice(0,n)),e}let c=a&&rl(n)&&n>0&&nl(e),l=o,u=(e,t)=>l(e,t)||e.idx-t.idx,d;if(c){let t=new cu(n,u);nl(this._docs[0])?this._searchStringList(e,{heap:t,ignoreFieldNorm:s}):this._searchObjectList(e,{heap:t,ignoreFieldNorm:s}),d=t.extractSorted()}else d=nl(e)?nl(this._docs[0])?this._searchStringList(e):this._searchObjectList(e):this._searchLogical(e),su(d,{ignoreFieldNorm:s}),a&&d.sort(nl(e)?u:l),rl(n)&&n>-1&&(d=d.slice(0,n));return uu(d,this._docs,{includeMatches:r,includeScore:i})}_searchStringList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=t?null:[];return a.forEach(({v:e,i:a,n:s})=>{if(!sl(e))return;let c=r.searchIn(e);if(c.isMatch){let r={score:c.score,value:e,norm:s,indices:c.indices};i&&(r.matchedMask=c.matchedMask,r.matchedTerms=c.matchedTerms,r.termCount=c.termCount);let l=[r];if(!i||this._coversAllTokens(l)){let r={item:e,idx:a,matches:l};t?(r.score=ou(r.matches,{ignoreFieldNorm:n}),t.insert(r)):o.push(r)}}}),o}_searchLogical(e){let t=au(e,this.options),n=this._normalizedKeys(),r=(e,t,i)=>{if(!(`children`in e)){let{keyId:r,searcher:a}=e,o;return r===null?(o=[],n.forEach((e,n)=>{o.push(...this._findMatches({key:e,value:t[n],searcher:a}))})):o=this._findMatches({key:this._keyStore.get(r),value:this._myIndex.getValueForItemAtKeyId(t,r),searcher:a}),o&&o.length?[{idx:i,item:t,matches:o}]:[]}let{children:a,operator:o}=e,s=[];for(let e=0,n=a.length;e<n;e+=1){let n=a[e],c=r(n,t,i);if(c.length)s.push(...c);else if(o===$l.AND)return[]}return s},i=this._myIndex.records,a=new Map,o=[];return i.forEach(({$:e,i:n})=>{if(sl(e)){let i=r(t,e,n);i.length&&(a.has(n)||(a.set(n,{idx:n,item:e,matches:[]}),o.push(a.get(n))),i.forEach(({matches:e})=>{a.get(n).matches.push(...e)}))}}),o}_searchObjectList(e,{heap:t,ignoreFieldNorm:n}={}){let r=this._getSearcher(e),i=this.options.useTokenSearch&&this.options.tokenMatch===`all`,{records:a}=this._myIndex,o=this._normalizedKeys(),s=t?null:[];return a.forEach(({$:e,i:a})=>{if(!sl(e))return;let c=[],l=!1,u=!1;if(o.forEach((t,n)=>{let i=this._findMatches({key:t,value:e[n],searcher:r});i.length?(c.push(...i),i[0].hasInverse&&(u=!0)):l=!0}),!(u&&l)&&c.length&&(!i||this._coversAllTokens(c))){let r={idx:a,item:e,matches:c};t?(r.score=ou(r.matches,{ignoreFieldNorm:n}),t.insert(r)):s.push(r)}}),s}_findMatches({key:e,value:t,searcher:n}){if(!sl(t))return[];let r=[];if($c(t))t.forEach(({v:t,i,n:a})=>{if(!sl(t))return;let o=n.searchIn(t);if(o.isMatch){let n={score:o.score,key:e,value:t,idx:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(n.matchedMask=o.matchedMask,n.matchedTerms=o.matchedTerms,n.termCount=o.termCount),r.push(n)}});else{let{v:i,n:a}=t,o=n.searchIn(i);if(o.isMatch){let t={score:o.score,key:e,value:i,norm:a,indices:o.indices,hasInverse:o.hasInverse};o.termCount!==void 0&&(t.matchedMask=o.matchedMask,t.matchedTerms=o.matchedTerms,t.termCount=o.termCount),r.push(t)}}return r}_coversAllTokens(e){let t=e.length?e[0].termCount:void 0;if(t===void 0)return!0;if(t<=31){let n=0;for(let t=0;t<e.length;t++)n|=e[t].matchedMask||0;return n===2**t-1}let n=new Set;for(let t=0;t<e.length;t++){let r=e[t].matchedTerms;if(r)for(let e of r)n.add(e)}return n.size===t}};Cu.version=`7.5.0`,Cu.createIndex=Al,Cu.parseIndex=jl,Cu.config=H,Cu.match=function(e,t,n){if(n&&n.useTokenSearch)throw Error(gl);return Ql(e,{...H,...n}).searchIn(t)},Cu.parseQuery=au,Zl(Yl),Zl(gu),Cu.use=function(...e){e.forEach(e=>Zl(e))};var wu=Cu;function Tu(e){let t=new RegExp(/\.([0-9a-z]+)(?:[?#]|$)/i).exec(e);if(!t)return``;let[,n]=t;return n}function Eu(e,t){let n=Qa(e);if(!n)return``;let r=n.getFullYear(),i=n.getMonth(),a=n.getDate(),o=n.getDay(),s=n.getHours(),c=n.getMinutes(),l=n.getSeconds(),u=e=>e.toString().padStart(2,`0`),d=[`January`,`February`,`March`,`April`,`May`,`June`,`July`,`August`,`September`,`October`,`November`,`December`],f=[`Jan`,`Feb`,`Mar`,`Apr`,`May`,`Jun`,`Jul`,`Aug`,`Sep`,`Oct`,`Nov`,`Dec`],p=[`Sunday`,`Monday`,`Tuesday`,`Wednesday`,`Thursday`,`Friday`,`Saturday`],m=[`Sun`,`Mon`,`Tue`,`Wed`,`Thu`,`Fri`,`Sat`],h=e=>{let t=[`th`,`st`,`nd`,`rd`],n=e%100;return e+(t[(n-20)%10]||t[n]||t[0])},g=s%12||12,_=s>=12,v={YYYY:r.toString(),YY:r.toString().slice(-2),MMMM:d[i],MMM:f[i],MM:u(i+1),Mo:h(i+1),M:(i+1).toString(),dddd:p[o],ddd:m[o],Do:h(a),DD:u(a),D:a.toString(),HH:u(s),H:s.toString(),hh:u(g),h:g.toString(),mm:u(c),m:c.toString(),ss:u(l),s:l.toString(),A:_?`PM`:`AM`,a:_?`pm`:`am`},y=Object.keys(v).sort((e,t)=>t.length-e.length).map(e=>e.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)).join(`|`),b=RegExp(`\\[([^\\]]*)]|(${y})|.`,`g`),x=``,S;for(;(S=b.exec(t))!==null;)S[1]===void 0?S[2]===void 0?x+=S[0]:x+=v[S[2]]:x+=S[1];return x}function Du(e,t){(!Number.isFinite(e)||e<0)&&(e=0);let n=Math.floor(e/3600),r=Math.floor(e%3600/60),i=Math.floor(e%60),a=n%12||12,o=n>=12,s=e=>e.toString().padStart(2,`0`),c={HH:s(n),hh:s(a),mm:s(r),ss:s(i),H:n.toString(),h:a.toString(),m:r.toString(),s:i.toString(),A:o?`PM`:`AM`,a:o?`pm`:`am`};return t.replace(/\\(.)|HH|hh|mm|ss|H|h|m|s|A|a/g,(e,t)=>t===void 0?c[e]:t)}function Ou(e,t){if(!t||!t.trim())return e>=3600?Du(e,`H:mm:ss`):Du(e,`m:ss`);let n=t.trim().toLowerCase();return n===`seconds`?String(Math.floor(e)):n===`minutes`?String(Math.floor(e/60)):Du(e,t)}function ku(e,t){if(e===void 0)return``;let n=String(e),r=t?.trim();return r&&/^0+$/.test(r)?n.padStart(r.length,`0`):n}function Au(e,t){let n=ju(e);return n===void 0?Mu(t):n}function ju(e){if(e==null)return;let t=e.trim();if(!/^\d+$/.test(t))return;let n=Number(t);return Number.isSafeInteger(n)?n:void 0}function Mu(e){let t=(e??``).trim();if(!t)return;let n=t.slice(0,64),r=n.match(/^(?:#\s*|ep(?:isode)?\.?\s*#?|e)(\d{1,6})\b(?!\.\d)/i);if(r)return Number(r[1]);let i=n.match(/^(\d{1,6})\s*(?:[-:)|]|\.(?!\d))/);if(i)return Number(i[1])}function Nu(e,t,n,r){let i=new URL(`obsidian://podnotes`),a=new URLSearchParams;return a.set(`episodeName`,e),a.set(`url`,t),n!==void 0&&(a.set(`time`,n.toString()),r!==void 0&&a.set(`endTime`,r.toString())),i.search=a.toString().replace(/\+/g,`%20`),i}function Pu(e){return e.podcastName===`local file`}function Fu(e){let t=()=>ho.getEpisode(e)?.filePath,n=Pu(e)?e.filePath??t():e.feedUrl??t();return!n||!e.title?``:Nu(e.title,n).href}function Iu(e,t){let n=t.startsWith(`.`)?t:`.${t}`;return e.endsWith(n)?e:`${e}${n}`}var Lu=`Untitled`,Ru=new TextEncoder;function zu(e){return Ru.encode(e).length}function Bu(e,t){return t===`bytes`?zu(e):e.length}function Vu(){return r.Platform.isWin||r.Platform.isMacOS||r.Platform.isIosApp?{mode:`utf16`,max:255}:{mode:`bytes`,max:255}}function Hu(e,t,n){if(Bu(e,n)<=t)return e;let r=``,i=0;for(let a of e){let e=Bu(a,n);if(i+e>t)break;r+=a,i+=e}return r}function Uu(e){return e.replace(/[\s.]+$/g,``).replace(/^\s+/,``)}function Wu(e,t){return Uu(Bu(e,t.mode)<=t.max?e:Hu(e,t.max,t.mode))||`Untitled`}function Gu(e,t,n){return`${Uu(Hu(e.toLowerCase().endsWith(t.toLowerCase())?e.slice(0,e.length-t.length):e,Math.max(1,n.max-Bu(t,n.mode)),n.mode))||`Untitled`}${t}`}function Ku(e){let t=e.split(`/`).pop()??``,n=t.lastIndexOf(`.`);if(n<=0)return``;let r=t.slice(n);return/^\.[A-Za-z0-9]{1,16}$/.test(r)?r:``}function qu(e,t=`.md`,n=Vu()){let r=e.split(`/`).filter(e=>e.length>0);if(r.length===0)return`${Lu}${t}`;let i=r.length-1;return r.map((e,r)=>r===i?Gu(e,t,n):Wu(e,n)).join(`/`)}var Ju=500,Yu=500;function Xu(e){return e.filter(Zu).map(e=>({...e,title:typeof e.title==`string`?e.title.slice(0,Yu):``})).sort((e,t)=>e.startTime-t.startTime).slice(0,Ju)}function Zu(e){if(!e||typeof e!=`object`)return!1;let t=e;return t.toc!==!1&&(t.title===void 0||typeof t.title==`string`)&&Number.isFinite(t.startTime)}var Qu=/[()]/g,$u={"(":`%28`,")":`%29`};function ed(e){let t=e.trim();if(!t)return t;let n;try{n=new URL(t).toString()}catch{n=td(t)}return n.replace(Qu,e=>$u[e]??e)}function td(e){return e.replace(/\s/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)}var nd=32,rd=128,id=[[`0.0.0.0`,8],[`10.0.0.0`,8],[`100.64.0.0`,10],[`127.0.0.0`,8],[`169.254.0.0`,16],[`172.16.0.0`,12],[`192.0.0.0`,24],[`192.0.2.0`,24],[`192.31.196.0`,24],[`192.52.193.0`,24],[`192.88.99.0`,24],[`192.168.0.0`,16],[`192.175.48.0`,24],[`198.18.0.0`,15],[`198.51.100.0`,24],[`203.0.113.0`,24],[`224.0.0.0`,4],[`240.0.0.0`,4]],ad=[[`::`,128],[`::1`,128],[`64:ff9b::`,96],[`64:ff9b:1::`,48],[`100::`,64],[`100:0:0:1::`,64],[`2001::`,23],[`2001:db8::`,32],[`2002::`,16],[`2620:4f:8000::`,48],[`3fff::`,20],[`5f00::`,16],[`fc00::`,7],[`fe80::`,10],[`fec0::`,10],[`ff00::`,8]];function od(e){let t=e.split(`.`);if(t.length!==4)return;let n=0n;for(let e of t){if(!/^(?:0|[1-9][0-9]{0,2})$/.test(e))return;let t=Number(e);if(t>255)return;n=n<<8n|BigInt(t)}return n}function sd(e){let t=e.toLowerCase();if(t.length===0||t.includes(`%`))return;let n=t.indexOf(`::`);if(n!==-1&&t.indexOf(`::`,n+2)!==-1)return;let r=e=>{if(e.length===0)return[];let t=e.split(`:`);if(!t.some(e=>e.length===0))return t},i=r(n===-1?t:t.slice(0,n)),a=r(n===-1?``:t.slice(n+2));if(!i||!a)return;let o=a.length>0?a:i,s=o[o.length-1];if(s?.includes(`.`)){if(n!==-1&&a.length===0)return;let e=od(s);if(e===void 0)return;o.splice(o.length-1,1,Number(e>>16n&65535n).toString(16),Number(e&65535n).toString(16))}let c=[...i,...a];if(c.some(e=>e.includes(`.`))||c.some(e=>!/^[0-9a-f]{1,4}$/.test(e))||n===-1&&c.length!==8||n!==-1&&c.length>=8)return;let l=8-c.length,u=n===-1?c:[...i,...Array.from({length:l},()=>`0`),...a];if(u.length!==8)return;let d=0n;for(let e of u)d=d<<16n|BigInt(`0x${e}`);return d}function cd(e,t){let n=od(e);if(n===void 0)throw Error(`Invalid internal IPv4 range`);return Object.freeze({network:n,prefixLength:t})}function ld(e,t){let n=sd(e);if(n===void 0)throw Error(`Invalid internal IPv6 range`);return Object.freeze({network:n,prefixLength:t})}var ud=id.map(([e,t])=>cd(e,t)),dd=ad.map(([e,t])=>ld(e,t));function fd(e,t,n){let r=BigInt(n-t.prefixLength);return e>>r===t.network>>r}function pd(e){return ud.some(t=>fd(e,t,nd))?`non-public-or-special-literal`:`ordinary-public-literal`}function md(e){return e>>32n==65535n?pd(e&4294967295n):dd.some(t=>fd(e,t,rd))?`non-public-or-special-literal`:e>>125n==1n?`ordinary-public-literal`:`non-public-or-special-literal`}function hd(e){for(let t=0;t<e.length;t+=1){let n=e.charCodeAt(t);if(n>=55296&&n<=56319){let n=e.charCodeAt(t+1);if(n<56320||n>57343)return!0;t+=1;continue}if(n>=56320&&n<=57343||n<32||n>=127&&n<=159||n===1564||n===8203||n===8204||n===8205||n===8206||n===8207||n>=8232&&n<=8238||n>=8294&&n<=8297||n===65279)return!0}return!1}function gd(e){let t=od(e);if(t!==void 0)return pd(t);let n=sd(e);if(n!==void 0)return md(n);let r=e.split(`.`);return r.length===1||r.some(e=>e.length===0||e.length>63)||e.length>253||e===`localhost`||e.endsWith(`.localhost`)||e===`local`||e.endsWith(`.local`)||e===`internal`||e.endsWith(`.internal`)||e===`home.arpa`||e.endsWith(`.home.arpa`)?`non-public-or-special-literal`:`hostname-requires-resolution`}function _d(e){let t=e.hostname.toLowerCase();if(t.startsWith(`[`)&&t.endsWith(`]`))t=t.slice(1,-1);else if(t.endsWith(`.`)&&(t=t.slice(0,-1),t.endsWith(`.`)))return;return t.length===0?void 0:t}function vd(e){return e.length>16384||new TextEncoder().encode(e).byteLength>16384}function yd(e){if(typeof e!=`string`||e.length===0)return{ok:!1,reason:`empty`};if(e.length>16384)return{ok:!1,reason:`too-large`};if(e!==e.trim())return{ok:!1,reason:`empty`};if(hd(e))return{ok:!1,reason:`unsafe-unicode`};if(vd(e))return{ok:!1,reason:`too-large`};if(e.includes(`\\`))return{ok:!1,reason:`malformed`};let t=/^([a-z][a-z0-9+.-]*):/i.exec(e)?.[1]?.toLowerCase();if(t!==`http`&&t!==`https`)return{ok:!1,reason:t?`unsupported-scheme`:`malformed`};if(!/^https?:\/\/[^/?#]/i.test(e))return{ok:!1,reason:`malformed`};let n;try{n=new URL(e)}catch{return{ok:!1,reason:`malformed`}}if(n.protocol!==`http:`&&n.protocol!==`https:`)return{ok:!1,reason:`unsupported-scheme`};if(n.hash.length>0)return{ok:!1,reason:`malformed`};let r=_d(n);if(!r)return{ok:!1,reason:`malformed`};let i=n.port.length>0?Number(n.port):n.protocol===`https:`?443:80;return!Number.isSafeInteger(i)||i<1||i>65535?{ok:!1,reason:`malformed`}:{ok:!0,value:{url:n,hostClassification:gd(r)}}}var bd=Object.freeze({empty:`Refusing to fetch an empty URL.`,"too-large":`Refusing to fetch an oversized URL.`,malformed:`Refusing to fetch a malformed URL.`,"unsupported-scheme":`Refusing to fetch an unsupported URL scheme.`,"unsafe-unicode":`Refusing to fetch a URL containing unsafe characters.`,"non-public-or-special-host":`Refusing to fetch a non-public or special address.`}),xd=class extends Error{constructor(e){super(bd[e]),this.reason=e,this.name=`UnsafeFetchUrlError`}};function Sd(e){let t=yd(e);if(!t.ok)throw new xd(t.reason);if(t.value.hostClassification===`non-public-or-special-literal`)throw new xd(`non-public-or-special-host`);let n=ed(t.value.url.href);if(vd(n))throw new xd(`too-large`);return new URL(n)}function Cd(e){try{return Sd(e),!0}catch{return!1}}var wd=/\{\{(.*?)(:\s*.*?)?\}\}/g;function Td(e,t){return Array.from(e.matchAll(wd)).some(([,e])=>e.toLowerCase()===t)}function Ed(){let e={};function t(t,n){e[t]=n}function n(t){return t.replace(wd,(t,n,i)=>{let a=e[n.toLowerCase()];if(a==null){let i=new wu(Object.keys(e),{shouldSort:!0,findAllMatches:!1,threshold:.4,isCaseSensitive:!1}).search(n);return new r.Notice(`Tag ${n} is invalid.${i.length>0?` Did you mean ${i[0].item}?`:``}`),t}if(typeof a==`function`){let e=i?i.slice(1):``;return e===``?a():a(e)}return a})}return[n,t]}function Dd(e){return e.episodeNumber??Mu(e.title)}function Od(e,t=Jd){return n=>{let r=t(e);return n?r.replace(/\s+/g,n):r}}function kd(e,t,n=Jd){e(`title`,Od(t.title,n)),e(`podcast`,Od(t.podcastName,n)),e(`date`,e=>t.episodeDate?Eu(t.episodeDate,e??`YYYY-MM-DD`):``),e(`currentdate`,e=>Eu(new Date,e??`YYYY-MM-DD`)),e(`episodenumber`,e=>ku(Dd(t),e))}function Ad(e){return e.replace(/\s+/g,` `).trim()}function jd(e){return e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/[\\`*_{}[\]()#+.!|=~$%^-]/g,`\\$&`)}function Md(e){return jd(e.replace(/[\u0000-\u001f\u007f]+/g,` `).trim())}function Nd(e){return e.replace(/(`{3,}|~{3,})[ \t]*(?:dataviewjs|dataview)\b/gi,`$1text`)}function Pd(e){return e.replace(/\\*!\[/g,e=>{let t=e.length-2,n=t%2==0?t+1:t;return`${`\\`.repeat(n)}![`})}function Fd(e){let t=new DOMParser().parseFromString(e,`text/html`);for(let e of t.querySelectorAll(`img, audio, video, source, iframe, object, embed, link`)){let n=e instanceof HTMLImageElement?e.alt.trim():``;e.replaceWith(t.createTextNode(n))}return Pd(Nd((0,r.htmlToMarkdown)(t.body.innerHTML)))}function Id(e,t){let n=Xu(e??[]).map(e=>{let t=Ad(e.title),n=t?` ${jd(t)}`:``;return`- ${Ou(e.startTime)}${n}`});return t?n.map(e=>`${t}${e}`).join(`
|
||
`):n.join(`
|
||
`)}function Ld(e){return Pu(e)&&e.filePath?e.url:Kd(e.url)}function Rd(e,t,n={}){let[r,i]=Ed(),a=Ld(t);i(`title`,Md(t.title)),i(`description`,e=>{let n=Fd(t.description).replace(/\n{3,}/g,`
|
||
|
||
`);return e?n.split(`
|
||
`).map(t=>`${e}${t}`).join(`
|
||
`):n}),i(`content`,e=>e?Fd(t.content).split(`
|
||
`).map(t=>`${e}${t}`).join(`
|
||
`):Fd(t.content)),i(`safetitle`,Jd(t.title)),i(`stream`,qd(t.streamUrl)),i(`url`,a),i(`date`,e=>t.episodeDate?Eu(t.episodeDate,e??`YYYY-MM-DD`):``),i(`currentdate`,e=>Eu(new Date,e??`YYYY-MM-DD`)),i(`episodenumber`,e=>ku(Dd(t),e)),i(`duration`,e=>t.duration===void 0?``:Ou(t.duration,e)),i(`chapters`,e=>Id(n.chapters,e)),i(`podcast`,Jd(t.podcastName)),i(`artwork`,qd(t.artworkUrl??``)),i(`episodeurl`,a),i(`episodeartwork`,qd(t.artworkUrl??``)),i(`feedurl`,Kd(t.feedUrl??``));let o=E(L)?.settings?.savedFeeds?.[t.podcastName];return i(`feedartwork`,qd(o?.artworkUrl??t.artworkUrl??``)),i(`podcastlink`,Gd(t.podcastName)),i(`episodelink`,Fu(t)),r(e)}function zd(e,t={}){let[n,r]=Ed(),{api:i,settings:a}=E(L),o=a.timestamp.offset??0;return r(`time`,e=>i.getPodcastTimeFormatted(e??`HH:mm:ss`,!1,o)),r(`linktime`,e=>i.getPodcastTimeFormatted(e??`HH:mm:ss`,!0,o)),r(`segment`,e=>t.segment?i.getPodcastSegmentFormatted(e??`HH:mm:ss`,t.segment.startTime,t.segment.endTime,!1):i.getPodcastTimeFormatted(e??`HH:mm:ss`,!1,o)),r(`linksegment`,e=>t.segment?i.getPodcastSegmentFormatted(e??`HH:mm:ss`,t.segment.startTime,t.segment.endTime,!0):i.getPodcastTimeFormatted(e??`HH:mm:ss`,!0,o)),n(e)}function Bd(e,t,n=Jd){let[r,i]=Ed();return kd(i,t,n),r(e)}function Vd(e,t){let n=Tu(e),r=n?e.replace(RegExp(`\\.${n.replace(/[.*+?^${}()|[\]\\]/g,`\\$&`)}$`,`i`),``):e,[i,a]=Ed();return kd(a,t),i(r)}function Hd(e,t,n){let[r,i]=Ed();return kd(i,t),i(`duration`,e=>t.duration===void 0?``:Ou(t.duration,e)),i(`transcript`,n),i(`description`,e=>e?Fd(t.description).split(`
|
||
`).map(t=>`${e}${t}`).join(`
|
||
`):Fd(t.description)),i(`url`,Ld(t)),i(`artwork`,qd(t.artworkUrl??``)),r(e)}function Ud(e,t){let[n,r]=Ed(),i=Jd(t.title);return r(`title`,Md(t.title)),r(`safetitle`,i),r(`podcast`,i),r(`url`,Kd(t.link??``)),r(`feedurl`,Kd(t.url)),r(`artwork`,qd(t.artworkUrl??``)),r(`feedartwork`,qd(t.artworkUrl??``)),r(`author`,Md(t.author??``)),r(`description`,e=>{let n=Fd(t.description??``).replace(/\n{3,}/g,`
|
||
|
||
`);return e?n.split(`
|
||
`).map(t=>`${e}${t}`).join(`
|
||
`):n}),r(`date`,e=>Eu(new Date,e??`YYYY-MM-DD`)),n(e)}function Wd(e,t){let[n,r]=Ed(),i=Od(t.title);return r(`title`,i),r(`podcast`,i),r(`date`,e=>Eu(new Date,e??`YYYY-MM-DD`)),n(e)}function Gd(e){let t=Jd(e),n=E(L)?.settings?.feedNote?.path?.trim();if(!n)return`[[${t}]]`;let r=qu(Iu(Wd(n,{title:e,url:``,artworkUrl:``}),`md`)).replace(/\.md$/i,``).trim(),i=r.split(`/`).pop()?.trim()||t;return r.includes(`/`)?`[[${r}|${i}]]`:`[[${i}]]`}function Kd(e){return e.replace(/[\u0000-\u0020"'`()[\]<>\\]/g,e=>`%${e.charCodeAt(0).toString(16).toUpperCase().padStart(2,`0`)}`)}function qd(e){if(!e||!Cd(e))return``;let t=new URL(e);return t.username||t.password?``:Kd(e)}function Jd(e){return e.replace(/[\\,#%&{}/*<>$'":@\u2023|?[\]]/g,``).replace(/[\u0000-\u001f]/g,` `).replace(/\s+/g,` `).trim().replace(/^\.+/,``).replace(/\.+$/,``).trim()}function Yd(e){return e.replace(/[\\,#%&{}/*<>$'":@\u2023|\\.?]/g,``).replace(/\n/g,` `).replace(` `,` `)}function Xd(e){return e.replace(/^\s*(?:>\s?)+/,``)}function Zd(e){return Xd(e).includes(`|`)}function Qd(e){let t=Xd(e).trim();if(!t.includes(`|`))return!1;let n=t.replace(/^\|/,``).replace(/\|$/,``).split(`|`);return n.length>0&&n.every(e=>/^\s*:?-+:?\s*$/.test(e))}function $d(e,t,n){let r=e(n);if(!r||!Zd(r))return!1;for(let t=n;t>=0;t--){let n=e(t);if(!n||!Zd(n))break;if(Qd(n))return!0}for(let r=n;r<t;r++){let t=e(r);if(!t||!Zd(t))break;if(Qd(t))return!0}return!1}function ef(e){return e.replace(/\r\n?|\n/g,` `).replace(/(\\*)\|/g,(e,t)=>t.length%2==0?`${t}\\|`:e)}function tf(e,t){return $d(t.getLine,t.lineCount,t.cursorLine)?ef(e):e}function nf(e,t){if(!Number.isFinite(e)||!Number.isFinite(t))return null;let n={startTime:Math.max(0,e),endTime:Math.max(0,t)};return n.endTime>n.startTime?n:null}function rf(e,t,n=0){if(!Number.isFinite(e)||!Number.isFinite(t)||t<=0)return null;let r=Math.max(0,e-n);return nf(Math.max(0,r-t),r)}function af(e,t,n){return`${Du(Math.max(0,e),n)}-${Du(Math.max(0,t),n)}`}function of(e){if(/\{\{(?:linksegment|segment)(?::\s*?.+?)?\}\}/i.test(e))return e;let t=e.replace(/\{\{linktime(:\s*?.+?)?\}\}/gi,`{{linksegment$1}}`).replace(/\{\{time(:\s*?.+?)?\}\}/gi,`{{segment$1}}`);return t===e?`- {{linksegment}}`:t}async function sf(e,t=E(L).app.vault,n){let r=e.split(`/`).filter(Boolean),i=``;for(let e of r)if(n?.(),i=i?`${i}/${e}`:e,!t.getAbstractFileByPath(i)){try{await t.createFolder(i)}catch(e){if(n?.(),!(e instanceof Error&&/already exists/i.test(e.message))&&!t.getAbstractFileByPath(i))throw e}n?.()}}var cf=Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,`byteLength`)?.get,lf={"invalid-options":`Network request options are invalid.`,"unsafe-target":`Network request target is not allowed.`,"request-too-large":`Network request body exceeds the configured limit.`,"response-too-large":`Network response exceeds the configured limit.`,"unexpected-status":`Network response status is not accepted.`,timeout:`Network request timed out.`,aborted:`Network request was aborted.`,"transport-failure":`Network request failed.`,"invalid-response":`Network response is invalid.`},uf=new Set(Object.keys(lf)),df=class extends Error{constructor(e,t){let n=e===`unexpected-status`&&Number.isSafeInteger(t)&&t!==void 0&&t>=100&&t<=599?t:void 0;super(n===void 0?lf[e]:`Network response returned HTTP ${n}.`),this.code=e,this.name=`NetworkError`,this.status=n}},ff=class extends df{constructor(){super(`timeout`),this.name=`TimeoutError`}};function pf(e,t){try{if(e instanceof df){let t=e.code;if(typeof t==`string`&&uf.has(t)){let n=t;return n===`timeout`?new ff:new df(n,e.status)}}}catch{}return new df(t)}function mf(){return new df(`invalid-options`)}function hf(e){return typeof e==`number`&&Number.isSafeInteger(e)&&e>=0}function gf(e){if(e!==void 0){if(typeof e!=`object`||!e)throw mf();try{let t=Reflect.get(e,`addEventListener`),n=Reflect.get(e,`removeEventListener`);if(typeof t!=`function`||typeof n!=`function`)throw mf();return{target:e,addEventListener:t,removeEventListener:n}}catch{throw mf()}}}function _f(e){try{let t=Reflect.get(e.target,`aborted`);if(typeof t!=`boolean`)throw mf();return t}catch{throw mf()}}function vf(e,t){try{Reflect.apply(e.addEventListener,e.target,[`abort`,t,{once:!0}])}catch{throw mf()}}function yf(e,t){try{Reflect.apply(e.removeEventListener,e.target,[`abort`,t])}catch{}}function bf(e){if(!(typeof e!=`object`||!e||cf===void 0))try{let t=Reflect.apply(cf,e,[]);return Number.isSafeInteger(t)&&t>=0?t:void 0}catch{return}}function xf(e){if(e!==void 0){if(typeof e!=`object`||!e||Array.isArray(e))throw mf();try{let t=Object.create(null);for(let[n,r]of Object.entries(e)){if(typeof r!=`string`)throw mf();t[n]=r}return t}catch{throw mf()}}}function Sf(e){if(typeof e!=`object`||!e||Array.isArray(e))throw mf();try{return{timeoutMs:Reflect.get(e,`timeoutMs`),maxRequestBodyBytes:Reflect.get(e,`maxRequestBodyBytes`),maxResponseBytes:Reflect.get(e,`maxResponseBytes`),acceptedStatuses:Reflect.get(e,`acceptedStatuses`),signal:Reflect.get(e,`signal`),method:Reflect.get(e,`method`),contentType:Reflect.get(e,`contentType`),headers:Reflect.get(e,`headers`),body:Reflect.get(e,`body`),request:Reflect.get(e,`request`)}}catch{throw mf()}}function Cf(e){if(e!==void 0){if(!Array.isArray(e))throw mf();try{let t=Reflect.get(e,`length`);if(!Number.isSafeInteger(t)||t<1||t>500)throw mf();let n=new Set;for(let r=0;r<t;r+=1){let t=Reflect.get(e,String(r));if(!Number.isSafeInteger(t)||t<100||t>599)throw mf();n.add(t)}return n}catch{throw mf()}}}function wf(e){try{let t=Sf(e),n=t.timeoutMs??3e4,i=t.maxRequestBodyBytes??16777216,a=t.maxResponseBytes??33554432;if(typeof n!=`number`||!Number.isSafeInteger(n)||n<1||n>2147483647||!hf(i)||!hf(a)||t.method!==void 0&&typeof t.method!=`string`||t.contentType!==void 0&&typeof t.contentType!=`string`||t.request!==void 0&&typeof t.request!=`function`)throw mf();let o=Cf(t.acceptedStatuses),s=gf(t.signal),c=xf(t.headers),l=Ef(t.body,i);return{timeoutMs:n,maxRequestBodyBytes:i,maxResponseBytes:a,acceptedStatuses:o,signal:s,method:t.method,contentType:t.contentType,headers:c,body:l,request:t.request??r.requestUrl}}catch(e){throw pf(e,`invalid-options`)}}function Tf(e,t){let n=0;for(let r=0;r<e.length;r+=1){let i=e.charCodeAt(r),a;if(i<=127)a=1;else if(i<=2047)a=2;else if(i>=55296&&i<=56319){let t=e.charCodeAt(r+1);t>=56320&&t<=57343?(a=4,r+=1):a=3}else a=3;if(a>t-n)return null;n+=a}return n}function Ef(e,t){if(e===void 0)return;if(typeof e==`string`){if(Tf(e,t)===null)throw new df(`request-too-large`);return e}let n=bf(e);if(n===void 0)throw mf();if(n>t)throw new df(`request-too-large`);return e}function Df(e){try{return Sd(e).href}catch{throw new df(`unsafe-target`)}}function Of(e,t,n,r){return new Promise((i,a)=>{let o=!1,s,c=!1,l=()=>{s!==void 0&&window.clearTimeout(s),r&&c&&yf(r,f)},u=e=>{o||(o=!0,l(),a(e))},d=e=>{o||(o=!0,l(),i(e))},f=()=>u(new df(`aborted`));try{if(r&&(c=!0,vf(r,f),_f(r)&&f()),o)return;s=window.setTimeout(()=>u(new ff),n)}catch{u(mf());return}let p;try{p=e(t)}catch(e){u(pf(e,`transport-failure`));return}Promise.resolve(p).then(d,()=>{u(new df(`transport-failure`))})})}function kf(e){try{return{status:Reflect.get(e,`status`),headers:Reflect.get(e,`headers`),arrayBuffer:Reflect.get(e,`arrayBuffer`)}}catch{throw new df(`invalid-response`)}}function Af(e){try{return{status:Reflect.get(e,`status`),arrayBuffer:Reflect.get(e,`arrayBuffer`),text:Reflect.get(e,`text`)}}catch{throw new df(`invalid-response`)}}function jf(e,t){if(!Number.isSafeInteger(e)||e<100||e>599)throw new df(`invalid-response`);return{status:e,arrayBuffer:t}}function Mf(e){if(typeof e!=`object`||!e||Array.isArray(e))throw new df(`invalid-response`);try{let t=Object.create(null);for(let[n,r]of Object.entries(e)){if(typeof r!=`string`)throw new df(`invalid-response`);t[n]=r}return Object.freeze(t)}catch{throw new df(`invalid-response`)}}function Nf(e,t,n){let r=bf(e.arrayBuffer);if(r===void 0)throw new df(`invalid-response`);if(r>t)throw new df(`response-too-large`);if(!(n?n.has(e.status):e.status>=200&&e.status<300))throw new df(`unexpected-status`,e.status)}function Pf(e,t,n){try{if(typeof e!=`object`||!e)throw new df(`invalid-response`);let{status:r,headers:i,arrayBuffer:a}=kf(e),o=jf(r,a),s=Mf(i);return Nf(o,t,n),Object.freeze({...o,headers:s})}catch(e){throw pf(e,`invalid-response`)}}function Ff(e,t,n){try{if(typeof e!=`object`||!e)throw new df(`invalid-response`);let{status:r,arrayBuffer:i,text:a}=Af(e);if(typeof a!=`string`)throw new df(`invalid-response`);let o=jf(r,i);if(Nf(o,t,n),Tf(a,t)===null)throw new df(`response-too-large`);return Object.freeze({...o,text:a})}catch(e){throw pf(e,`invalid-response`)}}async function If(e,t,n){let r=wf(t),i={method:r.method,contentType:r.contentType,headers:r.headers,body:r.body,throw:!1,url:Df(e)};return n(await Of(r.request,i,r.timeoutMs,r.signal),r.maxResponseBytes,r.acceptedStatuses)}async function Lf(e,t={}){return If(e,t,Pf)}async function Rf(e,t={}){let n=await If(e,t,Ff);try{return JSON.parse(n.text)}catch{throw new df(`invalid-response`)}}async function zf(e,t={}){return(await If(e,t,Ff)).text}var Bf=1e6,Vf=Bf*4,Hf=1e4;async function Uf(e){if(!e)return[];try{let t=await zf(e,{timeoutMs:Hf,maxResponseBytes:Vf,acceptedStatuses:[200]});if(t.length>Bf)return[];let n=JSON.parse(t);return!n.chapters||!Array.isArray(n.chapters)?[]:Xu(n.chapters)}catch{return[]}}var Wf=.75;function Gf(e){let t=e.toLowerCase().replace(/[^a-z0-9]+/g,` `).trim().split(/\s+/).filter(Boolean);return new Set(t)}function Kf(e){let t=new Set;for(let n of e)t.add(/^\d+$/.test(n)?String(Number(n)):n);return t}function qf(e){let t=new Set;for(let n of e)/^\d+$/.test(n)&&t.add(n);return t}function Jf(e,t){let n=qf(e),r=qf(t);if(n.size===0||r.size===0)return!1;if(n.size!==r.size)return!0;for(let e of n)if(!r.has(e))return!0;return!1}function Yf(e,t){let n=Kf(Gf(e)),r=Kf(Gf(t));if(n.size===0||r.size===0||Jf(n,r))return 0;let i=0;for(let e of n)r.has(e)&&(i+=1);return i/(n.size+r.size-i)}function Xf(e,t,n,r=Wf){let i=[];for(let a of t){let t=n(a),o=0;for(let n of e)o=Math.max(o,Yf(n,t));o>=r&&i.push({candidate:a,score:o})}if(i.length===1)return i[0].candidate}function Zf(e){return Qf(E(L).settings.note.path,e)}function Qf(e,t,n){return qu(Iu(Bd(e,t,n),`md`))}function $f(e){let t=E(L).settings.note.path;return[...new Set([Qf(t,e),Qf(t,e,Yd)])]}function ep(e){let t=e.lastIndexOf(`/`);return t===-1?``:e.slice(0,t)}function tp(e){return(e.split(`/`).pop()??``).replace(/\.md$/i,``)}function np(e){return[...new Set([Bd(`{{title}}`,e),Bd(`{{title}}`,e,Yd)])]}async function rp(e){try{let t=await ip(e);E(L).app.workspace.getLeaf().openFile(t)}catch{new r.Notice(`Failed to create note: "${Zf(e)}"`)}}async function ip(e){let t=op(e);if(t)return new r.Notice(`Note for "${e.title}" already exists`),t;let n=E(L),i=Zf(e),a=n.settings.note.template;return await lp(i,Rd(a,e,{chapters:await ap(a,e)}),e)}async function ap(e,t){if(!(!t.chaptersUrl||!Td(e,`chapters`)))return await Uf(t.chaptersUrl)}function op(e){let{vault:t}=E(L).app;for(let n of $f(e)){let e=t.getAbstractFileByPath(n);if(e instanceof r.TFile)return e}return sp(e)}function sp(e){let{vault:t}=E(L).app;if(typeof t.getMarkdownFiles!=`function`)return null;let n=ep(Zf(e)),i=t.getMarkdownFiles().filter(e=>ep(e.path)===n&&e instanceof r.TFile);return Xf(np(e),i,e=>tp(e.path))??null}function cp(e){let t=op(e);if(!t){new r.Notice(`Note for "${e.title}" does not exist`);return}E(L).app.workspace.getLeaf().openFile(t)}async function lp(e,t,n){let i=op(n);if(i)return new r.Notice(`Note for "${n.title}" already exists`),i;await sf(e.split(`/`).slice(0,-1).join(`/`));let{app:a}=E(L);try{return await a.vault.create(e,t)}catch(t){let n=a.vault.getAbstractFileByPath(e);if(n instanceof r.TFile)return n;throw t}}var up=new Set([`mp3`,`m4a`,`aac`,`ogg`,`wav`,`flac`,`wma`,`amr`]),dp=new Set([`mp4`,`m4v`,`mov`,`webm`,`ogv`]);[...up,...dp];function fp(e){if(!e)return null;let t=e.toLowerCase();return dp.has(t)?`video`:up.has(t)?`audio`:null}function pp(e){return fp(e)!==null}function mp(e){if(!e)return null;let t=e.split(`;`)[0].trim().toLowerCase();return t.startsWith(`video/`)?`video`:t.startsWith(`audio/`)?`audio`:null}function hp(e){return e?fp(Tu(e)):null}function gp(e){if(!e)return null;let t=Tu(e);return vp(t)?null:fp(t)}function _p(e){if(e.mediaType)return e.mediaType;let t=e.filePath;return gp(t)||(gp(e.streamUrl)??`audio`)}function vp(e){if(!e)return!1;let t=e.toLowerCase();return t===`mp4`||t===`webm`}function yp(e,t){if(e.mediaType)return e.mediaType;let n=e.filePath,r=n?Tu(n):null;return t&&vp(r)?t:_p(e)}function bp(e,t){if(e===t)return!0;if(!e||!t)return!1;try{let n=new URL(e),r=new URL(t);if(n.origin!==r.origin||n.pathname!==r.pathname)return!1;if(n.search===r.search)return!0;let i=Sp(n.searchParams),a=Sp(r.searchParams);return xp(i,a)?!0:(hp(n.pathname)!==null||hp(r.pathname)!==null)&&i.length===0&&a.length===0}catch{return!1}}function xp(e,t){return e.length===0||t.length===0||e.length!==t.length?!1:e.every((e,n)=>e===t[n])}function Sp(e){return Array.from(e.entries()).filter(([e])=>!Cp(e)).map(([e,t])=>`${e.toLowerCase()}=${t}`).sort()}function Cp(e){let t=e.toLowerCase();return t===`token`||t===`access_token`||t===`auth`||t===`authorization`||t===`signature`||t===`sig`||t===`expires`||t===`expiry`||t===`exp`||t===`policy`||t===`key-pair-id`||t.startsWith(`x-amz-`)}var wp=31622400;function Tp(e){if(e==null)return;let t=e.trim();if(!t)return;let n;if(t.includes(`:`)){let e=t.split(`:`).map(e=>e.trim());if(e.length>3||e.some(e=>!/^\d+$/.test(e)))return;n=e.reduce((e,t)=>e*60+Number(t),0)}else{if(!/^\d+(\.\d+)?$/.test(t))return;n=Math.floor(Number(t))}if(!(!Number.isFinite(n)||n>wp))return n}var Ep=`http://www.w3.org/1999/xhtml`;function Dp(e){let t=e.documentElement;return!t||t.localName.toLowerCase()===`parsererror`||Array.from(e.getElementsByTagName(`parsererror`)).some(e=>e.namespaceURI===Ep&&e.parentElement===t)}var Op=class{parseFeed(e,t){return this.extractFeed(this.parseXml(e),t)}parseEpisodes(e,t){let n=this.parseXml(e);return{feed:this.extractFeed(n,t),episodes:this.parsePage(n)}}parseEpisodeItems(e){return this.parsePage(this.parseXml(e))}parseXml(e){let t=new DOMParser().parseFromString(e,`text/xml`);if(Dp(t))throw Error(`Invalid RSS feed`);return t}extractFeed(e,t){let n=e.querySelector(`title`);if(!n)throw Error(`Invalid RSS feed`);let r=e.querySelector(`channel`)??e,i=this.findChannelImageElement(r),a=i?.getAttribute(`href`)||i?.querySelector(`url`)?.textContent||``,o=this.findFeedLink(r),s=this.findDirectChildText(r,[`description`,`itunes:summary`]),c=this.findDirectChildText(r,[`itunes:author`,`author`,`managingEditor`]),l=this.findDirectChildText(r,[`podcast:guid`,`id`]);return{title:n.textContent||``,subscriptionUrl:t,...a?{artworkUrl:a}:{},...o?{siteUrl:o}:{},...s?{description:s}:{},...c?{author:c}:{},...l?{guid:l}:{}}}findImageElement(e){return e.getElementsByTagName(`itunes:image`)[0]??e.querySelector(`image`)}findChannelImageElement(e){let t=Array.from(e.children);return t.find(e=>e.tagName.toLowerCase()===`itunes:image`)||(t.find(e=>e.tagName.toLowerCase()===`image`)??null)}findFeedLink(e){let t=Array.from(e.children).filter(e=>{let t=e.tagName.toLowerCase();return t===`link`||t===`atom:link`});for(let e of t){let t=e.textContent?.trim();if(t&&/^https?:\/\//i.test(t))return t}for(let e of t){let t=e.getAttribute(`rel`);if(t&&t!==`alternate`)continue;let n=e.getAttribute(`href`)?.trim();if(n&&/^https?:\/\//i.test(n))return n}return``}findDirectChildText(e,t){let n=Array.from(e.children);for(let e of t){let t=e.toLowerCase();for(let e of n){if(e.tagName.toLowerCase()!==t)continue;let n=e.textContent?.trim()??``;if(n)return n}}return``}parsePage(e){return Array.from(e.querySelectorAll(`item`)).map(e=>this.parseItem(e)).filter(e=>e!==null)}parseItem(e){let t=e.querySelector(`title`),n=e.querySelector(`enclosure`),r=e.querySelector(`pubDate`);if(!t||!n||!r)return null;let i=t.textContent||``,a=n.getAttribute(`url`)||``,o=e.querySelector(`link`)?.textContent||``,s=e.querySelector(`description`)?.textContent||``,c=e.querySelector(`*|encoded`)?.textContent||``,l=Qa(r.textContent),u=this.findImageElement(e)?.getAttribute(`href`)||``,d=e.getElementsByTagName(`itunes:title`)[0]?.textContent||``,f=Au(e.getElementsByTagName(`itunes:episode`)[0]?.textContent,i),p=Tp(e.getElementsByTagName(`itunes:duration`)[0]?.textContent),m=e.getElementsByTagName(`podcast:chapters`)[0]?.getAttribute(`url`)||``,h=this.findDirectChildText(e,[`guid`]),g=n.getAttribute(`type`);return{title:i,streamUrl:a,...o?{itemLink:o}:{},description:s,content:c,...u?{artworkUrl:u}:{},...l?{episodeDate:l}:{},...d?{itunesTitle:d}:{},...f===void 0?{}:{episodeNumber:f},...p===void 0?{}:{duration:p},...m?{chaptersUrl:m}:{},...h?{guid:h}:{},mediaType:mp(g)??gp(a)??`audio`}}},kp=3e4,Ap=16777216,jp=Object.freeze({async load(e){return zf(e,{timeoutMs:kp,maxResponseBytes:Ap,acceptedStatuses:[200]})}}),Mp=new Op;function Np(e){return{title:e.title,url:e.subscriptionUrl,artworkUrl:e.artworkUrl??``,...e.siteUrl?{link:e.siteUrl}:{},...e.description?{description:e.description}:{},...e.author?{author:e.author}:{}}}function Pp(e,t){return{title:e.title,streamUrl:e.streamUrl,url:e.itemLink||t.url,description:e.description,content:e.content,podcastName:t.title,artworkUrl:e.artworkUrl||t.artworkUrl,episodeDate:e.episodeDate,feedUrl:t.url,itunesTitle:e.itunesTitle||``,episodeNumber:e.episodeNumber,duration:e.duration,chaptersUrl:e.chaptersUrl,mediaType:e.mediaType}}var Fp=class{constructor(e,t=jp){if(this.source=t,typeof t?.load!=`function`)throw TypeError(`A feed document source is required.`);this.feed=e}async getEpisodes(e){let t=await this.source.load(e),n=this.feed;if(n&&(n.url===e||n.urlSecretId))return Mp.parseEpisodeItems(t).map(e=>Pp(e,n));let r=Mp.parseEpisodes(t,e),i=Np(r.feed);return this.feed=i,r.episodes.map(e=>Pp(e,i))}async getFeed(e){let t=await this.source.load(e);return this.feed=Np(Mp.parseFeed(t,e)),this.feed}},Ip=`podnotes-private-feed:`,Lp=/^(auth|token|key|secret|pass|password|apikey|api[-_]key|access[-_]token|sig|signature|jwt|credential|credentials)$/i;function Rp(e){let t;try{t=new URL(e)}catch{return!1}if(t.protocol!==`http:`&&t.protocol!==`https:`)return!1;if(t.username.length>0||t.password.length>0)return!0;for(let e of t.searchParams.keys())if(Lp.test(e))return!0;return!1}function zp(e){return`${Ip}${encodeURIComponent(e)}`}function Bp(e){return e.startsWith(Ip)}function Vp(e){if(!Bp(e))return null;try{return decodeURIComponent(e.slice(22))}catch{return null}}function Hp(e,t,n=e.title){if(!Rp(e.url))return e;try{let r=t.store(e.url);return{...e,url:zp(n),urlSecretId:r}}catch{return e}}function Up(e,t){return e.urlSecretId?t.resolve(e.urlSecretId):Bp(e.url)?null:e.url}function Wp(e,t){let n=Up(e,t);return n===null&&new r.Notice(`The private feed URL for "${e.title}" is not available on this device. Remove the feed and add it again with its private URL.`),n}function Gp(e,t){let n=new Map,r=[],i={};for(let[a,o]of Object.entries(e)){let e=Hp(o,t,a);e===o?Rp(o.url)&&r.push(a):n.set(o.url,e.url),i[a]=e}return{savedFeeds:i,replacements:n,failed:r}}function Kp(e,t){if(t.size===0)return e;if(Array.isArray(e))return e.map(e=>Kp(e,t));if(typeof e!=`object`||!e||Object.getPrototypeOf(e)!==Object.prototype)return e;let n=e,r=!1,i={};for(let[e,a]of Object.entries(n)){let n;n=(e===`url`||e===`feedUrl`)&&typeof a==`string`?t.get(a)??a:Kp(a,t),n!==a&&(r=!0),i[e]=n}return r?i:e}function qp(e){return qu(Iu(Wd(E(L).settings.feedNote.path,e),`md`))}function Jp(e){let t=qp(e),n=E(L).app.vault.getAbstractFileByPath(t);return!n||!(n instanceof r.TFile)?null:n}function Yp(e){let t=Jp(e);if(!t){new r.Notice(`Note for "${e.title}" does not exist`);return}E(L).app.workspace.getLeaf().openFile(t)}async function Xp(e){let{path:t,template:n}=E(L).settings.feedNote;if(!t||!n){new r.Notice(`Please set a podcast feed note path and template in the settings.`);return}let i=Jp(e);if(i){new r.Notice(`Note for "${e.title}" already exists`),E(L).app.workspace.getLeaf().openFile(i);return}let a=qp(e),o=Ud(n,await Zp(e));try{let t=await Qp(a,o,e);E(L).app.workspace.getLeaf().openFile(t)}catch{new r.Notice(`Failed to create note: "${a}"`)}}async function Zp(e){if(!(!e.description||!e.link||!e.author)||!e.url)return e;let t=Up(e,E(L).feedUrls);if(t===null)return e;try{let n=await new Fp(e).getFeed(t);return{...e,description:e.description||n.description,link:e.link||n.link,author:e.author||n.author}}catch{return e}}async function Qp(e,t,n){let i=Jp(n);if(i)return new r.Notice(`Note for "${n.title}" already exists`),i;await sf(e.split(`/`).slice(0,-1).join(`/`));let{app:a}=E(L);try{return await a.vault.create(e,t)}catch(t){let n=a.vault.getAbstractFileByPath(e);if(n instanceof r.TFile)return n;throw t}}function $p(e,t){return t?[...e.filter(e=>e.title===t),...e.filter(e=>e.title!==t)]:e}var em=class extends r.FuzzySuggestModal{constructor(e,t,n){super(e),this.feeds=t,this.onChoose=n,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)}},tm=[{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 nm(e){if(!e)return null;for(let{pattern:t,extension:n}of tm)if(t.test(e))return n;return null}var rm=4194304,im=2147483648,am=9e5,om=3e5;function sm(e){let t=Math.round(e/1048576);return Error(`Download exceeds the maximum allowed size (${t} MB). Aborting.`)}function cm(){return E(L).app.vault.adapter}function lm(e,t){if(!e)return;let n=e[t]??e[t.toLowerCase()];if(n!==void 0)return n;let r=t.toLowerCase();for(let t of Object.keys(e))if(t.toLowerCase()===r)return e[t]}async function um(e,t=rm,n=im){let r;try{r=await Lf(e,{method:`GET`,headers:{Range:`bytes=0-${t-1}`},timeoutMs:am,maxResponseBytes:n,acceptedStatuses:[200,206]})}catch(e){throw e instanceof df&&e.code===`response-too-large`?sm(n):e}let i=lm(r.headers,`content-type`)??``,a=r.status===206,o=null;if(a){let e=lm(r.headers,`content-range`)?.match(/\/(\d+)\s*$/);e&&(o=Number.parseInt(e[1],10))}else{let e=lm(r.headers,`content-length`);if(e){let t=Number.parseInt(e,10);Number.isFinite(t)&&(o=t)}}if(o!==null&&o>n||!a&&r.arrayBuffer.byteLength>n)throw sm(n);return{firstChunk:r.arrayBuffer,contentType:i,supportsRange:a,totalSize:o}}async function dm(e,t,n,r,i=rm,a=im){Sd(e);let o=cm();if(n.firstChunk.byteLength>a)throw sm(a);await o.writeBinary(t,n.firstChunk);let s=n.firstChunk.byteLength;if(r?.(s,n.totalSize),!n.supportsRange||typeof o.appendBinary!=`function`)return s;for(;!(n.totalSize!==null&&s>=n.totalSize);){let c=n.totalSize===null?s+i-1:Math.min(s+i,n.totalSize)-1,l;try{l=await Lf(e,{method:`GET`,headers:{Range:`bytes=${s}-${c}`},timeoutMs:om,maxResponseBytes:a-s,acceptedStatuses:[206,416]})}catch(e){throw e instanceof df&&e.code===`response-too-large`?sm(a):e}if(l.status===416)break;let u=l.arrayBuffer;if(u.byteLength===0)break;if(await o.appendBinary(t,u),s+=u.byteLength,r?.(s,n.totalSize),s>a)throw sm(a);if(n.totalSize===null&&u.byteLength<i)break}return s}var fm=`.podnotes-partial`,pm=0;function mm(e){let t=e.lastIndexOf(`/`),n=t===-1?``:e.slice(0,t+1),r=t===-1?e:e.slice(t+1);return qu(`${n}.${`${Date.now().toString(36)}-${(pm++).toString(36)}`}.${r}${fm}`,fm)}function hm(e){let t=e.slice(e.lastIndexOf(`/`)+1);return t.startsWith(`.`)&&t.endsWith(fm)}async function gm(e,t){await cm().rename(e,t)}async function _m(e,t){let n=cm();try{let r=await n.list(e);for(let e of r.files)hm(e)&&!t(e)&&await n.remove(e)}catch{}}function vm(e){if(e.length<12||e[4]!==102||e[5]!==116||e[6]!==121||e[7]!==112)return null;let t=String.fromCharCode(e[8],e[9],e[10],e[11]);if(t.startsWith(`M4A`))return`m4a`;if(t.startsWith(`M4V`))return`m4v`;if(t===`qt `)return`mov`;switch(t){case`mp42`:case`isom`:case`iso2`:case`mp41`:case`dash`:case`M4B `:case`M4P `:return`mp4`;default:return`mp4`}}function ym(e){let t=[{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,...t.map(e=>e.signature.length)),r=new Uint8Array(e,0,Math.min(n,e.byteLength)),i=vm(r);if(i)return i;for(let{signature:e,mask:n,fileExtension:i}of t){if(e.length>r.length)continue;let t=!0;for(let i=0;i<e.length;i++)if(n){if((r[i]&n[i])!==(e[i]&n[i])){t=!1;break}}else if(r[i]!==e[i]){t=!1;break}if(t)return i}return null}var bm=9e5;function xm(e){return e instanceof Error?e.message:String(e)}async function Sm(e){let t;try{t=await Lf(e,{method:`GET`,timeoutMs:bm,maxResponseBytes:im,acceptedStatuses:[200]})}catch(e){throw e instanceof df?Error(`Failed to download episode: ${e.message}`):Error(`Failed to download episode.`)}let n=t.arrayBuffer;return{data:n,contentType:t.headers[`content-type`]??t.headers[`Content-Type`]??``,byteLength:n.byteLength}}function Cm(e){return e.split(`/`).slice(0,-1).join(`/`)}var wm=new Map;function Tm(e,t){return(0,r.normalizePath)(Im(e,t))}function Em(){return Error(`A download is already in progress for the selected destination.`)}function Dm(){return Error(`A different episode already occupies the selected destination.`)}function Om(e,t,n,r){let i=Um(e,n,r)??`mp3`;if(!Gm(r,i,e.mediaType))throw Error(`Not a playable media file`);return{extension:i,filePath:Lm(t,e,i)}}function km(e,t){let n=(0,r.normalizePath)(t),i=ho.getEpisode(e);return!i||(0,r.normalizePath)(i.filePath)!==n||Object.values(E(ho)).flat().some(e=>e!==i&&(0,r.normalizePath)(e.filePath)===n)?!1:Pu(e)?!!(e.filePath&&(0,r.normalizePath)(e.filePath)===n):bp(i.streamUrl,e.streamUrl)}function Am(e,t){if(E(L).app.vault.getAbstractFileByPath(t)instanceof r.TFile&&km(e,t))return ho.getEpisode(e)?.size}function jm(e,t){if(E(L).app.vault.getAbstractFileByPath(t)instanceof r.TFile){if(!km(e,t))throw Dm();return ho.getEpisode(e)?.size}}async function Mm(e,t,n){let r=Tu(e.streamUrl);if(r){let n=Lm(t,e,r),i=Am(e,n);if(i!==void 0)return ho.addEpisode(e,n,i),n}let i=cm();if(typeof i.writeBinary!=`function`||typeof i.appendBinary!=`function`){let{data:n,contentType:r}=await Sm(e.streamUrl),{extension:i,filePath:a}=Om(e,t,n,r),o=jm(e,a);return o===void 0?(await Rm({episode:e,downloadPathTemplate:t,data:n,extension:i}),a):(ho.addEpisode(e,a,o),a)}let a=await um(e.streamUrl),{filePath:o}=Om(e,t,a.firstChunk,a.contentType),s=jm(e,o);if(s!==void 0)return ho.addEpisode(e,o,s),o;await sf(Cm(o));let c=mm(o),l=!1;try{await _m(Cm(o),()=>wm.size>1);let t=await dm(e.streamUrl,c,a,n);if(a.totalSize!==null&&t!==a.totalSize)throw Error(`Incomplete download: got ${t} of ${a.totalSize} bytes.`);return await gm(c,o),l=!0,ho.addEpisode(e,o,t),o}finally{l||await Bm(c)}}async function Nm(e,t,n){let r=Tm(t,e);if(wm.has(r))throw Em();wm.set(r,!0);try{return await Mm(e,t,n)}finally{wm.delete(r)}}async function Pm(e,t){let{doc:n,update:i}=Fm(`Download "${e.title}"`),a=new r.Notice(n,999999999),o=()=>i(t=>t.createEl(`p`,{text:`Successfully downloaded "${e.title}" from ${e.podcastName}.`}));try{i(e=>e.createEl(`p`,{text:`Starting download...`})),await Nm(e,t,(e,t)=>{let n=(e/1048576).toFixed(1),r=t&&t>0?` ${Math.round(e/t*100)}%`:``;i(e=>e.createEl(`p`,{text:`Downloading...${r} (${n} MB)`}))}),o()}catch(e){throw i(t=>{t.createEl(`p`,{text:`Download failed: ${xm(e)}`}).setCssStyles({fontStyle:`italic`})}),e}finally{window.setTimeout(()=>a.hide(),1e4)}}function Fm(e){let t=new DocumentFragment,n=t.createDiv();n.setCssStyles({width:`100%`,display:`flex`}),n.createEl(`span`,{text:e}).setCssStyles({textAlign:`center`,fontWeight:`bold`,marginBottom:`0.5em`});let r=t.createDiv();return r.setCssStyles({display:`flex`,flexDirection:`column`,alignItems:`center`,justifyContent:`center`}),{doc:t,update:(e,t=!0)=>{t&&r.empty(),e(r)}}}function Im(e,t){let n=Vd(e,t).split(`/`),r=n.length-1;return n[r].trim()===``&&(n[r]=Jd(t.title)||`episode`),n.filter((e,t)=>t===r||e.trim()!==``).join(`/`)}function Lm(e,t,n){return qu(`${Im(e,t)}.${n}`,`.${n}`)}async function Rm({episode:e,downloadPathTemplate:t,data:n,extension:r}){let{app:i}=E(L),a=Lm(t,e,r);await sf(a.split(`/`).slice(0,-1).join(`/`));try{await i.vault.createBinary(a,n)}catch(e){throw Error(`Failed to write file "${a}": ${xm(e)}`)}ho.addEpisode(e,a,n.byteLength)}async function zm(e){let t=ho.removeEpisode(e);t&&await Bm(t)}async function Bm(e){if(!e)return;let{app:t}=E(L);try{let n=t.vault.getAbstractFileByPath(e);if(n instanceof r.TFile){await t.vault.delete(n);return}let{adapter:i}=t.vault;await i.exists(e)&&await i.remove(e)}catch{}}function Vm(e){let{app:t}=E(L),n=ho.getEpisode(e),i=[e.filePath,n?.filePath,Hm(e.url)];for(let e of i){if(!e)continue;let n=t.vault.getAbstractFileByPath(e);if(n instanceof r.TFile)return n.path}return null}function Hm(e){if(!e)return null;let{app:t}=E(L),n=e.trim();if(!n)return null;let[i]=(n.match(/^\[\[(.*)\]\]$/)?.[1]??n).split(`|`),a=i?.trim();if(!a)return null;let o=t.vault.getAbstractFileByPath(a);if(o instanceof r.TFile)return o.path;let s=t.metadataCache?.getFirstLinkpathDest(a,``);return s instanceof r.TFile?s.path:null}function Um(e,t,n){let r=nm(n);if(mp(n)===`video`&&r)return r;let i=Tu(e.streamUrl);if(fp(i)===`video`&&!vp(i))return i;let a=ym(t);return a?Jm(a,mp(n)===`audio`||e.mediaType===`audio`?`audio`:void 0)??a:r||i||null}function Wm(e){let t=e.split(`;`)[0].trim().toLowerCase();return t?t.startsWith(`text/`)||t===`application/json`||t===`application/xml`||t.endsWith(`+xml`)||t.endsWith(`+json`):!1}function Gm(e,t,n){if(Wm(e))return!1;let r=e.toLowerCase(),i=mp(r);return i===`video`||r===``&&n===`video`?fp(t)===`video`:r===``||i===`audio`||pp(t)}function Km(e,t,n){if(Wm(e))return!1;let r=mp(e);return r?r===`audio`||qm(t,n):e.toLowerCase()===``||fp(t)===`audio`||qm(t,n)}function qm(e,t){return t===`audio`&&vp(e)}function Jm(e,t){return t===`audio`&&e?.toLowerCase()===`mp4`?`m4a`:e}async function Ym(e){let{app:t}=E(L),n=_p(e);if(n!==`audio`)throw Error(`Transcription supports audio episodes only.`);let i=Xm(e,n);if(Pu(e)){let t=Vm(e);if(!t)throw Error(`Unable to locate the local audio file for "${e.title}". Try playing the file again.`);return Zm(t,n)}let a=ho.getEpisode(e);if(a?.filePath&&bp(a.streamUrl,e.streamUrl)){let e=yp(a,i);if(e!==`audio`)throw Error(`Transcription supports audio episodes only.`);if(t.vault.getAbstractFileByPath(a.filePath)instanceof r.TFile)return Zm(a.filePath,e)}try{let{data:t,contentType:n}=await Sm(e.streamUrl),r=Um(e,t,n);if(!Km(n,r,i))throw Error(`The downloaded file is not audio (received "${n}"). The episode may be unavailable or require re-authentication.`);return{buffer:t,extension:Jm(r,i)??`mp3`,basename:Jd(e.title)||`episode`}}catch(t){throw Error(`Failed to fetch ${e.title}: ${xm(t)}`)}}function Xm(e,t){if(t===`audio`)return e.mediaType===`audio`||vp(Tu(e.streamUrl))?`audio`:void 0}async function Zm(e,t){let{app:n}=E(L),i=n.vault.getAbstractFileByPath(e);if(!(i instanceof r.TFile))throw Error(`Unable to read the audio file at "${e}".`);let a=i.extension||Tu(i.path||e)||``;if((t===`audio`&&(a.toLowerCase()===`mp4`||a.toLowerCase()===`webm`)?`audio`:fp(a)??hp(i.path||e))!==`audio`)throw Error(`Unable to read the non-audio file at "${e}".`);return{buffer:await n.vault.readBinary(i),extension:t===`audio`&&a.toLowerCase()===`mp4`?`m4a`:a,basename:i.basename||Qm(i.path||e)}}function Qm(e){let t=e.split(`/`).pop()??e,n=t.lastIndexOf(`.`);return n>0?t.slice(0,n):t}var $m=15e3,eh=2097152;async function th(e){let t=new URL(`https://itunes.apple.com/search?`);t.searchParams.append(`term`,e),t.searchParams.append(`media`,`podcast`),t.searchParams.append(`limit`,`3`),t.searchParams.append(`kind`,`podcast`);try{let e=await Rf(t.href,{timeoutMs:$m,maxResponseBytes:eh,acceptedStatuses:[200]});if(!e||typeof e!=`object`||!Array.isArray(e.results))throw new df(`invalid-response`);return e.results.map(e=>({title:e.collectionName,url:e.feedUrl,artworkUrl:e.artworkUrl100,collectionId:e.collectionId}))}catch(e){throw e instanceof df?e:new df(`invalid-response`)}}var nh=15e3,rh=4194304,ih=e=>(e??``).trim().replace(/\/+$/,``).toLowerCase();async function ah(e,t){let n=E(ro),r=ih(t),i=(r?Object.values(n).find(e=>ih(e.url)===r):void 0)??n[e]??Object.values(n).find(t=>t.title===e);if(i?.collectionId)return i.collectionId;let a=await th(e);return((r?a.find(e=>ih(e.url)===r):void 0)??a.find(t=>t.title===e))?.collectionId}async function oh(e){let{title:t,itunesTitle:n,podcastName:i,feedUrl:a}=e.podcast,o;try{let e=await ah(i,a);if(!e){new r.Notice(`Could not find "${i}" on Apple Podcasts to build a universal link.`);return}let s=await Rf(`https://pod.link/${e}.json?limit=1000`,{timeoutMs:nh,maxResponseBytes:rh,acceptedStatuses:[200]}),c=n??t;if(!s||typeof s!=`object`||!Array.isArray(s.episodes))throw new df(`invalid-response`);let l=s.episodes.find(e=>typeof e==`object`&&!!e&&typeof e.episodeId==`string`&&typeof e.title==`string`&&e.title===c);if(!l){new r.Notice(`Could not find episode "${c}" on pod.link to build a universal link.`);return}o=`https://pod.link/${e}/episode/${l.episodeId}`}catch{new r.Notice(`Could not get podcast link.`);return}if(navigator.clipboard?.writeText)try{await navigator.clipboard.writeText(o),new r.Notice(`Universal episode link copied to clipboard.`)}catch{new r.Notice(`Could not copy to clipboard. Episode link: ${o}`)}else new r.Notice(`Clipboard unavailable. Episode link: ${o}`)}function sh(e){let t=()=>!!e.api.podcast&&!!e.settings.timestamp.template,n=(e,t)=>{let n=e.getCursor(`from`),r=tf(t,{getLine:t=>e.getLine(t),lineCount:e.lineCount(),cursorLine:n.line});e.replaceSelection(r)},i=(t,i)=>{let a=rf(e.api.currentTime,i,e.settings.timestamp.offset??0);if(!a){new r.Notice(`Play more of the episode before capturing a segment`);return}let o=zd(of(e.settings.timestamp.template),{segment:a});n(t,o)};e.addCommand({id:`podnotes-show-leaf`,name:`Show player`,icon:`podcast`,callback:()=>{e.activateView()}}),e.addCommand({id:`start-playing`,name:`Play Podcast`,icon:`play-circle`,checkCallback:t=>{if(t)return!e.api.isPlaying&&!!e.api.podcast;e.api.start()}}),e.addCommand({id:`stop-playing`,name:`Stop Podcast`,icon:`stop-circle`,checkCallback:t=>{if(t)return e.api.isPlaying&&!!e.api.podcast;e.api.stop()}}),e.addCommand({id:`skip-backward`,name:`Skip Backward`,icon:`skip-back`,checkCallback:t=>{if(t)return!!e.api.podcast;e.api.skipBackward()}}),e.addCommand({id:`skip-forward`,name:`Skip Forward`,icon:`skip-forward`,checkCallback:t=>{if(t)return!!e.api.podcast;e.api.skipForward()}}),e.addCommand({id:`download-playing-episode`,name:`Download Playing Episode`,icon:`download`,checkCallback:t=>{if(t)return!!e.api.podcast;let n=e.api.podcast;Pm(n,e.settings.download.path).catch(e=>void 0)}}),e.addCommand({id:`reorder-queue`,name:`Reorder Queue`,icon:`list-ordered`,checkCallback:t=>{if(t)return E(ko).episodes.length>1;new Qc(e.app).open()}}),e.addCommand({id:`capture-timestamp`,name:`Capture Timestamp`,icon:`clock`,editorCallback:t=>{e.captureTimestamp(t)||new r.Notice(`Play an episode and set a Capture timestamp format in settings to capture a timestamp.`)}}),e.addCommand({id:`capture-segment-10s`,name:`Capture Last 10 Seconds`,icon:`scissors`,editorCheckCallback:(e,n)=>{if(e)return t();i(n,10)}}),e.addCommand({id:`capture-segment-20s`,name:`Capture Last 20 Seconds`,icon:`scissors`,editorCheckCallback:(e,n)=>{if(e)return t();i(n,20)}}),e.addCommand({id:`create-podcast-note`,name:`Create episode note`,icon:`file-plus`,checkCallback:t=>{if(t)return!!e.api.podcast&&!!e.settings.note.path&&!!e.settings.note.template;rp(e.api.podcast)}}),e.addCommand({id:`create-podcast-feed-note`,name:`Create podcast feed note`,icon:`file-plus`,checkCallback:t=>{let n=Object.values(E(ro)),r=n.length>0&&!!e.settings.feedNote.path&&!!e.settings.feedNote.template;if(t)return r;if(!r)return;let i=$p(n,e.api.podcast?.podcastName);new em(e.app,i,e=>{Xp(e)}).open()}}),e.addCommand({id:`get-share-link-episode`,name:`Copy universal episode link to clipboard`,icon:`share`,checkCallback:t=>{if(t)return!!e.api.podcast;oh(e.api)}}),e.addCommand({id:`podnotes-toggle-playback`,name:`Toggle playback`,icon:`play`,checkCallback:t=>{if(t)return!!e.api.podcast;e.api.togglePlayback()}}),e.addCommand({id:`increase-playback-rate`,name:`Increase playback rate`,icon:`gauge`,checkCallback:t=>{if(t)return!!e.api.podcast;e.api.increasePlaybackRate()}}),e.addCommand({id:`decrease-playback-rate`,name:`Decrease playback rate`,icon:`gauge`,checkCallback:t=>{if(t)return!!e.api.podcast;e.api.decreasePlaybackRate()}}),e.addCommand({id:`reset-playback-rate`,name:`Reset playback rate`,icon:`rotate-ccw`,checkCallback:t=>{if(t)return!!e.api.podcast;e.api.resetPlaybackRate()}}),e.addCommand({id:`podnotes-transcribe`,name:`Transcribe current episode`,checkCallback:t=>{let n=!!e.api.podcast&&_p(e.api.podcast)===`audio`;if(t)return n;n&&e.getTranscriptionService().transcribeCurrentEpisode()}})}function ch(e,t){let n=Bd(t,e);return qu(n,Ku(n))}var lh=15,uh=e=>Number.isFinite(e)&&e>0?e:lh,dh=(e,t=1)=>{let n=Number.isFinite(t)?Math.min(1,Math.max(0,t)):1;return Number.isFinite(e)?Math.min(1,Math.max(0,e)):n},fh=class{get podcast(){return E(Co)}get transcript(){return this.getTranscript()}get length(){return E(yo)}get currentTime(){return E(go)}set currentTime(e){vo.set(null),go.update(t=>e)}get isPlaying(){return!E(wo)}get volume(){return E(xo)}set volume(e){xo.set(dh(e,E(xo)))}get playbackRate(){return E(bo)}set playbackRate(e){bo.set(Pa(e,this.defaultPlaybackRate))}getPodcastTimeFormatted(e,t=!1,n=0){if(!this.podcast)throw Error(`No podcast loaded`);let r=Math.max(0,this.currentTime-n),i=Du(r,e);if(!t)return i;let a=this.getEpisodeLinkTarget();return!a||a===``?i:`[${i}](${Nu(this.podcast.title,a,r).href})`}getPodcastSegmentFormatted(e,t,n,r=!1){if(!this.podcast)throw Error(`No podcast loaded`);let i=nf(t,n),a=i?af(i.startTime,i.endTime,e):af(t,n,e);if(!r||!i)return a;let o=this.getEpisodeLinkTarget();return!o||o===``?a:`[${a}](${Nu(this.podcast.title,o,i.startTime,i.endTime).href})`}async getTranscript(e=this.podcast){if(!e)return null;let t=E(L),n=ch(e,t.settings.transcript.path),i=t.app.vault.getAbstractFileByPath(n);return i instanceof r.TFile?await t.app.vault.read(i):null}getEpisodeLinkTarget(){return Pu(this.podcast)?ho.getEpisode(this.podcast)?.filePath:this.podcast.feedUrl}start(){wo.update(e=>!1)}stop(){wo.update(e=>!0)}togglePlayback(){wo.update(e=>!e)}skipBackward(){let e=uh(E(L).settings.skipBackwardLength);this.currentTime=Math.max(0,this.currentTime-e)}skipForward(){let e=uh(E(L).settings.skipForwardLength),t=this.currentTime+e,n=this.length;this.currentTime=n>0?Math.max(this.currentTime,Math.min(t,n-.25)):t}increasePlaybackRate(){bo.update(e=>Fa(e,Na))}decreasePlaybackRate(){bo.update(e=>Fa(e,-Na))}resetPlaybackRate(){this.playbackRate=this.defaultPlaybackRate}get defaultPlaybackRate(){return Pa(E(L).settings.defaultPlaybackRate)}};function ph(e){try{return new URL(e)}catch{return null}}var mh=z(`<span></span>`);function hh(e,t){lt(t,!1);let n=V(t,`value`,12,``),i=V(t,`disabled`,8,!1),a=V(t,`placeholder`,8,``),o=V(t,`type`,8,`text`),s=V(t,`el`,12,null),c=A(),l=Fc(),u=A(),d=V(t,`style`,24,()=>({})),f=null,p=null,m=!1;Mc(()=>{j(u,new r.TextComponent(N(c)))}),Nc(()=>{N(u)?.inputEl&&f&&N(u).inputEl.removeEventListener(`input`,f)});function h(e){if(m)return;let t=e.target?.value??``;n(t),l(`input`,{value:t})}function g(e){m||(n(e),l(`change`,{value:e}))}function _(e){!e?.inputEl||f||(p=g,e.onChange(p),f=h,e.inputEl.addEventListener(`input`,f))}function v(e,t,n,r,i,a){let o=typeof e.getValue==`function`?e.getValue():e.inputEl?.value;t!==void 0&&o!==t&&(m=!0,e.setValue(t),m=!1),e?.inputEl&&(e.inputEl.disabled!==n&&e.setDisabled(n),r&&e.inputEl.placeholder!==r&&e.setPlaceholder(r),e.inputEl.type!==i&&(e.inputEl.type=i),a&&e.inputEl.setAttr(`style`,Bc(a)),s(e.inputEl))}Zi(()=>(N(u),F(n()),F(i()),F(a()),F(o()),F(d())),()=>{N(u)&&(_(N(u)),v(N(u),n(),i(),a(),o(),d()))}),Qi(),Oc();var y=mh();Tc(y,e=>j(c,e),()=>N(c)),B(e,y),ut()}var gh=z(`<span></span>`);function _h(e,t){lt(t,!1);let n=V(t,`text`,8,``),i=V(t,`tooltip`,8,``),a=V(t,`ariaLabel`,8,``),o=V(t,`icon`,8,void 0),s=V(t,`disabled`,8,!1),c=V(t,`warning`,8,!1),l=V(t,`cta`,8,!1),u=A(),d=V(t,`class`,8),f=V(t,`style`,8),p,m=Fc();Mc(()=>h(N(u))),Ic(()=>g(p));function h(e){p=new r.ButtonComponent(e),g(p)}function g(e){n()&&e.setButtonText(n()),i()&&e.setTooltip(i()),o()&&e.setIcon(o()),s()&&e.setDisabled(s()),c()?e.setWarning():e.buttonEl.classList.remove(`mod-warning`),d()&&e.setClass(d()),l()?e.setCta():e.removeCta(),e.onClick(e=>{m(`click`,{event:e})}),f()&&e.buttonEl.setAttr(`style`,Bc(f())),a()?e.buttonEl.setAttr(`aria-label`,a()):e.buttonEl.removeAttribute(`aria-label`)}Oc();var _=gh();Tc(_,e=>j(u,e),()=>N(u)),B(e,_),ut()}var vh=e=>e;function yh(e,{delay:t=0,duration:n=400,easing:r=vh}={}){let i=+getComputedStyle(e).opacity;return{delay:t,duration:n,easing:r,css:e=>`opacity: ${e*i}`}}var bh=z(`<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>`),xh={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 Sh(e,t){lt(t,!1),Gs(e,xh);let n=V(t,`podcast`,8),r=V(t,`isSaved`,8,!1),i=Fc();Oc();var a=bh(),o=w(a),s=w(o);C(o);var c=T(o,2),l=w(c),u=w(l,!0);C(l),C(c);var d=T(c,2),f=w(d),p=e=>{{let t=ar(()=>(F(n()),P(()=>`Remove ${n().title} podcast`)));_h(e,{text:`Remove`,warning:!0,get ariaLabel(){return N(t)},$$events:{click:()=>i(`removePodcast`,{podcast:n()})}})}},m=e=>{{let t=ar(()=>(F(n()),P(()=>`Add ${n().title} podcast`)));_h(e,{text:`Add`,cta:!0,get ariaLabel(){return N(t)},$$events:{click:()=>i(`addPodcast`,{podcast:n()})}})}};Ss(f,e=>{r()?e(p):e(m,-1)}),C(d),C(a),ta(()=>{oc(s,`src`,(F(n()),P(()=>n().artworkUrl))),oc(s,`alt`,(F(n()),P(()=>`Artwork for ${n().title}`))),cs(u,(F(n()),P(()=>n().title)))}),Us(3,a,()=>yh,()=>({duration:300})),B(e,a),ut()}var Ch=z(`<div class="podcast-query-status svelte-8ek8i8" role="status" aria-live="polite">Searching...</div>`),wh=z(`<div class="podcast-query-status podcast-query-error svelte-8ek8i8" role="alert"> </div>`),Th=z(`<div class="podcast-query-status svelte-8ek8i8" role="status" aria-live="polite">No results.</div>`),Eh=z(`<div role="listitem"><!></div>`),Dh=z(`<div class="podcast-query-container svelte-8ek8i8"><!> <!> <div class="podcast-query-results svelte-8ek8i8" role="list" aria-label="Podcast search results"></div></div>`),Oh={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 kh(e,t){lt(t,!1),Gs(e,Oh);let n=()=>sn(ro,`$savedFeeds`,a),i=()=>sn(no,`$podcastsUpdated`,a),[a,o]=ln(),s=A([]),c=A(`grid-3`),l=A(``),u=A(!1),d=A(``),f=A();Mc(()=>{p(),N(f)&&N(f).focus()});function p(){N(l).trim()===``&&j(s,Object.values(n()))}let m=(0,r.debounce)(async({detail:{value:e}})=>{j(l,e),j(d,``);let t=ph(e);if((t?.protocol===`http:`||t?.protocol===`https:`)&&t){j(u,!0);try{let e=await new Fp().getFeed(t.href);j(s,[e])}catch(e){j(s,[]);let t=e instanceof Error?e.message:String(e);j(d,`Could not load feed: ${t}`),new r.Notice(N(d))}finally{j(u,!1)}}else if(e.trim()===``)p();else{j(u,!0);try{j(s,await th(e))}catch{j(s,[]),j(d,`Could not search podcasts. Please try again.`)}finally{j(u,!1)}}},300,!0);function h(e){let t=Hp(e.detail.podcast,E(L).feedUrls);ro.update(e=>({...e,[t.title]:t})),p()}function g(e){let{podcast:t}=e.detail;ro.update(e=>{let n=e[t.title],r={...e};delete r[t.title];let i=Object.values(r).some(e=>e.urlSecretId===n?.urlSecretId);return n?.urlSecretId&&!i&&E(L).feedUrls.delete(n.urlSecretId),r}),p()}Zi(()=>(N(l),n(),i()),()=>{N(l).trim()===``&&j(s,Object.values(n())),i()}),Zi(()=>N(s),()=>{N(s).length%3==0||N(s).length>3?j(c,`grid-3`):N(s).length%2==0?j(c,`grid-2`):N(s).length%1==0&&j(c,`grid-1`)}),Qi(),Oc();var _=Dh(),v=w(_);hh(v,{placeholder:`Search or enter feed URL...`,style:{width:`100%`,"margin-bottom":`1rem`},get el(){return N(f)},set el(e){j(f,e)},$$events:{change:m},$$legacy:!0});var y=T(v,2),b=e=>{B(e,Ch())},x=e=>{var t=wh(),n=w(t,!0);C(t),ta(()=>cs(n,N(d))),B(e,t)},S=e=>{B(e,Th())},ee=ir(()=>(N(l),N(s),P(()=>N(l).trim()!==``&&N(s).length===0)));Ss(y,e=>{N(u)?e(b):N(d)?e(x,1):N(ee)&&e(S,2)});var te=T(y,2);Ds(te,5,()=>N(s),e=>e.url,(e,t)=>{var r=Eh(),i=w(r);{let e=ar(()=>(N(t),n(),P(()=>typeof N(t).url==`string`&&n()[N(t).title]?.url===N(t).url)));Sh(i,{get podcast(){return N(t)},get isSaved(){return N(e)},$$events:{addPodcast:h,removePodcast:g}})}C(r),B(e,r)}),C(te),C(_),Us(3,_,()=>yh,()=>({duration:300})),B(e,_),ut(),o()}var Ah=z(`<button type="button"><!></button>`),jh=z(`<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>`),Mh={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 Nh(e,t){lt(t,!1),Gs(e,Mh);let n=V(t,`playlist`,8),r=V(t,`showDeleteButton`,8,!0),i=A(!1),a=Fc();function o(){if(N(i)){a(`delete`,{value:n()});return}j(i,!0),setTimeout(()=>{j(i,!1)},2e3)}Zi(()=>F(n()),()=>{n()&&j(i,!1)}),Qi(),Oc();var s=jh(),c=w(s),l=w(c);Wc(l,{get icon(){return F(n()),P(()=>n().icon)},clickable:!1,size:18});var u=T(l,2),d=w(u,!0);C(u);var f=T(u,2),p=w(f);C(f),C(c);var m=T(c,2),h=w(m),g=e=>{var t=Ah();let n;var r=w(t);{let e=ar(()=>N(i)?`check`:`trash`);Wc(r,{get icon(){return N(e)},clickable:!1,size:16})}C(t),ta(()=>{n=ec(t,1,`delete-button svelte-jzsw7l`,null,n,{confirm:N(i)}),oc(t,`aria-label`,N(i)?`Confirm deletion`:`Delete playlist`)}),R(`click`,t,o),B(e,t)};Ss(h,e=>{r()&&e(g)}),C(m),C(s),ta(()=>{cs(d,(F(n()),P(()=>n().name))),cs(p,`(${F(n()),P(()=>n().episodes.length)??``})`)}),B(e,s),ut()}var Ph=z(`<span></span>`);function Fh(e,t){lt(t,!1);let n=V(t,`value`,8,``),i=V(t,`options`,24,()=>({})),a=V(t,`disabled`,8,!1),o=A(),s=A(),c=V(t,`style`,8),l=Fc();Mc(()=>{j(s,new r.DropdownComponent(N(o))),d(N(s))});function u(e){return typeof e.getValue==`function`?e.getValue():e.selectEl?.value}function d(e){i()&&e.addOptions(i()),n()&&e.setValue(n()),a()&&e.setDisabled(a()),e.onChange(e=>{l(`change`,{value:e})}),c()&&e.selectEl.setAttr(`style`,Bc(c()))}Zi(()=>(N(s),F(n())),()=>{N(s)&&n()!==void 0&&u(N(s))!==n()&&N(s).setValue(n())}),Qi(),Oc();var f=Ph();Tc(f,e=>j(o,e),()=>N(o)),B(e,f),ut()}var Ih=`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`.split(`.`),Lh=z(`<div class="playlist-manager-container svelte-w5in4v"><div class="playlist-list svelte-w5in4v"><!> <!> <!></div> <div class="add-playlist-container svelte-w5in4v"><!> <!> <!></div></div>`),Rh={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 zh(e,t){lt(t,!1),Gs(e,Rh);let n=()=>sn(ko,`$queue`,a),i=()=>sn(Ao,`$favorites`,a),[a,o]=ln(),s=A([]),c=A(``),l=Ih.reduce((e,t)=>(e[t]=t,e),{}),u=A(Ih[0]);Mc(()=>{let e=Po.subscribe(e=>{j(s,Object.values(e))});return()=>{e()}});function d(){let e=N(c).trim();if(!e){new r.Notice(`Playlist name cannot be empty.`);return}if(new Set([E(ko).name,E(Ao).name,E(No).name,Aa.name]).has(e)){new r.Notice(`"${e}" is a reserved playlist name.`);return}if(Object.prototype.hasOwnProperty.call(E(Po),e)){new r.Notice(`A playlist with that name already exists.`);return}Po.update(t=>(t[e]={name:e,icon:N(u),episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},t)),j(c,``),j(u,Ih[0])}function f(e){j(u,e.detail.value)}function p(e){Po.update(t=>(delete t[e.detail.value.name],t))}Oc();var m=Lh(),h=w(m),g=w(h);Nh(g,{get playlist(){return n()},showDeleteButton:!1});var _=T(g,2);Nh(_,{get playlist(){return i()},showDeleteButton:!1}),Ds(T(_,2),1,()=>N(s),e=>e.name,(e,t)=>{Nh(e,{get playlist(){return N(t)},$$events:{delete:p}})}),C(h);var v=T(h,2),y=w(v);Fh(y,{get options(){return l},get value(){return N(u)},set value(e){j(u,e)},$$events:{change:f},$$legacy:!0});var b=T(y,2);hh(b,{placeholder:`Playlist name`,get value(){return N(c)},set value(e){j(c,e)},$$legacy:!0}),_h(T(b,2),{text:`Add`,cta:!0,ariaLabel:`Add playlist`,$$events:{click:d}}),C(v),C(m),B(e,m),ut(),o()}function Bh(e,t){let n=t.toLowerCase();for(let t=0;t<e.attributes.length;t++){let r=e.attributes.item(t);if(r&&r.name.toLowerCase()===n)return r.value?.trim()||null}return null}function Vh(e,t){let n=t,i=Date.now(),a,o,s=new r.Notice(t,0);function c(t){return`${e} (${u()}):\n\n${t}`}function l(e){n=e,s.setMessage(c(n))}function u(){return Hh(a?a-i:Date.now()-i)}function d(){o!==void 0&&(window.clearInterval(o),o=void 0)}return o=window.setInterval(()=>{s.setMessage(c(n))},1e3),{update:l,hide:()=>{d(),s.hide()},stop:()=>{a=Date.now(),d()}}}function Hh(e){let t=Math.floor(e/1e3),n=Math.floor(t/60);return`${Math.floor(n/60).toString().padStart(2,`0`)}:${(n%60).toString().padStart(2,`0`)}:${(t%60).toString().padStart(2,`0`)}`}async function Uh(e){try{let t=new DOMParser().parseFromString(e,`application/xml`);if(t.querySelector(`parsererror`))throw Error(`Invalid XML format`);let n=t.querySelectorAll(`outline[text]`),i=[];for(let e=0;e<n.length;e++){let t=n.item(e),r=t.getAttribute(`text`),a=Bh(t,`xmlUrl`);!r||!a||i.push({title:r,url:a})}if(i.length===0)throw Error(`No valid podcast entries found in OPML`);let a=E(ro),o=i.filter(e=>!Object.values(a).some(t=>t.url===e.url)),s=Vh(`Importing podcasts`,`Preparing to import...`),c=0,l=()=>{let e=o.length;if(e===0){s.update(`No new podcasts to import.`);return}let t=(c/e*100).toFixed(1);s.update(`Importing... ${c}/${e} podcasts completed (${t}%)`)};l();let u=await Promise.all(o.map(async e=>{try{let t=await new Fp().getFeed(e.url);return c++,l(),t}catch{return c++,l(),null}}));s.stop();let d=u.filter(e=>e!==null),f=0;ro.update(e=>{for(let t of d)e[t.title]||(e[t.title]=Hp(structuredClone(t),E(L).feedUrls),f++);return e});let p=i.length-o.length,m=d.length-f,h=`OPML import complete. Saved ${f} new podcasts. Skipped ${p} existing podcasts.`;if(m>0&&(h+=` Skipped ${m} with duplicate titles.`),s.update(h),d.length!==o.length){let e=o.length-d.length;new r.Notice(`Failed to import ${e} podcasts. Check console for details.`,1e4)}window.setTimeout(()=>s.hide(),5e3)}catch(e){new r.Notice(`Error importing OPML: ${e instanceof Error?e.message:`Unknown error`}`,1e4)}}async function Wh(e,t,n=`PodNotes_Export.opml`){let i=e=>`<opml version="1.0">${e}</opml>`,a=e=>`<head>${e}</head>`,o=e=>`<body>${e}</body>`,s=e=>e.replace(/&/g,`&`).replace(/</g,`<`).replace(/>/g,`>`).replace(/"/g,`"`),c=0,l=e=>{let t=Up(e,E(L).feedUrls)??``;return e.urlSecretId&&t&&(c+=1),`<outline text="${s(e.title)}" type="rss" xmlUrl="${s(t)}" />`},u=`<?xml version="1.0" encoding="utf-8" standalone="no"?>`+i(`${a(`<title>PodNotes Feeds</title>`)}\n${o((e=>`<outline text="feeds">${t.map(l).join(``)}</outline>`)(t))}`);try{await e.vault.create(n,u),new r.Notice(`Exported ${t.length} podcast feeds to file "${n}".`),c>0&&new r.Notice(`The export contains ${c} private feed ${c===1?`URL`:`URLs`} in plaintext. The file is inside your vault - delete it after importing it elsewhere.`,1e4)}catch(e){e instanceof Error?e.message.includes(`Folder does not exist`)?new r.Notice(`Unable to create export file: Folder does not exist.`):new r.Notice(`Unable to create podcast export file:\n\n${e.message}`):new r.Notice(`An unexpected error occurred during export.`)}}var Gh=new Set([`__proto__`,`constructor`,`prototype`]);function Kh(e,t,n,r,i=``){let a=e[t];return a===void 0?n:typeof a==`string`?a:(U(r,og(i,t),`expected a string`),n)}function qh(e,t,n,r){let i=e[t];if(i==null||typeof i==`string`)return i;U(n,og(r,t),`expected a string`)}function Jh(e,t,n,r,i=``){let a=e[t];return a===void 0?n:typeof a==`boolean`?a:(U(r,og(i,t),`expected a boolean`),n)}function Yh(e,t,n,r,i=``){let a=e[t];return a===void 0?n:typeof a==`number`&&Number.isFinite(a)?a:(U(r,og(i,t),`expected a finite number`),n)}function Xh(e,t,n,r,i){let a=e[t];return a===void 0?n:typeof a==`number`&&Number.isFinite(a)&&a>=0?a:(U(r,og(i,t),`expected a non-negative number`),n)}function Zh(e,t,n,r,i){let a=e[t];return a===void 0?n:typeof a==`number`&&Number.isFinite(a)&&a>0?a:(U(r,og(i,t),`expected a positive number`),n)}function Qh(e,t,n,r,i,a){let o=e[t];if(o===void 0)return n;if(typeof o!=`number`||!Number.isFinite(o))return U(a,t,`expected a finite number`),n;let s=Math.min(i,Math.max(r,o));return s!==o&&U(a,t,`value was clamped`),s}function $h(e,t,n,r,i){let a=t[n];a==null?delete e[n]:typeof a==`string`?e[n]=a:(delete e[n],U(r,og(i,n),`expected a string`))}function eg(e,t,n,r,i,a){let o=t[n];o==null?delete e[n]:typeof o==`number`&&Number.isFinite(o)&&o>=a?e[n]=o:(delete e[n],U(r,og(i,n),`expected a finite number >= ${a}`))}function tg(e,t,n){return e==null?{}:ag(e)?e:(U(t,n,`expected an object`),{})}function ng(e){let t={};for(let[n,r]of Object.entries(e))Gh.has(n)||(t[n]=r);return t}function rg(e,t,n){let r=[];for(let[i,a]of Object.entries(e)){if(Gh.has(i)){U(t,`${n}.${i}`,`unsafe key was removed`);continue}r.push([i,a])}return r}function ig(e,t){let n={};for(let[r,i]of Object.entries(e))Gh.has(r)||(n[r]=t(i));return n}function ag(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function U(e,t,n){e.add(`${t}: ${n}`)}function og(e,t){return e?`${e}.${t}`:t}function sg(e,t=new Set,n=`episode`){if(!ag(e)){U(t,n,`expected an object`);return}if(typeof e.title!=`string`){U(t,`${n}.title`,`expected a string; episode was skipped`);return}let r=ng(e);if(r.title=e.title,r.streamUrl=Kh(e,`streamUrl`,``,t,n),r.url=Kh(e,`url`,``,t,n),r.description=Kh(e,`description`,``,t,n),r.content=Kh(e,`content`,``,t,n),r.podcastName=Kh(e,`podcastName`,``,t,n),$h(r,e,`feedUrl`,t,n),$h(r,e,`artworkUrl`,t,n),$h(r,e,`itunesTitle`,t,n),$h(r,e,`chaptersUrl`,t,n),$h(r,e,`filePath`,t,n),eg(r,e,`episodeNumber`,t,n,0),eg(r,e,`duration`,t,n,0),eg(r,e,`size`,t,n,0),e.mediaType===void 0?delete r.mediaType:e.mediaType===`audio`||e.mediaType===`video`?r.mediaType=e.mediaType:(delete r.mediaType,U(t,`${n}.mediaType`,`expected audio or video`)),e.episodeDate===void 0||e.episodeDate===null||e.episodeDate===``)delete r.episodeDate;else{let i=Qa(e.episodeDate);i?r.episodeDate=i:(delete r.episodeDate,U(t,`${n}.episodeDate`,`invalid date was removed`))}return r}function cg(e){if(!e)return;let t=ng(e),n=$a(e.episodeDate);return n?t.episodeDate=n:delete t.episodeDate,t}function lg(e,t,n=new Set,r=`playlist`){if(!ag(e))return e!==void 0&&U(n,r,`expected an object`),dg(t);let i=ng(e);i.icon=Kh(e,`icon`,t.icon,n,r),i.name=Kh(e,`name`,t.name,n,r),i.shouldEpisodeRemoveAfterPlay=Jh(e,`shouldEpisodeRemoveAfterPlay`,t.shouldEpisodeRemoveAfterPlay,n,r),i.shouldRepeat=Jh(e,`shouldRepeat`,t.shouldRepeat,n,r),Array.isArray(e.episodes)?i.episodes=e.episodes.flatMap((e,t)=>{let i=sg(e,n,`${r}.episodes[${t}]`);return i?[i]:[]}):(e.episodes!==void 0&&U(n,`${r}.episodes`,`expected an array`),i.episodes=t.episodes.map((e,t)=>sg(e,n,`${r}.fallbackEpisodes[${t}]`)).filter(e=>!!e));let a=e.currentEpisode===void 0||e.currentEpisode===null?void 0:sg(e.currentEpisode,n,`${r}.currentEpisode`);return a?i.currentEpisode=a:delete i.currentEpisode,e.isVirtual===void 0?delete i.isVirtual:typeof e.isVirtual==`boolean`?i.isVirtual=e.isVirtual:(delete i.isVirtual,U(n,`${r}.isVirtual`,`expected a boolean`)),i}function ug(e){let t=ng(e);t.episodes=e.episodes.map(e=>cg(e));let n=e.currentEpisode?cg(e.currentEpisode):void 0;return n?t.currentEpisode=n:delete t.currentEpisode,t}function dg(e){return{...e,episodes:e.episodes.map(e=>({...e})),currentEpisode:e.currentEpisode?{...e.currentEpisode}:void 0}}var fg=`podnotes:feed-cache:v5`,pg=[`podnotes:feed-cache:v1`,`podnotes:feed-cache:v2`,`podnotes:feed-cache:v3`,`podnotes:feed-cache:v4`],mg=216e5,hg=75,gg=4194304,_g=null;function vg(){let e;try{e=typeof window<`u`?window.localStorage:null}catch{e=null}if(e)for(let t of pg)try{e.removeItem(t)}catch{}}function yg(){let e=E(L)?.app;if(e&&typeof e.loadLocalStorage==`function`&&typeof e.saveLocalStorage==`function`)return{getItem:t=>{let n=e.loadLocalStorage(t);return typeof n==`string`?n:null},setItem:(t,n)=>e.saveLocalStorage(t,n),removeItem:t=>e.saveLocalStorage(t,null)};try{return typeof window<`u`&&window.localStorage?window.localStorage:null}catch{return null}}function bg(){if(_g)return _g;vg();let e=yg();if(!e)return _g={},_g;try{let t=e.getItem(fg);return t?(_g=xg(JSON.parse(t)),_g):(_g={},_g)}catch{return _g={},_g}}function xg(e){if(!Sg(e))throw TypeError(`Feed cache root must be an object`);let t={};for(let[n,r]of Object.entries(e))Gh.has(n)||!Sg(r)||!Array.isArray(r.episodes)||typeof r.updatedAt!=`number`||!Number.isFinite(r.updatedAt)||r.updatedAt<0||(t[n]={updatedAt:r.updatedAt,episodes:r.episodes.flatMap(e=>{let t=sg(e);return t?[Tg(t)]:[]})});return t}function Sg(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}function Cg(e,t){let n=Object.entries(e);n.sort((e,t)=>e[1].updatedAt-t[1].updatedAt);let r={},i=0;for(let e=n.length-1;e>=0;e--){let[a,o]=n[e],s=JSON.stringify({[a]:o}).length;i+s<=t&&(r[a]=o,i+=s)}return r}function wg(){let e=yg();if(!(!e||!_g))try{let t=JSON.stringify(_g);t.length>gg&&(_g=Cg(_g,gg*.8),t=JSON.stringify(_g)),e.setItem(fg,t)}catch(t){if(t instanceof DOMException&&(t.name===`QuotaExceededError`||t.name===`NS_ERROR_DOM_QUOTA_REACHED`))try{_g={},e.setItem(fg,`{}`)}catch{e.removeItem(fg)}}}function Tg(e){return{...e,episodeDate:$a(e.episodeDate)}}function Eg(e){return eo(e.episodeDate)??0}function Dg(e,t){if(e.length<=t)return e;let n=new Set(e.map((e,t)=>({index:t,time:Eg(e)})).sort((e,t)=>t.time-e.time).slice(0,t).map(e=>e.index));return e.filter((e,t)=>n.has(t))}function Og(e){return{...e,episodeDate:Qa(e.episodeDate)}}function kg(e){return e.url??e.title}function Ag(e,t=mg){let n=bg(),r=kg(e),i=n[r];return i?Date.now()-i.updatedAt>t?(delete n[r],wg(),null):i.episodes.map(Og):null}function jg(e,t){if(!t.length)return;let n=bg(),r=kg(e);n[r]={updatedAt:Date.now(),episodes:Dg(t,hg).map(Tg)},wg()}function Mg(e){if(!e.length)return;let t=bg(),n=!1;for(let r of e)r in t&&(delete t[r],n=!0);n&&wg()}function Ng(){_g={};let e=yg();if(e)try{e.removeItem(fg)}catch{}vg()}var Pg=[`openai`,`deepgram`],Fg=`gpt-4o-transcribe-diarize`;function Ig(e){return e==null||e===``?ja.download.path:e}function Lg(e){let t=e?.path??``,n=e?.template??``;return t===``&&n===``?{path:ja.note.path,template:ja.note.template}:{path:t,template:n}}function Rg(e){let t=ja.transcript,n=e??{},r=n.diarization??{};return{path:typeof n.path==`string`?n.path:t.path,template:typeof n.template==`string`?n.template:t.template,diarization:{enabled:typeof r.enabled==`boolean`?r.enabled:t.diarization.enabled,provider:zg(r.provider),speakerTemplate:typeof r.speakerTemplate==`string`?r.speakerTemplate:t.diarization.speakerTemplate}}}function zg(e){return Pg.includes(e)?e:ja.transcript.diarization.provider}function Bg(e){let t=e??{};return{path:typeof t.path==`string`?t.path:ja.feedNote.path,template:typeof t.template==`string`?t.template:ja.feedNote.template}}function Vg(e,t){let n=typeof e==`number`?e:Number(e);return Number.isFinite(n)&&n>0?Math.floor(n):t}function Hg(e){return/^(?=.*[a-z0-9])[a-z0-9-]+$/.test(e)}var Ug={openai:/^podnotes-openai-api-key(?:-[1-9]\d*)?$/,deepgram:/^podnotes-deepgram-api-key(?:-[1-9]\d*)?$/};function Wg(e,t){return Ug[e].test(t)}function Gg(e,t){if(!ag(e))return e!==void 0&&U(t,`savedFeeds`,`expected an object`),{};let n={};for(let[r,i]of rg(e,t,`savedFeeds`)){if(!ag(i)){U(t,`savedFeeds.${r}`,`expected an object; feed was skipped`);continue}let e=ng(i);e.title=Kh(i,`title`,r,t,`savedFeeds.${r}`),e.url=Kh(i,`url`,``,t,`savedFeeds.${r}`),e.artworkUrl=Kh(i,`artworkUrl`,``,t,`savedFeeds.${r}`),$h(e,i,`urlSecretId`,t,`savedFeeds.${r}`),$h(e,i,`description`,t,`savedFeeds.${r}`),$h(e,i,`link`,t,`savedFeeds.${r}`),$h(e,i,`author`,t,`savedFeeds.${r}`),typeof i.collectionId==`number`&&Number.isFinite(i.collectionId)?(e.collectionId=String(i.collectionId),U(t,`savedFeeds.${r}.collectionId`,`number was converted to text`)):$h(e,i,`collectionId`,t,`savedFeeds.${r}`),n[r]=e}return n}function Kg(e,t){if(!ag(e))return e!==void 0&&U(t,`podNotes`,`expected an object`),{};let n={};for(let[r,i]of rg(e,t,`podNotes`)){if(!ag(i)){U(t,`podNotes.${r}`,`expected an object; note mapping was skipped`);continue}n[r]={...ng(i),episodeName:Kh(i,`episodeName`,r,t,`podNotes.${r}`),filePath:Kh(i,`filePath`,``,t,`podNotes.${r}`),podcastFeedKey:Kh(i,`podcastFeedKey`,``,t,`podNotes.${r}`)}}return n}function qg(e,t){if(!ag(e))return e!==void 0&&U(t,`playedEpisodes`,`expected an object`),{};let n={};for(let[r,i]of rg(e,t,`playedEpisodes`)){if(!ag(i)){U(t,`playedEpisodes.${r}`,`expected an object; progress was skipped`);continue}n[r]={...ng(i),title:Kh(i,`title`,r,t,`playedEpisodes.${r}`),podcastName:Kh(i,`podcastName`,``,t,`playedEpisodes.${r}`),time:Xh(i,`time`,0,t,`playedEpisodes.${r}`),duration:Xh(i,`duration`,0,t,`playedEpisodes.${r}`),finished:Jh(i,`finished`,!1,t,`playedEpisodes.${r}`)}}return n}function Jg(e,t){if(!ag(e))return e!==void 0&&U(t,`playlists`,`expected an object`),{};let n={};for(let[r,i]of rg(e,t,`playlists`)){if(!ag(i)){U(t,`playlists.${r}`,`expected an object; playlist was skipped`);continue}n[r]=lg(i,{name:r,icon:`list`,episodes:[],shouldEpisodeRemoveAfterPlay:!1,shouldRepeat:!1},t,`playlists.${r}`)}return n}function Yg(e,t){if(!ag(e))return e!==void 0&&U(t,`downloadedEpisodes`,`expected an object`),{};let n={};for(let[r,i]of rg(e,t,`downloadedEpisodes`)){if(!Array.isArray(i)){U(t,`downloadedEpisodes.${r}`,`expected an array; download list was skipped`);continue}n[r]=i.flatMap((e,n)=>{let i=`downloadedEpisodes.${r}[${n}]`,a=sg(e,t,i);if(!a||!ag(e)||typeof e.filePath!=`string`)return a&&U(t,`${i}.filePath`,`missing path; download was skipped`),[];let o=typeof e.size==`number`&&Number.isFinite(e.size)&&e.size>=0?e.size:0;return o!==e.size&&U(t,`${i}.size`,`value was normalized`),[{...a,filePath:e.filePath,size:o}]})}return n}function Xg(e,t,n=2){let r=Pa(e.defaultPlaybackRate);e.defaultPlaybackRate!==void 0&&(typeof e.defaultPlaybackRate!=`number`||e.defaultPlaybackRate!==r)&&U(t,`defaultPlaybackRate`,`value was normalized`);let i=Qh(e,`defaultVolume`,ja.defaultVolume,0,1,t),a=to(e.episodeListLimit);return e.episodeListLimit!==void 0&&(typeof e.episodeListLimit!=`number`||e.episodeListLimit!==a)&&U(t,`episodeListLimit`,`value was normalized`),{savedFeeds:Gg(e.savedFeeds,t),podNotes:Kg(e.podNotes,t),defaultPlaybackRate:r,defaultVolume:i,hidePlayedEpisodes:Jh(e,`hidePlayedEpisodes`,ja.hidePlayedEpisodes,t),episodeListLimit:a,playedEpisodes:qg(e.playedEpisodes,t),skipBackwardLength:i_(e.skipBackwardLength,ja.skipBackwardLength,`skipBackwardLength`,t),skipForwardLength:i_(e.skipForwardLength,ja.skipForwardLength,`skipForwardLength`,t),playlists:Jg(e.playlists,t),queue:lg(e.queue,ja.queue,t,`queue`),autoQueue:Jh(e,`autoQueue`,ja.autoQueue,t),favorites:lg(e.favorites,ja.favorites,t,`favorites`),localFiles:lg(e.localFiles,ja.localFiles,t,`localFiles`),currentEpisode:e.currentEpisode===void 0||e.currentEpisode===null?void 0:sg(e.currentEpisode,t,`currentEpisode`),timestamp:Qg(e.timestamp,t),note:$g(e.note,t,n),feedNote:e_(e.feedNote,t),download:t_(e.download,t),downloadedEpisodes:Yg(e.downloadedEpisodes,t),openAISecretId:Zg(e,`openAISecretId`,t),deepgramSecretId:Zg(e,`deepgramSecretId`,t),transcript:n_(e.transcript,t),feedCache:r_(e.feedCache,t)}}function Zg(e,t,n){let r=Kh(e,t,ja[t],n);return!r||Wg(t===`openAISecretId`?`openai`:`deepgram`,r)?r:(U(n,t,`foreign or wrong-provider SecretStorage ID; reference was removed`),``)}function Qg(e,t){let n=tg(e,t,`timestamp`);return{...ng(n),template:Kh(n,`template`,ja.timestamp.template,t,`timestamp`),offset:Yh(n,`offset`,ja.timestamp.offset,t,`timestamp`)}}function $g(e,t,n){let r=tg(e,t,`note`),i=qh(r,`path`,t,`note`),a=qh(r,`template`,t,`note`),o=n===0?Lg({path:i,template:a}):{path:typeof i==`string`?i:ja.note.path,template:typeof a==`string`?a:ja.note.template};return{...ng(r),...o}}function e_(e,t){let n=tg(e,t,`feedNote`),r=Bg({path:qh(n,`path`,t,`feedNote`),template:qh(n,`template`,t,`feedNote`)});return{...ng(n),...r}}function t_(e,t){let n=tg(e,t,`download`);return{...ng(n),path:Ig(qh(n,`path`,t,`download`))}}function n_(e,t){let n=tg(e,t,`transcript`),r=tg(n.diarization,t,`transcript.diarization`),i=Rg({path:n.path,template:n.template,diarization:r});return n.path!==void 0&&typeof n.path!=`string`&&U(t,`transcript.path`,`expected a string`),n.template!==void 0&&typeof n.template!=`string`&&U(t,`transcript.template`,`expected a string`),r.enabled!==void 0&&typeof r.enabled!=`boolean`&&U(t,`transcript.diarization.enabled`,`expected a boolean`),r.provider!==void 0&&r.provider!==`openai`&&r.provider!==`deepgram`&&U(t,`transcript.diarization.provider`,`unknown provider`),r.speakerTemplate!==void 0&&typeof r.speakerTemplate!=`string`&&U(t,`transcript.diarization.speakerTemplate`,`expected a string`),{...ng(n),...i,diarization:{...ng(r),...i.diarization}}}function r_(e,t){let n=tg(e,t,`feedCache`);return{...ng(n),enabled:Jh(n,`enabled`,ja.feedCache.enabled,t,`feedCache`),ttlHours:Zh(n,`ttlHours`,ja.feedCache.ttlHours,t,`feedCache`)}}function i_(e,t,n,r){let i=Vg(e,t);return e!==void 0&&e!==i&&U(r,n,`value was normalized`),i}var a_=new Set([`openAIApiKey`,`diarizationApiKey`]),o_=new Set([...Object.keys(ja),...a_,`schemaVersion`]),s_=class extends Error{constructor(e,t){super(e),this.code=t,this.name=`PodNotesDataError`}};function c_(e){if(e??(e={}),!ag(e))throw new s_(`PodNotes data.json does not contain an object. The file was not modified.`,`invalid-data`);let t=u_(e),n=new Set,r=Xg(e,n,t),i=d_(e,t,n),a=[...a_].some(t=>Object.prototype.hasOwnProperty.call(e,t)),o=p_(e);return{settings:r,sourceVersion:t,changed:t!==2||a||n.size>0,warnings:[...n],legacySecrets:i,retiredPlaintextPresent:a,unknownFields:o}}function l_(e,t={}){let n=Xg(e,new Set,2);return{...p_(t),...n,schemaVersion:2,currentEpisode:n.currentEpisode?cg(n.currentEpisode):void 0,favorites:ug(n.favorites),queue:ug(n.queue),localFiles:ug(n.localFiles),playlists:ig(n.playlists,e=>ug(e)),downloadedEpisodes:ig(n.downloadedEpisodes,e=>e.map(e=>cg(e)))}}function u_(e){if(!Object.prototype.hasOwnProperty.call(e,`schemaVersion`))return 0;let t=e.schemaVersion;if(t===1||t===2)return t;throw typeof t==`number`&&Number.isInteger(t)&&t>2?new s_(`PodNotes data schema v${t} requires a newer version of PodNotes. The file was not modified.`,`unsupported-version`):new s_(`PodNotes data.json has an invalid schemaVersion. The file was not modified.`,`invalid-data`)}function d_(e,t,n){if(t>=2)return{};let r={};return f_(e,`openAIApiKey`,`openAI`,r,n),f_(e,`diarizationApiKey`,`deepgram`,r,n),r}function f_(e,t,n,r,i){let a=e[t];if(a==null||a===``)return;if(typeof a!=`string`){i.add(`${t}: expected a string; value was ignored`);return}let o=a.trim();o&&(r[n]=o)}function p_(e){let t={};for(let[n,r]of Object.entries(e))Gh.has(n)||o_.has(n)||(t[n]=r);return t}var m_=`podnotes-settings`,h_=[`podNotes`,`playedEpisodes`,`downloadedEpisodes`,`currentEpisode`],g_=new Set([`openAISecretId`,`deepgramSecretId`]),__={openAIApiKey:`openAI`,diarizationApiKey:`deepgram`},v_={openAI:`OpenAI API key`,deepgram:`Deepgram API key`};function y_(e){return Object.keys(v_).filter(t=>!!e[t]?.trim()).map(e=>v_[e])}var b_=new Set([`__proto__`,`constructor`,`prototype`]),x_=new Set(Object.keys(ja).filter(e=>!h_.includes(e)&&!g_.has(e))),S_=[`timestamp`,`note`,`feedNote`,`download`,`transcript`,`feedCache`];function C_(e){if(typeof e!=`object`||!e||Array.isArray(e))return e;let t={};for(let[n,r]of Object.entries(e))if(typeof r==`object`&&r&&!Array.isArray(r)){let e={...r};delete e.urlSecretId,t[n]=e}else t[n]=r;return t}function w_(e,t,n,r){let i={},a=l_(e);for(let t of Object.keys(e))b_.has(t)||x_.has(t)&&(i[t]=a[t]);i.savedFeeds=C_(i.savedFeeds);let o=A_(t.secrets??{});return{type:m_,version:2,pluginVersion:n,exportedAt:r,settings:i,...Object.keys(o).length>0?{secrets:o}:{}}}function T_(e){let t;try{t=JSON.parse(e)}catch{return{ok:!1,error:`File is not valid JSON.`}}if(!P_(t))return{ok:!1,error:`File does not contain a settings object.`};let n=t,r=!1,i=null,a=null,o={};if(t.type===`podnotes-settings`){if(r=!0,typeof t.version!=`number`||!Number.isInteger(t.version)||t.version<1)return{ok:!1,error:`Export file has an invalid version.`};if(t.version>2)return{ok:!1,error:`This file was exported by a newer version of PodNotes (format v${t.version}). Update PodNotes to import it.`};if(i=t.version,typeof t.pluginVersion==`string`&&(a=t.pluginVersion),!P_(t.settings))return{ok:!1,error:`Export file is missing its settings payload.`};if(n=t.settings,i>=2){let e=k_(t.secrets);if(`error`in e)return{ok:!1,error:e.error};o=e.values}else o=O_(n)}else if(Object.prototype.hasOwnProperty.call(t,`schemaVersion`))try{c_(t).sourceVersion<2&&(o=O_(n))}catch(e){if(e instanceof s_)return{ok:!1,error:e.message};throw e}else o=O_(n);let s=D_(n);return`savedFeeds`in s&&(s.savedFeeds=C_(s.savedFeeds)),Object.keys(s).length===0&&Object.keys(o).length===0?{ok:!1,error:`No recognizable PodNotes settings were found in the file.`}:{ok:!0,settings:s,secrets:o,meta:{fromEnvelope:r,version:i,pluginVersion:a,includesSecret:Object.keys(o).length>0}}}function E_(e,t){let n={...e,...t};for(let r of S_)n[r]={...ja[r],...e[r],...t[r]};return c_({...n,schemaVersion:2}).settings}function D_(e){let t={};for(let[n,r]of Object.entries(e)){if(b_.has(n)||!x_.has(n))continue;let e=ja[n];N_(e,r)&&(S_.includes(n)?t[n]=M_(e,r):n===`favorites`||n===`localFiles`?Array.isArray(r.episodes)&&(t[n]=r):t[n]=n===`playlists`?j_(r):r)}return t}function O_(e){let t={};for(let[n,r]of Object.entries(__)){let i=e[n];typeof i==`string`&&i.trim()&&(t[r]=i.trim())}return t}function k_(e){if(e===void 0)return{values:{}};if(!P_(e))return{error:`Export file has an invalid secrets payload.`};for(let t of[`openAI`,`deepgram`])if(e[t]!==void 0&&typeof e[t]!=`string`)return{error:`Export file has an invalid ${v_[t]}.`};return{values:A_(e)}}function A_(e){let t=e.openAI?.trim(),n=e.deepgram?.trim();return{...t?{openAI:t}:{},...n?{deepgram:n}:{}}}function j_(e){let t={};for(let[n,r]of Object.entries(e))b_.has(n)||P_(r)&&Array.isArray(r.episodes)&&(t[n]=r);return t}function M_(e,t){let n={};for(let[r,i]of Object.entries(t))b_.has(r)||r in e&&N_(e[r],i)&&(n[r]=i);return n}function N_(e,t){return e==null?!1:Array.isArray(e)?Array.isArray(t):typeof e==`object`?P_(t):typeof t==typeof e}function P_(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}async function F_(e){let{getClient:t,chunkFiles:n,maxRetries:r,onProgress:i,signal:a}=e;I_(a);let o=await t();I_(a);let s=[],c=0,l;for(let e=0;e<n.length;e++){I_(a),i(`Diarizing with OpenAI... chunk ${e+1}/${n.length}`);let t=n[e],u=0;for(;;){I_(a);try{let e=await o.audio.transcriptions.create({model:Fg,file:t,response_format:`diarized_json`,chunking_strategy:`auto`},{signal:a});I_(a),s.push(...ya(e));break}catch(t){if(I_(a),u++,u>=r){c++,l=t,s.push({speaker:`?`,text:`[Error diarizing chunk ${e+1}]`});break}await L_(1e3*u,a)}}}if(n.length>0&&c===n.length){let e=l instanceof Error?l.message:String(l);throw Error(`OpenAI diarization failed for every chunk: ${e}`)}return s}function I_(e){if(e.aborted)throw e.reason??new DOMException(`OpenAI diarization was aborted.`,`AbortError`)}function L_(e,t){return I_(t),new Promise((n,r)=>{let i=window.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{window.clearTimeout(i),t.removeEventListener(`abort`,a),r(t.reason??new DOMException(`OpenAI diarization was aborted.`,`AbortError`))};t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}var R_=`https://api.deepgram.com/v1/listen`,z_=18e5,B_=2147483648,V_=16777216,H_=`model=nova-3&diarize=true&punctuate=true&smart_format=true&utterances=true`;async function U_(e){let{audio:t,apiKey:n,onProgress:r,signal:i}=e;return r(`Diarizing with Deepgram...`),ba(await Rf(`${R_}?${H_}`,{method:`POST`,headers:{Authorization:`Token ${n}`},contentType:t.mimeType,body:t.buffer,timeoutMs:z_,maxRequestBodyBytes:B_,maxResponseBytes:V_,signal:i}))}function W_(e,t){let n=e.transcript?.diarization;return n?.enabled&&n.provider===`deepgram`?t(`deepgram`):t(`openai`)}function G_(e){if(typeof e!=`object`||!e||Array.isArray(e))return!1;let t=Object.getPrototypeOf(e);return t===Object.prototype||t===null}function K_(e,t){if(Object.is(e,t))return!0;if(e instanceof Date||t instanceof Date)return e instanceof Date&&t instanceof Date&&e.getTime()===t.getTime();if(Array.isArray(e)||Array.isArray(t))return Array.isArray(e)&&Array.isArray(t)&&e.length===t.length&&e.every((e,n)=>K_(e,t[n]));if(!G_(e)||!G_(t))return!1;let n=Object.keys(e),r=Object.keys(t);return n.length===r.length&&n.every(n=>Object.prototype.hasOwnProperty.call(t,n)&&K_(e[n],t[n]))}function q_(e,t,n){let r=structuredClone(n);return J_(e,t,n,r),r}function J_(e,t,n,r){for(let i of new Set([...Object.keys(e),...Object.keys(t)])){let a=Object.prototype.hasOwnProperty.call(e,i),o=Object.prototype.hasOwnProperty.call(t,i),s=Object.prototype.hasOwnProperty.call(n,i);if(!(a===o&&(!a||K_(e[i],t[i])))){if(s===o&&(!s||K_(n[i],t[i]))){a?r[i]=structuredClone(e[i]):delete r[i];continue}a&&o&&s&&G_(e[i])&&G_(t[i])&&G_(n[i])&&G_(r[i])&&J_(e[i],t[i],n[i],r[i])}}}var Y_={openAISecretId:`openai`,deepgramSecretId:`deepgram`};function X_(e){e.settingEl.setCssStyles({flexDirection:`column`,alignItems:`unset`,gap:`10px`})}function Z_(e,t){t.empty(),r.MarkdownRenderer.renderMarkdown(e,t,``,new r.Component)}var Q_=class extends r.PluginSettingTab{constructor(e,t){super(e,t),this.podcastQueryGrid=null,this.playlistManager=null,this.settingsMutationTail=Promise.resolve(),this.credentialSaveGenerations={openAISecretId:0,deepgramSecretId:0},this.settingsInteractionLockCount=0,this.settingsControlDisabledStates=new Map,this.plugin=t,this.settingsTab=this}display(){let{containerEl:e}=this;e.empty(),new r.Setting(e).setName(`PodNotes`).setHeading();let t=e.createDiv();t.classList.add(`settings-container`),new r.Setting(t).setName(`Search Podcasts`).setHeading().setDesc(`Search for podcasts by name or custom feed URL.`);let n=t.createDiv();this.podcastQueryGrid=ls(kh,{target:n}),new r.Setting(t).setName(`Playlists`).setHeading().setDesc(`Add playlists to gather podcast episodes.`);let i=t.createDiv();this.playlistManager=ls(zh,{target:i}),this.addQueueSettings(t),this.addEpisodeListSettings(t),this.addDefaultPlaybackRateSetting(t),this.addDefaultVolumeSetting(t),this.addSkipLengthSettings(t),this.addNoteSettings(t),this.addFeedNoteSettings(t),this.addDownloadSettings(t),this.addPerformanceSettings(t),this.addImportExportSettings(t),this.addTranscriptSettings(t)}hide(){this.podcastQueryGrid&&(ps(this.podcastQueryGrid),this.podcastQueryGrid=null),this.playlistManager&&(ps(this.playlistManager),this.playlistManager=null)}addQueueSettings(e){new r.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(e=>e.setValue(this.plugin.settings.autoQueue).onChange(async e=>{this.plugin.settings.autoQueue=e,await this.plugin.saveSettings(),L.set(this.plugin)}))}addEpisodeListSettings(e){new r.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-75; default 10).`).addText(e=>{e.inputEl.type=`number`,e.inputEl.min=`1`,e.inputEl.max=`75`,e.setValue(`${to(this.plugin.settings.episodeListLimit)}`).setPlaceholder(`10`).onChange(async e=>{let t=e.trim();if(t===``||!Number.isFinite(Number(t)))return;let n=to(t);n!==this.plugin.settings.episodeListLimit&&(this.plugin.settings.episodeListLimit=n,ao.set(n),await this.plugin.saveSettings())}),e.inputEl.addEventListener(`blur`,()=>{e.setValue(`${to(this.plugin.settings.episodeListLimit)}`)})})}addDefaultPlaybackRateSetting(e){new r.Setting(e).setName(`Default Playback Rate`).addSlider(e=>e.setLimits(.5,4,.1).setValue(this.plugin.settings.defaultPlaybackRate).onChange(e=>{this.plugin.settings.defaultPlaybackRate=e,this.plugin.saveSettings()}).setDynamicTooltip())}addDefaultVolumeSetting(e){new r.Setting(e).setName(`Default Volume`).setDesc(`Set the default playback volume.`).addSlider(e=>e.setLimits(0,1,.05).setValue(this.plugin.settings.defaultVolume).onChange(e=>{this.plugin.settings.defaultVolume=e,this.plugin.saveSettings()}).setDynamicTooltip())}addSkipLengthSettings(e){new r.Setting(e).setName(`Skip backward length (s)`).addText(e=>{e.inputEl.type=`number`,e.setValue(`${this.plugin.settings.skipBackwardLength}`).onChange(e=>{let t=Number.parseInt(e,10);!Number.isFinite(t)||t<=0||(this.plugin.settings.skipBackwardLength=t,this.plugin.saveSettings())}).setPlaceholder(`seconds`)}),new r.Setting(e).setName(`Skip forward length (s)`).addText(e=>{e.inputEl.type=`number`,e.setValue(`${this.plugin.settings.skipForwardLength}`).onChange(e=>{let t=Number.parseInt(e,10);!Number.isFinite(t)||t<=0||(this.plugin.settings.skipForwardLength=t,this.plugin.saveSettings())}).setPlaceholder(`seconds`)})}addNoteSettings(e){let t=e.createDiv();new r.Setting(t).setName(`Note settings`).setHeading(),X_(new r.Setting(t).setName(`Capture timestamp format`).setHeading().addTextArea(e=>{e.setValue(this.plugin.settings.timestamp.template),e.setPlaceholder(`- {{linktime}} `),e.onChange(e=>{this.plugin.settings.timestamp.template=e,this.plugin.saveSettings(),i(e)}),e.inputEl.setCssStyles({width:`100%`})}));let n=t.createDiv(),i=e=>{if(!this.plugin.api.podcast){n.setText(`Play an episode to preview the timestamp format.`);return}Z_(zd(e),n)};new r.Setting(t).setName(`Timestamp offset (s)`).setDesc(`Subtract this many seconds when capturing a timestamp to compensate for reaction time.`).addText(e=>{e.inputEl.type=`number`,e.setValue(`${this.plugin.settings.timestamp.offset}`).onChange(e=>{let t=Number.parseInt(e,10);this.plugin.settings.timestamp.offset=Number.isNaN(t)?0:Math.max(0,t),this.plugin.saveSettings(),i(this.plugin.settings.timestamp.template)}).setPlaceholder(`e.g. 5`)}),i(this.plugin.settings.timestamp.template);let a=$_();X_(new r.Setting(t).setName(`Note creation file path`).setHeading().addText(e=>{e.setValue(this.plugin.settings.note.path),e.setPlaceholder(`inputs/podcasts/{{podcast}} - {{title}}.md`),e.onChange(e=>{this.plugin.settings.note.path=e,this.plugin.saveSettings(),Z_(Bd(e,a),o)}),e.inputEl.setCssStyles({width:`100%`})}));let o=t.createDiv();X_(new r.Setting(t).setName(`Note creation template`).setHeading().addTextArea(e=>{e.setValue(this.plugin.settings.note.template),e.onChange(e=>{this.plugin.settings.note.template=e,this.plugin.saveSettings()}),e.inputEl.setCssStyles({width:`100%`,height:`25vh`}),e.setPlaceholder(`---
|
||
type: podcastEpisode
|
||
podcast: "{{podcastlink}}"
|
||
url: "{{url}}"
|
||
date: {{date:YYYY-MM-DD}}
|
||
tags:
|
||
- podcastEpisode
|
||
---
|
||
# {{title}}
|
||
|
||

|
||
|
||
{{description}}`)}))}addFeedNoteSettings(e){let t=e.createDiv();new r.Setting(t).setName(`Podcast feed note settings`).setHeading(),t.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)`});let n=ev();X_(new r.Setting(t).setName(`Feed note file path`).setHeading().addText(e=>{e.setValue(this.plugin.settings.feedNote.path),e.setPlaceholder(`PodNotes/Podcasts/{{podcast}}.md`),e.onChange(e=>{this.plugin.settings.feedNote.path=e,this.plugin.saveSettings(),a(e)}),e.inputEl.setCssStyles({width:`100%`})}));let i=t.createDiv(),a=e=>{Z_(Wd(e,n),i)};a(this.plugin.settings.feedNote.path),X_(new r.Setting(t).setName(`Feed note template`).setHeading().addTextArea(e=>{e.setValue(this.plugin.settings.feedNote.template),e.onChange(e=>{this.plugin.settings.feedNote.template=e,this.plugin.saveSettings()}),e.inputEl.setCssStyles({width:`100%`,height:`25vh`})}))}addDownloadSettings(e){new r.Setting(e).setName(`Download settings`).setHeading();let t=$_();X_(new r.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(e=>{e.setValue(this.plugin.settings.download.path),e.setPlaceholder(`inputs/podcasts/{{podcast}} - {{title}}`),e.onChange(e=>{this.plugin.settings.download.path=e,this.plugin.saveSettings(),a(e)}),e.inputEl.setCssStyles({width:`100%`})}));let n=e.createDiv(),i=e.createDiv();i.setCssStyles({color:`var(--text-error)`});let a=e=>{Z_(`${Vd(e,t)}.mp3`,n),i.toggle(!/\{\{title(:[^}]*)?\}\}/i.test(e)),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 r.Setting(e).setName(`Performance`).setHeading(),new r.Setting(e).setName(`Cache podcast feeds`).setDesc(`Store recently downloaded feeds locally for faster startup.`).addToggle(e=>e.setValue(this.plugin.settings.feedCache.enabled).onChange(async e=>{this.plugin.settings.feedCache.enabled=e,await this.plugin.saveSettings()})),new r.Setting(e).setName(`Cache duration (hours)`).setDesc(`Choose how long to reuse cached feeds before fetching again.`).addSlider(e=>e.setLimits(1,24,1).setValue(this.plugin.settings.feedCache.ttlHours).setDynamicTooltip().onChange(async e=>{this.plugin.settings.feedCache.ttlHours=e,await this.plugin.saveSettings()})),new r.Setting(e).setName(`Clear cached feeds`).setDesc(`Remove stored feed data. PodNotes will refetch feeds as needed.`).addButton(e=>e.setButtonText(`Clear cache`).onClick(()=>{Ng(),io.set({}),new r.Notice(`Cleared cached podcast feeds.`)}))}addImportExportSettings(e){new r.Setting(e).setName(`Import/Export`).setHeading(),new r.Setting(e).setName(`Import OPML`).setDesc(`Import podcasts from an OPML file.`).addButton(e=>e.setButtonText(`Import`).onClick(()=>{this.pickFile(`.opml`,async e=>{try{await Uh(e)}catch(e){new r.Notice(`Error importing OPML: ${e instanceof Error?e.message:`Unknown error`}`,1e4)}},{tooLargeMessage:`That file is too large to be an OPML file.`})}));let t=`PodNotes_Export.opml`;new r.Setting(e).setName(`Export OPML`).setDesc(`Export saved podcast feeds to an OPML file.`).addText(e=>e.setPlaceholder(`Export file name`).setValue(t).onChange(e=>{t=e})).addButton(e=>e.setButtonText(`Export`).onClick(()=>{let e=Object.values(E(ro));if(e.length===0){new r.Notice(`No podcasts to export.`);return}Wh(this.app,e,t.endsWith(`.opml`)?t:`${t}.opml`)})),this.addSettingsTransferControls(e)}addSettingsTransferControls(e){new r.Setting(e).setName(`Settings & templates`).setHeading(),new r.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(e=>e.setButtonText(`Import`).onClick(()=>{this.pickFile(`.json`,e=>this.handleSettingsImport(e))}));let t=`PodNotes_Settings.json`,n=!1;new r.Setting(e).setName(`Include API keys`).setDesc(`When enabled, a separate plaintext secrets payload is added for the OpenAI and Deepgram keys available on this device. The file is stored in your vault, so it may sync to other devices and be read by other plugins.`).addToggle(e=>e.setValue(n).onChange(e=>{n=e})),new r.Setting(e).setName(`Export settings`).setDesc(`Export PodNotes preferences, templates, feeds, and playlists.`).addText(e=>e.setPlaceholder(`Export file name`).setValue(t).onChange(e=>{t=e})).addButton(e=>e.setButtonText(`Export`).onClick(()=>{let e=t.trim()||`PodNotes_Settings.json`,r=e.endsWith(`.json`)?e:`${e}.json`;this.handleSettingsExport(r,n)}))}pickFile(e,t,n={}){let i=n.maxBytes??5242880,a=n.tooLargeMessage??`That file is too large to be a PodNotes settings file.`,o=activeDocument.createElement(`input`);o.type=`file`,o.accept=e,o.setCssStyles({display:`none`}),activeDocument.body.appendChild(o),o.oncancel=()=>o.remove(),o.onchange=e=>{let n=e.target.files?.[0];if(o.remove(),!n){new r.Notice(`No file selected.`);return}if(n.size>i){new r.Notice(a);return}let s=new FileReader;s.onload=e=>{let n=e.target?.result;typeof n==`string`?t(n):new r.Notice(`Could not read the selected file.`)},s.onerror=()=>new r.Notice(`Could not read the selected file.`),s.readAsText(n)},o.click()}async handleSettingsExport(e,t){try{let n=t?this.plugin.credentials.exportValues(this.plugin.settings,{requireConfigured:!0}):{},i=w_(this.plugin.settings,{secrets:t?n:void 0},this.plugin.manifest.version,new Date().toISOString()),a=JSON.stringify(i,null,2);if(this.app.vault.getAbstractFileByPath(e)){new r.Notice(`A file named "${e}" already exists. Choose a different name.`);return}await this.app.vault.create(e,a);let o=y_(n);new r.Notice(o.length?`Exported PodNotes settings to "${e}" (includes your ${o.join(` and `)}).`:`Exported PodNotes settings to "${e}".`)}catch(e){e instanceof Error&&e.message.includes(`Folder does not exist`)?new r.Notice(`Unable to create export file: folder does not exist.`):new r.Notice(`Unable to export settings:\n\n${e instanceof Error?e.message:`Unknown error`}`)}}handleSettingsImport(e){let t=T_(e);if(!t.ok){new r.Notice(`Could not import settings: ${t.error}`,1e4);return}let n=(e,n)=>Object.prototype.hasOwnProperty.call(t.settings,e)&&Object.keys(n??{}).length>0,i=[];n(`savedFeeds`,this.plugin.settings.savedFeeds)&&i.push(`podcast feeds`),n(`playlists`,this.plugin.settings.playlists)&&i.push(`playlists`),i.push(...y_(t.secrets));let a=i.length?` This also replaces your ${i.join(`, `)}.`:``,o=Object.keys(t.secrets).length>0?` Existing Obsidian secrets are never overwritten; conflicts are saved under a new PodNotes name.`:``;new tv(this.app,`Import PodNotes settings?`,`This overwrites your current PodNotes preferences and templates with the imported values.${a}${o} Your playback progress and downloads are kept.`,`Import`,()=>{this.applyImportedSettings(t.settings,t.secrets)}).open()}async applyImportedSettings(e,t={}){let n=this.lockSettingsInteractions();try{let n=await this.enqueueSettingsMutation(()=>this.persistImportedSettings(e,t));if(n===`failed`)return;await this.waitForSettingsMutationLaneToDrain(),this.display(),n===`complete`&&new r.Notice(`Imported PodNotes settings.`)}finally{await this.waitForSettingsMutationLaneToDrain(),n()}}async persistImportedSettings(e,t){let n=this.plugin.settings,i=structuredClone(n),a={};try{a=this.plugin.credentials.storeValues(t)}catch{return new r.Notice(`Could not finish importing API keys into Obsidian SecretStorage. Existing settings were kept, and retrying will safely reuse any PodNotes secrets already created.`,1e4),`failed`}let o=E_(i,{...e,...a});o.savedFeeds=Gp(o.savedFeeds,this.plugin.feedUrls).savedFeeds;let s=structuredClone(o),c=o.openAISecretId!==i.openAISecretId;c&&this.plugin.invalidateTranscriptionCredentialCache();let l=Uo();this.plugin.settings=o;try{await this.plugin.saveSettingsStrict()}catch{let e;try{e=q_(i,s,this.plugin.settings),l.replayInto(e)}finally{l.dispose()}this.plugin.settings=K_(e,i)&&K_(n,i)?n:e,c&&this.plugin.invalidateTranscriptionCredentialCache();try{await this.plugin.saveSettingsStrict(),new r.Notice(`Could not import PodNotes settings. The failed import was rolled back without overwriting newer changes.`,1e4)}catch{new r.Notice(`Could not import PodNotes settings or persist its rollback. The safest recovered settings remain active for this session.`,1e4)}return`failed`}l.dispose(),ro.set(o.savedFeeds),Po.set(o.playlists),Ao.set(o.favorites),ko.set(o.queue),No.set(o.localFiles),So.set(o.hidePlayedEpisodes);let u=to(o.episodeListLimit);o.episodeListLimit=u,ao.set(u);let d=Number.isFinite(o.defaultVolume)?o.defaultVolume:1;xo.set(Math.min(1,Math.max(0,d))),bo.set(Pa(o.defaultPlaybackRate));try{await this.plugin.saveSettingsStrict()}catch{return new r.Notice(`Imported PodNotes settings, but could not finish saving normalized live state. Change any setting to retry.`,1e4),`applied`}return L.set(this.plugin),`complete`}enqueueSettingsMutation(e){let t=this.settingsMutationTail.then(e);return this.settingsMutationTail=t.then(()=>void 0,()=>void 0),t}lockSettingsInteractions(){if(this.settingsInteractionLockCount++,this.settingsInteractionLockCount===1)for(let e of this.containerEl.querySelectorAll(`button, input, select, textarea`))this.settingsControlDisabledStates.set(e,e.disabled),e.disabled=!0;let e=!1;return()=>{if(!e&&(e=!0,this.settingsInteractionLockCount--,!(this.settingsInteractionLockCount>0))){for(let[e,t]of this.settingsControlDisabledStates)e.disabled=t;this.settingsControlDisabledStates.clear()}}}async waitForSettingsMutationLaneToDrain(){for(;;){let e=this.settingsMutationTail;if(await e,e===this.settingsMutationTail)return}}async saveSecretReference(e,t){let n=++this.credentialSaveGenerations[e];return{...await this.enqueueSettingsMutation(()=>this.persistSecretReference(e,t)),isLatest:n===this.credentialSaveGenerations[e]}}async persistSecretReference(e,t){let n=this.plugin.settings[e],i;try{i=t?this.plugin.credentials.adoptReference(Y_[e],t):``}catch{return new r.Notice(`Could not use the selected API key. It may no longer be available in Obsidian SecretStorage.`,0),{persistedId:n,saved:!1}}if(i===n)return{persistedId:i,saved:!0};e===`openAISecretId`&&this.plugin.invalidateTranscriptionCredentialCache(),this.plugin.settings[e]=i;try{return await this.plugin.saveSettingsStrict(),{persistedId:i,saved:!0}}catch{this.plugin.settings[e]=n,e===`openAISecretId`&&this.plugin.invalidateTranscriptionCredentialCache();try{await this.plugin.saveSettingsStrict(),new r.Notice(`Could not save the API key selection. The previous selection was kept.`,0)}catch{new r.Notice(`Could not save the API key selection or its rollback. The previous selection remains active for this session.`,0)}return{persistedId:n,saved:!1}}}async handleSecretSelection(e,t,n,r){let i=await this.saveSecretReference(e,t);i.isLatest&&(n.setValue(i.persistedId),r())}addTranscriptSettings(e){new r.Setting(e).setName(`Transcript settings`).setHeading();let t=$_(),n=new r.Setting(e).setName(`OpenAI API key`),i=()=>{n.setDesc(this.plugin.credentials.status(this.plugin.settings,`openai`)===`missing`?`The selected secret is not available on this device. Select an existing secret or create one.`:`Select an existing Obsidian secret or create one for transcription.`)};i(),n.addComponent(e=>{let t=new r.SecretComponent(this.app,e).setValue(this.plugin.settings.openAISecretId);return t.onChange(async e=>{await this.handleSecretSelection(`openAISecretId`,e,t,i)}),t}),new r.Setting(e).setName(`Transcript file path`).setDesc(`The path where transcripts will be saved. Use {{}} for dynamic values.`).addText(e=>{e.setPlaceholder(`transcripts/{{podcast}}/{{title}}.md`).setValue(this.plugin.settings.transcript.path).onChange(async e=>{this.plugin.settings.transcript.path=e,await this.plugin.saveSettings(),o(e)})});let a=e.createDiv(),o=e=>{let n=Bd(e,t);a.empty(),a.createEl(`p`,{text:`Example: ${n}`})};o(this.plugin.settings.transcript.path),X_(new r.Setting(e).setName(`Transcript template`).setDesc(`The template for the transcript file content.`).setHeading().addTextArea(e=>{e.setPlaceholder(`# {{title}}
|
||
|
||
Podcast: {{podcast}}
|
||
Date: {{date}}
|
||
URL: {{url}}
|
||
|
||
## Description
|
||
|
||
{{description}}
|
||
|
||
## Transcript
|
||
|
||
{{transcript}}`).setValue(this.plugin.settings.transcript.template).onChange(async e=>{this.plugin.settings.transcript.template=e,await this.plugin.saveSettings()}),e.inputEl.setCssStyles({width:`100%`,height:`25vh`})})),this.addDiarizationSettings(e)}addDiarizationSettings(e){let t=e.createDiv(),n=this.plugin.settings.transcript.diarization,i=()=>{};new r.Setting(t).setName(`Speaker diarization`).setDesc(`Label transcript segments by speaker. Routes the episode audio to a diarization-capable provider instead of plain Whisper.`).addToggle(e=>e.setValue(n.enabled).onChange(async e=>{this.plugin.settings.transcript.diarization.enabled=e,await this.plugin.saveSettings(),i()}));let a=new r.Setting(t).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(e=>e.addOption(`openai`,`OpenAI (gpt-4o-transcribe-diarize)`).addOption(`deepgram`,`Deepgram`).setValue(n.provider).onChange(async e=>{this.plugin.settings.transcript.diarization.provider=e,await this.plugin.saveSettings(),i()})),o=new r.Setting(t).setName(`Deepgram API key`),s=()=>{o.setDesc(this.plugin.credentials.status(this.plugin.settings,`deepgram`)===`missing`?`The selected secret is not available on this device. Select an existing secret or create one.`:`Select an Obsidian secret for Deepgram diarization, or create one at deepgram.com.`)};s(),o.addComponent(e=>{let t=new r.SecretComponent(this.app,e).setValue(this.plugin.settings.deepgramSecretId);return t.onChange(async e=>{await this.handleSecretSelection(`deepgramSecretId`,e,t,s)}),t});let c=new r.Setting(t).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(e=>e.setPlaceholder(ga).setValue(n.speakerTemplate).onChange(async e=>{this.plugin.settings.transcript.diarization.speakerTemplate=e,await this.plugin.saveSettings()}));i=()=>{a.settingEl.toggle(n.enabled),o.settingEl.toggle(n.enabled&&n.provider===`deepgram`),c.settingEl.toggle(n.enabled)},i()}};function $_(){let e={description:`demo`,content:`demo`,podcastName:`demo`,title:`demo`,url:`demo`,artworkUrl:`demo`,streamUrl:`demo`,episodeDate:new Date,feedUrl:`demo`},t=Object.values(E(io));if(!t.length)return e;let n=t[Math.floor(Math.random()*t.length)];return n.length?n[Math.floor(Math.random()*n.length)]:e}function ev(){let e={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`},t=Object.values(E(ro));return t.length?t[Math.floor(Math.random()*t.length)]:e}var tv=class extends r.Modal{constructor(e,t,n,r,i){super(e),this.title=t,this.body=n,this.confirmText=r,this.onConfirm=i}onOpen(){let{contentEl:e}=this;e.createEl(`h3`,{text:this.title}),e.createEl(`p`,{text:this.body}),new r.Setting(e).addButton(e=>e.setButtonText(`Cancel`).onClick(()=>this.close())).addButton(e=>e.setButtonText(this.confirmText).setWarning().onClick(()=>{this.close(),this.onConfirm()}))}onClose(){this.contentEl.empty()}},nv=z(`<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>`),rv={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 iv(e,t){lt(t,!1),Gs(e,rv);let n=V(t,`playlist`,8),r=Fc();function i(e){r(`clickPlaylist`,{playlist:n(),event:e})}Oc();var a=nv(),o=w(a);Wc(o,{get icon(){return F(n()),P(()=>n().icon)},size:32,clickable:!1});var s=T(o,2),c=w(s,!0);C(s);var l=T(s,2),u=w(l);C(l),C(a),ta(()=>{oc(a,`aria-label`,(F(n()),P(()=>n().name))),oc(a,`title`,(F(n()),P(()=>n().name))),cs(c,(F(n()),P(()=>n().name))),cs(u,`(${F(n()),P(()=>n().episodes.length)??``})`)}),R(`click`,a,i),B(e,a),ut()}var av=z(`<button type="button" class="pn_image_container svelte-ds4mor"><img draggable="false"/></button>`),ov=z(`<div class="pn_image_container pn_image_container--static svelte-ds4mor"><img draggable="false"/></div>`),sv={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 cv(e,t){lt(t,!1),Gs(e,sv);let n=V(t,`src`,8),r=V(t,`alt`,8),i=V(t,`fadeIn`,8,!1),a=V(t,`opacity`,8,0),o=V(t,`interactive`,8,!1),s=V(t,`loading`,8,`lazy`),c=V(t,`class`,8,``),l=A(!1),u=A(!0),d=A(!1),f=Fc();function p(e){f(`click`,{event:e})}Oc();var m=os(),h=Rt(m),g=e=>{var t=os(),f=Rt(t),m=e=>{var t=av(),o=w(t);let f;C(t),ta(()=>{oc(o,`src`,n()),oc(o,`alt`,r()),oc(o,`loading`,s()),ec(o,1,Js(c()),`svelte-ds4mor`),f=nc(o,``,f,{opacity:a()?a():i()?+!!N(l):1,transition:i()?`opacity 0.5s ease-out`:``})}),R(`load`,o,()=>{j(l,!0),j(u,!1)}),R(`error`,o,()=>{j(d,!0),j(u,!1)}),R(`click`,t,p),B(e,t)},h=e=>{var t=ov(),o=w(t);let f;C(t),ta(()=>{oc(o,`src`,n()),oc(o,`alt`,r()),oc(o,`loading`,s()),ec(o,1,Js(c()),`svelte-ds4mor`),f=nc(o,``,f,{opacity:a()?a():i()?+!!N(l):1,transition:i()?`opacity 0.5s ease-out`:``})}),R(`load`,o,()=>{j(l,!0),j(u,!1)}),R(`error`,o,()=>{j(d,!0),j(u,!1)}),B(e,t)};Ss(f,e=>{o()?e(m):e(h,-1)}),B(e,t)},_=e=>{var n=os();Ps(Rt(n),t,`fallback`,{},null),B(e,n)};Ss(h,e=>{N(u)||N(l)?e(g):N(d)&&e(_,1)}),B(e,m),ut()}var lv={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 uv(e,t){lt(t,!1),Gs(e,lv);let n=V(t,`feed`,8),r=Fc();function i(e){r(`clickPodcast`,{feed:e})}Oc();var a=ir(()=>i.bind(null,n()));cv(e,{get src(){return F(n()),P(()=>n().artworkUrl)},get alt(){return F(n()),P(()=>n().title)},interactive:!0,class:`podcast-image`,$$events:{click(...e){N(a)?.apply(this,e)}}}),ut()}var dv=z(`<div><p>No saved podcasts.</p></div>`),fv=z(`<div class="podcast-grid svelte-1x0bcng"><!> <!></div>`),pv={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 mv(e,t){lt(t,!1),Gs(e,pv);let n=V(t,`feeds`,24,()=>[]),r=V(t,`playlists`,24,()=>[]),i=Fc();function a({detail:{playlist:e,event:t}}){i(`clickPlaylist`,{playlist:e,event:t})}Oc();var o=fv(),s=w(o),c=e=>{var t=os();Ds(Rt(t),1,r,e=>e.name,(e,t)=>{iv(e,{get playlist(){return N(t)},$$events:{clickPlaylist:a}})}),B(e,t)};Ss(s,e=>{F(r()),P(()=>r().length>0)&&e(c)});var l=T(s,2),u=e=>{var r=os();Ds(Rt(r),1,n,e=>e.url,(e,n)=>{uv(e,{get feed(){return N(n)},$$events:{clickPodcast(e){Ac.call(this,t,e)}}})}),B(e,r)},d=e=>{B(e,dv())};Ss(l,e=>{F(n()),P(()=>n().length>0)?e(u):e(d,-1)}),C(o),B(e,o),ut()}var hv=z(`<span></span>`);function gv(e,t){lt(t,!1);let n=V(t,`value`,8),i=V(t,`limits`,8),a=A(),o=Fc(),s=A(),c=V(t,`style`,24,()=>({})),l=null,u=!1;Mc(()=>{j(s,new r.SliderComponent(N(a))),l=e=>{if(u)return;let t=Number(e.target.value);o(`change`,{value:t})},N(s).sliderEl.addEventListener(`input`,l)}),Nc(()=>{N(s)?.sliderEl&&l&&N(s).sliderEl.removeEventListener(`input`,l)});function d(e,t,n,r){let i=typeof e.getValue==`function`?e.getValue():Number(e.sliderEl?.value);t!==void 0&&i!==t&&(u=!0,e.setValue(t),u=!1),n&&(n.length===2?e.setLimits(n[0],n[1],1):e.setLimits(n[0],n[1],n[2])),r&&e.sliderEl.setAttr(`style`,Bc(r))}Zi(()=>(N(s),F(n()),F(i()),F(c())),()=>{N(s)&&d(N(s),n(),i(),c())}),Qi(),Oc();var f=hv();Tc(f,e=>j(a,e),()=>N(a)),B(e,f),ut()}var _v=z(`<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>`),vv={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:-0.9s;-moz-animation-delay:-0.9s;-o-animation-delay:-0.9s;animation-delay:-0.9s;}.la-line-scale.svelte-k6ycv0 > div:where(.svelte-k6ycv0):nth-child(5) {-webkit-animation-delay:-0.8s;-moz-animation-delay:-0.8s;-o-animation-delay:-0.8s;animation-delay:-0.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(0.4);
|
||
transform: scaleY(0.4);
|
||
}
|
||
20% {
|
||
-webkit-transform: scaleY(1);
|
||
transform: scaleY(1);
|
||
}
|
||
}
|
||
@-moz-keyframes svelte-k6ycv0-line-scale {
|
||
0%,
|
||
40%,
|
||
100% {
|
||
-webkit-transform: scaleY(0.4);
|
||
-moz-transform: scaleY(0.4);
|
||
transform: scaleY(0.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(0.4);
|
||
-o-transform: scaleY(0.4);
|
||
transform: scaleY(0.4);
|
||
}
|
||
20% {
|
||
-webkit-transform: scaleY(1);
|
||
-o-transform: scaleY(1);
|
||
transform: scaleY(1);
|
||
}
|
||
}
|
||
@keyframes svelte-k6ycv0-line-scale {
|
||
0%,
|
||
40%,
|
||
100% {
|
||
-webkit-transform: scaleY(0.4);
|
||
-moz-transform: scaleY(0.4);
|
||
-o-transform: scaleY(0.4);
|
||
transform: scaleY(0.4);
|
||
}
|
||
20% {
|
||
-webkit-transform: scaleY(1);
|
||
-moz-transform: scaleY(1);
|
||
-o-transform: scaleY(1);
|
||
transform: scaleY(1);
|
||
}
|
||
}`};function yv(e){Gs(e,vv),B(e,_v())}var bv=z(`<div class="image-loader svelte-jp8vu"><!></div>`),xv={hash:`svelte-jp8vu`,code:`.image-loader.svelte-jp8vu {position:relative;width:100%;}`};function Sv(e,t){lt(t,!1),Gs(e,xv);let n=A(),r=A(),i=A(),a=V(t,`src`,8),o=V(t,`alt`,8),s=V(t,`fadeIn`,8,!1),c=V(t,`interactive`,8,!1),l=V(t,`width`,8),u=V(t,`height`,8),d=V(t,`aspectRatio`,8,`1 / 1`),f=V(t,`loading`,8,`lazy`),p=V(t,`class`,8,``),m=Fc(),h=e=>typeof e==`number`?`${e}px`:e;Zi(()=>F(l()),()=>{j(n,h(l()))}),Zi(()=>F(u()),()=>{j(r,h(u()))}),Zi(()=>(N(r),F(d())),()=>{j(i,N(r)?void 0:d())}),Qi(),Oc();var g=bv();let _;cv(w(g),{get alt(){return o()},get src(){return a()},get fadeIn(){return s()},get interactive(){return c()},get loading(){return f()},get class(){return p()},$$events:{click:e=>m(`click`,{event:e})}}),C(g),ta(()=>_=nc(g,``,_,{width:N(n),height:N(r),"aspect-ratio":N(i)})),B(e,g),ut()}var Cv=z(`<div class="podcast-episode-thumbnail-container svelte-dmhmse"><!></div>`),wv=z(`<div class="podcast-episode-thumbnail-container svelte-dmhmse"></div>`),Tv=z(`<span class="episode-item-status svelte-dmhmse"> </span>`),Ev=z(`<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>`),Dv={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 Ov(e,t){lt(t,!1),Gs(e,Dv);let n=V(t,`episode`,8),r=V(t,`episodeFinished`,8,!1),i=V(t,`showEpisodeImage`,8,!1),a=V(t,`unavailableReason`,8,void 0),o=Fc(),s=new Intl.DateTimeFormat(`en-GB`,{day:`2-digit`,month:`long`,year:`numeric`}),c=new Map,l=A();function u(){o(`clickEpisode`,{episode:n()})}function d(e){o(`contextMenu`,{episode:n(),event:e})}function f(){if(!N(l))return;let e=N(l).getBoundingClientRect();o(`contextMenu`,{episode:n(),event:{x:e.left,y:e.bottom}})}function p(e){if(!e)return null;let t=new Date(e);return Number.isNaN(t.getTime())?null:t}function m(e,t){return`${e.url??e.streamUrl??e.title??`episode`}|${t.getTime()}`}function h(e){let t=p(e?.episodeDate);if(!t)return``;let n=m(e,t),r=c.get(n);if(r)return r;let i=s.format(t).toUpperCase();return c.set(n,i),i}let g=A(``);Zi(()=>F(n()),()=>{j(g,h(n()))}),Qi(),Oc();var _=Ev(),v=w(_),y=w(v),b=e=>{var t=Cv();Sv(w(t),{get src(){return F(n()),P(()=>n().artworkUrl)},get alt(){return F(n()),P(()=>n().title)},fadeIn:!0,width:`100%`,height:`100%`,class:`podcast-episode-thumbnail`}),C(t),B(e,t)},x=e=>{B(e,wv())};Ss(y,e=>{F(i()),F(n()),P(()=>i()&&n()?.artworkUrl)?e(b):i()&&e(x,1)});var S=T(y,2),ee=w(S),te=w(ee,!0);C(ee);var ne=T(ee,2),re=w(ne,!0);C(ne);var ie=T(ne,2),ae=e=>{var t=Tv(),n=w(t,!0);C(t),ta(()=>cs(n,a())),B(e,t)};Ss(ie,e=>{a()&&e(ae)}),C(S),C(v);var oe=T(v,2),se=w(oe);{let e=ar(()=>(F(n()),P(()=>`More options for ${n().title}`)));Wc(se,{icon:`more-vertical`,size:20,get label(){return N(e)},$$events:{click:f}})}C(oe),Tc(oe,e=>j(l,e),()=>N(l)),C(_),ta(()=>{oc(v,`title`,(F(a()),F(n()),P(()=>a()??n().title))),cs(te,N(g)),ec(ne,1,`episode-item-title ${r()&&`strikeout`}`,`svelte-dmhmse`),cs(re,(F(n()),P(()=>n().title)))}),R(`click`,v,u),R(`contextmenu`,v,d),B(e,_),ut()}function kv(e){return{episode:e,isAvailable:!0}}function Av(e){return e.map(kv)}function jv(e,t){let n=Pv(t.flat());return Ya(e).map(({key:e,episode:t})=>Mv(e,t,n)).sort(Iv)}function Mv(e,t,n){let r=Nv(e,t,n);return r?{episode:r,isAvailable:!0,playedEpisode:t,playedEpisodeKey:e}:{episode:Fv(t),isAvailable:!1,unavailableReason:`Unavailable in current feeds`,playedEpisode:t,playedEpisodeKey:e}}function Nv(e,t,n){let r=[e,qa(t),t.title];for(let e of r){let t=n.get(e);if(t)return t}}function Pv(e){let t=new Map;for(let n of e){let e=[Ha(n),n.podcastName?`${n.podcastName}::${n.title}`:``,n.title].filter(Boolean);for(let r of e)t.has(r)||t.set(r,n)}return t}function Fv(e){return{title:e.title,podcastName:e.podcastName,streamUrl:``,url:``,description:``,content:``}}function Iv(e,t){if(e.isAvailable!==t.isAvailable)return e.isAvailable?-1:1;let n=Lv(e.episode),r=Lv(t.episode);return n===r?e.episode.title.localeCompare(t.episode.title):r-n}function Lv(e){if(!e.episodeDate)return 0;let t=Number(new Date(e.episodeDate));return Number.isNaN(t)?0:t}var Rv=z(`<div class="episode-list-menu svelte-ozfrsd"><div class="episode-list-search svelte-ozfrsd"><!></div> <!> <!></div>`),zv=z(`<div class="episode-list-loading svelte-ozfrsd" role="status" aria-live="polite"><!> <span>Fetching episodes...</span></div>`),Bv=z(`<p class="svelte-ozfrsd">No episodes found.</p>`),Vv=z(`<div class="episode-list-view-container svelte-ozfrsd"><!> <!> <div class="podcast-episode-list svelte-ozfrsd"><!> <!> <!></div></div>`),Hv={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 Uv(e,t){lt(t,!1),Gs(e,Hv);let n=()=>sn(So,`$hidePlayedEpisodes`,i),r=()=>sn(To,`$playedEpisodes`,i),[i,a]=ln(),o=A(),s=A(),c=A(),l=V(t,`episodes`,24,()=>[]),u=V(t,`episodeEntries`,8,null),d=V(t,`showThumbnails`,8,!1),f=V(t,`showListMenu`,8,!0),p=V(t,`showPlayedToggle`,8,!0),m=V(t,`alwaysShowPlayedEpisodes`,8,!1),h=V(t,`isLoading`,8,!1),g=A(``),_=Fc();function v(e,t){_(`clickEpisode`,{episode:t.detail.episode,entry:e})}function y(e,t){_(`contextMenuEpisode`,{episode:t.detail.episode,entry:e,event:t.detail.event})}function b(e){_(`search`,{query:e.detail.value})}Zi(()=>(F(u()),F(l())),()=>{j(o,u()??Av(l()))}),Zi(()=>(n(),F(m())),()=>{j(s,n()&&!m())}),Zi(()=>(N(o),N(s),r()),()=>{j(c,N(o).filter(e=>!N(s)||!Ka(e.episode,r())))}),Qi(),Oc();var x=Vv(),S=w(x);Ps(S,t,`header`,{},e=>{B(e,as(`Fallback`))});var ee=T(S,2),te=e=>{var t=Rv(),r=w(t);hh(w(r),{placeholder:`Search episodes`,style:{width:`100%`},get value(){return N(g)},set value(e){j(g,e)},$$events:{input:b},$$legacy:!0}),C(r);var i=T(r,2),a=e=>{{let t=ar(()=>n()?`eye-off`:`eye`),r=ar(()=>n()?`Show played episodes`:`Hide played episodes`);Wc(e,{get icon(){return N(t)},size:25,get label(){return N(r)},get pressed(){return n()},$$events:{click:()=>So.update(e=>!e)}})}};Ss(i,e=>{p()&&e(a)}),Wc(T(i,2),{icon:`refresh-cw`,size:25,label:`Refresh episodes`,$$events:{click:()=>_(`clickRefresh`)}}),C(t),B(e,t)};Ss(ee,e=>{f()&&e(te)});var ne=T(ee,2),re=w(ne),ie=e=>{var t=zv();yv(w(t),{}),bt(2),C(t),B(e,t)};Ss(re,e=>{h()&&e(ie)});var ae=T(re,2),oe=e=>{B(e,Bv())};Ss(ae,e=>{N(c),F(h()),P(()=>N(c).length===0&&!h())&&e(oe)}),Ds(T(ae,2),3,()=>N(c),(e,t)=>Ha(e.episode)??`${e.episode.title}-${e.episode.episodeDate??``}-${t}`,(e,t)=>{var n=ir(()=>v.bind(null,N(t))),i=ir(()=>y.bind(null,N(t)));{let a=ar(()=>(F(Ka),N(t),r(),P(()=>Ka(N(t).episode,r()))));Ov(e,{get episode(){return N(t),P(()=>N(t).episode)},get episodeFinished(){return N(a)},get showEpisodeImage(){return d()},get unavailableReason(){return N(t),P(()=>N(t).unavailableReason)},$$events:{clickEpisode(...e){N(n)?.apply(this,e)},contextMenu(...e){N(i)?.apply(this,e)}}})}}),C(ne),C(x),B(e,x),ut(),a()}var Wv=z(`<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>`),Gv=z(`<ul class="chapters svelte-1vxfdxx"></ul>`),Kv=z(`<div class="chapter-list svelte-1vxfdxx"><button type="button" class="chapter-header svelte-1vxfdxx"><!> <h3 class="svelte-1vxfdxx"> </h3></button> <!></div>`),qv={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 Jv(e,t){lt(t,!1),Gs(e,qv);let n=A(),r=V(t,`chapters`,24,()=>[]),i=V(t,`currentTime`,8,0),a=Fc(),o=A(!0),s=`chapter-list-`+Math.random().toString(36).slice(2);function c(e,t){for(let n=e.length-1;n>=0;n--)if(t>=e[n].startTime)return n;return-1}function l(e){a(`seek`,{time:e.startTime})}Zi(()=>(F(r()),F(i())),()=>{j(n,c(r(),i()))}),Qi(),Oc();var u=os(),d=Rt(u),f=e=>{var t=Kv(),i=w(t),a=w(i);{let e=ar(()=>N(o)?`chevron-down`:`chevron-right`);Wc(a,{get icon(){return N(e)},size:16})}var c=T(a,2),u=w(c);C(c),C(i);var d=T(i,2),f=e=>{var t=Gv();Ds(t,5,r,Cs,(e,t,r)=>{var i=Wv();let a;var o=w(i),s=w(o),c=w(s,!0);C(s);var u=T(s,2),d=w(u,!0);C(u),C(o),C(i),ta(e=>{a=ec(i,1,`svelte-1vxfdxx`,null,a,{active:r===N(n)}),oc(o,`aria-label`,(N(t),P(()=>`Jump to ${N(t).title}`))),cs(c,e),cs(d,(N(t),P(()=>N(t).title)))},[()=>(F(Du),N(t),P(()=>Du(N(t).startTime,`H:mm:ss`)))]),R(`click`,o,()=>l(N(t))),B(e,i)}),C(t),ta(()=>oc(t,`id`,s)),B(e,t)};Ss(d,e=>{N(o)&&e(f)}),C(t),ta(()=>{oc(i,`aria-expanded`,N(o)),oc(i,`aria-controls`,N(o)?s:void 0),cs(u,`Chapters (${F(r()),P(()=>r().length)??``})`)}),R(`click`,i,()=>j(o,!N(o))),B(e,t)};Ss(d,e=>{F(r()),P(()=>r().length>0)&&e(f)}),B(e,u),ut()}var Yv=z(`<div class="progress svelte-aac6sw" role="slider" tabindex="0" aria-valuemin="0"><div class="progress__bar svelte-aac6sw"></div></div>`),Xv={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 Zv(e,t){lt(t,!1),Gs(e,Xv);let n=V(t,`max`,8),r=V(t,`value`,8),i=V(t,`ariaLabel`,8,`Seek`),a=V(t,`valueText`,8,void 0),o=!1,s=V(t,`style`,24,()=>({})),c=A(),l=A(),u=Fc();function d(e,t){u(`click`,{event:e,percent:t})}function f(){o=!0}function p(){o=!1}function m(e){o&&d(e)}function h(e){if(!N(c)||!n())return;let t=n()*.05,i=r();switch(e.key){case`ArrowRight`:case`ArrowUp`:i=Math.min(n(),r()+t);break;case`ArrowLeft`:case`ArrowDown`:i=Math.max(0,r()-t);break;case`Home`:i=0;break;case`End`:i=n();break;case`Enter`:case` `:i=r();break;default:return}e.preventDefault(),d(e,n()?i/n():0)}Zi(()=>F(s()),()=>{j(l,Bc(s()))}),Qi(),Oc();var g=Yv(),_=w(g);C(g),Tc(g,e=>j(c,e),()=>N(c)),ta(e=>{oc(g,`aria-label`,i()),oc(g,`aria-valuemax`,n()),oc(g,`aria-valuenow`,r()),oc(g,`aria-valuetext`,a()),nc(g,N(l)),nc(_,e)},[()=>(F(n()),F(r()),P(()=>`width: ${n()?Math.min(100,r()/n()*100):0}%;`))]),R(`click`,g,d),R(`mousedown`,g,f),R(`mouseup`,g,p),R(`mousemove`,g,m),R(`keydown`,g,h),B(e,g),ut()}function Qv(e,t,n){if(e!==I.Player)return[];let r=t.findIndex(e=>e.title===n.title);if(r===-1||t.length<=1)return[];let i=[],a=r===0,o=r===t.length-1;return a||(i.push({icon:`chevrons-up`,title:`Move to top of queue`,kind:`top`,index:r}),i.push({icon:`chevron-up`,title:`Move up in queue`,kind:`up`,index:r})),o||(i.push({icon:`chevron-down`,title:`Move down in queue`,kind:`down`,index:r}),i.push({icon:`chevrons-down`,title:`Move to bottom of queue`,kind:`bottom`,index:r})),i}function $v(e,t,n,i){let a=new r.Menu;if(n?.play||a.addItem(t=>t.setIcon(`play`).setTitle(`Play`).onClick(()=>{Co.set(e),Io.set(I.Player)})),!n?.markPlayed){let t=E(To),n=i?t[i]?.finished??Ka(e,t):Ka(e,t);a.addItem(t=>t.setIcon(n?`x`:`check`).setTitle(`Mark as ${n?`Unplayed`:`Played`}`).onClick(()=>{n?i?To.markKeyAsUnplayed(i):To.markAsUnplayed(e):To.markAsPlayed(e)}))}if(!n?.download){let t=ho.isEpisodeDownloaded(e);a.addItem(n=>n.setIcon(t?`cross`:`download`).setTitle(t?`Remove file`:`Download`).onClick(()=>{t?zm(e):Pm(e,E(L).settings.download.path).catch(e=>void 0)}))}if(!n?.createNote){let t=!!op(e);a.addItem(n=>n.setIcon(`pencil`).setTitle(`${t?`Open`:`Create`} Note`).onClick(async()=>{if(t)cp(e);else{let{path:t,template:n}=E(L).settings.note;if(!(t&&n)){new r.Notice(`Please set a note path and template in the settings.`);return}await rp(e)}}));let n=ey(e),i=!!Jp(n);a.addItem(e=>e.setIcon(`rss`).setTitle(`${i?`Open`:`Create`} feed note`).onClick(async()=>{if(i)Yp(n);else{let{path:e,template:t}=E(L).settings.feedNote;if(!e||!t){new r.Notice(`Please set a podcast feed note path and template in the settings.`);return}await Xp(n)}}))}if(!n?.favorite){let t=E(Ao).episodes.find(t=>Wa(t,e));a.addItem(n=>n.setIcon(`lucide-star`).setTitle(`${t?`Remove from`:`Add to`} Favorites`).onClick(()=>{t?Ao.update(t=>(t.episodes=t.episodes.filter(t=>!Wa(t,e)),t)):Ao.update(t=>(t.episodes=[...t.episodes,e],t))}))}if(!n?.queue){let t=E(ko).episodes.find(t=>t.title===e.title);a.addItem(n=>n.setIcon(`list-ordered`).setTitle(`${t?`Remove from`:`Add to`} Queue`).onClick(()=>{t?ko.remove(e):ko.add(e)}));let n=Qv(E(Io),E(ko).episodes,e);if(n.length>0){a.addSeparator();for(let t of n)a.addItem(n=>n.setIcon(t.icon).setTitle(t.title).onClick(()=>{let n=E(ko).episodes.findIndex(t=>t.title===e.title);if(n!==-1)switch(t.kind){case`top`:ko.moveToTop(n);break;case`up`:ko.moveUp(n);break;case`down`:ko.moveDown(n);break;case`bottom`:ko.moveToBottom(n)}}))}}if(!n?.playlists){let t=E(Po),n=Object.values(t);if(n.length>0){a.addSeparator();for(let t of n){let n=t.episodes.find(t=>Wa(t,e));a.addItem(r=>r.setIcon(t.icon).setTitle(`${n?`Remove from`:`Add to`} ${t.name}`).onClick(()=>{n?Po.update(n=>(n[t.name].episodes=n[t.name].episodes.filter(t=>!Wa(t,e)),n)):Po.update(n=>{let r=[...n[t.name].episodes,e];return n[t.name].episodes=r,n})}))}}}t instanceof MouseEvent?a.showAtMouseEvent(t):a.showAtPosition(t)}function ey(e){return E(ro)[e.podcastName]||{title:e.podcastName,url:e.feedUrl??``,artworkUrl:e.artworkUrl??``}}function ty(e,t){let n=e.getAbstractFileByPath(t);return!n||!(n instanceof r.TFile)?``:e.getResourcePath(n)}var ny=z(`<div class="podcast-artwork-isloading-overlay svelte-vlhi04"><!></div>`),ry=z(`<div class="podcast-artwork-load-error svelte-vlhi04" role="alert"><!> <span> </span></div>`),iy=z(`<button type="button" aria-label="Toggle playback"><!></button>`),ay=z(`<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),oy=z(`<div><!></div>`),sy=z(`<div class="episode-image-container svelte-vlhi04"><button type="button" class="hover-container svelte-vlhi04" aria-label="Toggle playback"><!> <!></button></div>`),cy=z(`<audio></audio>`),ly=z(`<h3>Queue</h3>`),uy=z(`<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>`),dy={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-load-error.svelte-vlhi04 {position:absolute;top:0;left:0;width:100%;height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:0.5rem;text-align:center;padding:0.5rem;background-color:rgba(0, 0, 0, 0.6);color:var(--text-error);font-size:0.85rem;}.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 fy(e,t){lt(t,!1),Gs(e,dy);let n=()=>sn(L,`$plugin`,p),r=()=>sn(ko,`$queue`,p),i=()=>sn(Co,`$currentEpisode`,p),a=()=>sn(ho,`$downloadedEpisodes`,p),o=()=>sn(yo,`$duration`,p),s=()=>sn(vo,`$activePlaybackSegment`,p),c=()=>sn(go,`$currentTime`,p),l=()=>sn(To,`$playedEpisodes`,p),u=()=>sn(_o,`$requestedPlaybackTime`,p),d=()=>sn(bo,`$playbackRate`,p),f=()=>sn(wo,`$isPaused`,p),[p,m]=ln(),h=A(),g=A(),_=A(),v=A(),y=e=>Math.min(1,Math.max(0,e)),b=A(Ae(i())),x=A(!1),S=A(!0),ee=A(null),te=!1,ne=A(1),re=A(null),ie=!1,ae=A([]),oe,se=null;function ce(){wo.update(e=>!e)}function le({detail:{event:e,percent:t}}){if(typeof t==`number`){ge(t*o());return}if(e instanceof MouseEvent){let t=e.currentTarget;ge((t.offsetWidth?e.offsetX/t.offsetWidth:0)*o())}}function ue(){Po.update(e=>(Object.values(e).forEach(e=>{e.episodes=e.episodes.filter(e=>!Wa(e,i()))}),e)),ko.remove(i())}function de(){let e=s();if(e&&Ua(i(),e.episodeKey)){let t=Number.isFinite(o())&&o()>0?Math.min(e.endTime,o()):c();go.set(t),se=t,vo.set(null),wo.set(!0);return}To.markAsPlayed(i()),ue(),ko.playNext()}function fe(e){bo.set(Pa(e.detail.value))}function pe(e){let t=y(e.detail.value);xo.set(t)}function me(e){ge(e.detail.time)}function he(){let e=N(re)?.closest(`.episode-video-container`);if(e?.requestFullscreen){e.requestFullscreen();return}let t=N(re);t?.requestFullscreen?t.requestFullscreen():t?.webkitEnterFullscreen&&t.webkitEnterFullscreen()}function ge(e){vo.set(null),se=null,go.set(e)}function _e(){j(S,!1),j(ee,null),te=!0,ye()}function ve(){j(S,!1),j(ee,`Could not load this episode's media.`)}function ye(){let e=l(),t=i(),n=u();if(!t){go.set(0),wo.set(!1);return}if(n!==null){if(_o.set(null),vo.set(null),se=null,!Ua(t,n.episodeKey)){be(t,e);return}go.set(n.time),vo.set(n.endTime===void 0?null:{episodeKey:n.episodeKey,startTime:n.time,endTime:n.endTime}),wo.set(!1);return}vo.set(null),se=null,be(t,e)}function be(e,t){let n=Ha(e),r=t[e.title],i=!!r&&(!r.podcastName||!e.podcastName||r.podcastName===e.podcastName),a=n&&t[n]||(i?r:void 0);a?.time?go.set(a.time):go.set(0),wo.set(!1)}let xe=-1/0;function Se(){!te||!i()||we()||To.setEpisodeTime(i(),c(),o(),o()>0&&c()===o())}function Ce(e){if(Te(e))return;let t=Date.now();t-xe<5e3||(xe=t,Se())}function we(){let e=s();return e&&Ua(i(),e.episodeKey)?!0:se===null?!1:c()===se||(se=null,!1)}function Te(e){let t=s();if(!t)return!1;if(!Ua(i(),t.episodeKey))return vo.set(null),!1;if(c()<t.endTime)return!1;let n=e.currentTarget;return n&&(n.currentTime=t.endTime),go.set(t.endTime),se=t.endTime,vo.set(null),wo.set(!0),!0}function Ee(){Se()}Mc(()=>{let e=Co.subscribe(e=>{j(S,!0),j(ee,null),te=!1,xe=-1/0,se=null,ie&&(go.set(0),yo.set(0)),ie=!0;let t=e?.chaptersUrl;if(t&&t!==oe){oe=t,j(ae,[]);let e=t;Uf(e).then(t=>{e===oe&&j(ae,t)})}else t||(oe=void 0,j(ae,[]))}),t=xo.subscribe(e=>{j(ne,y(e))}),n=()=>{document.visibilityState===`hidden`&&Se()};return document.addEventListener(`visibilitychange`,n),()=>{e(),t(),document.removeEventListener(`visibilitychange`,n)}}),Nc(()=>{Se(),wo.set(!0)});function De({detail:{event:e,episode:t}}){$v(t,e)}function Oe(e){$v(i(),e,{play:!0,markPlayed:!0})}function ke(e){let{episode:t}=e.detail;Co.set(t),Io.set(I.Player)}function Ae(e,t={}){if(!e)return{src:``,mediaType:`audio`};let r=je(e,t);return Me(e,r)?{src:ty(n().app.vault,r.filePath),mediaType:Ne(e,r)}:{src:e.streamUrl,mediaType:_p(e)}}function je(e,t){return t[e.podcastName]?.find(t=>t.title===e.title)}function Me(e,t){if(!t?.filePath)return!1;let n=Ne(e,t);if(e.mediaType&&n!==e.mediaType)return!1;if(e.podcastName===`local file`){let n=e.filePath;return!n||t.filePath===n}return bp(t.streamUrl,e.streamUrl)}function Ne(e,t){return yp(t,e.mediaType)}Zi(()=>(n(),r()),()=>{j(h,n()?.settings?.autoQueue!==!1||r().episodes.length>0)}),Zi(()=>i(),()=>{j(g,i()?.title?.length??0)}),Zi(()=>(i(),a()),()=>{j(b,Ae(i(),a()))}),Zi(()=>N(b),()=>{j(_,N(b).mediaType)}),Zi(()=>N(_),()=>{j(v,N(_)===`video`)}),Zi(()=>(N(re),d()),()=>{N(re)&&N(re).playbackRate!==d()&&ci(re,N(re).playbackRate=d())}),Qi(),Oc();var Pe=uy(),Fe=w(Pe),Ie=e=>{var n=ay(),r=w(n);r.autoplay=!0,Tc(r,e=>j(re,e),()=>N(re));var a=T(r,2),o=e=>{var t=ny();yv(w(t),{}),C(t),B(e,t)},s=e=>{var t=ry(),n=w(t);Wc(n,{icon:`alert-triangle`,clickable:!1});var r=T(n,2),i=w(r,!0);C(r),C(t),ta(()=>cs(i,N(ee))),B(e,t)},l=e=>{var t=iy();let n;var r=w(t);{let e=ar(()=>f()?`play`:`pause`);Wc(r,{get icon(){return N(e)},clickable:!1})}C(t),ta(()=>n=ec(t,1,`podcast-video-overlay svelte-vlhi04`,null,n,{visible:f()})),R(`click`,t,ce),R(`contextmenu`,t,Oe),B(e,t)};Ss(a,e=>{N(S)?e(o):N(ee)?e(s,1):e(l,-1)});var u=T(a,2);Wc(w(u),{icon:`maximize`,clickable:!1}),C(u),C(n),ta(()=>{oc(r,`src`,(N(b),P(()=>N(b).src))),oc(r,`aria-label`,(i(),P(()=>i().title)))}),Ec(`duration`,`durationchange`,r,e=>cn(yo,e)),mc(r,c,e=>cn(go,e)),hc(r,f,e=>cn(wo,e)),gc(r,()=>N(ne),e=>j(ne,e)),R(`ended`,r,de),R(`loadedmetadata`,r,_e),R(`error`,r,ve),R(`timeupdate`,r,Ce),R(`pause`,r,Ee),R(`play`,r,Dc(function(e){Ac.call(this,t,e)})),R(`click`,u,he),B(e,n)},Le=e=>{var t=sy(),n=w(t),r=w(n);{let e=ar(()=>(i(),P(()=>i().artworkUrl??``))),t=ar(()=>N(x)||f()?.5:1);cv(r,{class:`podcast-artwork`,get src(){return N(e)},get alt(){return i(),P(()=>i().title)},get opacity(){return N(t)},$$slots:{fallback:(e,t)=>{var n=oy();Wc(w(n),{icon:`image`,size:150,clickable:!1}),C(n),ta(()=>ec(n,1,`podcast-artwork-placeholder`+(N(x)||f()?` opacity-50`:``),`svelte-vlhi04`)),B(e,n)}}})}var a=T(r,2),o=e=>{var t=ny();yv(w(t),{}),C(t),B(e,t)},s=e=>{var t=ry(),n=w(t);Wc(n,{icon:`alert-triangle`,clickable:!1});var r=T(n,2),i=w(r,!0);C(r),C(t),ta(()=>cs(i,N(ee))),B(e,t)},c=e=>{var t=oy();let n;var r=w(t);{let e=ar(()=>f()?`play`:`pause`);Wc(r,{get icon(){return N(e)},clickable:!1})}C(t),ta(()=>n=ec(t,1,`podcast-artwork-overlay svelte-vlhi04`,null,n,{visible:N(x)||f()})),B(e,t)};Ss(a,e=>{N(S)?e(o):N(ee)?e(s,1):e(c,-1)}),C(n),C(t),R(`click`,n,ce),R(`contextmenu`,n,Oe),R(`mouseenter`,n,()=>j(x,!0)),R(`mouseleave`,n,()=>j(x,!1)),B(e,t)};Ss(Fe,e=>{N(v)?e(Ie):e(Le,-1)});var Re=T(Fe,2),ze=w(Re,!0);C(Re);var Be=T(Re,2),Ve=e=>{var n=cy();n.autoplay=!0,Tc(n,e=>j(re,e),()=>N(re)),ta(()=>oc(n,`src`,(N(b),P(()=>N(b).src)))),Ec(`duration`,`durationchange`,n,e=>cn(yo,e)),mc(n,c,e=>cn(go,e)),hc(n,f,e=>cn(wo,e)),gc(n,()=>N(ne),e=>j(ne,e)),R(`ended`,n,de),R(`loadedmetadata`,n,_e),R(`error`,n,ve),R(`timeupdate`,n,Ce),R(`pause`,n,Ee),R(`play`,n,Dc(function(e){Ac.call(this,t,e)})),B(e,n)};Ss(Be,e=>{N(v)||e(Ve)});var He=T(Be,2),Ue=w(He),We=w(Ue,!0);C(Ue);var Ge=T(Ue,2);{let e=ar(()=>(F(Du),c(),o(),P(()=>`${Du(c(),`HH:mm:ss`)} of ${Du(o(),`HH:mm:ss`)}`)));Zv(Ge,{get value(){return c()},get max(){return o()},ariaLabel:`Seek within episode`,get valueText(){return N(e)},$$events:{click:le}})}var Ke=T(Ge,2),qe=w(Ke,!0);C(Ke),C(He);var Je=T(He,2),Ye=w(Je),Xe=ir(()=>n().api.skipBackward.bind(n().api));_h(Ye,{icon:`skip-back`,tooltip:`Skip backward`,class:`player-control-button`,$$events:{click(...e){N(Xe)?.apply(this,e)}}});var Ze=T(Ye,2),Qe=ir(()=>n().api.skipForward.bind(n().api));_h(Ze,{icon:`skip-forward`,tooltip:`Skip forward`,class:`player-control-button`,$$events:{click(...e){N(Qe)?.apply(this,e)}}}),C(Je);var $e=T(Je,2),et=w($e),tt=w(et),nt=w(tt);C(tt),gv(T(tt,2),{get value(){return N(ne)},limits:[0,1,.05],$$events:{change:pe}}),C(et);var rt=T(et,2),it=w(rt),at=w(it);C(it);var ot=T(it,2);{let e=ar(()=>[Ma,4,Na]);gv(ot,{get value(){return d()},get limits(){return N(e)},$$events:{change:fe}})}C(rt),C($e);var st=T($e,2),ct=w(st);Jv(ct,{get chapters(){return N(ae)},get currentTime(){return c()},$$events:{seek:me}});var dt=T(ct,2),ft=e=>{Uv(e,{get episodes(){return r(),P(()=>r().episodes)},showListMenu:!1,showThumbnails:!0,$$events:{contextMenuEpisode:De,clickEpisode:ke},$$slots:{header:(e,t)=>{B(e,ly())}}})};Ss(dt,e=>{N(h)&&e(ft)}),C(st),C(Pe),ta((e,t,n)=>{nc(Re,`--title-char-count: ${N(g)??``}`),cs(ze,(i(),P(()=>i().title))),cs(We,e),cs(qe,t),cs(nt,`Volume: ${n??``}%`),cs(at,`${d()??``}x`)},[()=>(F(Du),c(),P(()=>Du(c(),`HH:mm:ss`))),()=>(F(Du),o(),c(),P(()=>Du(o()-c(),`HH:mm:ss`))),()=>(N(ne),P(()=>Math.round(N(ne)*100)))]),B(e,Pe),ut(),m()}var py=z(`<div class="topbar-container svelte-1uvslqs"><button type="button" aria-label="Podcast grid"><!></button> <button type="button"><!></button> <button type="button"><!></button></div>`),my={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 hy(e,t){lt(t,!1),Gs(e,my);let n=A(),r=A(),i=V(t,`viewState`,28,()=>I.PodcastGrid),a=V(t,`canShowEpisodeList`,8,!1),o=V(t,`canShowPlayer`,8,!1);function s(e){i()!==e&&(e===I.EpisodeList&&!a()||e===I.Player&&!o()||i(e))}Zi(()=>F(a()),()=>{j(n,a()?`View episode list`:`Select a podcast or playlist to view its episodes.`)}),Zi(()=>F(o()),()=>{j(r,o()?`Open player`:`Start playing an episode to open the player.`)}),Qi(),Oc();var c=py(),l=w(c),u=ir(()=>s.bind(null,I.PodcastGrid));oc(l,`title`,`Browse podcast grid`),Wc(w(l),{icon:`grid`,size:20,clickable:!1}),C(l);var d=T(l,2),f=ir(()=>s.bind(null,I.EpisodeList));Wc(w(d),{icon:`list-minus`,size:20,clickable:!1}),C(d);var p=T(d,2),m=ir(()=>s.bind(null,I.Player));Wc(w(p),{icon:`play`,size:20,clickable:!1}),C(p),C(c),ta(()=>{ec(l,1,(F(i()),F(I),P(()=>`
|
||
topbar-menu-button
|
||
topbar-selectable
|
||
${i()===I.PodcastGrid?`topbar-selected`:``}
|
||
`)),`svelte-1uvslqs`),oc(l,`aria-pressed`,(F(i()),F(I),P(()=>i()===I.PodcastGrid))),ec(d,1,(F(i()),F(I),F(a()),P(()=>`
|
||
topbar-menu-button
|
||
${i()===I.EpisodeList?`topbar-selected`:``}
|
||
${a()?`topbar-selectable`:`topbar-disabled`}
|
||
`)),`svelte-1uvslqs`),oc(d,`aria-label`,a()?`Episode list`:`Episode list (select a podcast or playlist first)`),oc(d,`aria-pressed`,(F(i()),F(I),P(()=>i()===I.EpisodeList))),d.disabled=!a(),oc(d,`title`,N(n)),ec(p,1,(F(i()),F(I),F(o()),P(()=>`
|
||
topbar-menu-button
|
||
${i()===I.Player?`topbar-selected`:``}
|
||
${o()?`topbar-selectable`:`topbar-disabled`}
|
||
`)),`svelte-1uvslqs`),oc(p,`aria-label`,o()?`Player`:`Player (start playing an episode to open the player)`),oc(p,`aria-pressed`,(F(i()),F(I),P(()=>i()===I.Player))),p.disabled=!o(),oc(p,`title`,N(r))}),R(`click`,l,function(...e){N(u)?.apply(this,e)}),R(`click`,d,function(...e){N(f)?.apply(this,e)}),R(`click`,p,function(...e){N(m)?.apply(this,e)}),B(e,c),ut()}var gy=z(`<img id="podcast-artwork" class="svelte-4w31cc"/>`),_y=z(`<div class="podcast-header svelte-4w31cc"><!> <h2 class="podcast-heading svelte-4w31cc"> </h2></div>`),vy={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 yy(e,t){Gs(e,vy);let n=V(t,`text`,8,``),r=V(t,`artworkUrl`,8,``);var i=_y(),a=w(i),o=e=>{var t=gy();ta(()=>{oc(t,`src`,r()),oc(t,`alt`,n())}),B(e,t)};Ss(a,e=>{r()&&e(o)});var s=T(a,2),c=w(s,!0);C(s),C(i),ta(()=>cs(c,n())),B(e,i)}var by={shouldSort:!0,findAllMatches:!0,threshold:.4,isCaseSensitive:!1,keys:[`title`]},xy=new WeakMap;function Sy(e){return JSON.stringify(e.map(e=>[e.title,e.streamUrl]))}function Cy(e){let t=Sy(e),n=xy.get(e);if(n&&n.signature===t)return n.fuse;let r=new wu(e,by);return xy.set(e,{fuse:r,signature:t}),r}function wy(e,t){return t.length===0?[]:e.trim().length===0?t:Cy(t).search(e).map(e=>e.item)}var Ty=z(`<span class="feed-loading-names svelte-14kt8yt"> </span>`),Ey=z(`<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>`),Dy=z(`<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <!>`,1),Oy=z(`<button type="button" class="go-back svelte-14kt8yt"><!> Latest Episodes</button> <div class="playlist-header-icon svelte-14kt8yt"><!></div> <!>`,1),ky=z(`<!> <!>`,1),Ay=z(`<div class="podcast-view svelte-14kt8yt"><!> <!></div>`),jy={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 My(e,t){lt(t,!1),Gs(e,jy);let n=()=>sn(ko,`$queue`,s),i=()=>sn(Co,`$currentEpisode`,s),a=()=>sn(Fo,`$podcastView`,s),o=()=>sn(Io,`$viewState`,s),[s,c]=ln(),l=A(),u=A([]),d=A(null),f=A(null),p=A(!1),m=A([]),h=A(null),g=A([]),_=[],v=A(!1),y=A(new Set),b=``,x=A([]),S=A(``),ee=!0;Nc(()=>{ee=!1}),Mc(()=>{let e=()=>{let e=Object.values(E(Po)),t=E(ko),n=E(L)?.settings?.autoQueue!==!1||t.episodes.length>0;j(g,[...n?[t]:[],E(Ao),E(No),ce(),...e])},t=()=>{e(),me()},n=[Po.subscribe(t),ko.subscribe(e),Ao.subscribe(t),No.subscribe(t),L.subscribe(e),To.subscribe(()=>{e(),N(p)&&de()})],r=ro.subscribe(e=>{let t=Object.values(e),n=new Set(N(u).map(e=>e.title));j(u,t);let r=t.filter(e=>!n.has(e.title));r.length>0&&ve(r)}),i=E(Io),a=Io.subscribe(e=>{i=e}),o=mo.subscribe(e=>{_=e,i===I.EpisodeList&&!N(d)&&!N(f)&&!N(p)&&j(m,b?wy(b,e):e)});return()=>{o(),a(),r(),n.forEach(e=>e())}});function te(){let e=E(L)?.settings?.feedCache;return Math.max(1,e?.ttlHours??6)*60*60*1e3}function ne(){return E(L)?.settings?.feedCache?.enabled!==!1}function re(e,t){return e?.length?!t?.length||e.length>t.length:!1}async function ie(e,t=!0,n=!1){let i=ne(),a=te(),o=E(io)[e.title];if(t&&o&&o.length>0)return o;if(t&&i){let t=Ag(e,a);if(t?.length)return io.update(n=>({...n,[e.title]:t})),t}try{let t=Wp(e,E(L).feedUrls);if(t===null)return[];let n=await new Fp(e).getEpisodes(t);return io.update(t=>({...t,[e.title]:n})),i&&jg(e,n),n}catch{let s=E(ho);if(s[e.title]?.length)return s[e.title];if(!t){if(o?.length)return o;if(i){let t=Ag(e,a);if(t?.length)return io.update(n=>({...n,[e.title]:t})),t}}return n&&new r.Notice(`Could not load episodes for ${e.title}. Check your connection and try again.`),[]}}function ae(){let e=new Set(Ya(E(To)).map(({episode:e})=>e.podcastName));return N(u).filter(t=>e.has(t.title))}async function oe(e,t=!1){let n=ne()?Ag(e,te()):null,r=E(io)[e.title];return re(r,n)?r:ie(e,!1,t)}async function se(e,t=`cached`,n=!1){return t===`network`?ie(e,!1,n):t===`full`?oe(e,n):ie(e,!0,n)}function ce(){return{...Aa,episodes:Ya(E(To)).map(({episode:e})=>Fv(e)),isVirtual:!0}}function le(){let e=Object.values(E(io)),t=Object.values(E(ho)),n=Object.values(E(Po)).map(e=>e.episodes);return[...e,...t,E(ko).episodes,E(Ao).episodes,E(No).episodes,...n]}function ue(e,t){if(!t)return e;let n=new Map(e.map(e=>[e.episode,e]));return wy(t,e.map(e=>e.episode)).map(e=>n.get(e)).filter(e=>!!e)}function de(){let e=jv(E(To),le());j(h,ue(e,b)),j(m,N(h).map(e=>e.episode))}function fe(){return N(p)&&N(f)?.isVirtual&&N(f).name===Aa.name}function pe(){fe()&&de()}function me(){if(!N(f)||N(f).isVirtual)return;let e=N(f).name;if(e===E(ko).name)return;let t;if(e===E(Ao).name)t=E(Ao);else if(e===E(No).name)t=E(No);else if(t=E(Po)[e],!t){he();return}t&&(j(f,t),j(m,b?wy(b,t.episodes):t.episodes))}function he(){j(d,null),j(f,null),j(p,!1),j(h,null),j(m,b?wy(b,_):_),Io.set(I.EpisodeList)}function ge(e){if(`playedEpisodeKey`in e)return typeof e.playedEpisodeKey==`string`?e.playedEpisodeKey:void 0}function _e(e,t){if(!ee)return;let n=new Set(N(y));t?n.add(e):n.delete(e),j(y,n)}function ve(e,t=`cached`){return e.length?Promise.all(e.map(async e=>{_e(e.title,!0);try{await se(e,t)}finally{_e(e.title,!1)}})).then(()=>void 0):Promise.resolve()}async function ye(e){let{feed:t}=e.detail;j(d,t),j(f,null),j(p,!1),j(h,null),j(m,[]),Io.set(I.EpisodeList),_e(t.title,!0);try{let e=await oe(t,!0);j(m,b?wy(b,e):e)}finally{_e(t.title,!1)}}function be(e){let{episode:t,entry:n}=e.detail;if(!n.isAvailable){new r.Notice(`This played episode is no longer available in current feeds.`);return}Co.set(t),Io.set(I.Player)}function xe({detail:{event:e,episode:t,entry:n}}){$v(t,e,n.isAvailable?void 0:{play:!0,download:!0,createNote:!0,favorite:!0,queue:!0,playlists:!0},ge(n))}async function Se(){if(N(p)){await ve(ae(),`network`),pe();return}if(!N(d)&&!N(f)){await ve(N(u),`network`);return}if(N(d)){_e(N(d).title,!0);try{let e=await se(N(d),`network`,!0);j(h,null),j(m,b?wy(b,e):e)}finally{_e(N(d).title,!1)}}}let Ce=(0,r.debounce)(e=>{let{query:t}=e.detail;if(b=t,N(p)){de();return}if(N(d)){let e=E(io)[N(d).title]??[];j(h,null),j(m,wy(t,e));return}if(N(f)){j(h,null),j(m,wy(t,N(f).episodes));return}j(h,null),j(m,wy(t,_))},250);function we(e){let{playlist:t}=e.detail;if(t.isVirtual&&t.name===Aa.name){j(d,null),j(f,t),j(p,!0),j(m,[]),j(h,[]),Io.set(I.EpisodeList),ve(ae(),`full`).then(()=>{pe()});return}t.name===n().name&&n().episodes.length>0?(j(d,null),j(f,null),j(p,!1),j(h,null),i()||Co.set(n().episodes[0]),Io.set(I.Player)):(j(d,null),j(f,t),j(p,!1),j(h,null),j(m,t.episodes),Io.set(I.EpisodeList))}Zi(()=>N(y),()=>{j(x,Array.from(N(y)))}),Zi(()=>(N(x),N(d)),()=>{j(l,N(x).filter(e=>e!==N(d)?.title))}),Zi(()=>N(l),()=>{j(S,N(l).length>3?`${N(l).slice(0,3).join(`, `)} +${N(l).length-3} more`:N(l).join(`, `))}),Zi(()=>N(x),()=>{j(v,N(x).length>0)}),Qi(),Oc();var Te=Ay(),Ee=w(Te);{let e=ar(()=>!!i());hy(Ee,{canShowEpisodeList:!0,get canShowPlayer(){return N(e)},get viewState(){return dn(),o()},set viewState(e){cn(Io,e)},$$legacy:!0})}var De=T(Ee,2),Oe=e=>{fy(e,{})},ke=e=>{var t=ky(),n=Rt(t),r=e=>{var t=Ey(),n=w(t);Wc(w(n),{icon:`loader-2`,size:18,clickable:!1}),C(n);var r=T(n,2),i=w(r),a=w(i);C(i);var o=T(i,2),s=e=>{var t=Ty(),n=w(t,!0);C(t),ta(()=>cs(n,N(S))),B(e,t)};Ss(o,e=>{N(S)&&e(s)}),C(r),C(t),ta(()=>cs(a,`Updating ${N(l),P(()=>N(l).length)??``} feed${N(l),P(()=>N(l).length===1?``:`s`)??``}`)),B(e,t)};Ss(n,e=>{N(l),P(()=>N(l).length>0)&&e(r)});var i=T(n,2);{let e=ar(()=>!N(f)||N(p)),t=ar(()=>!N(p)),n=ar(()=>(N(d),N(y),N(v),P(()=>N(d)?N(y).has(N(d).title):N(v))));Uv(i,{get episodes(){return N(m)},get episodeEntries(){return N(h)},get showThumbnails(){return N(e)},get showPlayedToggle(){return N(t)},get alwaysShowPlayedEpisodes(){return N(p)},get isLoading(){return N(n)},$$events:{clickEpisode:be,contextMenuEpisode:xe,clickRefresh:Se,search:Ce},$$slots:{header:(e,t)=>{var n=os(),r=Rt(n),i=e=>{var t=Dy(),n=Rt(t);Wc(w(n),{icon:`arrow-left`,size:20,clickable:!1}),bt(),C(n),yy(T(n,2),{get text(){return N(d),P(()=>N(d).title)},get artworkUrl(){return N(d),P(()=>N(d).artworkUrl)}}),R(`click`,n,he),B(e,t)},a=e=>{var t=Oy(),n=Rt(t);Wc(w(n),{icon:`arrow-left`,size:20,clickable:!1}),bt(),C(n);var r=T(n,2);Wc(w(r),{get icon(){return N(f),P(()=>N(f).icon)},size:40,clickable:!1}),C(r),yy(T(r,2),{get text(){return N(f),P(()=>N(f).name)}}),R(`click`,n,he),B(e,t)},o=e=>{yy(e,{text:`Latest Episodes`})};Ss(r,e=>{N(d)?e(i):N(f)?e(a,1):e(o,-1)}),B(e,n)}}})}B(e,t)},Ae=e=>{mv(e,{get feeds(){return N(u)},get playlists(){return N(g)},$$events:{clickPodcast:ye,clickPlaylist:we}})};Ss(De,e=>{o(),F(I),P(()=>o()===I.Player)?e(Oe):(o(),F(I),P(()=>o()===I.EpisodeList)?e(ke,1):(o(),F(I),P(()=>o()===I.PodcastGrid)&&e(Ae,2)))}),C(Te),Tc(Te,e=>cn(Fo,e),()=>a()),B(e,Te),ut(),c()}var Ny=class extends r.ItemView{constructor(e,t){super(e),this.plugin=t,this.podcastView=null}getViewType(){return Ea}getDisplayText(){return`Podcast Player`}getIcon(){return`play-circle`}async onOpen(){this.plugin.shouldMountPodcastView()&&this.mountPodcastView()}mountPodcastView(){this.podcastView||(this.podcastView=ls(My,{target:this.contentEl}))}async onClose(){this.podcastView&&(await ps(this.podcastView),this.podcastView=null),this.contentEl.empty(),this.plugin.unregisterPodcastView(this)}};function Py(e){let t=e.replace(/\+/g,` `);return e===t?[e]:[e,t]}function Fy(e,t){for(let n of t){let t=n.trim().toLowerCase(),r=e.find(e=>e.title.trim().toLowerCase()===t);if(r)return r}return Xf(t,e,e=>e.title,1)}function Iy(e){for(let t of e){let e=No.getLocalEpisode(t);if(e)return e}return Xf(e,E(No).episodes,e=>e.title,1)}function Ly(e){let t=To.get(e);return t?t.finished||t.duration>0&&t.time>=t.duration?0:t.time:0}async function Ry({url:e,episodeName:t,time:n,endTime:i,end:a,to:o},s,c){if(!e||!t){new r.Notice(`URL and episode name are required to play an episode`);return}let l=n!==void 0&&n!==``,u=0;if(l){if(u=parseFloat(n),!Number.isFinite(u)){new r.Notice(`Timestamp must be a valid number`);return}if(u<0){new r.Notice(`Timestamp must be zero or greater`);return}}let d=zy(i??a??o,l,u);if(d===null)return;let f=Py(t),p=E(Co),m=!!p&&(f.includes(p.title)||f.some(e=>Yf(e,p.title)===1)),h=E(Io)===I.Player;if(m){if(l){let e=Ha(p);_o.set({episodeKey:e,time:u,endTime:d}),Io.set(I.Player),s.currentTime=u,By(e,u,d),wo.set(!1),h&&_o.set(null),await c?.();return}vo.set(null),Io.set(I.Player);let e=E(go),t=E(yo);t>0&&e>=t&&(s.currentTime=0),wo.set(!1),await c?.();return}let{vault:g}=E(L).app,_=Py(e).map(e=>g.getAbstractFileByPath(e)).find(e=>e!==null),v,y=Bp(e);if(!y&&_)v=Iy(f);else if(!y&&!Py(e).some(e=>/^https?:\/\//i.test(e)))v=Iy(f);else{let t=e,n,i=Vp(e);if(i!==null){n=E(ro)[i];let e=n?Up(n,E(L).feedUrls):null;if(e===null){new r.Notice(`This link points to a private feed that is not available on this device.`);return}t=e}if(!Cd(t)){new r.Notice(`Refusing to load a feed from a private, local, or non-http(s) URL`);return}try{v=Fy(await new Fp(n).getEpisodes(t),f)}catch{new r.Notice(`Could not load the podcast feed`);return}}if(!v){new r.Notice(`Episode not found`);return}_o.set({episodeKey:Ha(v),time:l?u:Ly(v),endTime:l?d:void 0}),By(Ha(v),l?u:Ly(v),l?d:void 0),Co.set(v),Io.set(I.Player),await c?.()}function zy(e,t,n){if(e===void 0||e===``)return;if(!t)return new r.Notice(`Segment links require a start timestamp`),null;if(n<0)return new r.Notice(`Segment start time must be zero or greater`),null;let i=parseFloat(e);return Number.isFinite(i)?i<=n?(new r.Notice(`Segment end time must be after the start time`),null):i:(new r.Notice(`Segment end time must be a valid number`),null)}function By(e,t,n){vo.set(n===void 0?null:{episodeKey:e,startTime:t,endTime:n})}function Vy(e){return e.workspace.on(`file-menu`,(t,n)=>{if(!(n instanceof r.TFile))return;let i=hp(n.path),a=vp(n.extension);if(!(!i&&!a)){if(a){Hy(t,e,n,`audio`),Hy(t,e,n,`video`);return}i&&Hy(t,e,n,i)}})}function Hy(e,t,n,i){let a=vp(n.extension)?`Play as ${i} with PodNotes`:`Play with PodNotes`;e.addItem(e=>e.setIcon(`play`).setTitle(a).onClick(async()=>{let e={title:n.basename,description:``,content:``,podcastName:`local file`,url:t.fileManager.generateMarkdownLink(n,``),streamUrl:ty(t.vault,n.path),filePath:n.path,episodeDate:new Date(n.stat.ctime),mediaType:i},a=ho.addEpisode(e,n.path,n.stat.size);a&&new r.Notice(`A local file named "${n.basename}" was already tracked at "${a}". It has been replaced by "${n.path}".`),To.get(e)?.finished&&To.markAsUnplayed(e),Co.set(e),Io.set(I.Player),E(L)?.enablePodcastViewMount(),await Uy(t)}))}async function Uy(e){let{workspace:t}=e,n=t.getLeavesOfType(`podcast_player_view`)[0]??null;if(!n){if(n=t.getRightLeaf(!1),!n)return;await n.setViewState({type:Ea,active:!0})}await t.revealLeaf(n)}var Wy=20971520,Gy=44,Ky=2;function qy(e){switch(e.toLowerCase()){case`mp3`:return`audio/mp3`;case`m4a`:return`audio/mp4`;case`ogg`:return`audio/ogg`;case`wav`:return`audio/wav`;case`flac`:return`audio/flac`;case`webm`:return`audio/webm`;default:return`audio/mpeg`}}function Jy(e,t){return e.toLowerCase()!==`mp3`&&t.toLowerCase()!==`audio/mp3`}async function Yy({buffer:e,basename:t,extension:n,mimeType:r}){if(e.byteLength<=20971520)return[new File([e],`${t}.${n}`,{type:r})];if(Jy(n,r)){let r=await Zy(e,t);if(r.length>0)return r;throw Error(`Could not split ${n||`audio`} audio for transcription. This format must be decoded to WAV before splitting, but the audio decoder is unavailable or could not decode it.`)}return Xy(e,t,n,r)}function Xy(e,t,n,r){if(e.byteLength<=20971520)return[new File([e],`${t}.${n}`,{type:r})];let i=[];for(let a=0,o=0;a<e.byteLength;a+=Wy,o++){let s=e.slice(a,a+Wy);i.push(new File([s],`${t}.part${o}.${n}`,{type:r}))}return i}async function Zy(e,t){let n=Qy();if(!n)return[];try{return $y(await n.decodeAudioData(e.slice(0)),t)}catch{return[]}finally{try{await n.close()}catch{}}}function Qy(){if(typeof window>`u`)return null;let e=window.AudioContext||window.webkitAudioContext;return e?new e:null}function $y(e,t){let n=e.numberOfChannels,r=n*Ky,i=Math.max(1,Math.floor(20971476/r)),a=Array.from({length:n},(t,n)=>e.getChannelData(n)),o=[],s=0;for(let n=0;n<e.length;n+=i){let r=Math.min(e.length,n+i),c=eb(a,e.sampleRate,n,r);o.push(new File([c],`${t}.part${s}.wav`,{type:`audio/wav`})),s++}return o}function eb(e,t,n,r){let i=e.length,a=Math.max(0,r-n),o=i*Ky,s=new ArrayBuffer(Gy+a*o),c=new DataView(s);tb(c,t,i,a);let l=Gy;for(let t=0;t<a;t++)for(let r=0;r<i;r++){let i=e[r][n+t]??0,a=Math.max(-1,Math.min(1,i)),o=a<0?a*32768:a*32767;c.setInt16(l,Math.round(o),!0),l+=Ky}return s}function tb(e,t,n,r){let i=n*Ky,a=t*i,o=r*i;nb(e,0,`RIFF`),e.setUint32(4,36+o,!0),nb(e,8,`WAVE`),nb(e,12,`fmt `),e.setUint32(16,16,!0),e.setUint16(20,1,!0),e.setUint16(22,n,!0),e.setUint32(24,t,!0),e.setUint32(28,a,!0),e.setUint16(32,i,!0),e.setUint16(34,16,!0),nb(e,36,`data`),e.setUint32(40,o,!0)}function nb(e,t,n){for(let r=0;r<n.length;r++)e.setUint8(t+r,n.charCodeAt(r))}function W(e,t,n,r,i){if(r===`m`)throw TypeError(`Private method is not writable`);if(r===`a`&&!i)throw TypeError(`Private accessor was defined without a setter`);if(typeof t==`function`?e!==t||!i:!t.has(e))throw TypeError(`Cannot write private member to an object whose class did not declare it`);return r===`a`?i.call(e,n):i?i.value=n:t.set(e,n),n}function G(e,t,n,r){if(n===`a`&&!r)throw TypeError(`Private accessor was defined without a getter`);if(typeof t==`function`?e!==t||!r:!t.has(e))throw TypeError(`Cannot read private member from an object whose class did not declare it`);return n===`m`?r:n===`a`?r.call(e):r?r.value:t.get(e)}var rb=t((()=>{})),ib,ab=t((()=>{ib=function(){let{crypto:e}=globalThis;if(e?.randomUUID)return ib=e.randomUUID.bind(e),e.randomUUID();let t=new Uint8Array(1),n=e?()=>e.getRandomValues(t)[0]:()=>Math.random()*255&255;return`10000000-1000-4000-8000-100000000000`.replace(/[018]/g,e=>(e^n()&15>>e/4).toString(16))}}));function ob(e){return typeof e==`object`&&!!e&&(`name`in e&&e.name===`AbortError`||`message`in e&&String(e.message).includes(`FetchRequestCanceledException`))}var sb,cb=t((()=>{sb=e=>{if(e instanceof Error)return e;if(typeof e==`object`&&e){try{if(Object.prototype.toString.call(e)===`[object Error]`){let t=Error(e.message,e.cause?{cause:e.cause}:{});return e.stack&&(t.stack=e.stack),e.cause&&!t.cause&&(t.cause=e.cause),e.name&&(t.name=e.name),t}}catch{}try{return Error(JSON.stringify(e))}catch{}}return Error(e)}})),K,lb,ub,db,fb,pb,mb,hb,gb,_b,vb,yb,bb,xb,Sb,Cb,wb,Tb,Eb=t((()=>{cb(),K=class extends Error{},lb=class e extends K{constructor(t,n,r,i){super(`${e.makeMessage(t,n,r)}`),this.status=t,this.headers=i,this.requestID=i?.get(`x-request-id`),this.error=n;let a=n;this.code=a?.code,this.param=a?.param,this.type=a?.type}static makeMessage(e,t,n){let r=t?.message?typeof t.message==`string`?t.message:JSON.stringify(t.message):t?JSON.stringify(t):n;return e&&r?`${e} ${r}`:e?`${e} status code (no body)`:r||`(no status code or body)`}static generate(t,n,r,i){if(!t||!i)return new db({message:r,cause:sb(n)});let a=n?.error;return t===400?new pb(t,a,r,i):t===401?new mb(t,a,r,i):t===403?new hb(t,a,r,i):t===404?new gb(t,a,r,i):t===409?new _b(t,a,r,i):t===422?new vb(t,a,r,i):t===429?new yb(t,a,r,i):t>=500?new bb(t,a,r,i):new e(t,a,r,i)}},ub=class extends lb{constructor({message:e}={}){super(void 0,void 0,e||`Request was aborted.`,void 0)}},db=class extends lb{constructor({message:e,cause:t}){super(void 0,void 0,e||`Connection error.`,void 0),t&&(this.cause=t)}},fb=class extends db{constructor({message:e}={}){super({message:e??`Request timed out.`})}},pb=class extends lb{},mb=class extends lb{},hb=class extends lb{},gb=class extends lb{},_b=class extends lb{},vb=class extends lb{},yb=class extends lb{},bb=class extends lb{},xb=class extends K{constructor(){super(`Could not parse response content as the length limit was reached`)}},Sb=class extends K{constructor(){super(`Could not parse response content as the request was rejected by the content filter`)}},Cb=class extends Error{constructor(e){super(e)}},wb=class extends lb{constructor(e,t,n){let r=`OAuth2 authentication error`,i;if(t&&typeof t==`object`){let e=t;i=e.error;let n=e.error_description;n&&typeof n==`string`?r=n:i&&(r=i)}super(e,t,r,n),this.error_code=i}},Tb=class extends K{constructor(e,t,n){super(e),this.provider=t,this.cause=n}}}));function Db(e){return typeof e==`object`?e??{}:{}}function Ob(e){if(!e)return!0;for(let t in e)return!1;return!0}function kb(e,t){return Object.prototype.hasOwnProperty.call(e,t)}function Ab(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}var jb,Mb,Nb,Pb,Fb,Ib,Lb=t((()=>{Eb(),jb=/^[a-z][a-z0-9+.-]*:/i,Mb=e=>jb.test(e),Nb=e=>(Nb=Array.isArray,Nb(e)),Pb=Nb,Fb=(e,t)=>{if(typeof t!=`number`||!Number.isInteger(t))throw new K(`${e} must be an integer`);if(t<0)throw new K(`${e} must be a positive integer`);return t},Ib=e=>{try{return JSON.parse(e)}catch{return}}})),Rb,zb=t((()=>{Rb=e=>new Promise(t=>setTimeout(t,e))})),Bb,Vb=t((()=>{Bb=`7.3.0`}));function Hb(){return typeof Deno<`u`&&Deno.build!=null?`deno`:typeof EdgeRuntime<`u`?`edge`:Object.prototype.toString.call(globalThis.process===void 0?0:globalThis.process)===`[object process]`?`node`:`unknown`}function Ub(){if(typeof navigator>`u`||!navigator)return null;for(let{key:e,pattern:t}of[{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/}]){let n=t.exec(navigator.userAgent);if(n)return{browser:e,version:`${n[1]||0}.${n[2]||0}.${n[3]||0}`}}return null}var Wb,Gb,Kb,qb,Jb,Yb,Xb=t((()=>{Vb(),Wb=()=>typeof window<`u`&&window.document!==void 0&&typeof navigator<`u`,Gb=()=>{let e=Hb();if(e===`deno`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Bb,"X-Stainless-OS":qb(Deno.build.os),"X-Stainless-Arch":Kb(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":Bb,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":`edge`,"X-Stainless-Runtime-Version":globalThis.process.version};if(e===`node`)return{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Bb,"X-Stainless-OS":qb(globalThis.process.platform??`unknown`),"X-Stainless-Arch":Kb(globalThis.process.arch??`unknown`),"X-Stainless-Runtime":`node`,"X-Stainless-Runtime-Version":globalThis.process.version??`unknown`};let t=Ub();return t?{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Bb,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`browser:${t.browser}`,"X-Stainless-Runtime-Version":t.version}:{"X-Stainless-Lang":`js`,"X-Stainless-Package-Version":Bb,"X-Stainless-OS":`Unknown`,"X-Stainless-Arch":`unknown`,"X-Stainless-Runtime":`unknown`,"X-Stainless-Runtime-Version":`unknown`}},Kb=e=>e===`x32`?`x32`:e===`x86_64`||e===`x64`?`x64`:e===`arm`?`arm`:e===`aarch64`||e===`arm64`?`arm64`:e?`other:${e}`:`unknown`,qb=e=>(e=e.toLowerCase(),e.includes(`ios`)?`iOS`:e===`android`?`Android`:e===`darwin`?`MacOS`:e===`win32`?`Windows`:e===`freebsd`?`FreeBSD`:e===`openbsd`?`OpenBSD`:e===`linux`?`Linux`:e?`Other:${e}`:`Unknown`),Yb=()=>Jb??(Jb=Gb())}));function Zb(){if(typeof fetch<`u`)return fetch;throw 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 Qb(...e){let t=globalThis.ReadableStream;if(t===void 0)throw Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new t(...e)}function $b(e){let t=Symbol.asyncIterator in e?e[Symbol.asyncIterator]():e[Symbol.iterator]();return Qb({start(){},async pull(e){let{done:n,value:r}=await t.next();n?e.close():e.enqueue(r)},async cancel(){await t.return?.()}})}function ex(e){if(e[Symbol.asyncIterator])return e;let t=e.getReader();return{async next(){try{let e=await t.read();return e?.done&&t.releaseLock(),e}catch(e){throw t.releaseLock(),e}},async return(){let e=t.cancel();return t.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function tx(e){if(typeof e!=`object`||!e)return;if(e[Symbol.asyncIterator]){await e[Symbol.asyncIterator]().return?.();return}let t=e.getReader(),n=t.cancel();t.releaseLock(),await n}var nx=t((()=>{})),rx,ix=t((()=>{rx=({headers:e,body:t})=>({bodyHeaders:{"content-type":`application/json`},body:JSON.stringify(t)})})),ax,ox,sx,cx=t((()=>{ax=`RFC3986`,ox=e=>String(e),sx={RFC1738:e=>String(e).replace(/%20/g,`+`),RFC3986:ox}}));function lx(e){return!e||typeof e!=`object`?!1:!!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e))}function ux(e,t){if(Nb(e)){let n=[];for(let r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)}var dx,fx,px,mx,hx=t((()=>{cx(),Lb(),dx=(e,t)=>(dx=Object.hasOwn??Function.prototype.call.bind(Object.prototype.hasOwnProperty),dx(e,t)),fx=(()=>{let e=[];for(let t=0;t<256;++t)e.push(`%`+((t<16?`0`:``)+t.toString(16)).toUpperCase());return e})(),px=1024,mx=(e,t,n,r,i)=>{if(e.length===0)return e;let a=e;if(typeof e==`symbol`?a=Symbol.prototype.toString.call(e):typeof e!=`string`&&(a=String(e)),n===`iso-8859-1`)return escape(a).replace(/%u[0-9a-f]{4}/gi,function(e){return`%26%23`+parseInt(e.slice(2),16)+`%3B`});let o=``;for(let e=0;e<a.length;e+=px){let t=a.length>=px?a.slice(e,e+px):a,n=[];for(let e=0;e<t.length;++e){let r=t.charCodeAt(e);if(r===45||r===46||r===95||r===126||r>=48&&r<=57||r>=65&&r<=90||r>=97&&r<=122||i===`RFC1738`&&(r===40||r===41)){n[n.length]=t.charAt(e);continue}if(r<128){n[n.length]=fx[r];continue}if(r<2048){n[n.length]=fx[192|r>>6]+fx[128|r&63];continue}if(r<55296||r>=57344){n[n.length]=fx[224|r>>12]+fx[128|r>>6&63]+fx[128|r&63];continue}e+=1,r=65536+((r&1023)<<10|t.charCodeAt(e)&1023),n[n.length]=fx[240|r>>18]+fx[128|r>>12&63]+fx[128|r>>6&63]+fx[128|r&63]}o+=n.join(``)}return o}}));function gx(e){return typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`symbol`||typeof e==`bigint`}function _x(e,t,n,r,i,a,o,s,c,l,u,d,f,p,m,h,g,_){let v=e,y=_,b=0,x=!1;for(;(y=y.get(wx))!==void 0&&!x;){let t=y.get(e);if(b+=1,t!==void 0){if(t===b)throw RangeError(`Cyclic object value`);x=!0}y.get(wx)===void 0&&(b=0)}if(typeof l==`function`?v=l(t,v):v instanceof Date?v=f?.(v):n===`comma`&&Nb(v)&&(v=ux(v,function(e){return e instanceof Date?f?.(e):e})),v===null){if(a)return c&&!h?c(t,Cx.encoder,g,`key`,p):t;v=``}if(gx(v)||lx(v)){if(c){let e=h?t:c(t,Cx.encoder,g,`key`,p);return[m?.(e)+`=`+m?.(c(v,Cx.encoder,g,`value`,p))]}return[m?.(t)+`=`+m?.(String(v))]}let S=[];if(v===void 0)return S;let ee;if(n===`comma`&&Nb(v))h&&c&&(v=ux(v,c)),ee=[{value:v.length>0?v.join(`,`)||null:void 0}];else if(Nb(l))ee=l;else{let e=Object.keys(v);ee=u?e.sort(u):e}let te=s?String(t).replace(/\./g,`%2E`):String(t),ne=r&&Nb(v)&&v.length===1?te+`[]`:te;if(i&&Nb(v)&&v.length===0)return ne+`[]`;for(let t=0;t<ee.length;++t){let y=ee[t],x=typeof y==`object`&&y.value!==void 0?y.value:v[y];if(o&&x===null)continue;let te=d&&s?y.replace(/\./g,`%2E`):y,re=Nb(v)?typeof n==`function`?n(ne,te):ne:ne+(d?`.`+te:`[`+te+`]`);_.set(e,b);let ie=new WeakMap;ie.set(wx,_),xx(S,_x(x,re,n,r,i,a,o,s,n===`comma`&&h&&Nb(v)?null:c,l,u,d,f,p,m,h,g,ie))}return S}function vx(e=Cx){if(e.allowEmptyArrays!==void 0&&typeof e.allowEmptyArrays!=`boolean`)throw TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(e.encodeDotInKeys!==void 0&&typeof e.encodeDotInKeys!=`boolean`)throw TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(e.encoder!==null&&e.encoder!==void 0&&typeof e.encoder!=`function`)throw TypeError(`Encoder has to be a function.`);let t=e.charset||Cx.charset;if(e.charset!==void 0&&e.charset!==`utf-8`&&e.charset!==`iso-8859-1`)throw TypeError(`The charset option must be either utf-8, iso-8859-1, or undefined`);let n=ax;if(e.format!==void 0){if(!dx(sx,e.format))throw TypeError(`Unknown format option provided.`);n=e.format}let r=sx[n],i=Cx.filter;(typeof e.filter==`function`||Nb(e.filter))&&(i=e.filter);let a;if(a=e.arrayFormat&&e.arrayFormat in bx?e.arrayFormat:`indices`in e?e.indices?`indices`:`repeat`:Cx.arrayFormat,`commaRoundTrip`in e&&typeof e.commaRoundTrip!=`boolean`)throw TypeError("`commaRoundTrip` must be a boolean, or absent");let o=e.allowDots===void 0?e.encodeDotInKeys?!0:Cx.allowDots:!!e.allowDots;return{addQueryPrefix:typeof e.addQueryPrefix==`boolean`?e.addQueryPrefix:Cx.addQueryPrefix,allowDots:o,allowEmptyArrays:typeof e.allowEmptyArrays==`boolean`?!!e.allowEmptyArrays:Cx.allowEmptyArrays,arrayFormat:a,charset:t,charsetSentinel:typeof e.charsetSentinel==`boolean`?e.charsetSentinel:Cx.charsetSentinel,commaRoundTrip:!!e.commaRoundTrip,delimiter:e.delimiter===void 0?Cx.delimiter:e.delimiter,encode:typeof e.encode==`boolean`?e.encode:Cx.encode,encodeDotInKeys:typeof e.encodeDotInKeys==`boolean`?e.encodeDotInKeys:Cx.encodeDotInKeys,encoder:typeof e.encoder==`function`?e.encoder:Cx.encoder,encodeValuesOnly:typeof e.encodeValuesOnly==`boolean`?e.encodeValuesOnly:Cx.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:typeof e.serializeDate==`function`?e.serializeDate:Cx.serializeDate,skipNulls:typeof e.skipNulls==`boolean`?e.skipNulls:Cx.skipNulls,sort:typeof e.sort==`function`?e.sort:null,strictNullHandling:typeof e.strictNullHandling==`boolean`?e.strictNullHandling:Cx.strictNullHandling}}function yx(e,t={}){let n=e,r=vx(t),i,a;typeof r.filter==`function`?(a=r.filter,n=a(``,n)):Nb(r.filter)&&(a=r.filter,i=a);let o=[];if(typeof n!=`object`||!n)return``;let s=bx[r.arrayFormat],c=s===`comma`&&r.commaRoundTrip;i||(i=Object.keys(n)),r.sort&&i.sort(r.sort);let l=new WeakMap;for(let e=0;e<i.length;++e){let t=i[e];r.skipNulls&&n[t]===null||xx(o,_x(n[t],t,s,c,r.allowEmptyArrays,r.strictNullHandling,r.skipNulls,r.encodeDotInKeys,r.encode?r.encoder:null,r.filter,r.sort,r.allowDots,r.serializeDate,r.format,r.formatter,r.encodeValuesOnly,r.charset,l))}let u=o.join(r.delimiter),d=r.addQueryPrefix===!0?`?`:``;return r.charsetSentinel&&(r.charset===`iso-8859-1`?d+=`utf8=%26%2310003%3B&`:d+=`utf8=%E2%9C%93&`),u.length>0?d+u:``}var bx,xx,Sx,Cx,wx,Tx=t((()=>{hx(),cx(),Lb(),bx={brackets(e){return String(e)+`[]`},comma:`comma`,indices(e,t){return String(e)+`[`+t+`]`},repeat(e){return String(e)}},xx=function(e,t){Array.prototype.push.apply(e,Nb(t)?t:[t])},Cx={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:`indices`,charset:`utf-8`,charsetSentinel:!1,delimiter:`&`,encode:!0,encodeDotInKeys:!1,encoder:mx,encodeValuesOnly:!1,format:ax,formatter:ox,indices:!1,serializeDate(e){return(Sx??(Sx=Function.prototype.call.bind(Date.prototype.toISOString)))(e)},skipNulls:!1,strictNullHandling:!1},wx={}}));function Ex(e){return yx(e,{arrayFormat:`brackets`})}var Dx=t((()=>{Tx()}));function Ox(e){let t=0;for(let n of e)t+=n.length;let n=new Uint8Array(t),r=0;for(let t of e)n.set(t,r),r+=t.length;return n}function kx(e){let t;return(jx??(t=new globalThis.TextEncoder,jx=t.encode.bind(t)))(e)}function Ax(e){let t;return(Mx??(t=new globalThis.TextDecoder,Mx=t.decode.bind(t)))(e)}var jx,Mx,Nx=t((()=>{}));function Px(e,t){for(let n=t??0;n<e.length;n++){if(e[n]===10)return{preceding:n,index:n+1,carriage:!1};if(e[n]===13)return{preceding:n,index:n+1,carriage:!0}}return null}function Fx(e){for(let t=0;t<e.length-1;t++){if(e[t]===10&&e[t+1]===10||e[t]===13&&e[t+1]===13)return t+2;if(e[t]===13&&e[t+1]===10&&t+3<e.length&&e[t+2]===13&&e[t+3]===10)return t+4}return-1}var Ix,Lx,Rx,zx=t((()=>{rb(),Nx(),Rx=class{constructor(){Ix.set(this,void 0),Lx.set(this,void 0),W(this,Ix,new Uint8Array,`f`),W(this,Lx,null,`f`)}decode(e){if(e==null)return[];let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e==`string`?kx(e):e;W(this,Ix,Ox([G(this,Ix,`f`),t]),`f`);let n=[],r;for(;(r=Px(G(this,Ix,`f`),G(this,Lx,`f`)))!=null;){if(r.carriage&&G(this,Lx,`f`)==null){W(this,Lx,r.index,`f`);continue}if(G(this,Lx,`f`)!=null&&(r.index!==G(this,Lx,`f`)+1||r.carriage)){n.push(Ax(G(this,Ix,`f`).subarray(0,G(this,Lx,`f`)-1))),W(this,Ix,G(this,Ix,`f`).subarray(G(this,Lx,`f`)),`f`),W(this,Lx,null,`f`);continue}let e=G(this,Lx,`f`)===null?r.preceding:r.preceding-1,t=Ax(G(this,Ix,`f`).subarray(0,e));n.push(t),W(this,Ix,G(this,Ix,`f`).subarray(r.index),`f`),W(this,Lx,null,`f`)}return n}flush(){return G(this,Ix,`f`).length?this.decode(`
|
||
`):[]}},Ix=new WeakMap,Lx=new WeakMap,Rx.NEWLINE_CHARS=new Set([`
|
||
`,`\r`]),Rx.NEWLINE_REGEXP=/\r\n|[\n\r]/g}));function Bx(){}function Vx(e,t,n){return!t||Ux[e]>Ux[n]?Bx:t[e].bind(t)}function Hx(e){let t=e.logger,n=e.logLevel??`off`;if(!t)return Gx;let r=Kx.get(t);if(r&&r[0]===n)return r[1];let i={error:Vx(`error`,t,n),warn:Vx(`warn`,t,n),info:Vx(`info`,t,n),debug:Vx(`debug`,t,n)};return Kx.set(t,[n,i]),i}var Ux,Wx,Gx,Kx,qx,Jx=t((()=>{Lb(),Ux={off:0,error:200,warn:300,info:400,debug:500},Wx=(e,t,n)=>{if(e){if(kb(Ux,e))return e;Hx(n).warn(`${t} was set to ${JSON.stringify(e)}, expected one of ${JSON.stringify(Object.keys(Ux))}`)}},Gx={error:Bx,warn:Bx,info:Bx,debug:Bx},Kx=new WeakMap,qx=e=>(e.options&&(e.options={...e.options},delete e.options.headers),e.headers&&(e.headers=Object.fromEntries((e.headers instanceof Headers?[...e.headers]:Object.entries(e.headers)).map(([e,t])=>[e,e.toLowerCase()===`authorization`||e.toLowerCase()===`api-key`||e.toLowerCase()===`x-api-key`||e.toLowerCase()===`x-amz-security-token`||e.toLowerCase()===`cookie`||e.toLowerCase()===`set-cookie`?`***`:t]))),`retryOfRequestLogID`in e&&(e.retryOfRequestLogID&&(e.retryOf=e.retryOfRequestLogID),delete e.retryOfRequestLogID),e)}));async function*Yx(e,t){if(!e.body)throw t.abort(),globalThis.navigator!==void 0&&globalThis.navigator.product===`ReactNative`?new K(`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 K(`Attempted to iterate over a response with no body`);let n=new eS,r=new Rx,i=ex(e.body);for await(let e of Xx(i))for(let t of r.decode(e)){let e=n.decode(t);e&&(yield e)}for(let e of r.flush()){let t=n.decode(e);t&&(yield t)}}async function*Xx(e){let t=new Uint8Array;for await(let n of e){if(n==null)continue;let e=n instanceof ArrayBuffer?new Uint8Array(n):typeof n==`string`?kx(n):n,r=new Uint8Array(t.length+e.length);r.set(t),r.set(e,t.length),t=r;let i;for(;(i=Fx(t))!==-1;)yield t.slice(0,i),t=t.slice(i)}t.length>0&&(yield t)}function Zx(e,t){let n=e.indexOf(t);return n===-1?[e,``,``]:[e.substring(0,n),t,e.substring(n+t.length)]}var Qx,$x,eS,tS=t((()=>{rb(),Eb(),nx(),zx(),cb(),Nx(),Jx(),$x=class e{constructor(e,t,n){this.iterator=e,Qx.set(this,void 0),this.controller=t,W(this,Qx,n,`f`)}static fromSSEResponse(t,n,r,i){let a=!1,o=r?Hx(r):console;async function*s(){if(a)throw new K("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");a=!0;let e=!1;try{for await(let r of Yx(t,n))if(!e){if(r.data.startsWith(`[DONE]`)){e=!0;continue}if(r.event===null||!r.event.startsWith(`thread.`)){let e;try{e=JSON.parse(r.data)}catch(e){throw o.error(`Could not parse message into JSON:`,r.data),o.error(`From chunk:`,r.raw),e}if(e&&e.error)throw new lb(void 0,e.error,void 0,t.headers);yield i?{event:r.event,data:e}:e}else{let e;try{e=JSON.parse(r.data)}catch(e){throw e}if(r.event==`error`)throw new lb(void 0,e.error,e.message,void 0);yield{event:r.event,data:e}}}e=!0}catch(e){if(ob(e))return;throw e}finally{e||n.abort()}}return new e(s,n,r)}static fromReadableStream(t,n,r){let i=!1;async function*a(){let e=new Rx,r=t.getReader(),i=!1,a,o=()=>{a??(a=r.cancel()),a.catch(()=>{})};n.signal.addEventListener(`abort`,o,{once:!0});try{if(n.signal.aborted){o();return}for(;;){let{value:t,done:a}=await r.read();if(a){i=!0;break}if(n.signal.aborted)return;for(let r of e.decode(t)){if(n.signal.aborted)return;yield r}}if(n.signal.aborted)return;for(let t of e.flush()){if(n.signal.aborted)return;yield t}}finally{n.signal.removeEventListener(`abort`,o),i||o(),r.releaseLock()}}async function*o(){if(i)throw new K("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");i=!0;let e=!1;try{for await(let t of a())e||t&&(yield JSON.parse(t));e=!0}catch(e){if(n.signal.aborted||ob(e))return;throw e}finally{e||n.abort()}}return new e(o,n,r)}[(Qx=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let t=[],n=[],r=this.iterator(),i=e=>({next:()=>{if(e.length===0){let e=r.next();t.push(e),n.push(e)}return e.shift()}});return[new e(()=>i(t),this.controller,G(this,Qx,`f`)),new e(()=>i(n),this.controller,G(this,Qx,`f`))]}toReadableStream(){let e=this,t;return Qb({async start(){t=e[Symbol.asyncIterator]()},async pull(e){try{let{value:n,done:r}=await t.next();if(r)return e.close();let i=kx(JSON.stringify(n)+`
|
||
`);e.enqueue(i)}catch(t){e.error(t)}},async cancel(){await t.return?.()}})}},eS=class{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;let e={event:this.event,data:this.data.join(`
|
||
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],e}if(this.chunks.push(e),e.startsWith(`:`))return null;let[t,n,r]=Zx(e,`:`);return r.startsWith(` `)&&(r=r.substring(1)),t===`event`?this.event=r:t===`data`&&this.data.push(r),null}}}));async function nS(e,t){let{response:n,requestLogID:r,retryOfRequestLogID:i,startTime:a}=t,o=await(async()=>{if(t.options.stream)return Hx(e).debug(`response`,n.status,n.url,n.headers,n.body),t.options.__streamClass?t.options.__streamClass.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData):$x.fromSSEResponse(n,t.controller,e,t.options.__synthesizeEventData);if(n.status===204)return null;if(t.options.__binaryResponse)return n;let r=n.headers.get(`content-type`)?.split(`;`)[0]?.trim();return r?.includes(`application/json`)||r?.endsWith(`+json`)?n.headers.get(`content-length`)===`0`?void 0:rS(await n.json(),n):await n.text()})();return Hx(e).debug(`[${r}] response parsed`,qx({retryOfRequestLogID:i,url:n.url,status:n.status,body:o,durationMs:Date.now()-a})),o}function rS(e,t){return!e||typeof e!=`object`||Array.isArray(e)?e:Object.defineProperty(e,"_request_id",{value:t.headers.get(`x-request-id`),enumerable:!1})}var iS=t((()=>{tS(),Jx()})),aS,oS,sS=t((()=>{rb(),iS(),oS=class e extends Promise{constructor(e,t,n=nS){super(e=>{e(null)}),this.responsePromise=t,this.parseResponse=n,aS.set(this,void 0),W(this,aS,e,`f`)}_thenUnwrap(t){return new e(G(this,aS,`f`),this.responsePromise,async(e,n)=>rS(t(await this.parseResponse(e,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,t]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:t,request_id:t.headers.get(`x-request-id`)}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(G(this,aS,`f`),e))),this.parsedPromise}then(e,t){return this.parse().then(e,t)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}},aS=new WeakMap})),cS,lS,uS,dS,fS,pS,mS,q=t((()=>{rb(),Eb(),iS(),sS(),Lb(),lS=class{constructor(e,t,n,r){cS.set(this,void 0),W(this,cS,e,`f`),this.options=r,this.response=t,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new K("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await G(this,cS,`f`).requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(cS=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let t of e.getPaginatedItems())yield t}},uS=class extends oS{constructor(e,t,n){super(e,t,async(e,t)=>new n(e,t.response,await nS(e,t),t.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let t of e)yield t}},dS=class extends lS{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.object=n.object}getPaginatedItems(){return this.data??[]}nextPageRequestOptions(){return null}},fS=class extends lS{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.getPaginatedItems(),t=e[e.length-1]?.id;return t?{...this.options,query:{...Db(this.options.query),after:t}}:null}},pS=class extends lS{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.last_id=n.last_id||``}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.last_id;return e?{...this.options,query:{...Db(this.options.query),after:e}}:null}},mS=class extends lS{constructor(e,t,n,r){super(e,t,n,r),this.data=n.data||[],this.has_more=n.has_more||!1,this.next=n.next||null}getPaginatedItems(){return this.data??[]}hasNextPage(){return this.has_more!==!1&&super.hasNextPage()}nextPageRequestOptions(){let e=this.next;return e?{...this.options,query:{...Db(this.options.query),after:e}}:null}}})),hS,gS,_S,vS=t((()=>{nx(),Eb(),hS={jwt:`urn:ietf:params:oauth:token-type:jwt`,id:`urn:ietf:params:oauth:token-type:id_token`},gS=`urn:ietf:params:oauth:grant-type:token-exchange`,_S=class{constructor(e,t){this.cachedToken=null,this.refreshPromise=null,this.tokenExchangeUrl=`https://auth.openai.com/oauth/token`,this.config=e,this.fetch=t??Zb()}async getToken(){if(!this.cachedToken||this.isTokenExpired(this.cachedToken)){if(this.refreshPromise)return await this.refreshPromise;this.refreshPromise=this.refreshToken();try{return await this.refreshPromise}finally{this.refreshPromise=null}}return this.needsRefresh(this.cachedToken)&&!this.refreshPromise&&(this.refreshPromise=this.refreshToken().finally(()=>{this.refreshPromise=null})),this.cachedToken.token}async refreshToken(){let e=await this.config.provider.getToken(),t={grant_type:gS,subject_token:e,subject_token_type:hS[this.config.provider.tokenType],identity_provider_id:this.config.identityProviderId,service_account_id:this.config.serviceAccountId};this.config.clientId&&(t.client_id=this.config.clientId);let n=await this.fetch(this.tokenExchangeUrl,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=await n.text(),t;try{t=JSON.parse(e)}catch{}throw n.status===400||n.status===401||n.status===403?new wb(n.status,t,n.headers):lb.generate(n.status,t,`Token exchange failed with status ${n.status}`,n.headers)}let r=await n.json();if(typeof r!=`object`||!r||!(`access_token`in r)||typeof r.access_token!=`string`||r.access_token.trim().length===0)throw new K(`Token exchange response missing 'access_token' field`);let i=r.access_token,a=r.expires_in??3600,o=Date.now()+a*1e3;return this.cachedToken={token:i,expiresAt:o},i}isTokenExpired(e){return Date.now()>=e.expiresAt}needsRefresh(e){let t=(this.config.refreshBufferSeconds??1200)*1e3;return Date.now()>=e.expiresAt-t}invalidateToken(){this.cachedToken=null,this.refreshPromise=null}}}));function*yS(e){if(!e)return;if(bS in e){let{values:t,nulls:n}=e;yield*t.entries();for(let e of n)yield[e,null];return}let t=!1,n;e instanceof Headers?n=e.entries():Pb(e)?n=e:(t=!0,n=Object.entries(e??{}));for(let e of n){let n=e[0];if(typeof n!=`string`)throw TypeError(`expected header name to be a string`);let r=Pb(e[1])?e[1]:[e[1]],i=!1;for(let e of r)e!==void 0&&(t&&!i&&(i=!0,yield[n,null]),yield[n,e])}}var bS,xS,J,SS=t((()=>{Lb(),bS=Symbol(`brand.privateNullableHeaders`),xS=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/,J=e=>{let t=new Headers,n=new Set;for(let r of e){let e=new Set;for(let[i,a]of yS(r)){if(!xS.test(i))throw TypeError(`Header name must be a valid HTTP token ["${i}"]`);let r=i.toLowerCase();e.has(r)||(t.delete(r),e.add(r)),a===null?(t.delete(r),n.add(r)):(t.append(r,a),n.delete(r))}}return{[bS]:!0,values:t,nulls:n}}}));function CS(e,t,n){if(!t)throw TypeError(`toStreamingFile requires a non-empty file name`);return{[FS]:!0,data:e,name:t,...n?.type?{type:n.type}:{}}}function wS(e,t,n){return IS(),new File(e,t??`unknown_file`,n)}function TS(e){return(typeof e==`object`&&!!e&&(`name`in e&&e.name&&String(e.name)||`url`in e&&e.url&&String(e.url)||`filename`in e&&e.filename&&String(e.filename)||`path`in e&&e.path&&String(e.path))||``).split(/[\\/]/).pop()||void 0}function ES(e){let t=typeof e==`function`?e:e.fetch,n=BS.get(t);if(n)return n;let r=(async()=>{try{let e;if(`Response`in t)e=t.Response;else{let n=await t(`data:,`);await n.arrayBuffer(),e=n.constructor}let n=new FormData;return n.toString()!==await new e(n).text()}catch{return!0}})();return BS.set(t,r),r}async function*DS(e,t){for await(let{key:n,value:r}of OS(e)){if(yield kx(`--${t}\r\n`),GS(r)){let e=AS(r),t=jS(r);yield kx(`Content-Disposition: form-data; name="${PS(n)}"; filename="${PS(e)}"\r\nContent-Type: ${t}\r\n\r\n`),yield*NS(MS(r))}else yield kx(`Content-Disposition: form-data; name="${PS(n)}"\r\n\r\n${String(r)}`);yield kx(`\r
|
||
`)}yield kx(`--${t}--\r\n`)}async function*OS(e){if(!(!e||typeof e!=`object`))for(let[t,n]of Object.entries(e))yield*kS(t,n)}async function*kS(e,t){if(t!==void 0){if(t==null)throw TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof t==`string`||typeof t==`number`||typeof t==`boolean`||GS(t))yield{key:e,value:t};else if(Array.isArray(t))for(let n of t)yield*kS(e+`[]`,n);else if(typeof t==`object`)for(let[n,r]of Object.entries(t))yield*kS(`${e}[${n}]`,r);else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${t} instead`)}}function AS(e){return WS(e)?e.name:TS(e)??`unknown_file`}function jS(e){return WS(e)?e.type||`application/octet-stream`:HS(e)&&e.type?e.type:e instanceof Response&&e.headers.get(`content-type`)||`application/octet-stream`}function MS(e){return WS(e)?e.data:e}async function*NS(e){if(typeof e==`string`)yield kx(e);else if(ArrayBuffer.isView(e))yield new Uint8Array(e.buffer,e.byteOffset,e.byteLength);else if(e instanceof ArrayBuffer)yield new Uint8Array(e);else if(e instanceof Response)e.body?yield*NS(e.body):yield*NS(await e.blob());else if(e instanceof Blob)typeof e.stream==`function`?yield*NS(e.stream()):yield new Uint8Array(await e.arrayBuffer());else if(US(e))for await(let t of ex(e))yield*NS(t);else if(LS(e))for await(let t of e)yield*NS(t);else throw TypeError(`Invalid streaming file chunk: ${String(e)}`)}function PS(e){return e.replace(/["\\\r\n]/g,e=>encodeURIComponent(e))}var FS,IS,LS,RS,zS,BS,VS,HS,US,WS,GS,KS,qS,JS,YS,XS=t((()=>{SS(),nx(),Nx(),FS=Symbol(`brand.privateStreamingFile`),IS=()=>{if(typeof File>`u`){let{process:e}=globalThis,t=typeof e?.versions?.node==`string`&&parseInt(e.versions.node.split(`.`))<20;throw Error("`File` is not defined as a global, which is required for file uploads."+(t?" Update to a supported Node.js LTS release, or set `globalThis.File` to `import('node:buffer').File`.":``))}},LS=e=>typeof e==`object`&&!!e&&typeof e[Symbol.asyncIterator]==`function`,RS=async(e,t)=>qS(e.body)?KS(e.body)?JS(e):{...e,body:await VS(e.body,t)}:e,zS=async(e,t)=>KS(e.body)?JS(e):{...e,body:await VS(e.body,t)},BS=new WeakMap,VS=async(e,t)=>{if(!await ES(t))throw TypeError(`The provided fetch function does not support file uploads with the current global FormData class.`);let n=new FormData;return await Promise.all(Object.entries(e||{}).map(([e,t])=>YS(n,e,t))),n},HS=e=>e instanceof Blob&&`name`in e,US=e=>typeof e==`object`&&!!e&&`getReader`in e&&typeof e.getReader==`function`,WS=e=>typeof e==`object`&&!!e&&FS in e,GS=e=>typeof e==`object`&&!!e&&(e instanceof Response||LS(e)||US(e)||WS(e)||HS(e)),KS=e=>{if(WS(e)||LS(e)||US(e))return!0;if(Array.isArray(e))return e.some(KS);if(e&&typeof e==`object`&&!HS(e)&&!(e instanceof Response)){for(let t in e)if(KS(e[t]))return!0}return!1},qS=e=>{if(GS(e))return!0;if(Array.isArray(e))return e.some(qS);if(e&&typeof e==`object`){for(let t in e)if(qS(e[t]))return!0}return!1},JS=e=>{let t=`openai-${Math.random().toString(36).slice(2)}`,n=$b(DS(e.body,t));return{...e,body:n,headers:J([{"content-type":`multipart/form-data; boundary=${t}`},e.headers])}},YS=async(e,t,n)=>{if(n!==void 0){if(n==null)throw TypeError(`Received null for "${t}"; to pass null in FormData, you must use the string 'null'`);if(typeof n==`string`||typeof n==`number`||typeof n==`boolean`)e.append(t,String(n));else if(n instanceof Response)e.append(t,wS([await n.blob()],TS(n)));else if(LS(n))e.append(t,wS([await new Response($b(n)).blob()],TS(n)));else if(HS(n))e.append(t,n,TS(n));else if(Array.isArray(n))await Promise.all(n.map(n=>YS(e,t+`[]`,n)));else if(typeof n==`object`)await Promise.all(Object.entries(n).map(([n,r])=>YS(e,`${t}[${n}]`,r)));else throw TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${n} instead`)}}}));async function ZS(e,t,n){if(IS(),e=await e,tC(e))return e instanceof File?e:wS([await e.arrayBuffer()],e.name);if(nC(e)){let r=await e.blob();return t||(t=new URL(e.url).pathname.split(/[\\/]/).pop()),wS(await QS(r),t,n)}let r=await QS(e);if(t||(t=TS(e)),!n?.type){let e=r.find(e=>typeof e==`object`&&`type`in e&&e.type);typeof e==`string`&&(n={...n,type:e})}return wS(r,t,n)}async function QS(e){let t=[];if(typeof e==`string`||ArrayBuffer.isView(e)||e instanceof ArrayBuffer)t.push(e);else if(eC(e))t.push(e instanceof Blob?e:await e.arrayBuffer());else if(LS(e))for await(let n of e)t.push(...await QS(n));else{let t=e?.constructor?.name;throw Error(`Unexpected data type: ${typeof e}${t?`; constructor: ${t}`:``}${$S(e)}`)}return t}function $S(e){return typeof e!=`object`||!e?``:`; props: [${Object.getOwnPropertyNames(e).map(e=>`"${e}"`).join(`, `)}]`}var eC,tC,nC,rC=t((()=>{XS(),eC=e=>typeof e==`object`&&!!e&&typeof e.size==`number`&&typeof e.type==`string`&&typeof e.text==`function`&&typeof e.slice==`function`&&typeof e.arrayBuffer==`function`,tC=e=>typeof e==`object`&&!!e&&typeof e.name==`string`&&typeof e.lastModified==`number`&&eC(e),nC=e=>typeof e==`object`&&!!e&&typeof e.url==`string`&&typeof e.blob==`function`})),iC=t((()=>{XS(),rC()})),Y,X=t((()=>{Y=class{constructor(e){this._client=e}}}));function aC(e){return e.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var oC,sC,Z,Q=t((()=>{Eb(),oC=Object.freeze(Object.create(null)),sC=(e=aC)=>function(t,...n){if(t.length===1)return t[0];let r=!1,i=[],a=t.reduce((t,a,o)=>{/[?#]/.test(a)&&(r=!0);let s=n[o],c=(r?encodeURIComponent:e)(``+s);return o!==n.length&&(s==null||typeof s==`object`&&s.toString===Object.getPrototypeOf(Object.getPrototypeOf(s.hasOwnProperty??oC)??oC)?.toString)&&(c=s+``,i.push({start:t.length+a.length,length:c.length,error:`Value of type ${Object.prototype.toString.call(s).slice(8,-1)} is not a valid path parameter`})),t+a+(o===n.length?``:c)},``),o=a.split(/[?#]/,1)[0],s=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,c;for(;(c=s.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((e,t)=>e.start-t.start),i.length>0){let e=0,t=i.reduce((t,n)=>{let r=` `.repeat(n.start-e),i=`^`.repeat(n.length);return e=n.start+n.length,t+r+i},``);throw new K(`Path parameters result in path with invalid segments:\n${i.map(e=>e.error).join(`
|
||
`)}\n${a}\n${t}`)}return a},Z=sC(aC)})),cC,lC=t((()=>{X(),q(),Q(),cC=class extends Y{list(e,t={},n){return this._client.getAPIList(Z`/chat/completions/${e}/messages`,fS,{query:t,...n,__security:{bearerAuth:!0}})}}})),uC=t((()=>{Eb()}));function dC(e){return e!==void 0&&`function`in e&&e.function!==void 0}function fC(e){return e?.$brand===`auto-parseable-response-format`}function pC(e){return e?.$brand===`auto-parseable-tool`}function mC(e,t){return!t||!yC(t)?{...e,choices:e.choices.map(e=>(bC(e.message.tool_calls),{...e,message:{...e.message,parsed:null,...e.message.tool_calls?{tool_calls:e.message.tool_calls}:void 0}}))}:hC(e,t)}function hC(e,t){let n=e.choices.map(e=>{if(e.finish_reason===`length`)throw new xb;if(e.finish_reason===`content_filter`)throw new Sb;return bC(e.message.tool_calls),{...e,message:{...e.message,...e.message.tool_calls?{tool_calls:e.message.tool_calls?.map(e=>_C(t,e))??void 0}:void 0,parsed:e.message.content&&!e.message.refusal?gC(t,e.message.content):null}}});return{...e,choices:n}}function gC(e,t){return e.response_format?.type===`json_schema`&&e.response_format?.type===`json_schema`?`$parseRaw`in e.response_format?e.response_format.$parseRaw(t):JSON.parse(t):null}function _C(e,t){let n=e.tools?.find(e=>dC(e)&&e.function?.name===t.function.name);return{...t,function:{...t.function,parsed_arguments:pC(n)?n.$parseRaw(t.function.arguments):n?.function.strict?JSON.parse(t.function.arguments):null}}}function vC(e,t){if(!e||!(`tools`in e)||!e.tools)return!1;let n=e.tools?.find(e=>dC(e)&&e.function?.name===t.function.name);return dC(n)&&(pC(n)||n?.function.strict||!1)}function yC(e){return fC(e.response_format)?!0:e.tools?.some(e=>pC(e)||e.type===`function`&&e.function.strict===!0)??!1}function bC(e){for(let t of e||[])if(t.type!==`function`)throw new K(`Currently only \`function\` tool calls are supported; Received \`${t.type}\``)}function xC(e){for(let t of e??[]){if(t.type!==`function`)throw new K(`Currently only \`function\` tool types support auto-parsing; Received \`${t.type}\``);if(t.function.strict!==!0)throw new K(`The \`${t.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var SC=t((()=>{uC()})),CC,wC,TC=t((()=>{CC=e=>e?.role===`assistant`,wC=e=>e?.role===`tool`})),EC,DC,OC,kC,AC,jC,MC,NC,PC,FC,IC,LC,RC,zC,BC,VC,HC=t((()=>{rb(),uC(),VC=class{constructor(){EC.add(this),this.controller=new AbortController,DC.set(this,void 0),OC.set(this,()=>{}),kC.set(this,()=>{}),AC.set(this,void 0),jC.set(this,()=>{}),MC.set(this,()=>{}),NC.set(this,{}),PC.set(this,[]),FC.set(this,!1),IC.set(this,!1),LC.set(this,!1),RC.set(this,!1),W(this,DC,new Promise((e,t)=>{W(this,OC,e,`f`),W(this,kC,t,`f`)}),`f`),W(this,AC,new Promise((e,t)=>{W(this,jC,e,`f`),W(this,MC,t,`f`)}),`f`),G(this,DC,`f`).catch(()=>{}),G(this,AC,`f`).catch(()=>{})}_run(e){setTimeout(()=>{Promise.resolve().then(e).then(()=>{try{this._emitFinal()}catch(e){G(this,EC,`m`,BC).call(this,e);return}this._emit(`end`)},G(this,EC,`m`,BC).bind(this))},0)}_connected(){this.ended||(G(this,OC,`f`).call(this),this._emit(`connect`))}get ended(){return G(this,FC,`f`)}get errored(){return G(this,IC,`f`)}get aborted(){return G(this,LC,`f`)}abort(){this.controller.abort()}_listenForAbort(e){if(!e||this.ended)return;if(e.aborted){this.controller.abort();return}let t=()=>this.controller.abort();e.addEventListener(`abort`,t,{once:!0}),G(this,PC,`f`).push({signal:e,listener:t})}on(e,t){return(G(this,NC,`f`)[e]||(G(this,NC,`f`)[e]=[])).push({listener:t}),this}off(e,t){let n=G(this,NC,`f`)[e];if(!n)return this;let r=n.findIndex(e=>e.listener===t);return r>=0&&n.splice(r,1),this}once(e,t){return(G(this,NC,`f`)[e]||(G(this,NC,`f`)[e]=[])).push({listener:t,once:!0}),this}emitted(e){return new Promise((t,n)=>{W(this,RC,!0,`f`),e!==`error`&&this.once(`error`,n),this.once(e,t)})}events(e){let t=[],n=[],r=this.ended,i,a=!1,o=()=>({value:void 0,done:!0}),s=()=>{for(;n.length;)n.shift().resolve(o())},c=()=>{!i||a||!n.length||(a=!0,n.shift().reject(i))},l=()=>{this.off(e,u),this.off(`end`,f),e!==`error`&&this.off(`error`,d),e!==`abort`&&this.off(`abort`,d)},u=(...e)=>{if(r)return;let i=n.shift();i?i.resolve({value:e,done:!1}):t.push(e)},d=e=>{i=e,t.length||c()},f=()=>{r=!0,l(),t.length||(c(),s())};return r||(this.on(e,u),this.on(`end`,f),e!==`error`&&this.on(`error`,d),e!==`abort`&&this.on(`abort`,d)),{next:()=>{let e=t.shift();return e?Promise.resolve({value:e,done:!1}):i&&!a?(a=!0,Promise.reject(i)):r?Promise.resolve(o()):new Promise((e,t)=>{n.push({resolve:e,reject:t})})},return:()=>(r=!0,t.length=0,l(),s(),Promise.resolve(o())),[Symbol.asyncIterator](){return this}}}async done(){W(this,RC,!0,`f`),await G(this,AC,`f`)}_emit(e,...t){if(G(this,FC,`f`))return;e===`end`&&(G(this,EC,`m`,zC).call(this),W(this,FC,!0,`f`),G(this,jC,`f`).call(this));let n=G(this,NC,`f`)[e];if(n&&(G(this,NC,`f`)[e]=n.filter(e=>!e.once),n.forEach(({listener:e})=>e(...t))),e===`abort`){let e=t[0];!G(this,RC,`f`)&&!n?.length&&Promise.reject(e),G(this,kC,`f`).call(this,e),G(this,MC,`f`).call(this,e),this._emit(`end`);return}if(e===`error`){let e=t[0];!G(this,RC,`f`)&&!n?.length&&Promise.reject(e),G(this,kC,`f`).call(this,e),G(this,MC,`f`).call(this,e),this._emit(`end`)}}_emitFinal(){}},DC=new WeakMap,OC=new WeakMap,kC=new WeakMap,AC=new WeakMap,jC=new WeakMap,MC=new WeakMap,NC=new WeakMap,PC=new WeakMap,FC=new WeakMap,IC=new WeakMap,LC=new WeakMap,RC=new WeakMap,EC=new WeakSet,zC=function(){for(let{signal:e,listener:t}of G(this,PC,`f`).splice(0))e.removeEventListener(`abort`,t)},BC=function(e){if(W(this,IC,!0,`f`),e instanceof Error&&e.name===`AbortError`&&(e=new ub),e instanceof ub)return W(this,LC,!0,`f`),this._emit(`abort`,e);if(e instanceof K)return this._emit(`error`,e);if(e instanceof Error){let t=new K(e.message);return t.cause=e,this._emit(`error`,t)}return this._emit(`error`,new K(String(e)))}}));function UC(e){return typeof e.parse==`function`}var WC=t((()=>{}));function GC(e){for(let t of e.choices)for(let e of t.message.tool_calls??[])e.id||(e.id=`call_${ib()}`)}function KC(e){if(!CC(e))return e;let t={role:`assistant`};return e.audio!=null&&(t.audio={id:e.audio.id}),e.content!==void 0&&(t.content=e.content),e.function_call!=null&&(t.function_call=e.function_call),e.name!==void 0&&(t.name=e.name),e.refusal!=null&&(t.refusal=e.refusal),e.tool_calls!==void 0&&(t.tool_calls=e.tool_calls.map(e=>e.type===`custom`?{id:e.id,type:e.type,custom:{input:e.custom.input,name:e.custom.name}}:{id:e.id,type:e.type,function:{arguments:e.function.arguments,name:e.function.name}})),t}var qC,JC,YC,XC,ZC,QC,$C,ew,tw,nw,rw=t((()=>{rb(),uC(),ab(),SC(),TC(),HC(),WC(),tw=10,nw=class extends VC{constructor(){super(...arguments),qC.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){GC(e),this._chatCompletions.push(e),this._emit(`chatCompletion`,e);let t=e.choices[0]?.message;return t&&this._addMessage(t),e}_addMessage(e,t=!0){if(`content`in e||(e.content=null),this.messages.push(e),t){if(this._emit(`message`,e),wC(e)&&e.content)this._emit(`functionToolCallResult`,e.content);else if(CC(e)&&e.tool_calls)for(let t of e.tool_calls)t.type===`function`&&this._emit(`functionToolCall`,t.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new K(`stream ended without producing a ChatCompletion`);return e}async finalContent(){return await this.done(),G(this,qC,`m`,JC).call(this)}async finalMessage(){return await this.done(),G(this,qC,`m`,YC).call(this)}async finalFunctionToolCall(){return await this.done(),G(this,qC,`m`,XC).call(this)}async finalFunctionToolCallResult(){return await this.done(),G(this,qC,`m`,ZC).call(this)}async totalUsage(){return await this.done(),G(this,qC,`m`,QC).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit(`finalChatCompletion`,e);let t=G(this,qC,`m`,YC).call(this);t&&this._emit(`finalMessage`,t);let n=G(this,qC,`m`,JC).call(this);n&&this._emit(`finalContent`,n);let r=G(this,qC,`m`,XC).call(this);r&&this._emit(`finalFunctionToolCall`,r);let i=G(this,qC,`m`,ZC).call(this);i!=null&&this._emit(`finalFunctionToolCallResult`,i),this._chatCompletions.some(e=>e.usage)&&this._emit(`totalUsage`,G(this,qC,`m`,QC).call(this))}async _createChatCompletion(e,t,n){this._listenForAbort(n?.signal),G(this,qC,`m`,$C).call(this,t);let r=await e.chat.completions.create({...t,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(hC(r,t))}async _runChatCompletion(e,t,n){for(let e of t.messages)this._addMessage(e,!1);return await this._createChatCompletion(e,t,n)}async _runTools(e,t,n,r){let i=`tool`,{tool_choice:a=`auto`,stream:o,toolContext:s,...c}=t,l=s,u=typeof a!=`string`&&a.type===`function`&&a?.function?.name,{maxChatCompletions:d=tw,afterCompletion:f}=r||{},p=t.tools.map(e=>{if(pC(e)){if(!e.$callback)throw new K("Tool given to `.runTools()` that does not have an associated function");return{type:`function`,function:{function:e.$callback,name:e.function.name,description:e.function.description||``,parameters:e.function.parameters,parse:e.$parseRaw,strict:!0}}}return e}),m={};for(let e of p)e.type===`function`&&(m[e.function.name||e.function.function.name]=e.function);let h=`tools`in t?p.map(e=>e.type===`function`?{type:`function`,function:{name:e.function.name||e.function.function.name,parameters:e.function.parameters,description:e.function.description,strict:e.function.strict}}:e):void 0;for(let e of t.messages)this._addMessage(e,!1);let g=async e=>{if(e.type!==`function`)return{message:void 0,functionCalled:!1};let t=e.id,{name:r,arguments:a}=e.function,o=m[r];if(!o){let e=`Invalid tool_call: ${JSON.stringify(r)}. Available options are: ${Object.keys(m).map(e=>JSON.stringify(e)).join(`, `)}. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}if(u&&u!==r){let e=`Invalid tool_call: ${JSON.stringify(r)}. ${JSON.stringify(u)} requested. Please try again`;return{message:{role:i,tool_call_id:t,content:e},functionCalled:!1}}let s;if(UC(o)){let e;try{e=await o.parse(a)}catch(e){let n=e instanceof Error?e.message:String(e);return{message:{role:i,tool_call_id:t,content:n},functionCalled:!1}}s=await o.function(e,n,l)}else s=await o.function(a,n,l);let c=G(this,qC,`m`,ew).call(this,s);return{message:{role:i,tool_call_id:t,content:c},functionCalled:!0}};for(let i=0;i<d;++i){let i=await this._createChatCompletion(e,{...c,tool_choice:a,tools:h,messages:this.messages.map(KC)},r),o=i.choices[0]?.message;if(!o)throw new K(`missing message in ChatCompletion response`);if(!o.tool_calls?.length){await f?.(i,n);return}if(u||t.parallel_tool_calls===!1)for(let e of o.tool_calls){let t=await g(e);if(t.message&&this._addMessage(t.message),u&&t.functionCalled){await f?.(i,n);return}}else{let e=await Promise.allSettled(o.tool_calls.map(g));for(let t of e)if(t.status===`rejected`)throw t.reason;for(let t of e)t.status===`fulfilled`&&t.value.message&&this._addMessage(t.value.message)}await f?.(i,n)}}},qC=new WeakSet,JC=function(){return G(this,qC,`m`,YC).call(this).content??null},YC=function(){let e=this.messages.length;for(;e-->0;){let t=this.messages[e];if(CC(t))return{...t,content:t.content??null,refusal:t.refusal??null}}throw new K(`stream ended without producing a ChatCompletionMessage with role=assistant`)},XC=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(CC(t)&&t?.tool_calls?.length)for(let e=t.tool_calls.length-1;e>=0;e--){let n=t.tool_calls[e];if(n?.type===`function`)return n.function}}},ZC=function(){for(let e=this.messages.length-1;e>=0;e--){let t=this.messages[e];if(wC(t)&&t.content!=null&&typeof t.content==`string`&&this.messages.some(e=>e.role===`assistant`&&e.tool_calls?.some(e=>e.type===`function`&&e.id===t.tool_call_id)))return t.content}},QC=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:t}of this._chatCompletions)t&&(e.completion_tokens+=t.completion_tokens,e.prompt_tokens+=t.prompt_tokens,e.total_tokens+=t.total_tokens);return e},$C=function(e){if(e.n!=null&&e.n>1)throw new K(`ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.`)},ew=function(e){return typeof e==`string`?e:e===void 0?`undefined`:JSON.stringify(e)}})),iw,aw=t((()=>{rw(),TC(),iw=class e extends nw{static runTools(t,n,r){let i=new e,a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}_addMessage(e,t=!0){super._addMessage(e,t),CC(e)&&e.content&&this._emit(`content`,e.content)}}}));function ow(e,t=sw.ALL){if(typeof e!=`string`)throw TypeError(`expecting str, got ${typeof e}`);if(!e.trim())throw Error(`${e} is empty`);return uw(e.trim(),t)}var sw,cw,lw,uw,dw,fw=t((()=>{sw={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},cw=class extends Error{},lw=class extends Error{},uw=(e,t)=>{let n=e.length,r=0,i=e=>{throw new cw(`${e} at position ${r}`)},a=e=>{throw new lw(`${e} at position ${r}`)},o=()=>(d(),r>=n&&i(`Unexpected end of input`),e[r]===`"`?s():e[r]===`{`?c():e[r]===`[`?l():e.substring(r,r+4)===`null`||sw.NULL&t&&n-r<4&&`null`.startsWith(e.substring(r))?(r+=4,null):e.substring(r,r+4)===`true`||sw.BOOL&t&&n-r<4&&`true`.startsWith(e.substring(r))?(r+=4,!0):e.substring(r,r+5)===`false`||sw.BOOL&t&&n-r<5&&`false`.startsWith(e.substring(r))?(r+=5,!1):e.substring(r,r+8)===`Infinity`||sw.INFINITY&t&&n-r<8&&`Infinity`.startsWith(e.substring(r))?(r+=8,1/0):e.substring(r,r+9)===`-Infinity`||sw.MINUS_INFINITY&t&&1<n-r&&n-r<9&&`-Infinity`.startsWith(e.substring(r))?(r+=9,-1/0):e.substring(r,r+3)===`NaN`||sw.NAN&t&&n-r<3&&`NaN`.startsWith(e.substring(r))?(r+=3,NaN):u()),s=()=>{let o=r,s=!1;for(r++;r<n&&(e[r]!==`"`||s&&e[r-1]===`\\`);)s=e[r]===`\\`&&!s,r++;if(e.charAt(r)==`"`)try{return JSON.parse(e.substring(o,++r-Number(s)))}catch(e){a(String(e))}else if(sw.STR&t)try{return JSON.parse(e.substring(o,r-Number(s))+`"`)}catch{return JSON.parse(e.substring(o,e.lastIndexOf(`\\`))+`"`)}i(`Unterminated string literal`)},c=()=>{r++,d();let a={};try{for(;e[r]!==`}`;){if(d(),r>=n&&sw.OBJ&t)return a;let i=s();d(),r++;try{let e=o();Object.defineProperty(a,i,{value:e,writable:!0,enumerable:!0,configurable:!0})}catch(e){if(sw.OBJ&t)return a;throw e}d(),e[r]===`,`&&r++}}catch{if(sw.OBJ&t)return a;i(`Expected '}' at end of object`)}return r++,a},l=()=>{r++;let n=[];try{for(;e[r]!==`]`;)n.push(o()),d(),e[r]===`,`&&r++}catch{if(sw.ARR&t)return n;i(`Expected ']' at end of array`)}return r++,n},u=()=>{if(r===0){e===`-`&&sw.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e)}catch(n){if(sw.NUM&t)try{return e[e.length-1]===`.`?JSON.parse(e.substring(0,e.lastIndexOf(`.`))):JSON.parse(e.substring(0,e.lastIndexOf(`e`)))}catch{}a(String(n))}}let o=r;for(e[r]===`-`&&r++;e[r]&&!`,]}`.includes(e[r]);)r++;r==n&&!(sw.NUM&t)&&i(`Unterminated number literal`);try{return JSON.parse(e.substring(o,r))}catch{e.substring(o,r)===`-`&&sw.NUM&t&&i(`Not sure what '-' is`);try{return JSON.parse(e.substring(o,e.lastIndexOf(`e`)))}catch(e){a(String(e))}}},d=()=>{for(;r<n&&`
|
||
\r `.includes(e[r]);)r++};return o()},dw=e=>ow(e,sw.ALL^sw.NUM)})),pw=t((()=>{tS()}));function mw(e,t,n){let r={type:`message`,message:t,...n?{tool_call_ids:n}:{}};return{id:e.id,choices:[],created:e.created,model:e.model,object:`${Nw}${JSON.stringify(r)}`}}function hw(e){return`type`in e&&e.type===`message`&&`message`in e||`object`in e&&typeof e.object==`string`&&e.object.startsWith(Nw)}function gw(e){return`type`in e?e:JSON.parse(e.object.slice(30))}function _w(e,t,n){let{id:r,choices:i,created:a,model:o,system_fingerprint:s,...c}=e;return mC({...c,id:r,choices:i.map(({message:t,finish_reason:r,index:i,logprobs:a,...o})=>{let{content:s=null,function_call:c,tool_calls:l,audio:u,...d}=t,f=r??(n.has(i)&&vw(u)?`stop`:null);if(!f)throw new K(`missing finish_reason for choice ${i}`);let p=u?{audio:u}:{},m=t.role;if(!m)throw new K(`missing role for choice ${i}`);if(c){let{arguments:e,name:n}=c;if(e==null)throw new K(`missing function_call.arguments for choice ${i}`);if(!n)throw new K(`missing function_call.name for choice ${i}`);return{...o,message:{...p,content:s,function_call:{arguments:e,name:n},role:m,refusal:t.refusal??null},finish_reason:f,index:i,logprobs:a}}return l?{...o,index:i,finish_reason:f,logprobs:a,message:{...d,...p,role:m,content:s,refusal:t.refusal??null,tool_calls:l.map((t,n)=>{let{function:r,type:a,id:o,...s}=t,{arguments:c,name:l,...u}=r||{};if(a==null)throw new K(`missing choices[${i}].tool_calls[${n}].type\n${yw(e)}`);if(l==null)throw new K(`missing choices[${i}].tool_calls[${n}].function.name\n${yw(e)}`);if(c==null)throw new K(`missing choices[${i}].tool_calls[${n}].function.arguments\n${yw(e)}`);return{...s,id:o||`call_${ib()}`,type:a,function:{...u,name:l,arguments:c}}})}}:{...o,message:{...d,...p,content:s,role:m,refusal:t.refusal??null},finish_reason:f,index:i,logprobs:a}}),created:a,model:o,object:`chat.completion`,...s?{system_fingerprint:s}:{}},t)}function vw(e){return e?.id!=null&&e.data!=null&&e.transcript!=null&&e.expires_at!=null}function yw(e){return JSON.stringify(e)}var bw,xw,Sw,Cw,ww,Tw,Ew,Dw,Ow,kw,Aw,jw,Mw,Nw,Pw,Fw=t((()=>{rb(),fw(),uC(),ab(),SC(),pw(),rw(),Nw=`chat.completion.chunk.message:`,Pw=class e extends nw{constructor(e){super(),bw.add(this),xw.set(this,void 0),Sw.set(this,void 0),Cw.set(this,void 0),ww.set(this,void 0),W(this,xw,e,`f`),W(this,Sw,new Set,`f`),W(this,Cw,[],`f`)}get currentChatCompletionSnapshot(){return G(this,ww,`f`)}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}static createChatCompletion(t,n,r){let i=new e(n);return i._run(()=>i._runChatCompletion(t,{...n,stream:!0},{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createChatCompletion(e,t,n){super._createChatCompletion,this._listenForAbort(n?.signal),G(this,bw,`m`,Tw).call(this);let r=await e.chat.completions.create({...t,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let e of r)G(this,bw,`m`,Dw).call(this,e);if(r.controller.signal?.aborted)throw new ub;return this._addChatCompletion(G(this,bw,`m`,Aw).call(this))}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),G(this,bw,`m`,Tw).call(this),this._connected();let n=$x.fromReadableStream(e,this.controller),r;for await(let e of n){if(hw(e)){let t=gw(e);if(G(this,ww,`f`)){let e=G(this,ww,`f`).choices[0]?.message.tool_calls;for(let[n,r]of t.tool_call_ids?.entries()??[]){let t=e?.[n];t&&r&&(t.id=r)}this._addChatCompletion(G(this,bw,`m`,Aw).call(this)),r=void 0}this._addMessage(t.message);continue}let t=e;r&&t.id&&r!==t.id&&this._addChatCompletion(G(this,bw,`m`,Aw).call(this)),G(this,bw,`m`,Dw).call(this,t),t.id&&(r=t.id)}if(n.controller.signal?.aborted)throw new ub;if(G(this,ww,`f`))return this._addChatCompletion(G(this,bw,`m`,Aw).call(this));let i=this._chatCompletions[this._chatCompletions.length-1];if(i)return i;throw new K(`request ended without sending any chunks`)}[(xw=new WeakMap,Sw=new WeakMap,Cw=new WeakMap,ww=new WeakMap,bw=new WeakSet,Tw=function(){this.ended||(W(this,Sw,new Set,`f`),W(this,ww,void 0,`f`))},Ew=function(e){let t=G(this,Cw,`f`)[e.index];return t||(t={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},G(this,Cw,`f`)[e.index]=t,t)},Dw=function(e){if(this.ended)return;let t=G(this,bw,`m`,Mw).call(this,e);this._emit(`chunk`,e,t);for(let n of e.choices){let e=t.choices[n.index],{delta:r}=n;r?.content!=null&&e.message?.role===`assistant`&&e.message?.content&&(this._emit(`content`,r.content,e.message.content),this._emit(`content.delta`,{delta:r.content,snapshot:e.message.content,parsed:e.message.parsed})),r?.refusal!=null&&e.message?.role===`assistant`&&e.message?.refusal&&this._emit(`refusal.delta`,{delta:r.refusal,snapshot:e.message.refusal}),n.logprobs?.content!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.content.delta`,{content:n.logprobs?.content,snapshot:e.logprobs?.content??[]}),n.logprobs?.refusal!=null&&e.message?.role===`assistant`&&this._emit(`logprobs.refusal.delta`,{refusal:n.logprobs?.refusal,snapshot:e.logprobs?.refusal??[]});let i=G(this,bw,`m`,Ew).call(this,e);e.finish_reason&&(G(this,bw,`m`,kw).call(this,e),i.current_tool_call_index!=null&&G(this,bw,`m`,Ow).call(this,e,i.current_tool_call_index));for(let t of r?.tool_calls??[])i.current_tool_call_index!==t.index&&(G(this,bw,`m`,kw).call(this,e),i.current_tool_call_index!=null&&G(this,bw,`m`,Ow).call(this,e,i.current_tool_call_index)),i.current_tool_call_index=t.index;for(let t of r?.tool_calls??[]){let n=e.message.tool_calls?.[t.index];n?.type&&(n?.type===`function`?this._emit(`tool_calls.function.arguments.delta`,{name:n.function?.name,index:t.index,arguments:n.function.arguments,parsed_arguments:n.function.parsed_arguments,arguments_delta:t.function?.arguments??``}):n?.type)}}},Ow=function(e,t){if(G(this,bw,`m`,Ew).call(this,e).done_tool_calls.has(t))return;let n=e.message.tool_calls?.[t];if(!n)throw Error(`no tool call snapshot`);if(!n.type)throw Error("tool call snapshot missing `type`");if(n.type===`function`){let e=G(this,xw,`f`)?.tools?.find(e=>dC(e)&&e.function.name===n.function.name);this._emit(`tool_calls.function.arguments.done`,{name:n.function.name,index:t,arguments:n.function.arguments,parsed_arguments:pC(e)?e.$parseRaw(n.function.arguments):e?.function.strict?JSON.parse(n.function.arguments):null})}else n.type},kw=function(e){let t=G(this,bw,`m`,Ew).call(this,e);if(e.message.content&&!t.content_done){t.content_done=!0;let n=G(this,bw,`m`,jw).call(this);this._emit(`content.done`,{content:e.message.content,parsed:n?n.$parseRaw(e.message.content):null})}e.message.refusal&&!t.refusal_done&&(t.refusal_done=!0,this._emit(`refusal.done`,{refusal:e.message.refusal})),e.logprobs?.content&&!t.logprobs_content_done&&(t.logprobs_content_done=!0,this._emit(`logprobs.content.done`,{content:e.logprobs.content})),e.logprobs?.refusal&&!t.logprobs_refusal_done&&(t.logprobs_refusal_done=!0,this._emit(`logprobs.refusal.done`,{refusal:e.logprobs.refusal}))},Aw=function(){if(this.ended)throw new K(`stream has ended, this shouldn't happen`);let e=G(this,ww,`f`);if(!e)throw new K(`request ended without sending any chunks`);let t=G(this,Sw,`f`);return W(this,Sw,new Set,`f`),W(this,ww,void 0,`f`),W(this,Cw,[],`f`),_w(e,G(this,xw,`f`),t)},jw=function(){let e=G(this,xw,`f`)?.response_format;return fC(e)?e:null},Mw=function(e){var t,n,r,i,a;let o=G(this,ww,`f`),{choices:s,...c}=e;o?e.id&&Object.assign(o,c):o=W(this,ww,{...c,choices:[]},`f`);for(let{delta:s,finish_reason:c,index:l,logprobs:u=null,...d}of e.choices){let e=o.choices[l];if(e||(e=o.choices[l]={finish_reason:c,index:l,message:{},logprobs:u,...d}),u){if(!e.logprobs)e.logprobs=Object.assign({},u);else{let{content:r,refusal:i,...a}=u;Object.assign(e.logprobs,a),r&&((t=e.logprobs).content??(t.content=[]),e.logprobs.content.push(...r)),i&&((n=e.logprobs).refusal??(n.refusal=[]),e.logprobs.refusal.push(...i))}}if(c&&(e.finish_reason=c,G(this,xw,`f`)&&yC(G(this,xw,`f`)))){if(c===`length`)throw new xb;if(c===`content_filter`)throw new Sb}if(Object.assign(e,d),!s)continue;G(this,Sw,`f`).delete(l);let{audio:f,content:p,refusal:m,function_call:h,role:g,tool_calls:_,...v}=s;if(Object.assign(e.message,v),f?.expires_at!=null&&f.id==null&&f.data==null&&f.transcript==null&&p==null&&m==null&&h==null&&g==null&&_==null&&Object.keys(v).length===0&&G(this,Sw,`f`).add(l),m&&(e.message.refusal=(e.message.refusal||``)+m),g&&(e.message.role=g),f){let t=(r=e.message).audio??(r.audio={});f.id!=null&&(t.id=f.id),f.data!=null&&(t.data=(t.data??``)+f.data),f.transcript!=null&&(t.transcript=(t.transcript??``)+f.transcript),f.expires_at!=null&&(t.expires_at=f.expires_at)}if(h&&(e.message.function_call?(h.name&&(e.message.function_call.name=h.name),h.arguments&&((i=e.message.function_call).arguments??(i.arguments=``),e.message.function_call.arguments+=h.arguments)):e.message.function_call=h),p&&(e.message.content=(e.message.content||``)+p,!e.message.refusal&&G(this,bw,`m`,jw).call(this)&&(e.message.parsed=e.message.content.trim()?dw(e.message.content):null)),_){e.message.tool_calls||(e.message.tool_calls=[]);for(let{index:t,id:n,type:r,function:i,...o}of _){let s=(a=e.message.tool_calls)[t]??(a[t]={});Object.assign(s,o),n&&(s.id=n),r&&(s.type=r),i&&(s.function??(s.function={name:i.name??``,arguments:``})),i?.name&&(s.function.name=i.name),i?.arguments&&(s.function.arguments+=i.arguments,vC(G(this,xw,`f`),s)&&(s.function.parsed_arguments=dw(s.function.arguments)))}}}return o},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`chunk`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new $x(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}}})),Iw,Lw=t((()=>{Fw(),uC(),pw(),TC(),Iw=class e extends Pw{static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}toReadableStream(){let e=[],t=[],n=!1,r,i,a=n=>{let r=t.shift();r?r.resolve(n):e.push(n)};return this.on(`chunk`,e=>{r=e,a(e)}),this.on(`message`,e=>{if(CC(e)){i=e.tool_calls?.map(e=>e.id);return}if(wC(e)){if(!r)throw new K(`cannot serialize a tool message before receiving any chunks`);a(mw(r,e,i))}}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),new $x(()=>({next:async()=>{if(!e.length)return n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0});let r=e.shift();return r?{value:r,done:!1}:{value:void 0,done:!0}},return:async()=>(this.abort(),{value:void 0,done:!0})}),this.controller).toReadableStream()}static runTools(t,n,r){let i=new e(n),a={...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`runTools`}};return i._run(()=>i._runTools(t,n,i,a)),i}}})),Rw,zw=t((()=>{X(),lC(),q(),Q(),aw(),Lw(),Fw(),SC(),WC(),Rw=class extends Y{constructor(){super(...arguments),this.messages=new cC(this._client)}create(e,t){return this._client.post(`/chat/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(Z`/chat/completions/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chat/completions`,fS,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/chat/completions/${e}`,{...t,__security:{bearerAuth:!0}})}parse(e,t){return xC(e.tools),this._client.chat.completions.create(e,{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":`chat.completions.parse`}})._thenUnwrap(t=>hC(t,e))}runTools(e,t){return e.stream?Iw.runTools(this._client,e,t):iw.runTools(this._client,e,t)}stream(e,t){return Pw.createChatCompletion(this._client,e,t)}},Rw.Messages=cC})),Bw,Vw=t((()=>{X(),zw(),Bw=class extends Y{constructor(){super(...arguments),this.completions=new Rw(this._client)}},Bw.Completions=Rw})),Hw=t((()=>{zw(),zw(),lC()})),Uw=t((()=>{Vw(),Hw()})),Ww=t((()=>{})),Gw,Kw=t((()=>{X(),q(),Q(),Gw=class extends Y{create(e,t){return this._client.post(`/organization/admin_api_keys`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Z`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/admin_api_keys`,fS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/admin_api_keys/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),qw,Jw=t((()=>{X(),q(),qw=class extends Y{list(e={},t){return this._client.getAPIList(`/organization/audit_logs`,pS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}})),Yw,Xw=t((()=>{X(),q(),Q(),Yw=class extends Y{create(e,t){return this._client.post(`/organization/certificates`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(Z`/organization/certificates/${e}`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/certificates/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/certificates`,pS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/certificates/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}activate(e,t){return this._client.getAPIList(`/organization/certificates/activate`,dS,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t){return this._client.getAPIList(`/organization/certificates/deactivate`,dS,{body:e,method:`post`,...t,__security:{adminAPIKeyAuth:!0}})}}})),Zw,Qw=t((()=>{X(),Zw=class extends Y{retrieve(e){return this._client.get(`/organization/data_retention`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/data_retention`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}}})),$w,eT=t((()=>{X(),q(),Q(),$w=class extends Y{create(e,t){return this._client.post(`/organization/invites`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Z`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/invites`,pS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/invites/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),tT,nT=t((()=>{X(),q(),Q(),tT=class extends Y{create(e,t){return this._client.post(`/organization/roles`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Z`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/roles/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/roles`,mS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/roles/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),rT,iT=t((()=>{X(),q(),Q(),rT=class extends Y{create(e,t){return this._client.post(`/organization/spend_alerts`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Z`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/spend_alerts/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/spend_alerts`,pS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/spend_alerts/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),aT,oT=t((()=>{X(),aT=class extends Y{retrieve(e){return this._client.get(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}update(e,t){return this._client.post(`/organization/spend_limit`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e){return this._client.delete(`/organization/spend_limit`,{...e,__security:{adminAPIKeyAuth:!0}})}}})),sT,cT=t((()=>{X(),sT=class extends Y{audioSpeeches(e,t){return this._client.get(`/organization/usage/audio_speeches`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}audioTranscriptions(e,t){return this._client.get(`/organization/usage/audio_transcriptions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}codeInterpreterSessions(e,t){return this._client.get(`/organization/usage/code_interpreter_sessions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}completions(e,t){return this._client.get(`/organization/usage/completions`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}costs(e,t){return this._client.get(`/organization/costs`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}embeddings(e,t){return this._client.get(`/organization/usage/embeddings`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}fileSearchCalls(e,t){return this._client.get(`/organization/usage/file_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}images(e,t){return this._client.get(`/organization/usage/images`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}moderations(e,t){return this._client.get(`/organization/usage/moderations`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}vectorStores(e,t){return this._client.get(`/organization/usage/vector_stores`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}webSearchCalls(e,t){return this._client.get(`/organization/usage/web_search_calls`,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}}})),lT,uT=t((()=>{X(),q(),Q(),lT=class extends Y{create(e,t,n){return this._client.post(Z`/organization/groups/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(Z`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/groups/${e}/roles`,mS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(Z`/organization/groups/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),dT,fT=t((()=>{X(),q(),Q(),dT=class extends Y{create(e,t,n){return this._client.post(Z`/organization/groups/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{group_id:r}=t;return this._client.get(Z`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/groups/${e}/users`,mS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{group_id:r}=t;return this._client.delete(Z`/organization/groups/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),pT,mT=t((()=>{X(),uT(),fT(),q(),Q(),pT=class extends Y{constructor(){super(...arguments),this.users=new dT(this._client),this.roles=new lT(this._client)}create(e,t){return this._client.post(`/organization/groups`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Z`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/groups/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/groups`,mS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/groups/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},pT.Users=dT,pT.Roles=lT})),hT,gT=t((()=>{X(),q(),Q(),hT=class extends Y{retrieve(e,t,n){let{project_id:r}=t;return this._client.get(Z`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/projects/${e}/api_keys`,pS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(Z`/organization/projects/${r}/api_keys/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),_T,vT=t((()=>{X(),q(),Q(),_T=class extends Y{list(e,t={},n){return this._client.getAPIList(Z`/organization/projects/${e}/certificates`,pS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}activate(e,t,n){return this._client.getAPIList(Z`/organization/projects/${e}/certificates/activate`,dS,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}deactivate(e,t,n){return this._client.getAPIList(Z`/organization/projects/${e}/certificates/deactivate`,dS,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}}})),yT,bT=t((()=>{X(),Q(),yT=class extends Y{retrieve(e,t){return this._client.get(Z`/organization/projects/${e}/data_retention`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/projects/${e}/data_retention`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}})),xT,ST=t((()=>{X(),Q(),xT=class extends Y{retrieve(e,t){return this._client.get(Z`/organization/projects/${e}/hosted_tool_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/projects/${e}/hosted_tool_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}}})),CT,wT=t((()=>{X(),Q(),CT=class extends Y{retrieve(e,t){return this._client.get(Z`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/projects/${e}/model_permissions`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/projects/${e}/model_permissions`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),TT,ET=t((()=>{X(),q(),Q(),TT=class extends Y{listRateLimits(e,t={},n){return this._client.getAPIList(Z`/organization/projects/${e}/rate_limits`,pS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}updateRateLimit(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/organization/projects/${r}/rate_limits/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}}})),DT,OT=t((()=>{X(),q(),Q(),DT=class extends Y{create(e,t,n){return this._client.post(Z`/projects/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(Z`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/projects/${r}/roles/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/projects/${e}/roles`,mS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(Z`/projects/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),kT,AT=t((()=>{X(),q(),Q(),kT=class extends Y{create(e,t,n){return this._client.post(Z`/organization/projects/${e}/spend_alerts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(Z`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/organization/projects/${r}/spend_alerts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/projects/${e}/spend_alerts`,pS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(Z`/organization/projects/${r}/spend_alerts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),jT,MT=t((()=>{X(),Q(),jT=class extends Y{retrieve(e,t){return this._client.get(Z`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/projects/${e}/spend_limit`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/projects/${e}/spend_limit`,{...t,__security:{adminAPIKeyAuth:!0}})}}})),NT,PT=t((()=>{X(),q(),Q(),NT=class extends Y{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/projects/${r}/groups/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,group_id:i}=t;return this._client.get(Z`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(Z`/projects/${r}/groups/${e}/roles`,mS,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,group_id:i}=t;return this._client.delete(Z`/projects/${r}/groups/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),FT,IT=t((()=>{X(),PT(),q(),Q(),FT=class extends Y{constructor(){super(...arguments),this.roles=new NT(this._client)}create(e,t,n){return this._client.post(Z`/organization/projects/${e}/groups`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,...i}=t;return this._client.get(Z`/organization/projects/${r}/groups/${e}`,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/projects/${e}/groups`,mS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(Z`/organization/projects/${r}/groups/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},FT.Roles=NT})),LT,RT=t((()=>{X(),Q(),LT=class extends Y{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/organization/projects/${r}/service_accounts/${e}/api_keys`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}}})),zT,BT=t((()=>{X(),RT(),q(),Q(),zT=class extends Y{constructor(){super(...arguments),this.apiKeys=new LT(this._client)}create(e,t,n){return this._client.post(Z`/organization/projects/${e}/service_accounts`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(Z`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/organization/projects/${r}/service_accounts/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/projects/${e}/service_accounts`,pS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(Z`/organization/projects/${r}/service_accounts/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},zT.APIKeys=LT})),VT,HT=t((()=>{X(),q(),Q(),VT=class extends Y{create(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/projects/${r}/users/${e}/roles`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r,user_id:i}=t;return this._client.get(Z`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t,n){let{project_id:r,...i}=t;return this._client.getAPIList(Z`/projects/${r}/users/${e}/roles`,mS,{query:i,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r,user_id:i}=t;return this._client.delete(Z`/projects/${r}/users/${i}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),UT,WT=t((()=>{X(),HT(),q(),Q(),UT=class extends Y{constructor(){super(...arguments),this.roles=new VT(this._client)}create(e,t,n){return this._client.post(Z`/organization/projects/${e}/users`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{project_id:r}=t;return this._client.get(Z`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){let{project_id:r,...i}=t;return this._client.post(Z`/organization/projects/${r}/users/${e}`,{body:i,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/projects/${e}/users`,pS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{project_id:r}=t;return this._client.delete(Z`/organization/projects/${r}/users/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}},UT.Roles=VT})),GT,KT=t((()=>{X(),gT(),vT(),bT(),ST(),wT(),ET(),OT(),AT(),MT(),IT(),BT(),WT(),q(),Q(),GT=class extends Y{constructor(){super(...arguments),this.users=new UT(this._client),this.serviceAccounts=new zT(this._client),this.apiKeys=new hT(this._client),this.rateLimits=new TT(this._client),this.modelPermissions=new CT(this._client),this.hostedToolPermissions=new xT(this._client),this.groups=new FT(this._client),this.roles=new DT(this._client),this.dataRetention=new yT(this._client),this.spendLimit=new jT(this._client),this.spendAlerts=new kT(this._client),this.certificates=new _T(this._client)}create(e,t){return this._client.post(`/organization/projects`,{body:e,...t,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t){return this._client.get(Z`/organization/projects/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/projects/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/projects`,pS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}archive(e,t){return this._client.post(Z`/organization/projects/${e}/archive`,{...t,__security:{adminAPIKeyAuth:!0}})}},GT.Users=UT,GT.ServiceAccounts=zT,GT.APIKeys=hT,GT.RateLimits=TT,GT.ModelPermissions=CT,GT.HostedToolPermissions=xT,GT.Groups=FT,GT.Roles=DT,GT.DataRetention=yT,GT.SpendLimit=jT,GT.SpendAlerts=kT,GT.Certificates=_T})),qT,JT=t((()=>{X(),q(),Q(),qT=class extends Y{create(e,t,n){return this._client.post(Z`/organization/users/${e}/roles`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t,n){let{user_id:r}=t;return this._client.get(Z`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/organization/users/${e}/roles`,mS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{user_id:r}=t;return this._client.delete(Z`/organization/users/${r}/roles/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),YT,XT=t((()=>{X(),JT(),q(),Q(),YT=class extends Y{constructor(){super(...arguments),this.roles=new qT(this._client)}retrieve(e,t){return this._client.get(Z`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}update(e,t,n){return this._client.post(Z`/organization/users/${e}`,{body:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e={},t){return this._client.getAPIList(`/organization/users`,pS,{query:e,...t,__security:{adminAPIKeyAuth:!0}})}delete(e,t){return this._client.delete(Z`/organization/users/${e}`,{...t,__security:{adminAPIKeyAuth:!0}})}},YT.Roles=qT})),ZT,QT=t((()=>{X(),Kw(),Jw(),Xw(),Qw(),eT(),nT(),iT(),oT(),cT(),mT(),KT(),XT(),ZT=class extends Y{constructor(){super(...arguments),this.auditLogs=new qw(this._client),this.adminAPIKeys=new Gw(this._client),this.usage=new sT(this._client),this.invites=new $w(this._client),this.users=new YT(this._client),this.groups=new pT(this._client),this.roles=new tT(this._client),this.dataRetention=new Zw(this._client),this.spendLimit=new aT(this._client),this.spendAlerts=new rT(this._client),this.certificates=new Yw(this._client),this.projects=new GT(this._client)}},ZT.AuditLogs=qw,ZT.AdminAPIKeys=Gw,ZT.Usage=sT,ZT.Invites=$w,ZT.Users=YT,ZT.Groups=pT,ZT.Roles=tT,ZT.DataRetention=Zw,ZT.SpendLimit=aT,ZT.SpendAlerts=rT,ZT.Certificates=Yw,ZT.Projects=GT})),$T,eE=t((()=>{X(),QT(),$T=class extends Y{constructor(){super(...arguments),this.organization=new ZT(this._client)}},$T.Organization=ZT})),tE,nE=t((()=>{X(),SS(),tE=class extends Y{create(e,t){return this._client.post(`/audio/speech`,{body:e,...t,headers:J([{Accept:`application/octet-stream`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),rE,iE=t((()=>{X(),XS(),rE=class extends Y{create(e,t){return this._client.post(`/audio/transcriptions`,zS({body:e,...t,stream:e.stream??!1,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}})),aE,oE=t((()=>{X(),XS(),aE=class extends Y{create(e,t){return this._client.post(`/audio/translations`,zS({body:e,...t,__metadata:{model:e.model},__security:{bearerAuth:!0}},this._client))}}})),sE,cE=t((()=>{X(),nE(),iE(),oE(),sE=class extends Y{constructor(){super(...arguments),this.transcriptions=new rE(this._client),this.translations=new aE(this._client),this.speech=new tE(this._client)}},sE.Transcriptions=rE,sE.Translations=aE,sE.Speech=tE})),lE,uE=t((()=>{X(),q(),Q(),lE=class extends Y{create(e,t){return this._client.post(`/batches`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/batches/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/batches`,fS,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Z`/batches/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}}})),dE,fE=t((()=>{X(),q(),SS(),Q(),dE=class extends Y{create(e,t){return this._client.post(`/assistants`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(Z`/assistants/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/assistants`,fS,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/assistants/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),pE,mE=t((()=>{X(),SS(),pE=class extends Y{create(e,t){return this._client.post(`/realtime/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),hE,gE=t((()=>{X(),SS(),hE=class extends Y{create(e,t){return this._client.post(`/realtime/transcription_sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}}})),_E,vE=t((()=>{X(),mE(),gE(),_E=class extends Y{constructor(){super(...arguments),this.sessions=new pE(this._client),this.transcriptionSessions=new hE(this._client)}},_E.Sessions=pE,_E.TranscriptionSessions=hE})),yE,bE=t((()=>{X(),SS(),Q(),yE=class extends Y{create(e,t){return this._client.post(`/chatkit/sessions`,{body:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Z`/chatkit/sessions/${e}/cancel`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}}})),xE,SE=t((()=>{X(),q(),SS(),Q(),xE=class extends Y{retrieve(e,t){return this._client.get(Z`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/chatkit/threads`,pS,{query:e,...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/chatkit/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},t?.headers]),__security:{bearerAuth:!0}})}listItems(e,t={},n){return this._client.getAPIList(Z`/chatkit/threads/${e}/items`,pS,{query:t,...n,headers:J([{"OpenAI-Beta":`chatkit_beta=v1`},n?.headers]),__security:{bearerAuth:!0}})}}})),CE,wE=t((()=>{X(),bE(),SE(),CE=class extends Y{constructor(){super(...arguments),this.sessions=new yE(this._client),this.threads=new xE(this._client)}},CE.Sessions=yE,CE.Threads=xE})),TE,EE=t((()=>{X(),q(),SS(),Q(),TE=class extends Y{list(e,t={},n){let{betas:r,...i}=t??{};return this._client.getAPIList(Z`/responses/${e}/input_items?beta=true`,fS,{query:i,...n,headers:J([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}}})),DE,OE=t((()=>{X(),SS(),DE=class extends Y{count(e={},t){let{betas:n,...r}=e??{};return this._client.post(`/responses/input_tokens?beta=true`,{body:r,...t,headers:J([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}}})),kE,AE=t((()=>{X(),EE(),OE(),SS(),Q(),kE=class extends Y{constructor(){super(...arguments),this.inputItems=new TE(this._client),this.inputTokens=new DE(this._client)}create(e,t){let{betas:n,...r}=e;return this._client.post(`/responses?beta=true`,{body:r,...t,headers:J([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),stream:e.stream??!1,__security:{bearerAuth:!0}})}retrieve(e,t={},n){let{betas:r,...i}=t??{};return this._client.get(Z`/responses/${e}?beta=true`,{query:i,...n,headers:J([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),stream:t?.stream??!1,__security:{bearerAuth:!0}})}delete(e,t={},n){let{betas:r}=t??{};return this._client.delete(Z`/responses/${e}?beta=true`,{...n,headers:J([{Accept:`*/*`,...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t={},n){let{betas:r}=t??{};return this._client.post(Z`/responses/${e}/cancel?beta=true`,{...n,headers:J([{...r?.toString()==null?void 0:{"openai-beta":r?.toString()}},n?.headers]),__security:{bearerAuth:!0}})}compact(e,t){let{betas:n,...r}=e;return this._client.post(`/responses/compact?beta=true`,{body:r,...t,headers:J([{...n?.toString()==null?void 0:{"openai-beta":n?.toString()}},t?.headers]),__security:{bearerAuth:!0}})}},kE.InputItems=TE,kE.InputTokens=DE})),jE,ME=t((()=>{X(),q(),SS(),Q(),jE=class extends Y{create(e,t,n){return this._client.post(Z`/threads/${e}/messages`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(Z`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(Z`/threads/${r}/messages/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/threads/${e}/messages`,fS,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{thread_id:r}=t;return this._client.delete(Z`/threads/${r}/messages/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),NE,PE=t((()=>{X(),q(),SS(),Q(),NE=class extends Y{retrieve(e,t,n){let{thread_id:r,run_id:i,...a}=t;return this._client.get(Z`/threads/${r}/runs/${i}/steps/${e}`,{query:a,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t,n){let{thread_id:r,...i}=t;return this._client.getAPIList(Z`/threads/${r}/runs/${e}/steps`,fS,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),FE,IE=t((()=>{FE=e=>{if(typeof Buffer<`u`){let t=Buffer.from(e,`base64`);return Array.from(new Float32Array(t.buffer,t.byteOffset,t.length/Float32Array.BYTES_PER_ELEMENT))}{let t=atob(e),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.charCodeAt(e);return Array.from(new Float32Array(r.buffer))}}})),LE,RE=t((()=>{LE=e=>{if(globalThis.process!==void 0)return globalThis.process.env?.[e]?.trim()||void 0;if(globalThis.Deno!==void 0)return globalThis.Deno.env?.get?.(e)?.trim()||void 0}})),zE=t((()=>{Lb(),IE(),RE(),Jx(),ab(),zb(),Dx()})),BE,VE,HE,UE,WE,GE,KE,qE,JE,YE,XE,ZE,QE,$E,eD,tD,nD,rD,iD,aD,oD,sD,cD,lD,uD=t((()=>{rb(),pw(),uC(),HC(),zE(),lD=class extends VC{constructor(){super(...arguments),BE.add(this),HE.set(this,[]),UE.set(this,{}),WE.set(this,{}),GE.set(this,void 0),KE.set(this,void 0),qE.set(this,void 0),JE.set(this,void 0),YE.set(this,void 0),XE.set(this,void 0),ZE.set(this,void 0),QE.set(this,void 0),$E.set(this,void 0)}[(HE=new WeakMap,UE=new WeakMap,WE=new WeakMap,GE=new WeakMap,KE=new WeakMap,qE=new WeakMap,JE=new WeakMap,YE=new WeakMap,XE=new WeakMap,ZE=new WeakMap,QE=new WeakMap,$E=new WeakMap,BE=new WeakSet,Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=structuredClone(n),i=t.shift();i?i.resolve(r):e.push(r)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let t=new VE;return t._run(()=>t._fromReadableStream(e)),t}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),this._connected();let n=$x.fromReadableStream(e,this.controller);for await(let e of n)G(this,BE,`m`,eD).call(this,e);if(n.controller.signal?.aborted)throw new ub;return this._addRun(G(this,BE,`m`,tD).call(this))}toReadableStream(){return new $x(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,t,n,r){let i=new VE;return i._run(()=>i._runToolAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}async _createToolAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.submitToolOutputs(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)G(this,BE,`m`,eD).call(this,e);if(a.controller.signal?.aborted)throw new ub;return this._addRun(G(this,BE,`m`,tD).call(this))}static createThreadAssistantStream(e,t,n){let r=new VE;return r._run(()=>r._threadAssistantStream(e,t,{...n,headers:{...n?.headers,"X-Stainless-Helper-Method":`stream`}})),r}static createAssistantStream(e,t,n,r){let i=new VE;return i._run(()=>i._runAssistantStream(e,t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}currentEvent(){return G(this,ZE,`f`)}currentRun(){return G(this,QE,`f`)}currentMessageSnapshot(){return G(this,GE,`f`)}currentRunStepSnapshot(){return G(this,$E,`f`)}async finalRunSteps(){return await this.done(),Object.values(G(this,UE,`f`))}async finalMessages(){return await this.done(),Object.values(G(this,WE,`f`))}async finalRun(){if(await this.done(),!G(this,KE,`f`))throw Error(`Final run was not received.`);return G(this,KE,`f`)}async _createThreadAssistantStream(e,t,n){this._listenForAbort(n?.signal);let r={...t,stream:!0},i=await e.createAndRun(r,{...n,signal:this.controller.signal});this._connected();for await(let e of i)G(this,BE,`m`,eD).call(this,e);if(i.controller.signal?.aborted)throw new ub;return this._addRun(G(this,BE,`m`,tD).call(this))}async _createAssistantStream(e,t,n,r){this._listenForAbort(r?.signal);let i={...n,stream:!0},a=await e.create(t,i,{...r,signal:this.controller.signal});this._connected();for await(let e of a)G(this,BE,`m`,eD).call(this,e);if(a.controller.signal?.aborted)throw new ub;return this._addRun(G(this,BE,`m`,tD).call(this))}static accumulateDelta(e,t){for(let[n,r]of Object.entries(t)){if(!e.hasOwnProperty(n)){e[n]=r;continue}let t=e[n];if(t==null){e[n]=r;continue}if(n===`index`||n===`type`){e[n]=r;continue}if(typeof t==`string`&&typeof r==`string`)t+=r;else if(typeof t==`number`&&typeof r==`number`)t+=r;else if(Ab(t)&&Ab(r))t=this.accumulateDelta(t,r);else if(Array.isArray(t)&&Array.isArray(r)){if(t.every(e=>typeof e==`string`||typeof e==`number`)){t.push(...r);continue}for(let e of r){if(!Ab(e))throw Error(`Expected array delta entry to be an object but got: ${e}`);let n=e.index;if(n==null)throw Error("Expected array delta entry to have an `index` property");if(typeof n!=`number`)throw Error(`Expected array delta entry \`index\` property to be a number but got ${n}`);let r=t[n];r==null?t[n]=e:t[n]=this.accumulateDelta(r,e)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${r}, accValue: ${t}`);e[n]=t}return e}_addRun(e){return e}async _threadAssistantStream(e,t,n){return await this._createThreadAssistantStream(t,e,n)}async _runAssistantStream(e,t,n,r){return await this._createAssistantStream(t,e,n,r)}async _runToolAssistantStream(e,t,n,r){return await this._createToolAssistantStream(t,e,n,r)}},VE=lD,eD=function(e){if(!this.ended)switch(W(this,ZE,e,`f`),G(this,BE,`m`,iD).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`:G(this,BE,`m`,cD).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`:G(this,BE,`m`,rD).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`:G(this,BE,`m`,nD).call(this,e);break;case`error`:throw Error(`Encountered an error event in event processing - errors should be processed earlier`)}},tD=function(){if(this.ended)throw new K(`stream has ended, this shouldn't happen`);if(!G(this,KE,`f`))throw Error(`Final run has not been received`);return G(this,KE,`f`)},nD=function(e){let[t,n]=G(this,BE,`m`,oD).call(this,e,G(this,GE,`f`));W(this,GE,t,`f`),G(this,WE,`f`)[t.id]=t;for(let e of n){let n=t.content[e.index];n?.type==`text`&&this._emit(`textCreated`,n.text)}switch(e.event){case`thread.message.created`:this._emit(`messageCreated`,e.data);break;case`thread.message.in_progress`:break;case`thread.message.delta`:if(this._emit(`messageDelta`,e.data.delta,t),e.data.delta.content)for(let n of e.data.delta.content){if(n.type==`text`&&n.text){let e=n.text,r=t.content[n.index];if(r&&r.type==`text`)this._emit(`textDelta`,e,r.text);else throw Error(`The snapshot associated with this text delta is not text or missing`)}if(n.index!=G(this,qE,`f`)){if(G(this,JE,`f`))switch(G(this,JE,`f`).type){case`text`:this._emit(`textDone`,G(this,JE,`f`).text,G(this,GE,`f`));break;case`image_file`:this._emit(`imageFileDone`,G(this,JE,`f`).image_file,G(this,GE,`f`))}W(this,qE,n.index,`f`)}W(this,JE,t.content[n.index],`f`)}break;case`thread.message.completed`:case`thread.message.incomplete`:if(G(this,qE,`f`)!==void 0){let t=e.data.content[G(this,qE,`f`)];if(t)switch(t.type){case`image_file`:this._emit(`imageFileDone`,t.image_file,G(this,GE,`f`));break;case`text`:this._emit(`textDone`,t.text,G(this,GE,`f`))}}G(this,GE,`f`)&&this._emit(`messageDone`,e.data),W(this,GE,void 0,`f`)}},rD=function(e){let t=G(this,BE,`m`,aD).call(this,e);switch(W(this,$E,t,`f`),e.event){case`thread.run.step.created`:this._emit(`runStepCreated`,e.data);break;case`thread.run.step.delta`:let n=e.data.delta;if(n.step_details&&n.step_details.type==`tool_calls`&&n.step_details.tool_calls&&t.step_details.type==`tool_calls`)for(let e of n.step_details.tool_calls)e.index==G(this,YE,`f`)?this._emit(`toolCallDelta`,e,t.step_details.tool_calls[e.index]):(G(this,XE,`f`)&&this._emit(`toolCallDone`,G(this,XE,`f`)),W(this,YE,e.index,`f`),W(this,XE,t.step_details.tool_calls[e.index],`f`),G(this,XE,`f`)&&this._emit(`toolCallCreated`,G(this,XE,`f`)));this._emit(`runStepDelta`,e.data.delta,t);break;case`thread.run.step.completed`:case`thread.run.step.failed`:case`thread.run.step.cancelled`:case`thread.run.step.expired`:W(this,$E,void 0,`f`),e.data.step_details.type==`tool_calls`&&G(this,XE,`f`)&&(this._emit(`toolCallDone`,G(this,XE,`f`)),W(this,XE,void 0,`f`)),this._emit(`runStepDone`,e.data,t)}},iD=function(e){G(this,HE,`f`).push(e),this._emit(`event`,e)},aD=function(e){switch(e.event){case`thread.run.step.created`:return G(this,UE,`f`)[e.data.id]=e.data,e.data;case`thread.run.step.delta`:let t=G(this,UE,`f`)[e.data.id];if(!t)throw Error(`Received a RunStepDelta before creation of a snapshot`);let n=e.data;if(n.delta){let r=VE.accumulateDelta(t,n.delta);G(this,UE,`f`)[e.data.id]=r}return G(this,UE,`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`:G(this,UE,`f`)[e.data.id]=e.data}if(G(this,UE,`f`)[e.data.id])return G(this,UE,`f`)[e.data.id];throw Error(`No snapshot available`)},oD=function(e,t){let n=[];switch(e.event){case`thread.message.created`:return[e.data,n];case`thread.message.delta`:if(!t)throw Error(`Received a delta with no existing snapshot (there should be one from message creation)`);let r=e.data;if(r.delta.content)for(let e of r.delta.content)if(e.index in t.content){let n=t.content[e.index];t.content[e.index]=G(this,BE,`m`,sD).call(this,e,n)}else t.content[e.index]=e,n.push(e);return[t,n];case`thread.message.in_progress`:case`thread.message.completed`:case`thread.message.incomplete`:if(t)return[t,n];throw Error(`Received thread message event with no existing snapshot`)}throw Error(`Tried to accumulate a non-message event`)},sD=function(e,t){return VE.accumulateDelta(t,e)},cD=function(e){switch(W(this,QE,e.data,`f`),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`:W(this,KE,e.data,`f`),G(this,XE,`f`)&&(this._emit(`toolCallDone`,G(this,XE,`f`)),W(this,XE,void 0,`f`))}}})),dD,fD=t((()=>{X(),PE(),q(),SS(),uD(),zb(),Q(),dD=class extends Y{constructor(){super(...arguments),this.steps=new NE(this._client)}create(e,t,n){let{include:r,...i}=t;return this._client.post(Z`/threads/${e}/runs`,{query:{include:r},body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{thread_id:r}=t;return this._client.get(Z`/threads/${r}/runs/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{thread_id:r,...i}=t;return this._client.post(Z`/threads/${r}/runs/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/threads/${e}/runs`,fS,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{thread_id:r}=t;return this._client.post(Z`/threads/${r}/runs/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(r.id,{thread_id:e},n)}createAndStream(e,t,n){return lD.createAssistantStream(e,this._client.beta.threads.runs,t,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(e,t,{...n,headers:{...n?.headers,...r}}).withResponse();switch(i.status){case`queued`:case`in_progress`:case`cancelling`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Rb(e);break;case`requires_action`:case`incomplete`:case`cancelled`:case`completed`:case`failed`:case`expired`:return i}}}stream(e,t,n){return lD.createAssistantStream(e,this._client.beta.threads.runs,t,n)}submitToolOutputs(e,t,n){let{thread_id:r,...i}=t;return this._client.post(Z`/threads/${r}/runs/${e}/submit_tool_outputs`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),stream:t.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async submitToolOutputsAndPoll(e,t,n){let r=await this.submitToolOutputs(e,t,n);return await this.poll(r.id,t,n)}submitToolOutputsStream(e,t,n){return lD.createToolAssistantStream(e,this._client.beta.threads.runs,t,n)}},dD.Steps=NE})),pD,mD=t((()=>{X(),ME(),fD(),SS(),uD(),Q(),pD=class extends Y{constructor(){super(...arguments),this.runs=new dD(this._client),this.messages=new jE(this._client)}create(e={},t){return this._client.post(`/threads`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(Z`/threads/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/threads/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}createAndRun(e,t){return this._client.post(`/threads/runs`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),stream:e.stream??!1,__synthesizeEventData:!0,__security:{bearerAuth:!0}})}async createAndRunPoll(e,t){let n=await this.createAndRun(e,t);return await this.runs.poll(n.id,{thread_id:n.thread_id},t)}createAndRunStream(e,t){return lD.createThreadAssistantStream(e,this._client.beta.threads,t)}},pD.Runs=dD,pD.Messages=jE})),hD,gD=t((()=>{X(),fE(),vE(),wE(),AE(),mD(),hD=class extends Y{constructor(){super(...arguments),this.realtime=new _E(this._client),this.responses=new kE(this._client),this.chatkit=new CE(this._client),this.assistants=new dE(this._client),this.threads=new pD(this._client)}},hD.Realtime=_E,hD.Responses=kE,hD.ChatKit=CE,hD.Assistants=dE,hD.Threads=pD})),_D,vD=t((()=>{X(),_D=class extends Y{create(e,t){return this._client.post(`/completions`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}})),yD,bD=t((()=>{X(),SS(),Q(),yD=class extends Y{retrieve(e,t,n){let{container_id:r}=t;return this._client.get(Z`/containers/${r}/files/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),xD,SD=t((()=>{X(),bD(),q(),SS(),XS(),Q(),xD=class extends Y{constructor(){super(...arguments),this.content=new yD(this._client)}create(e,t,n){return this._client.post(Z`/containers/${e}/files`,RS({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{container_id:r}=t;return this._client.get(Z`/containers/${r}/files/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/containers/${e}/files`,fS,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{container_id:r}=t;return this._client.delete(Z`/containers/${r}/files/${e}`,{...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}},xD.Content=yD})),CD,wD=t((()=>{X(),SD(),q(),SS(),Q(),CD=class extends Y{constructor(){super(...arguments),this.files=new xD(this._client)}create(e,t){return this._client.post(`/containers`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/containers/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/containers`,fS,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/containers/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}},CD.Files=xD})),TD,ED=t((()=>{X(),XS(),TD=class extends Y{create(e,t){return this._client.post(`/content_provenance_checks`,zS({body:e,...t,__security:{bearerAuth:!0}},this._client))}}})),DD,OD=t((()=>{X(),q(),Q(),DD=class extends Y{create(e,t,n){let{include:r,...i}=t;return this._client.post(Z`/conversations/${e}/items`,{query:{include:r},body:i,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{conversation_id:r,...i}=t;return this._client.get(Z`/conversations/${r}/items/${e}`,{query:i,...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/conversations/${e}/items`,pS,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{conversation_id:r}=t;return this._client.delete(Z`/conversations/${r}/items/${e}`,{...n,__security:{bearerAuth:!0}})}}})),kD,AD=t((()=>{X(),OD(),Q(),kD=class extends Y{constructor(){super(...arguments),this.items=new DD(this._client)}create(e={},t){return this._client.post(`/conversations`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(Z`/conversations/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/conversations/${e}`,{...t,__security:{bearerAuth:!0}})}},kD.Items=DD})),jD,MD=t((()=>{X(),zE(),jD=class extends Y{create(e,t){let n=!!e.encoding_format,r=n?e.encoding_format:`base64`;n&&Hx(this._client).debug(`embeddings/user defined encoding_format:`,e.encoding_format);let i=this._client.post(`/embeddings`,{body:{...e,encoding_format:r},...t,__security:{bearerAuth:!0}});return n?i:(Hx(this._client).debug(`embeddings/decoding base64 embeddings from base64`),i._thenUnwrap(e=>(e&&e.data&&e.data.forEach(e=>{let t=e.embedding;e.embedding=FE(t)}),e)))}}})),ND,PD=t((()=>{X(),q(),Q(),ND=class extends Y{retrieve(e,t,n){let{eval_id:r,run_id:i}=t;return this._client.get(Z`/evals/${r}/runs/${i}/output_items/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t,n){let{eval_id:r,...i}=t;return this._client.getAPIList(Z`/evals/${r}/runs/${e}/output_items`,fS,{query:i,...n,__security:{bearerAuth:!0}})}}})),FD,ID=t((()=>{X(),PD(),q(),Q(),FD=class extends Y{constructor(){super(...arguments),this.outputItems=new ND(this._client)}create(e,t,n){return this._client.post(Z`/evals/${e}/runs`,{body:t,...n,__security:{bearerAuth:!0}})}retrieve(e,t,n){let{eval_id:r}=t;return this._client.get(Z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/evals/${e}/runs`,fS,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{eval_id:r}=t;return this._client.delete(Z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}cancel(e,t,n){let{eval_id:r}=t;return this._client.post(Z`/evals/${r}/runs/${e}`,{...n,__security:{bearerAuth:!0}})}},FD.OutputItems=ND})),LD,RD=t((()=>{X(),ID(),q(),Q(),LD=class extends Y{constructor(){super(...arguments),this.runs=new FD(this._client)}create(e,t){return this._client.post(`/evals`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(Z`/evals/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/evals`,fS,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/evals/${e}`,{...t,__security:{bearerAuth:!0}})}},LD.Runs=FD})),zD,BD=t((()=>{X(),q(),SS(),zb(),uC(),XS(),Q(),zD=class extends Y{create(e,t){return this._client.post(`/files`,zS({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(Z`/files/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/files`,fS,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/files/${e}`,{...t,__security:{bearerAuth:!0}})}content(e,t){return this._client.get(Z`/files/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:t=5e3,maxWait:n=18e5}={}){let r=new Set([`processed`,`error`,`deleted`]),i=Date.now(),a=await this.retrieve(e);for(;!a.status||!r.has(a.status);)if(await Rb(t),a=await this.retrieve(e),Date.now()-i>n)throw new fb({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return a}}})),VD,HD=t((()=>{X(),VD=class extends Y{}})),UD,WD=t((()=>{X(),UD=class extends Y{run(e,t){return this._client.post(`/fine_tuning/alpha/graders/run`,{body:e,...t,__security:{bearerAuth:!0}})}validate(e,t){return this._client.post(`/fine_tuning/alpha/graders/validate`,{body:e,...t,__security:{bearerAuth:!0}})}}})),GD,KD=t((()=>{X(),WD(),GD=class extends Y{constructor(){super(...arguments),this.graders=new UD(this._client)}},GD.Graders=UD})),qD,JD=t((()=>{X(),q(),Q(),qD=class extends Y{create(e,t,n){return this._client.getAPIList(Z`/fine_tuning/checkpoints/${e}/permissions`,dS,{body:t,method:`post`,...n,__security:{adminAPIKeyAuth:!0}})}retrieve(e,t={},n){return this._client.get(Z`/fine_tuning/checkpoints/${e}/permissions`,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/fine_tuning/checkpoints/${e}/permissions`,pS,{query:t,...n,__security:{adminAPIKeyAuth:!0}})}delete(e,t,n){let{fine_tuned_model_checkpoint:r}=t;return this._client.delete(Z`/fine_tuning/checkpoints/${r}/permissions/${e}`,{...n,__security:{adminAPIKeyAuth:!0}})}}})),YD,XD=t((()=>{X(),JD(),YD=class extends Y{constructor(){super(...arguments),this.permissions=new qD(this._client)}},YD.Permissions=qD})),ZD,QD=t((()=>{X(),q(),Q(),ZD=class extends Y{list(e,t={},n){return this._client.getAPIList(Z`/fine_tuning/jobs/${e}/checkpoints`,fS,{query:t,...n,__security:{bearerAuth:!0}})}}})),$D,eO=t((()=>{X(),QD(),q(),Q(),$D=class extends Y{constructor(){super(...arguments),this.checkpoints=new ZD(this._client)}create(e,t){return this._client.post(`/fine_tuning/jobs`,{body:e,...t,__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/fine_tuning/jobs/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/fine_tuning/jobs`,fS,{query:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Z`/fine_tuning/jobs/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}listEvents(e,t={},n){return this._client.getAPIList(Z`/fine_tuning/jobs/${e}/events`,fS,{query:t,...n,__security:{bearerAuth:!0}})}pause(e,t){return this._client.post(Z`/fine_tuning/jobs/${e}/pause`,{...t,__security:{bearerAuth:!0}})}resume(e,t){return this._client.post(Z`/fine_tuning/jobs/${e}/resume`,{...t,__security:{bearerAuth:!0}})}},$D.Checkpoints=ZD})),tO,nO=t((()=>{X(),HD(),KD(),XD(),eO(),tO=class extends Y{constructor(){super(...arguments),this.methods=new VD(this._client),this.jobs=new $D(this._client),this.checkpoints=new YD(this._client),this.alpha=new GD(this._client)}},tO.Methods=VD,tO.Jobs=$D,tO.Checkpoints=YD,tO.Alpha=GD})),rO,iO=t((()=>{X(),rO=class extends Y{}})),aO,oO=t((()=>{X(),iO(),aO=class extends Y{constructor(){super(...arguments),this.graderModels=new rO(this._client)}},aO.GraderModels=rO})),sO,cO=t((()=>{X(),XS(),sO=class extends Y{createVariation(e,t){return this._client.post(`/images/variations`,zS({body:e,...t,__security:{bearerAuth:!0}},this._client))}edit(e,t){return this._client.post(`/images/edits`,zS({body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}},this._client))}generate(e,t){return this._client.post(`/images/generations`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})}}})),lO,uO=t((()=>{X(),q(),Q(),lO=class extends Y{retrieve(e,t){return this._client.get(Z`/models/${e}`,{...t,__security:{bearerAuth:!0}})}list(e){return this._client.getAPIList(`/models`,dS,{...e,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/models/${e}`,{...t,__security:{bearerAuth:!0}})}}})),dO,fO=t((()=>{X(),dO=class extends Y{create(e,t){return this._client.post(`/moderations`,{body:e,...t,__security:{bearerAuth:!0}})}}})),pO,mO=t((()=>{X(),SS(),Q(),pO=class extends Y{accept(e,t,n){return this._client.post(Z`/realtime/calls/${e}/accept`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}hangup(e,t){return this._client.post(Z`/realtime/calls/${e}/hangup`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}refer(e,t,n){return this._client.post(Z`/realtime/calls/${e}/refer`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}reject(e,t={},n){return this._client.post(Z`/realtime/calls/${e}/reject`,{body:t,...n,headers:J([{Accept:`*/*`},n?.headers]),__security:{bearerAuth:!0}})}}})),hO,gO=t((()=>{X(),hO=class extends Y{create(e,t){return this._client.post(`/realtime/client_secrets`,{body:e,...t,__security:{bearerAuth:!0}})}}})),_O,vO=t((()=>{X(),mO(),gO(),_O=class extends Y{constructor(){super(...arguments),this.clientSecrets=new hO(this._client),this.calls=new pO(this._client)}},_O.ClientSecrets=hO,_O.Calls=pO}));function yO(e,t){if(!t||!SO(t)){let t={...e,output_parsed:null,output:e.output.map(e=>e.type===`function_call`?{...e,parsed_arguments:null}:e.type===`message`?{...e,content:e.content.map(e=>({...e,parsed:null}))}:e)};return EO(e,t)&&DO(t),t}return bO(e,t)}function bO(e,t){let n=!e.status||e.status===`completed`,r=e.output.map(e=>{if(e.type===`function_call`)return n?TO(t,e):{...e,parsed_arguments:null};if(e.type===`message`){let r=e.content.map(e=>e.type===`output_text`?{...e,parsed:n?xO(t,e.text):null}:e);return{...e,content:r}}return e}),i=Object.assign({},e,{output:r});return EO(e,i)&&DO(i),Object.defineProperty(i,"output_parsed",{enumerable:!0,get(){for(let e of i.output)if(e.type===`message`){for(let t of e.content)if(t.type===`output_text`&&t.parsed!==null)return t.parsed}return null}}),i}function xO(e,t){return e.text?.format?.type===`json_schema`?`$parseRaw`in e.text?.format?(e.text?.format).$parseRaw(t):JSON.parse(t):null}function SO(e){return fC(e.text?.format)?!0:Array.isArray(e.tools)&&e.tools.some(e=>CO(e)||e.type===`function`&&e.strict===!0)}function CO(e){return e?.$brand===`auto-parseable-tool`}function wO(e,t){return e.find(e=>e.type===`function`&&e.name===t)}function TO(e,t){let n=wO(e.tools??[],t.name);return{...t,...t,parsed_arguments:CO(n)?n.$parseRaw(t.arguments):n?.strict?JSON.parse(t.arguments):null}}function EO(e,t){return!Object.getOwnPropertyDescriptor(e,`output_text`)||t.output_text==null}function DO(e){let t=[];for(let n of e.output)if(n.type===`message`)for(let e of n.content)e.type===`output_text`&&t.push(e.text);e.output_text=t.join(``)}var OO=t((()=>{uC(),SC()}));function kO(e,t){if(!t){if(e.type!==`response.created`)throw new K(`When snapshot hasn't been set yet, expected 'response.created' event, got ${e.type}`);return AO(e.response)}switch(e.type){case`response.output_item.added`:t.output.push(structuredClone(e.item)),e.item.type===`message`&&DO(t);break;case`response.output_item.done`:jO(t,e.output_index),t.output[e.output_index]=structuredClone(e.item),e.item.type===`message`&&DO(t);break;case`response.content_part.added`:{let n=jO(t,e.output_index),r=n.type,i=e.part;r===`message`&&i.type!==`reasoning_text`?(n.content.push(structuredClone(i)),i.type===`output_text`&&DO(t)):r===`reasoning`&&i.type===`reasoning_text`&&(n.content||(n.content=[]),n.content.push(structuredClone(i)));break}case`response.content_part.done`:{let n=jO(t,e.output_index),r=e.part;if(n.type===`message`&&r.type!==`reasoning_text`)MO(n.content,e.content_index),n.content[e.content_index]=structuredClone(r),r.type===`output_text`&&DO(t);else if(n.type===`reasoning`&&r.type===`reasoning_text`){let t=n.content;if(!t)throw new K(`missing content at index ${e.content_index}`);MO(t,e.content_index),t[e.content_index]=structuredClone(r)}break}case`response.output_text.delta`:{let n=jO(t,e.output_index);if(n.type===`message`){let r=MO(n.content,e.content_index);if(r.type!==`output_text`)throw new K(`expected content to be 'output_text', got ${r.type}`);r.text+=e.delta,t.output_text+=e.delta}break}case`response.output_text.done`:{let n=jO(t,e.output_index);if(n.type===`message`){let r=MO(n.content,e.content_index);if(r.type!==`output_text`)throw new K(`expected content to be 'output_text', got ${r.type}`);r.text=e.text,DO(t)}break}case`response.output_text.annotation.added`:{let n=jO(t,e.output_index);if(n.type===`message`){let t=MO(n.content,e.content_index);if(t.type!==`output_text`)throw new K(`expected content to be 'output_text', got ${t.type}`);t.annotations[e.annotation_index]=structuredClone(e.annotation)}break}case`response.refusal.delta`:{let n=jO(t,e.output_index);if(n.type===`message`){let t=MO(n.content,e.content_index);if(t.type!==`refusal`)throw new K(`expected content to be 'refusal', got ${t.type}`);t.refusal+=e.delta}break}case`response.refusal.done`:{let n=jO(t,e.output_index);if(n.type===`message`){let t=MO(n.content,e.content_index);if(t.type!==`refusal`)throw new K(`expected content to be 'refusal', got ${t.type}`);t.refusal=e.refusal}break}case`response.function_call_arguments.delta`:{let n=jO(t,e.output_index);n.type===`function_call`&&(n.arguments+=e.delta);break}case`response.function_call_arguments.done`:{let n=jO(t,e.output_index);n.type===`function_call`&&(n.arguments=e.arguments);break}case`response.reasoning_text.delta`:{let n=jO(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new K(`missing content at index ${e.content_index}`);let t=MO(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new K(`expected content to be 'reasoning_text', got ${t.type}`);t.text+=e.delta}break}case`response.reasoning_text.done`:{let n=jO(t,e.output_index);if(n.type===`reasoning`){if(!n.content)throw new K(`missing content at index ${e.content_index}`);let t=MO(n.content,e.content_index);if(t.type!==`reasoning_text`)throw new K(`expected content to be 'reasoning_text', got ${t.type}`);t.text=e.text}break}case`response.reasoning_summary_part.added`:{let n=jO(t,e.output_index);n.type===`reasoning`&&n.summary.push(structuredClone(e.part));break}case`response.reasoning_summary_part.done`:{let n=jO(t,e.output_index);n.type===`reasoning`&&(MO(n.summary,e.summary_index),n.summary[e.summary_index]=structuredClone(e.part));break}case`response.reasoning_summary_text.delta`:{let n=jO(t,e.output_index);if(n.type===`reasoning`){let t=MO(n.summary,e.summary_index);t.text+=e.delta}break}case`response.reasoning_summary_text.done`:{let n=jO(t,e.output_index);if(n.type===`reasoning`){let t=MO(n.summary,e.summary_index);t.text=e.text}break}case`response.custom_tool_call_input.delta`:{let n=jO(t,e.output_index);n.type===`custom_tool_call`&&(n.input+=e.delta);break}case`response.custom_tool_call_input.done`:{let n=jO(t,e.output_index);n.type===`custom_tool_call`&&(n.input=e.input);break}case`response.mcp_call_arguments.delta`:{let n=jO(t,e.output_index);n.type===`mcp_call`&&(n.arguments+=e.delta);break}case`response.mcp_call_arguments.done`:{let n=jO(t,e.output_index);n.type===`mcp_call`&&(n.arguments=e.arguments);break}case`response.code_interpreter_call_code.delta`:{let n=jO(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=(n.code??``)+e.delta);break}case`response.code_interpreter_call_code.done`:{let n=jO(t,e.output_index);n.type===`code_interpreter_call`&&(n.code=e.code);break}case`response.code_interpreter_call.in_progress`:{let n=jO(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`in_progress`);break}case`response.code_interpreter_call.interpreting`:{let n=jO(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`interpreting`);break}case`response.code_interpreter_call.completed`:{let n=jO(t,e.output_index);n.type===`code_interpreter_call`&&(n.status=`completed`);break}case`response.file_search_call.in_progress`:{let n=jO(t,e.output_index);n.type===`file_search_call`&&(n.status=`in_progress`);break}case`response.file_search_call.searching`:{let n=jO(t,e.output_index);n.type===`file_search_call`&&(n.status=`searching`);break}case`response.file_search_call.completed`:{let n=jO(t,e.output_index);n.type===`file_search_call`&&(n.status=`completed`);break}case`response.web_search_call.in_progress`:{let n=jO(t,e.output_index);n.type===`web_search_call`&&(n.status=`in_progress`);break}case`response.web_search_call.searching`:{let n=jO(t,e.output_index);n.type===`web_search_call`&&(n.status=`searching`);break}case`response.web_search_call.completed`:{let n=jO(t,e.output_index);n.type===`web_search_call`&&(n.status=`completed`);break}case`response.image_generation_call.in_progress`:{let n=jO(t,e.output_index);n.type===`image_generation_call`&&(n.status=`in_progress`);break}case`response.image_generation_call.generating`:{let n=jO(t,e.output_index);n.type===`image_generation_call`&&(n.status=`generating`);break}case`response.image_generation_call.completed`:{let n=jO(t,e.output_index);n.type===`image_generation_call`&&(n.status=`completed`);break}case`response.mcp_call.in_progress`:{let n=jO(t,e.output_index);n.type===`mcp_call`&&(n.status=`in_progress`);break}case`response.mcp_call.completed`:{let n=jO(t,e.output_index);n.type===`mcp_call`&&(n.status=`completed`);break}case`response.mcp_call.failed`:{let n=jO(t,e.output_index);n.type===`mcp_call`&&(n.status=`failed`);break}case`response.created`:case`response.queued`:case`response.in_progress`:case`response.completed`:case`response.failed`:case`response.incomplete`:t=AO(e.response);break;case`response.audio.delta`:case`response.audio.done`:case`response.audio.transcript.delta`:case`response.audio.transcript.done`:case`response.image_generation_call.partial_image`:case`response.mcp_list_tools.in_progress`:case`response.mcp_list_tools.completed`:case`response.mcp_list_tools.failed`:case`keepalive`:case`error`:break;default:NO(e)}return t}function AO(e){let t=structuredClone(e);return(!Object.getOwnPropertyDescriptor(t,`output_text`)||t.output_text==null)&&DO(t),t}function jO(e,t){let n=e.output[t];if(!n)throw new K(`missing output at index ${t}`);return n}function MO(e,t){let n=e[t];if(!n)throw new K(`missing content at index ${t}`);return n}function NO(e){throw new K(`Unhandled response stream event: ${JSON.stringify(e)}`)}var PO=t((()=>{uC(),OO()}));function FO(e,t){return yO(e,t)}var IO,LO,RO,zO,BO,VO,HO,UO,WO=t((()=>{rb(),uC(),HC(),PO(),OO(),pw(),UO=class e extends VC{constructor(e){super(),IO.add(this),LO.set(this,void 0),RO.set(this,void 0),zO.set(this,void 0),W(this,LO,e,`f`)}static createResponse(t,n,r){let i=new e(n);return i._run(()=>i._createOrRetrieveResponse(t,n,{...r,headers:{...r?.headers,"X-Stainless-Helper-Method":`stream`}})),i}static fromReadableStream(t){let n=new e(null);return n._run(()=>n._fromReadableStream(t)),n}async _createOrRetrieveResponse(e,t,n){this._listenForAbort(n?.signal),G(this,IO,`m`,BO).call(this);let r,i=null;`response_id`in t?(r=await e.responses.retrieve(t.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=t.starting_after??null):r=await e.responses.create({...t,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let e of r)G(this,IO,`m`,VO).call(this,e,i);if(r.controller.signal?.aborted)throw new ub;return G(this,IO,`m`,HO).call(this)}async _fromReadableStream(e,t){this._listenForAbort(t?.signal),G(this,IO,`m`,BO).call(this),this._connected();let n=$x.fromReadableStream(e,this.controller);for await(let e of n)G(this,IO,`m`,VO).call(this,e,null);if(n.controller.signal?.aborted)throw new ub;return G(this,IO,`m`,HO).call(this)}[(LO=new WeakMap,RO=new WeakMap,zO=new WeakMap,IO=new WeakSet,BO=function(){this.ended||W(this,RO,void 0,`f`)},VO=function(e,t){if(this.ended)return;let n=(e,n)=>{(t==null||n.sequence_number>t)&&this._emit(e,n)},r=kO(e,G(this,RO,`f`));switch(W(this,RO,r,`f`),n(`event`,e),e.type){case`response.output_text.delta`:{let t=r.output[e.output_index];if(!t)throw new K(`missing output at index ${e.output_index}`);if(t.type===`message`){let r=t.content[e.content_index];if(!r)throw new K(`missing content at index ${e.content_index}`);if(r.type!==`output_text`)throw new K(`expected content to be 'output_text', got ${r.type}`);n(`response.output_text.delta`,{...e,snapshot:r.text})}break}case`response.function_call_arguments.delta`:{let t=r.output[e.output_index];if(!t)throw new K(`missing output at index ${e.output_index}`);t.type===`function_call`&&n(`response.function_call_arguments.delta`,{...e,snapshot:t.arguments});break}default:n(e.type,e)}},HO=function(){if(this.ended)throw new K(`stream has ended, this shouldn't happen`);let e=G(this,RO,`f`);if(!e)throw new K(`request ended without sending any events`);W(this,RO,void 0,`f`);let t=FO(e,G(this,LO,`f`));return W(this,zO,t,`f`),t},Symbol.asyncIterator)](){let e=[],t=[],n=!1;return this.on(`event`,n=>{let r=t.shift();r?r.resolve(n):e.push(n)}),this.on(`end`,()=>{n=!0;for(let e of t)e.resolve(void 0);t.length=0}),this.on(`abort`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),this.on(`error`,e=>{n=!0;for(let n of t)n.reject(e);t.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((e,n)=>t.push({resolve:e,reject:n})).then(e=>e?{value:e,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=G(this,zO,`f`);if(!e)throw new K(`stream ended without producing a ChatCompletion`);return e}}})),GO,KO=t((()=>{X(),q(),Q(),GO=class extends Y{list(e,t={},n){return this._client.getAPIList(Z`/responses/${e}/input_items`,fS,{query:t,...n,__security:{bearerAuth:!0}})}}})),qO,JO=t((()=>{X(),qO=class extends Y{count(e={},t){return this._client.post(`/responses/input_tokens`,{body:e,...t,__security:{bearerAuth:!0}})}}})),YO,XO=t((()=>{OO(),WO(),X(),KO(),JO(),SS(),Q(),YO=class extends Y{constructor(){super(...arguments),this.inputItems=new GO(this._client),this.inputTokens=new qO(this._client)}create(e,t){return this._client.post(`/responses`,{body:e,...t,stream:e.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&DO(e),e))}retrieve(e,t={},n){return this._client.get(Z`/responses/${e}`,{query:t,...n,stream:t?.stream??!1,__security:{bearerAuth:!0}})._thenUnwrap(e=>(`object`in e&&e.object===`response`&&DO(e),e))}delete(e,t){return this._client.delete(Z`/responses/${e}`,{...t,headers:J([{Accept:`*/*`},t?.headers]),__security:{bearerAuth:!0}})}parse(e,t){return this._client.responses.create(e,t)._thenUnwrap(t=>bO(t,e))}stream(e,t){return UO.createResponse(this._client,e,t)}cancel(e,t){return this._client.post(Z`/responses/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}compact(e,t){return this._client.post(`/responses/compact`,{body:e,...t,__security:{bearerAuth:!0}})}},YO.InputItems=GO,YO.InputTokens=qO})),ZO,QO=t((()=>{X(),SS(),Q(),ZO=class extends Y{retrieve(e,t){return this._client.get(Z`/skills/${e}/content`,{...t,headers:J([{Accept:`application/binary`},t?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),$O,ek=t((()=>{X(),SS(),Q(),$O=class extends Y{retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(Z`/skills/${r}/versions/${e}/content`,{...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}}})),tk,nk=t((()=>{X(),ek(),q(),XS(),Q(),tk=class extends Y{constructor(){super(...arguments),this.content=new $O(this._client)}create(e,t={},n){return this._client.post(Z`/skills/${e}/versions`,RS({body:t,...n,__security:{bearerAuth:!0}},this._client))}retrieve(e,t,n){let{skill_id:r}=t;return this._client.get(Z`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/skills/${e}/versions`,fS,{query:t,...n,__security:{bearerAuth:!0}})}delete(e,t,n){let{skill_id:r}=t;return this._client.delete(Z`/skills/${r}/versions/${e}`,{...n,__security:{bearerAuth:!0}})}},tk.Content=$O})),rk,ik=t((()=>{X(),QO(),nk(),q(),XS(),Q(),rk=class extends Y{constructor(){super(...arguments),this.content=new ZO(this._client),this.versions=new tk(this._client)}create(e={},t){return this._client.post(`/skills`,RS({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(Z`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(Z`/skills/${e}`,{body:t,...n,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/skills`,fS,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/skills/${e}`,{...t,__security:{bearerAuth:!0}})}},rk.Content=ZO,rk.Versions=tk})),ak,ok=t((()=>{X(),XS(),Q(),ak=class extends Y{create(e,t,n){return this._client.post(Z`/uploads/${e}/parts`,zS({body:t,...n,__security:{bearerAuth:!0}},this._client))}}})),sk,ck=t((()=>{X(),ok(),Q(),sk=class extends Y{constructor(){super(...arguments),this.parts=new ak(this._client)}create(e,t){return this._client.post(`/uploads`,{body:e,...t,__security:{bearerAuth:!0}})}cancel(e,t){return this._client.post(Z`/uploads/${e}/cancel`,{...t,__security:{bearerAuth:!0}})}complete(e,t,n){return this._client.post(Z`/uploads/${e}/complete`,{body:t,...n,__security:{bearerAuth:!0}})}},sk.Parts=ak})),lk,uk=t((()=>{lk=async e=>{let t=await Promise.allSettled(e),n=t.filter(e=>e.status===`rejected`);if(n.length){for(let e of n);throw Error(`${n.length} promise(s) failed - see the above errors`)}let r=[];for(let e of t)e.status===`fulfilled`&&r.push(e.value);return r}})),dk,fk=t((()=>{X(),q(),SS(),zb(),uk(),Q(),dk=class extends Y{create(e,t,n){return this._client.post(Z`/vector_stores/${e}/file_batches`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(Z`/vector_stores/${r}/file_batches/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}cancel(e,t,n){let{vector_store_id:r}=t;return this._client.post(Z`/vector_stores/${r}/file_batches/${e}/cancel`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t);return await this.poll(e,r.id,n)}listFiles(e,t,n){let{vector_store_id:r,...i}=t;return this._client.getAPIList(Z`/vector_stores/${r}/file_batches/${e}/files`,fS,{query:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let{data:i,response:a}=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse();switch(i.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=a.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Rb(e);break;case`failed`:case`cancelled`:case`completed`:return i}}}async uploadAndPoll(e,{files:t,fileIds:n=[]},r){if(t==null||t.length==0)throw Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let i=r?.maxConcurrency??5,a=Math.min(i,t.length),o=this._client,s=t.values(),c=[...n];async function l(e){for(let t of e){let e=await o.files.create({file:t,purpose:`assistants`},r);c.push(e.id)}}let u=Array(a).fill(s).map(l);return await lk(u),await this.createAndPoll(e,{file_ids:c})}}})),pk,mk=t((()=>{X(),q(),SS(),zE(),Q(),pk=class extends Y{create(e,t,n){return this._client.post(Z`/vector_stores/${e}/files`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t,n){let{vector_store_id:r}=t;return this._client.get(Z`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){let{vector_store_id:r,...i}=t;return this._client.post(Z`/vector_stores/${r}/files/${e}`,{body:i,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e,t={},n){return this._client.getAPIList(Z`/vector_stores/${e}/files`,fS,{query:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}delete(e,t,n){let{vector_store_id:r}=t;return this._client.delete(Z`/vector_stores/${r}/files/${e}`,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}async createAndPoll(e,t,n){let r=await this.create(e,t,n);return await this.poll(e,r.id,n)}async poll(e,t,n){let r=J([n?.headers,{"X-Stainless-Poll-Helper":`true`,"X-Stainless-Custom-Poll-Interval":n?.pollIntervalMs?.toString()??void 0}]);for(;;){let i=await this.retrieve(t,{vector_store_id:e},{...n,headers:r}).withResponse(),a=i.data;switch(a.status){case`in_progress`:let e=5e3;if(n?.pollIntervalMs)e=n.pollIntervalMs;else{let t=i.response.headers.get(`openai-poll-after-ms`);if(t){let n=parseInt(t);isNaN(n)||(e=n)}}await Rb(e);break;case`failed`:case`completed`:return a}}}async upload(e,t,n){let r=await this._client.files.create({file:t,purpose:`assistants`},n);return this.create(e,{file_id:r.id},n)}async uploadAndPoll(e,t,n){let r=await this.upload(e,t,n);return await this.poll(e,r.id,n)}content(e,t,n){let{vector_store_id:r}=t;return this._client.getAPIList(Z`/vector_stores/${r}/files/${e}/content`,dS,{...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}}})),hk,gk=t((()=>{X(),fk(),mk(),q(),SS(),Q(),hk=class extends Y{constructor(){super(...arguments),this.files=new pk(this._client),this.fileBatches=new dk(this._client)}create(e,t){return this._client.post(`/vector_stores`,{body:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}retrieve(e,t){return this._client.get(Z`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}update(e,t,n){return this._client.post(Z`/vector_stores/${e}`,{body:t,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/vector_stores`,fS,{query:e,...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/vector_stores/${e}`,{...t,headers:J([{"OpenAI-Beta":`assistants=v2`},t?.headers]),__security:{bearerAuth:!0}})}search(e,t,n){return this._client.getAPIList(Z`/vector_stores/${e}/search`,dS,{body:t,method:`post`,...n,headers:J([{"OpenAI-Beta":`assistants=v2`},n?.headers]),__security:{bearerAuth:!0}})}},hk.Files=pk,hk.FileBatches=dk})),_k,vk=t((()=>{X(),q(),SS(),XS(),Q(),_k=class extends Y{create(e,t){return this._client.post(`/videos`,zS({body:e,...t,__security:{bearerAuth:!0}},this._client))}retrieve(e,t){return this._client.get(Z`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}list(e={},t){return this._client.getAPIList(`/videos`,pS,{query:e,...t,__security:{bearerAuth:!0}})}delete(e,t){return this._client.delete(Z`/videos/${e}`,{...t,__security:{bearerAuth:!0}})}createCharacter(e,t){return this._client.post(`/videos/characters`,zS({body:e,...t,__security:{bearerAuth:!0}},this._client))}downloadContent(e,t={},n){return this._client.get(Z`/videos/${e}/content`,{query:t,...n,headers:J([{Accept:`application/binary`},n?.headers]),__security:{bearerAuth:!0},__binaryResponse:!0})}edit(e,t){return this._client.post(`/videos/edits`,zS({body:e,...t,__security:{bearerAuth:!0}},this._client))}extend(e,t){return this._client.post(`/videos/extensions`,zS({body:e,...t,__security:{bearerAuth:!0}},this._client))}getCharacter(e,t){return this._client.get(Z`/videos/characters/${e}`,{...t,__security:{bearerAuth:!0}})}remix(e,t,n){return this._client.post(Z`/videos/${e}/remix`,RS({body:t,...n,__security:{bearerAuth:!0}},this._client))}}})),yk,bk,xk,Sk,Ck=t((()=>{rb(),uC(),X(),SS(),Sk=class extends Y{constructor(){super(...arguments),yk.add(this)}async unwrap(e,t,n=this._client.webhookSecret,r=300){return await this.verifySignature(e,t,n,r),JSON.parse(e)}async verifySignature(e,t,n=this._client.webhookSecret,r=300){if(typeof crypto>`u`||typeof crypto.subtle.importKey!=`function`||typeof crypto.subtle.verify!=`function`)throw Error("Webhook signature verification is only supported when the `crypto` global is defined");G(this,yk,`m`,bk).call(this,n);let i=J([t]).values,a=G(this,yk,`m`,xk).call(this,i,`webhook-signature`),o=G(this,yk,`m`,xk).call(this,i,`webhook-timestamp`),s=G(this,yk,`m`,xk).call(this,i,`webhook-id`),c=parseInt(o,10);if(isNaN(c))throw new Cb(`Invalid webhook timestamp format`);let l=Math.floor(Date.now()/1e3);if(l-c>r)throw new Cb(`Webhook timestamp is too old`);if(c>l+r)throw new Cb(`Webhook timestamp is too new`);let u=a.split(` `).map(e=>e.startsWith(`v1,`)?e.substring(3):e),d=n.startsWith(`whsec_`)?Buffer.from(n.replace(`whsec_`,``),`base64`):Buffer.from(n,`utf-8`),f=s?`${s}.${o}.${e}`:`${o}.${e}`,p=await crypto.subtle.importKey(`raw`,d,{name:`HMAC`,hash:`SHA-256`},!1,[`verify`]);for(let e of u)try{let t=Buffer.from(e,`base64`);if(await crypto.subtle.verify(`HMAC`,p,t,new TextEncoder().encode(f)))return}catch{continue}throw new Cb(`The given webhook signature does not match the expected signature`)}},yk=new WeakSet,bk=function(e){if(typeof e!=`string`||e.length===0)throw 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`)},xk=function(e,t){if(!e)throw Error(`Headers are required`);let n=e.get(t);if(n==null)throw Error(`Missing required header: ${t}`);return n}})),wk=t((()=>{Ck()})),Tk=t((()=>{wk()})),Ek=t((()=>{Uw(),Ww(),eE(),cE(),uE(),gD(),vD(),wD(),ED(),AD(),MD(),RD(),BD(),nO(),oO(),cO(),uO(),fO(),vO(),XO(),ik(),ck(),gk(),vk(),Tk()}));function Dk(e){let t=jk.get(e);if(!t)throw Error(`Invalid provider. Providers must be created with createProvider().`);return t.configure()}var Ok,kk,Ak,jk,Mk=t((()=>{Ok=Symbol.for(`openai.node.providerDefinitions.v1`),kk=globalThis,Ak=kk[Ok],jk=Ak??new WeakMap,Ak||Object.defineProperty(kk,Ok,{value:jk})}));function Nk(e){if(Pk(e))return`Connection error. This may be caused by passing an undici dispatcher, such as ProxyAgent, that is incompatible with the fetch implementation. If you are using undici's ProxyAgent, pass the fetch implementation from the same undici package: import { fetch, ProxyAgent } from 'undici'; new OpenAI({ fetch, fetchOptions: { dispatcher: new ProxyAgent(...) } });`}function Pk(e){let t=e;for(let e=0;e<8&&t&&typeof t==`object`;e++){let e=t;if(e.code===`UND_ERR_INVALID_ARG`&&typeof e.message==`string`&&e.message.includes(`invalid onRequestStart method`))return!0;t=e.cause}return!1}var Fk,Ik,Lk,Rk,zk,$,Bk=t((()=>{rb(),ab(),Lb(),zb(),cb(),Xb(),nx(),ix(),Dx(),Vb(),Eb(),q(),vS(),iC(),Ek(),sS(),uE(),vD(),ED(),MD(),BD(),cO(),uO(),fO(),vk(),eE(),cE(),gD(),Vw(),wD(),AD(),RD(),nO(),oO(),vO(),XO(),ik(),ck(),gk(),Ck(),SS(),Mk(),RE(),Jx(),zk=`workload-identity-auth`,$=class{constructor(e={}){Fk.add(this),Lk.set(this,void 0),this.completions=new _D(this),this.chat=new Bw(this),this.embeddings=new jD(this),this.files=new zD(this),this.images=new sO(this),this.contentProvenanceChecks=new TD(this),this.audio=new sE(this),this.moderations=new dO(this),this.models=new lO(this),this.fineTuning=new tO(this),this.graders=new aO(this),this.vectorStores=new hk(this),this.webhooks=new Sk(this),this.beta=new hD(this),this.batches=new lE(this),this.uploads=new sk(this),this.admin=new $T(this),this.responses=new YO(this),this.realtime=new _O(this),this.conversations=new kD(this),this.evals=new LD(this),this.containers=new CD(this),this.skills=new rk(this),this.videos=new _k(this);let t=e.provider;if(t){let t=[`apiKey`,`adminAPIKey`,`workloadIdentity`,`baseURL`].filter(t=>e[t]!=null);if(t.length)throw new K(`The \`provider\` option cannot be used with ${t.map(e=>`\`${e}\``).join(`, `)}. Configure authentication and the base URL through the provider instead.`)}let{baseURL:n=t?null:LE(`OPENAI_BASE_URL`),apiKey:r=t?null:LE(`OPENAI_API_KEY`)??null,adminAPIKey:i=t?null:LE(`OPENAI_ADMIN_KEY`)??null,organization:a=t?null:LE(`OPENAI_ORG_ID`)??null,project:o=t?null:LE(`OPENAI_PROJECT_ID`)??null,webhookSecret:s=LE(`OPENAI_WEBHOOK_SECRET`)??null,workloadIdentity:c,...l}=e,u=t?Dk(t):void 0,d={apiKey:r,adminAPIKey:i,organization:a,project:o,webhookSecret:s,workloadIdentity:c,provider:t,...l,baseURL:u?.baseURL??(n||`https://api.openai.com/v1`)};if(r&&c)throw new K("The `apiKey` and `workloadIdentity` options are mutually exclusive");if(!u&&!r&&!i&&!c)throw new K("Missing credentials. Please pass an `apiKey`, `workloadIdentity`, `adminAPIKey`, or set the `OPENAI_API_KEY` or `OPENAI_ADMIN_KEY` environment variable.");if(!d.dangerouslyAllowBrowser&&Wb())throw new K(`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=d.baseURL,this.timeout=d.timeout??Ik.DEFAULT_TIMEOUT,this.logger=d.logger??console;let f=`warn`;this.logLevel=f,this.logLevel=Wx(d.logLevel,`ClientOptions.logLevel`,this)??Wx(LE(`OPENAI_LOG`),`process.env['OPENAI_LOG']`,this)??f,this.fetchOptions=d.fetchOptions,this.maxRetries=d.maxRetries??2,this.fetch=d.fetch??Zb(),W(this,Lk,rx,`f`);let p=t?void 0:LE(`OPENAI_CUSTOM_HEADERS`);if(p){let e={};for(let t of p.split(`
|
||
`)){let n=t.indexOf(`:`);n>=0&&(e[t.substring(0,n).trim()]=t.substring(n+1).trim())}d.defaultHeaders=J([e,d.defaultHeaders])}this._options=d,this._provider=u,c&&(this._workloadIdentityAuth=new _S(c,this.fetch)),this.apiKey=typeof r==`string`?r:null,this.adminAPIKey=i,this.organization=a,this.project=o,this.webhookSecret=s}withOptions(e){let t=this._options.provider,n=e.provider??t,r={...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._options.apiKey,adminAPIKey:this.adminAPIKey,workloadIdentity:this._options.workloadIdentity,organization:this.organization,project:this.project,webhookSecret:this.webhookSecret};return n&&(delete r.apiKey,delete r.adminAPIKey,delete r.workloadIdentity,delete r.baseURL,n!==t&&(delete r.organization,delete r.project,delete r.defaultHeaders)),new this.constructor({...r,...e,provider:n})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:t},n={bearerAuth:!0,adminAPIKeyAuth:!0}){if(!(e.get(`authorization`)||e.get(`api-key`))&&!(t.has(`authorization`)||t.has(`api-key`))&&!(this._workloadIdentityAuth&&n.bearerAuth))throw Error(`Could not resolve authentication method. Expected either apiKey or adminAPIKey to be set. Or for one of the "Authorization" or "api-key" headers to be explicitly omitted`)}async authHeaders(e,t={bearerAuth:!0,adminAPIKeyAuth:!0}){return J([t.bearerAuth?await this.bearerAuth(e):null,t.adminAPIKeyAuth?await this.adminAPIKeyAuth(e):null])}async bearerAuth(e){if(this._workloadIdentityAuth)return J([{Authorization:`Bearer ${await this._workloadIdentityAuth.getToken()}`}]);if(this.apiKey!=null)return J([{Authorization:`Bearer ${this.apiKey}`}])}async adminAPIKeyAuth(e){if(this.adminAPIKey!=null)return J([{Authorization:`Bearer ${this.adminAPIKey}`}])}stringifyQuery(e){return Ex(e)}getUserAgent(){return`${this.constructor.name}/JS ${Bb}`}defaultIdempotencyKey(){return`stainless-node-retry-${ib()}`}makeStatusError(e,t,n,r){return lb.generate(e,t,n,r)}async _callApiKey(){if(this._provider)return!1;let e=this._options.apiKey;if(typeof e!=`function`)return!1;let t;try{t=await e()}catch(e){throw e instanceof K?e:new K(`Failed to get token from 'apiKey' function: ${e.message}`,{cause:e})}if(typeof t!=`string`||!t)throw new K(`Expected 'apiKey' function argument to return a string but it returned ${t}`);return this.apiKey=t,!0}buildURL(e,t,n){let r=!G(this,Fk,`m`,Rk).call(this)&&n||this.baseURL,i=Mb(e)?new URL(e):new URL(r+(r.endsWith(`/`)&&e.startsWith(`/`)?e.slice(1):e)),a=this.defaultQuery(),o=Object.fromEntries(i.searchParams);return(!Ob(a)||!Ob(o))&&(t={...o,...a,...t}),typeof t==`object`&&t&&!Array.isArray(t)&&(i.search=this.stringifyQuery(t)),i.toString()}async prepareOptions(e){this._provider||(e.__security??{bearerAuth:!0}).bearerAuth&&await this._callApiKey()}async prepareRequest(e,{url:t,options:n}){}get(e,t){return this.methodRequest(`get`,e,t)}post(e,t){return this.methodRequest(`post`,e,t)}patch(e,t){return this.methodRequest(`patch`,e,t)}put(e,t){return this.methodRequest(`put`,e,t)}delete(e,t){return this.methodRequest(`delete`,e,t)}methodRequest(e,t,n){return this.request(Promise.resolve(n).then(n=>({method:e,path:t,...n})))}request(e,t=null){return new oS(this,this.makeRequest(e,t,void 0))}async makeRequest(e,t,n){let r=await e,i=r.maxRetries??this.maxRetries;t??(t=i),await this.prepareOptions(r);let{req:a,url:o,timeout:s}=await this.buildRequest(r,{retryCount:i-t}),c=r.__metadata?.hasStreamingBody===!0;await this.prepareRequest(a,{url:o,options:r}),await this._provider?.prepareRequest?.(a,{url:o,options:r});let l=`log_`+(Math.random()*(1<<24)|0).toString(16).padStart(6,`0`),u=n===void 0?``:`, retryOf: ${n}`,d=Date.now();if(Hx(this).debug(`[${l}] sending request`,qx({retryOfRequestLogID:n,method:r.method,url:o,options:r,headers:a.headers})),r.signal?.aborted)throw new ub;let f=r.__security??{bearerAuth:!0},p=new AbortController,m=await this.fetchWithAuth(o,a,s,p,f).catch(sb),h=Date.now();if(m instanceof globalThis.Error){let e=`retrying, ${t} attempts remaining`;if(r.signal?.aborted)throw new ub;let i=ob(m)||/timed? ?out/i.test(String(m)+(`cause`in m?String(m.cause):``));if(t&&!c)return Hx(this).info(`[${l}] connection ${i?`timed out`:`failed`} - ${e}`),Hx(this).debug(`[${l}] connection ${i?`timed out`:`failed`} (${e})`,qx({retryOfRequestLogID:n,url:o,durationMs:h-d,message:m.message})),this.retryRequest(r,t,n??l);let a=c?`error; streaming body cannot be retried`:`error; no more retries left`;throw Hx(this).info(`[${l}] connection ${i?`timed out`:`failed`} - ${a}`),Hx(this).debug(`[${l}] connection ${i?`timed out`:`failed`} (${a})`,qx({retryOfRequestLogID:n,url:o,durationMs:h-d,message:m.message})),m instanceof wb||m instanceof Tb?m:i?new fb:new db({message:Nk(m),cause:m})}let g=`[${l}${u}${[...m.headers.entries()].filter(([e])=>e===`x-request-id`).map(([e,t])=>`, `+e+`: `+JSON.stringify(t)).join(``)}] ${a.method} ${o} ${m.ok?`succeeded`:`failed`} with status ${m.status} in ${h-d}ms`;if(!m.ok){if(m.status===401&&this._workloadIdentityAuth&&f.bearerAuth&&!r.__metadata?.hasStreamingBody&&!r.__metadata?.workloadIdentityTokenRefreshed)return await tx(m.body),this._workloadIdentityAuth.invalidateToken(),this.makeRequest({...r,__metadata:{...r.__metadata,workloadIdentityTokenRefreshed:!0}},t,n??l);let e=await this.shouldRetry(m);if(t&&e&&!c){let e=`retrying, ${t} attempts remaining`;return await tx(m.body),Hx(this).info(`${g} - ${e}`),Hx(this).debug(`[${l}] response error (${e})`,qx({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:h-d})),this.retryRequest(r,t,n??l,m.headers)}let i=e?c?`error; streaming body cannot be retried`:`error; no more retries left`:`error; not retryable`;Hx(this).info(`${g} - ${i}`);let a=await m.text().catch(e=>sb(e).message),o=Ib(a),s=o?void 0:a;throw Hx(this).debug(`[${l}] response error (${i})`,qx({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,message:s,durationMs:Date.now()-d})),this.makeStatusError(m.status,o,s,m.headers)}return Hx(this).info(g),Hx(this).debug(`[${l}] response start`,qx({retryOfRequestLogID:n,url:m.url,status:m.status,headers:m.headers,durationMs:h-d})),{response:m,options:r,controller:p,requestLogID:l,retryOfRequestLogID:n,startTime:d}}getAPIList(e,t,n){return this.requestAPIList(t,n&&`then`in n?n.then(t=>({method:`get`,path:e,...t})):{method:`get`,path:e,...n})}requestAPIList(e,t){let n=this.makeRequest(t,null,void 0);return new uS(this,n,e)}async fetchWithAuth(e,t,n,r,i={bearerAuth:!0,adminAPIKeyAuth:!0}){if(this._workloadIdentityAuth&&i.bearerAuth){let e=t.headers,n=e.get(`Authorization`);if(!n||n===`Bearer ${zk}`){let t=await this._workloadIdentityAuth.getToken();e.set(`Authorization`,`Bearer ${t}`)}}return await this.fetchWithTimeout(e,t,n,r)}async fetchWithTimeout(e,t,n,r){let{signal:i,method:a,...o}=t||{},s=this._makeAbort(r);i&&i.addEventListener(`abort`,s,{once:!0});let c=setTimeout(s,n),l=globalThis.ReadableStream&&o.body instanceof globalThis.ReadableStream||typeof o.body==`object`&&o.body!==null&&Symbol.asyncIterator in o.body,u={signal:r.signal,...l?{duplex:`half`}:{},method:`GET`,...o};a&&(u.method=a.toUpperCase());try{return await this.fetch.call(void 0,e,u)}finally{clearTimeout(c)}}async shouldRetry(e){let t=e.headers.get(`x-should-retry`);return t===`true`?!0:t===`false`?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,t,n,r){let i,a=r?.get(`retry-after-ms`);if(a){let e=parseFloat(a);Number.isNaN(e)||(i=e)}let o=r?.get(`retry-after`);if(o&&!i){let e=parseFloat(o);i=Number.isNaN(e)?Date.parse(o)-Date.now():e*1e3}if(i===void 0){let n=e.maxRetries??this.maxRetries;i=this.calculateDefaultRetryTimeoutMillis(t,n)}return await Rb(i),this.makeRequest(e,t-1,n)}calculateDefaultRetryTimeoutMillis(e,t){let n=t-e;return Math.min(.5*2**n,8)*(1-Math.random()*.25)*1e3}async buildRequest(e,{retryCount:t=0}={}){let n={...e},{method:r,path:i,query:a,defaultBaseURL:o}=n,s=this.buildURL(i,a,o);`timeout`in n&&Fb(`timeout`,n.timeout),n.timeout=n.timeout??this.timeout;let{bodyHeaders:c,body:l,isStreamingBody:u}=this.buildBody({options:n});return u&&(e.__metadata={...e.__metadata,hasStreamingBody:!0}),{req:{method:r,headers:await this.buildHeaders({options:e,method:r,bodyHeaders:c,retryCount:t}),...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:`half`},...l&&{body:l},...this.fetchOptions??{},...n.fetchOptions??{}},url:s,timeout:n.timeout}}async buildHeaders({options:e,method:t,bodyHeaders:n,retryCount:r}){let i={};this.idempotencyHeader&&t!==`get`&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),i[this.idempotencyHeader]=e.idempotencyKey);let a=J([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))}:{},...Yb(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this._provider?void 0:await this.authHeaders(e,e.__security??{bearerAuth:!0}),this._options.defaultHeaders,n,e.headers]);return this._provider||this.validateHeaders(a,e.__security??{bearerAuth:!0}),a.values}_makeAbort(e){return()=>e.abort()}buildBody({options:e}){let{body:t,headers:n}=e;if(!t)return t===void 0&&`body`in e?{...G(this,Lk,`f`).call(this,{body:t,headers:J([n])}),isStreamingBody:!1}:{bodyHeaders:void 0,body:void 0,isStreamingBody:!1};let r=J([n]),i=globalThis.ReadableStream!==void 0&&t instanceof globalThis.ReadableStream,a=!i&&(typeof t==`string`||t instanceof ArrayBuffer||ArrayBuffer.isView(t)||globalThis.Blob!==void 0&&t instanceof globalThis.Blob||t instanceof URLSearchParams||t instanceof FormData);return ArrayBuffer.isView(t)||t instanceof ArrayBuffer||t instanceof DataView||typeof t==`string`&&r.values.has(`content-type`)||globalThis.Blob&&t instanceof globalThis.Blob||t instanceof FormData||t instanceof URLSearchParams||i?{bodyHeaders:void 0,body:t,isStreamingBody:!a}:typeof t==`object`&&(Symbol.asyncIterator in t||Symbol.iterator in t&&`next`in t&&typeof t.next==`function`)?{bodyHeaders:void 0,body:$b(t),isStreamingBody:!0}:typeof t==`object`&&r.values.get(`content-type`)===`application/x-www-form-urlencoded`?{bodyHeaders:{"content-type":`application/x-www-form-urlencoded`},body:this.stringifyQuery(t),isStreamingBody:!1}:{...G(this,Lk,`f`).call(this,{body:t,headers:r}),isStreamingBody:!1}}},Ik=$,Lk=new WeakMap,Fk=new WeakSet,Rk=function(){return this._provider!==void 0||this.baseURL!==`https://api.openai.com/v1`},$.OpenAI=Ik,$.DEFAULT_TIMEOUT=6e5,$.OpenAIError=K,$.APIError=lb,$.APIConnectionError=db,$.APIConnectionTimeoutError=fb,$.APIUserAbortError=ub,$.NotFoundError=gb,$.ConflictError=_b,$.RateLimitError=yb,$.BadRequestError=pb,$.AuthenticationError=mb,$.InternalServerError=bb,$.PermissionDeniedError=hb,$.UnprocessableEntityError=vb,$.InvalidWebhookSignatureError=Cb,$.toFile=ZS,$.toStreamingFile=CS,$.Completions=_D,$.Chat=Bw,$.Embeddings=jD,$.Files=zD,$.Images=sO,$.ContentProvenanceChecks=TD,$.Audio=sE,$.Moderations=dO,$.Models=lO,$.FineTuning=tO,$.Graders=aO,$.VectorStores=hk,$.Webhooks=Sk,$.Beta=hD,$.Batches=lE,$.Uploads=sk,$.Admin=$T,$.Responses=YO,$.Realtime=_O,$.Conversations=kD,$.Evals=LD,$.Containers=CD,$.Skills=rk,$.Videos=_k})),Vk,Hk,Uk=t((()=>{SS(),uC(),zE(),Bk(),Vk=class extends ${constructor({baseURL:e=LE(`OPENAI_BASE_URL`),apiKey:t=LE(`AZURE_OPENAI_API_KEY`),apiVersion:n=LE(`OPENAI_API_VERSION`),endpoint:r,deployment:i,azureADTokenProvider:a,dangerouslyAllowBrowser:o,...s}={}){if(!n)throw new K(`The OPENAI_API_VERSION environment variable is missing or empty; either provide it, or instantiate the AzureOpenAI client with an apiVersion option, like new AzureOpenAI({ apiVersion: 'My API Version' }).`);if(typeof a==`function`&&(o=!0),!a&&!t)throw new K("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(a&&t)throw new K("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(s.defaultQuery={...s.defaultQuery,"api-version":n},!e){if(r||(r=process.env.AZURE_OPENAI_ENDPOINT),!r)throw new K("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");let t=r.length;for(;t>0&&r[t-1]===`/`;)t--;e=`${r.slice(0,t)}/openai`}else if(r)throw new K(`baseURL and endpoint are mutually exclusive`);super({apiKey:a??t,baseURL:e,...s,...o===void 0?{}:{dangerouslyAllowBrowser:o}}),this.apiVersion=``,this.apiVersion=n,this.deploymentName=i}async buildRequest(e,t={}){if(Hk.has(e.path)&&e.method===`post`&&e.body!==void 0){if(!Ab(e.body))throw Error(`Expected request body to be an object`);let t=this.deploymentName||e.body.model||e.__metadata?.model;t!==void 0&&!this.baseURL.includes(`/deployments`)&&(e.path=`/deployments/${t}${e.path}`)}return super.buildRequest(e,t)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return n.bearerAuth&&typeof this._options.apiKey==`string`?J([{"api-key":this.apiKey}]):super.authHeaders(e,n)}},Hk=new Set([`/completions`,`/chat/completions`,`/embeddings`,`/audio/transcriptions`,`/audio/translations`,`/audio/speech`,`/images/generations`,`/batches`,`/images/edits`])}));function Wk(e){let t=e?.trim();if(!t)throw new K("Must provide one of the `baseURL` or `awsRegion` arguments, or set the `AWS_BEDROCK_BASE_URL`, `AWS_REGION`, or `AWS_DEFAULT_REGION` environment variable.");return`https://bedrock-mantle.${t}.api.aws/openai/v1`}function Gk(e){let t=new URL(e),n=t.pathname.match(/\/responses(?:\/.*)?$/);return n?.index!==void 0&&(t.pathname=t.pathname.slice(0,n.index)||`/`),t.toString().replace(/\/$/,``)}function Kk(e){return Object.getOwnPropertyDescriptor(e,`output_text`)||DO(e),e}function qk(e){let t=e.stream.bind(e);return e.stream=((e,n)=>{let r=t(e,n),i=r.finalResponse.bind(r);return r.finalResponse=async()=>Kk(await i()),r}),e}var Jk,Yk=t((()=>{uC(),Bk(),SS(),zE(),OO(),Ek(),Jk=class extends ${constructor({baseURL:e=LE(`AWS_BEDROCK_BASE_URL`),apiKey:t,awsRegion:n=LE(`AWS_REGION`)??LE(`AWS_DEFAULT_REGION`),bedrockTokenProvider:r,adminAPIKey:i,workloadIdentity:a,...o}={}){if(i||a)throw new K(`BedrockOpenAI only supports Bedrock bearer token authentication.`);if(t===void 0&&!r&&(t=LE(`AWS_BEARER_TOKEN_BEDROCK`)??null),typeof t==`function`)throw new K("Pass refreshable Bedrock credentials via `bedrockTokenProvider`, not `apiKey`.");if(t&&r)throw new K("The `apiKey` and `bedrockTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(!t&&!r)throw new K("Missing credentials. Please pass an `apiKey` or `bedrockTokenProvider`, or set the `AWS_BEARER_TOKEN_BEDROCK` environment variable.");let s=e?.trim()?e:Wk(n);super({apiKey:r??t,adminAPIKey:null,baseURL:Gk(s),...o}),this.bedrockTokenProvider=r,this.responses=qk(new YO(this))}async prepareOptions(e){let t=e.__security??{bearerAuth:!0};t.adminAPIKeyAuth&&!t.bearerAuth&&await this._callApiKey(),await super.prepareOptions(e)}async authHeaders(e,t){let n=t??{bearerAuth:!0,adminAPIKeyAuth:!0};return(n.bearerAuth||n.adminAPIKeyAuth)&&this.apiKey!==null?J([{Authorization:`Bearer ${this.apiKey}`}]):super.authHeaders(e,n)}withOptions(e){let t=e.apiKey===void 0?e.bedrockTokenProvider??this.bedrockTokenProvider:void 0;return super.withOptions({...e,...t?{apiKey:void 0,bedrockTokenProvider:t}:{}})}}})),Xk=n({APIConnectionError:()=>db,APIConnectionTimeoutError:()=>fb,APIError:()=>lb,APIPromise:()=>oS,APIUserAbortError:()=>ub,AuthenticationError:()=>mb,AzureOpenAI:()=>Vk,BadRequestError:()=>pb,BedrockOpenAI:()=>Jk,ConflictError:()=>_b,InternalServerError:()=>bb,InvalidWebhookSignatureError:()=>Cb,NotFoundError:()=>gb,OAuthError:()=>wb,OpenAI:()=>$,OpenAIError:()=>K,PagePromise:()=>uS,PermissionDeniedError:()=>hb,RateLimitError:()=>yb,SubjectTokenProviderError:()=>Tb,UnprocessableEntityError:()=>vb,default:()=>$,toFile:()=>ZS,toStreamingFile:()=>CS}),Zk=t((()=>{Bk(),iC(),sS(),q(),Eb(),Uk(),Yk()}));function Qk(e,t){let n=t,i=Date.now(),a,o=null,s=null,c=!1,l=new r.Notice(t,0);function u(t){return`${e} (${f()}):\n\n${t}`}function d(e){c||(n=e,l.setMessage(u(n)))}o=window.setInterval(()=>{l.setMessage(u(n))},1e3);function f(){return $k(a?a-i:Date.now()-i)}function p(){o!==null&&(a=Date.now(),window.clearInterval(o),o=null)}function m(e,t){c||(s!==null&&window.clearTimeout(s),s=window.setTimeout(()=>{s=null,!c&&(c=!0,l.hide(),t())},e))}function h(){c||(c=!0,p(),s!==null&&(window.clearTimeout(s),s=null),l.hide())}return{update:d,stop:p,scheduleHide:m,dispose:h}}function $k(e){let t=Math.floor(e/1e3),n=Math.floor(t/60);return`${Math.floor(n/60).toString().padStart(2,`0`)}:${(n%60).toString().padStart(2,`0`)}:${(t%60).toString().padStart(2,`0`)}`}function eA(e){return`[Error transcribing chunk ${e}]`}var tA=/\[Error transcribing chunk \d+\]/g,nA=class{constructor(e,t=()=>Promise.resolve().then(()=>(Zk(),Xk))){this.loadOpenAI=t,this.client=null,this.cachedApiKey=null,this.disposed=!1,this.lifetimeAbortController=new AbortController,this.activeNotices=new Set,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(this.disposed)return;if(!W_(this.plugin.settings,e=>this.plugin.credentials.has(this.plugin.settings,e))){let e=this.plugin.settings.transcript.diarization,t=e?.enabled&&e.provider===`deepgram`,n=t?`deepgram`:`openai`,i=this.plugin.credentials.status(this.plugin.settings,n)===`missing`;new r.Notice(i?`The selected ${t?`Deepgram`:`OpenAI`} API key is not available on this device. Select or create it in the transcript settings.`:t?`Select or create a Deepgram API key in the transcript settings on this device.`:`Select or create an OpenAI API key in the transcript settings on this device.`);return}let e=this.plugin.api.podcast;if(!e){new r.Notice(`No episode is currently playing.`);return}let t=this.getTranscriptPath(e);if(this.plugin.app.vault.getAbstractFileByPath(t)instanceof r.TFile){new r.Notice(`You've already transcribed this episode - found ${t}.`);return}let n=this.getEpisodeKey(e);if(this.pendingEpisodes.some(e=>this.getEpisodeKey(e)===n)||this.activeTranscriptions.has(n)){new r.Notice(`This episode is already queued or transcribing.`);return}this.pendingEpisodes.push(e),new r.Notice(`Queued "${e.title}" for transcription. It will start automatically.`),this.drainQueue()}drainQueue(){if(this.disposed){this.pendingEpisodes=[];return}for(;this.activeTranscriptions.size<this.MAX_CONCURRENT_TRANSCRIPTIONS&&this.pendingEpisodes.length>0;){let e=this.pendingEpisodes.shift();if(!e)return;let t=this.getEpisodeKey(e);this.activeTranscriptions.add(t),this.transcribeEpisode(e).finally(()=>{this.activeTranscriptions.delete(t),this.disposed||this.drainQueue()})}}getEpisodeKey(e){return`${e.podcastName}:${e.title}`}async transcribeEpisode(e){this.assertActive();let t=Qk(`Transcription: ${e.title}`,`Preparing to transcribe...`);this.activeNotices.add(t);let n=e=>{this.disposed||t.update(e)};try{let i=this.getTranscriptPath(e);if(this.plugin.app.vault.getAbstractFileByPath(i)instanceof r.TFile){t.stop(),n(`Transcript already exists - skipped (${i}).`);return}n(`Fetching episode audio...`);let{buffer:a,extension:o,basename:s}=await this.waitForLifecycle(Ym(e));this.assertActive();let c=qy(o),{body:l,warning:u}=await this.buildTranscriptBody({buffer:a,mimeType:c,extension:o,basename:s},n);this.assertActive(),n(`Saving transcription...`),await this.saveTranscription(e,l),this.assertActive(),t.stop(),n(u??`Transcription completed and saved.`)}catch(e){if(this.disposed||this.lifetimeAbortController.signal.aborted)return;let r=e instanceof Error?e.message:String(e);t.stop(),n(`Transcription failed: ${r}`)}finally{t.stop(),this.disposed?(t.dispose(),this.activeNotices.delete(t)):t.scheduleHide(5e3,()=>this.activeNotices.delete(t))}}async buildTranscriptBody(e,t){let n=this.plugin.settings.transcript.diarization;if(n?.enabled){let r=await this.diarize(e,n.provider,t);if(this.assertActive(),r.length===0)throw Error(`Diarization returned no speech segments.`);return{body:Ta(r,n.speakerTemplate)}}t(`Creating audio chunks...`);let r=await Yy(e);this.assertActive(),t(`Starting transcription...`);let{text:i,failedChunks:a}=await this.transcribeChunks(r,t);if(this.assertActive(),i.replace(tA,` `).trim().length===0)throw Error(a>0?`Transcription failed: all ${r.length} audio chunk(s) failed or returned no text.`:`Transcription returned no text.`);return{body:i.trim().replace(/\.\s+/g,`.
|
||
|
||
`),warning:a>0?`Transcription saved, but ${a} of ${r.length} chunk(s) failed - look for [Error transcribing chunk N] markers and re-run after deleting the note to retry.`:void 0}}async diarize(e,t,n){if(this.assertActive(),t===`deepgram`){let t=this.plugin.credentials.get(this.plugin.settings,`deepgram`);if(!t)throw Error(`Missing Deepgram API key on this device.`);let r=await this.waitForLifecycle(U_({audio:e,apiKey:t,onProgress:n,signal:this.lifetimeAbortController.signal}));return this.assertActive(),r}n(`Creating audio chunks...`);let r=await Yy(e);this.assertActive();let i=await F_({getClient:()=>this.getClient(),chunkFiles:r,maxRetries:this.MAX_RETRIES,onProgress:n,signal:this.lifetimeAbortController.signal});return this.assertActive(),i}async transcribeChunks(e,t){let n=await this.getClient();this.assertActive();let r=Array.from({length:e.length}),i=0,a=0,o=0,s=()=>{let n=(i/e.length*100).toFixed(1);t(`Transcribing... ${i}/${e.length} chunks completed (${n}%)`)};s();let c=async()=>{for(;;){this.assertActive();let t=o++;if(t>=e.length)return;let c=e[t],l=0;for(;l<this.MAX_RETRIES;){this.assertActive();try{let e=await n.audio.transcriptions.create({model:`whisper-1`,file:c},{signal:this.lifetimeAbortController.signal});this.assertActive(),r[t]=e.text,i++,s();break}catch{this.assertActive(),l++,l>=this.MAX_RETRIES?(r[t]=eA(t),a++,i++,s()):await this.waitForRetry(1e3*l)}}}},l=Math.min(this.MAX_CONCURRENT_CHUNK_TRANSCRIPTIONS,e.length),u=Array.from({length:l},()=>c());return await Promise.all(u),this.assertActive(),{text:r.join(` `),failedChunks:a}}waitForRetry(e){this.assertActive();let t=this.lifetimeAbortController.signal;return new Promise((n,r)=>{let i=window.setTimeout(()=>{t.removeEventListener(`abort`,a),n()},e),a=()=>{window.clearTimeout(i),t.removeEventListener(`abort`,a),r(this.getAbortReason())};t.addEventListener(`abort`,a,{once:!0}),t.aborted&&a()})}waitForLifecycle(e){this.assertActive();let t=this.lifetimeAbortController.signal;return new Promise((n,r)=>{let i=!1,a=()=>t.removeEventListener(`abort`,o),o=()=>{i||(i=!0,a(),r(this.getAbortReason()))};t.addEventListener(`abort`,o,{once:!0}),e.then(e=>{if(!i){if(t.aborted){o();return}i=!0,a(),n(e)}},e=>{if(!i){if(t.aborted){o();return}i=!0,a(),r(e)}}),t.aborted&&o()})}getTranscriptPath(e){return ch(e,this.plugin.settings.transcript.path)}async saveTranscription(e,t){this.assertActive();let n=this.getTranscriptPath(e),i=Hd(this.plugin.settings.transcript.template,e,t),a=this.plugin.app.vault;await sf(n.substring(0,n.lastIndexOf(`/`)),a,()=>this.assertActive()),this.assertActive();let o=a.getAbstractFileByPath(n);if(!o){this.assertActive();let e=await a.create(n,i);this.assertActive(),await this.plugin.app.workspace.getLeaf().openFile(e)}else if(o instanceof r.TFile)this.assertActive(),await this.plugin.app.workspace.getLeaf().openFile(o);else throw Error(`Expected a file but found a folder at transcript path.`)}async getClient(){this.assertActive();let e=this.plugin.credentials.get(this.plugin.settings,`openai`);if(!e)throw Error(`Missing OpenAI API key on this device`);if(this.client&&this.cachedApiKey===e)return this.client;let{OpenAI:t}=await this.loadOpenAI();return this.assertActive(),this.client=new t({apiKey:e,dangerouslyAllowBrowser:!0}),this.cachedApiKey=e,this.client}dispose(){if(!this.disposed){this.disposed=!0,this.lifetimeAbortController.abort(new DOMException(`PodNotes was unloaded during transcription.`,`AbortError`)),this.pendingEpisodes=[];for(let e of this.activeNotices)e.dispose();this.activeNotices.clear(),this.clearCredentialCache()}}clearCredentialCache(){this.client=null,this.cachedApiKey=null}assertActive(){if(this.disposed||this.lifetimeAbortController.signal.aborted)throw this.getAbortReason()}getAbortReason(){return this.lifetimeAbortController.signal.reason??new DOMException(`PodNotes was unloaded during transcription.`,`AbortError`)}},rA={openai:{baseId:`podnotes-openai-api-key`,settingsKey:`openAISecretId`},deepgram:{baseId:`podnotes-deepgram-api-key`,settingsKey:`deepgramSecretId`}},iA=class{constructor(e){this.storage=e}get(e,t){let n=e[rA[t].settingsKey].trim();if(!n||!Wg(t,n))return null;try{let e=this.storage.getSecret(n);return e?.trim()?e.trim():null}catch{return null}}has(e,t){return this.get(e,t)!==null}status(e,t){return e[rA[t].settingsKey].trim()?this.has(e,t)?`available`:`missing`:`unconfigured`}exportValues(e,t={}){let n=this.get(e,`openai`),r=this.get(e,`deepgram`);if(t.requireConfigured){if(e.openAISecretId.trim()&&!n)throw Error(`The selected OpenAI API key is not available in SecretStorage on this device.`);if(e.deepgramSecretId.trim()&&!r)throw Error(`The selected Deepgram API key is not available in SecretStorage on this device.`)}return{...n?{openAI:n}:{},...r?{deepgram:r}:{}}}storeValues(e){let t={},n=e.openAI?.trim(),r=e.deepgram?.trim();return n&&(t.openAISecretId=this.store(`openai`,n)),r&&(t.deepgramSecretId=this.store(`deepgram`,r)),t}adoptReference(e,t){let n=t.trim();if(!n)return``;if(!Hg(n))throw Error(`Obsidian returned an invalid SecretStorage ID.`);let r=this.storage.getSecret(n)?.trim();if(!r)throw Error(`The selected secret is not available on this device.`);return Wg(e,n)?n:this.store(e,r)}store(e,t){let{baseId:n}=rA[e];for(let r=1;r<=1e4;r++){let i=r===1?n:`${n}-${r}`,a=this.storage.getSecret(i);if(a===t)return i;if(a===null){if(this.storage.setSecret(i,t),this.storage.getSecret(i)!==t)throw Error(`SecretStorage did not retain the ${e} credential.`);return i}}throw Error(`Could not allocate a SecretStorage ID for the ${e} credential.`)}},aA=/^podnotes-feed-url-[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;function oA(e){return aA.test(e)}var sA=class{constructor(e){this.storage=e}resolve(e){let t=e.trim();if(!t||!oA(t)||!Hg(t))return null;try{let e=this.storage.getSecret(t);return e?.trim()?e.trim():null}catch{return null}}store(e){let t=e.trim();if(!t)throw Error(`A private feed URL must not be empty.`);let n=`podnotes-feed-url-${crypto.randomUUID()}`;if(this.storage.setSecret(n,t),this.storage.getSecret(n)!==t)throw Error(`SecretStorage did not retain the private feed URL.`);return n}delete(e){let t=e.trim();if(!(!t||!oA(t)))try{this.storage.setSecret(t,``)}catch{}}sweepOrphans(e){let t=new Set;for(let n of Object.values(e))n.urlSecretId?.trim()&&t.add(n.urlSecretId.trim());try{for(let e of this.storage.listSecrets())!oA(e)||t.has(e)||this.storage.getSecret(e)&&this.delete(e)}catch{}}},cA=class extends Error{constructor(e,t){super(e instanceof Error?e.message:String(e)),this.originalCause=e,this.includedCredentials=t,this.name=`PodNotesSchemaMigrationError`}},lA=class extends r.Plugin{constructor(...e){super(...e),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.pendingSaveWaiters=[],this.saveScheduled=!1,this.saveChain=Promise.resolve(),this.persistenceUnknownFields={},this.mediaSessionActions=[]}async onload(){this.isUnloaded=!1,this.podcastViewMountEnabled=!this.isMobileRuntime(),L.set(this),this.credentials=new iA(this.app.secretStorage),this.feedUrls=new sA(this.app.secretStorage),await this.loadSettings(),To.set(this.settings.playedEpisodes),ro.set(this.settings.savedFeeds),Po.set(this.settings.playlists),ko.set(this.settings.queue),Ao.set(this.settings.favorites),No.set(this.settings.localFiles),ho.set(this.settings.downloadedEpisodes),this.settings.currentEpisode&&Co.set(this.settings.currentEpisode),So.set(this.settings.hidePlayedEpisodes),ao.set(this.settings.episodeListLimit),xo.set(Math.min(1,Math.max(0,this.settings.defaultVolume??1))),bo.set(Pa(this.settings.defaultPlaybackRate)),this.storeUnsubscribers.push(Wo(this),Ro()),this.localFilesMirrorUnsubscribe=ho.subscribe(e=>No.syncWithDownloaded(e)),this.api=new fh,this.volumeUnsubscribe=xo.subscribe(e=>{let t=Math.min(1,Math.max(0,e));if(t!==e){xo.set(t);return}t!==this.settings.defaultVolume&&(this.settings.defaultVolume=t,this.saveSettings())}),sh(this),this.addSettingTab(new Q_(this.app,this)),this.registerView(Ea,e=>{let t=new Ny(e,this);return this.views.add(t),t}),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=>Ry(e,this.api,()=>this.activateView())),this.registerEvent(Vy(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(`podcast_player_view`).length)return;let e=this.app.workspace.getRightLeaf(!1);e&&e.setViewState({type:Ea}).catch(e=>{})}async activateView(){this.enablePodcastViewMount();let{workspace:e}=this.app,t=e.getLeavesOfType(`podcast_player_view`)[0]??null;t||(t=e.getRightLeaf(!1),await t?.setViewState({type:Ea,active:!0})),t&&await e.revealLeaf(t)}shouldMountPodcastView(){return this.podcastViewMountEnabled}enablePodcastViewMount(){this.podcastViewMountEnabled=!0;for(let e of this.views)e.mountPodcastView()}unregisterPodcastView(e){this.views.delete(e)}dedupePlayerLeaves(){let e=this.app.workspace.getLeavesOfType(Ea);for(let t of e.slice(1))t.detach()}isMobileRuntime(){return r.Platform.isMobileApp||this.app.isMobile===!0}getTranscriptionService(){return this.transcriptionService||(this.transcriptionService=new nA(this)),this.transcriptionService}invalidateTranscriptionCredentialCache(){this.transcriptionService?.clearCredentialCache()}captureTimestamp(e){if(!e||!this.api.podcast||!this.settings.timestamp.template)return!1;let t=zd(this.settings.timestamp.template),n=e.getCursor(`from`),r=tf(t,{getLine:t=>e.getLine(t),lineCount:e.lineCount(),cursorLine:n.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{let e=zd(this.settings.timestamp.template),t=e.endsWith(`
|
||
`)?e:`${e}\n`,n=op(this.api.podcast)??await ip(this.api.podcast),r=await this.app.vault.read(n),i=r.length>0&&!r.endsWith(`
|
||
`)?`
|
||
`:``;return await this.app.vault.modify(n,`${r}${i}${t}`),!0}catch{return new r.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,t){let n=window.navigator?.mediaSession;if(n?.setActionHandler)try{n.setActionHandler(e,t),this.mediaSessionActions.push(e)}catch{}}clearMediaSessionHandlers(){let e=window.navigator?.mediaSession;if(e?.setActionHandler){for(let t of this.mediaSessionActions)try{e.setActionHandler(t,null)}catch{}this.mediaSessionActions=[]}}onunload(){this.isUnloaded=!0,this.clearLayoutReadyRetry(),this.clearMediaSessionHandlers();for(let e of this.storeUnsubscribers)e();this.storeUnsubscribers=[],this.volumeUnsubscribe?.(),this.localFilesMirrorUnsubscribe?.(),this.transcriptionService?.dispose(),this.transcriptionService=void 0,this.views.clear()}clearLayoutReadyRetry(){this.layoutReadyRetry&&(window.clearTimeout(this.layoutReadyRetry),this.layoutReadyRetry=null)}async loadSettings(){try{let e=c_(await this.loadData()),t=e.settings;if(this.credentials??(this.credentials=new iA(this.app.secretStorage)),e.sourceVersion<2||e.retiredPlaintextPresent){try{let n=e.sourceVersion<2?this.credentials.storeValues(e.legacySecrets):{};t={...t,...n},await this.saveData(l_(t,e.unknownFields))}catch(t){throw new cA(t,!!(e.legacySecrets.openAI||e.legacySecrets.deepgram))}let n=[e.legacySecrets.openAI?`OpenAI`:null,e.legacySecrets.deepgram?`Deepgram`:null].filter(e=>e!==null);n.length>0&&new r.Notice(`Moved your ${n.join(` and `)} API ${n.length===1?`key`:`keys`} into Obsidian SecretStorage.`)}this.feedUrls??(this.feedUrls=new sA(this.app.secretStorage));let n=Gp(t.savedFeeds,this.feedUrls);if(n.replacements.size>0){t=Kp({...t,savedFeeds:n.savedFeeds},n.replacements),Mg([...n.replacements.keys()]),await this.saveData(l_(t,e.unknownFields));let i=n.replacements.size;new r.Notice(`Moved ${i} private feed ${i===1?`URL`:`URLs`} into Obsidian SecretStorage.`)}n.failed.length>0&&new r.Notice(`PodNotes could not protect the private feed ${n.failed.length===1?`URL`:`URLs`} for ${n.failed.join(`, `)}; ${n.failed.length===1?`it stays`:`they stay`} in data.json for now. Restart PodNotes to retry.`,0),this.feedUrls.sweepOrphans(t.savedFeeds),this.settings=t,this.persistenceUnknownFields=e.unknownFields,e.warnings.length}catch(e){throw e instanceof s_?new r.Notice(e.message,0):e instanceof cA&&new r.Notice(e.includedCredentials?`PodNotes could not securely migrate its API keys. Your existing data was kept unchanged. Restart PodNotes to retry.`:`PodNotes could not upgrade its settings data. Your existing data was kept unchanged. Restart PodNotes to retry.`,0),e}}saveSettings(){return this.requestSettingsSave().catch(()=>void 0)}saveSettingsStrict(){return this.requestSettingsSave()}requestSettingsSave(){if(!this.isReady)return Promise.resolve();try{this.pendingSave=this.cloneSettings()}catch(e){let t=Promise.reject(e);return t.catch(()=>void 0),t}let e=new Promise((e,t)=>{this.pendingSaveWaiters.push({resolve:e,reject:t})});return e.catch(()=>void 0),this.saveScheduled||(this.saveScheduled=!0,this.saveChain=this.runSaveLoop()),e}async runSaveLoop(){try{for(;this.pendingSave;){let e=this.pendingSave,t=this.pendingSaveWaiters;this.pendingSave=null,this.pendingSaveWaiters=[];try{await this.saveData(l_(e,this.persistenceUnknownFields));for(let e of t)e.resolve()}catch(e){for(let n of t)n.reject(e)}}}finally{this.saveScheduled=!1}}cloneSettings(){return typeof structuredClone==`function`?structuredClone(this.settings):JSON.parse(JSON.stringify(this.settings))}};module.exports=lA;
|
||
/* nosourcemap */ |