Files

1187 lines
8.0 MiB
JavaScript
Raw Permalink Normal View History

2025-10-25 20:35:10 +08:00
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var byI=Object.create;var MY=Object.defineProperty;var syI=Object.getOwnPropertyDescriptor;var myI=Object.getOwnPropertyNames;var ZyI=Object.getPrototypeOf,ryI=Object.prototype.hasOwnProperty;var oyI=(l,I,e)=>I in l?MY(l,I,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[I]=e;var tG=(l,I)=>()=>(l&&(I=l(l=0)),I);var w=(l,I)=>()=>(I||l((I={exports:{}}).exports,I),I.exports),pe=(l,I)=>{for(var e in I)MY(l,e,{get:I[e],enumerable:!0})},E_=(l,I,e,t)=>{if(I&&typeof I=="object"||typeof I=="function")for(let a of myI(I))!ryI.call(l,a)&&a!==e&&MY(l,a,{get:()=>I[a],enumerable:!(t=syI(I,a))||t.enumerable});return l};var y=(l,I,e)=>(e=l!=null?byI(ZyI(l)):{},E_(I||!l||!l.__esModule?MY(e,"default",{value:l,enumerable:!0}):e,l)),uyI=l=>E_(MY({},"__esModule",{value:!0}),l);var g=(l,I,e)=>(oyI(l,typeof I!="symbol"?I+"":I,e),e),NA=(l,I,e)=>{if(!I.has(l))throw TypeError("Cannot "+e)};var A=(l,I,e)=>(NA(l,I,"read from private field"),e?e.call(l):I.get(l)),pI=(l,I,e)=>{if(I.has(l))throw TypeError("Cannot add the same private member more than once");I instanceof WeakSet?I.add(l):I.set(l,e)},rI=(l,I,e,t)=>(NA(l,I,"write to private field"),t?t.call(l,e):I.set(l,e),e),OY=(l,I,e,t)=>({set _(a){rI(l,I,a,e)},get _(){return A(l,I,t)}}),_I=(l,I,e)=>(NA(l,I,"access private method"),e);var W,s=tG(()=>{W=typeof document>"u"?require("url").pathToFileURL(__filename).href:document.currentScript&&document.currentScript.src||new URL("main.js",document.baseURI).href});var M_=w(pl=>{"use strict";s();var BY=Symbol.for("react.element"),WyI=Symbol.for("react.portal"),iyI=Symbol.for("react.fragment"),NyI=Symbol.for("react.strict_mode"),pyI=Symbol.for("react.profiler"),hyI=Symbol.for("react.provider"),YyI=Symbol.for("react.context"),VyI=Symbol.for("react.forward_ref"),RyI=Symbol.for("react.suspense"),FyI=Symbol.for("react.memo"),XyI=Symbol.for("react.lazy"),g_=Symbol.iterator;function HyI(l){return l===null||typeof l!="object"?null:(l=g_&&l[g_]||l["@@iterator"],typeof l=="function"?l:null)}var J_={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A_=Object.assign,L_={};function ki(l,I,e){this.props=l,this.context=I,this.refs=L_,this.updater=e||J_}ki.prototype.isReactComponent={};ki.prototype.setState=function(l,I){if(typeof l!="object"&&typeof l!="function"&&l!=null)throw Error("setState(...): takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,l,I,"setState")};ki.prototype.forceUpdate=function(l){this.updater.enqueueForceUpdate(this,l,"forceUpdate")};function k_(){}k_.prototype=ki.prototype;function hA(l,I,e){this.props=l,this.context=I,this.refs=L_,this.updater=e||J_}var YA=hA.prototype=new k_;YA.constructor=hA;A_(YA,ki.prototype);YA.isPureReactComponent=!0;var y_=Array.isArray,x_=Object.prototype.hasOwnProperty,VA={current:null},f_={key:!0,ref:!0,__self:!0,__source:!0};function z_(l,I,e){var t,a={},G=null,c=null;if(I!=null)for(t in I.ref!==void 0&&(c=I.ref),I.key!==void 0&&(G=""+I.key),I)x_.call(I,t)&&!f_.hasOwnProperty(t)&&(a[t]=I[t]);var n=arguments.length-2;if(n===1)a.children=e;else if(1<n){for(var d=Array(n),b=0;b<n;b++)d[b]=arguments[b+2];a.children=d}if(l&&l.defaultProps)for(t in n=l.defaultProps,n)a[t]===void 0&&(a[t]=n[t]);return{$$typeof:BY,type:l,key:G,ref:c,props:a,_owner:VA.current}}function QyI(l,I){return{$$typeof:BY,type:l.type,key:I,ref:l.ref,props:l.props,_owner:l._owner}}function RA(l){return typeof l=="object"&&l!==null&&l.$$typeof===BY}function wyI(l){var I={"=":"=0",":":"=2"};return"$"+l.replace(/[=:]/g,function(e){return I[e]})}var C_=/\/+/g;function pA(l,I){return typeof l=="object"&&l!==null&&l.key!=null?wyI(""+l.key):I.toString(36)}function cH(l,I,e,t,a){var G=typeof l;(G==="undefined"||G==="boolean")&&(l=null);var c=!1;if(l===null)c=!0;else switch(G){case"string":case"number":c=!0;break;case"object":switch(l.$$typeof){case BY:case WyI:c=!0}}if(c)return c=l,a=a(c),l=t===""?"."+pA(c,0):t,y_(a)?(e="",l!=null&&(e=l.replace(C_,"$&/")+"/"),cH(a,I,e,"",function(b){return b})):
`+CA+l}var JA=!1;function AA(l,I){if(!l||JA)return"";JA=!0;var e=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{if(I)if(I=function(){throw Error()},Object.defineProperty(I.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(I,[])}catch(b){var t=b}Reflect.construct(l,[],I)}else{try{I.call()}catch(b){t=b}l.call(I.prototype)}else{try{throw Error()}catch(b){t=b}l()}}catch(b){if(b&&t&&typeof b.stack=="string"){for(var a=b.stack.split(`
`),G=t.stack.split(`
`),c=a.length-1,n=G.length-1;1<=c&&0<=n&&a[c]!==G[n];)n--;for(;1<=c&&0<=n;c--,n--)if(a[c]!==G[n]){if(c!==1||n!==1)do if(c--,n--,0>n||a[c]!==G[n]){var d=`
`+a[c].replace(" at new "," at ");return l.displayName&&d.includes("<anonymous>")&&(d=d.replace("<anonymous>",l.displayName)),d}while(1<=c&&0<=n);break}}}finally{JA=!1,Error.prepareStackTrace=e}return(l=l?l.displayName||l.name:"")?eV(l):""}function kyI(l){switch(l.tag){case 5:return eV(l.type);case 16:return eV("Lazy");case 13:return eV("Suspense");case 19:return eV("SuspenseList");case 0:case 2:case 15:return l=AA(l.type,!1),l;case 11:return l=AA(l.type.render,!1),l;case 1:return l=AA(l.type,!0),l;default:return""}}function GL(l){if(l==null)return null;if(typeof l=="function")return l.displayName||l.name||null;if(typeof l=="string")return l;switch(l){case Ui:return"Fragment";case zi:return"Portal";case eL:return"Profiler";case _L:return"StrictMode";case tL:return"Suspense";case aL:return"SuspenseList"}if(typeof l=="object")switch(l.$$typeof){case s6:return(l.displayName||"Context")+".Consumer";case b6:return(l._context.displayName||"Context")+".Provider";case qL:var I=l.render;return l=l.displayName,l||(l=I.displayName||I.name||"",l=l!==""?"ForwardRef("+l+")":"ForwardRef"),l;case PL:return I=l.displayName||null,I!==null?I:GL(l.type)||"Memo";case IZ:I=l._payload,l=l._init;try{return GL(l(I))}catch{}}return null}function xyI(l){var I=l.type;switch(l.tag){case 24:return"Cache";case 9:return(I.displayName||"Context")+".Consumer";case 10:return(I._context.displayName||"Context")+".Provider";case 18:return"DehydratedFragment";case 11:return l=I.render,l=l.displayName||l.name||"",I.displayName||(l!==""?"ForwardRef("+l+")":"ForwardRef");case 7:return"Fragment";case 5:return I;case 4:return"Portal";case 3:return"Root";case 6:return"Text";case 16:return GL(I);case 8:return I===_L?"StrictMode":"Mode";case 22:return"Offscreen";case 12:return"Profiler";case 21:return"Scope";case 13:return"Suspense";case 19:return"SuspenseList";case 25:return"TracingMarker";case 1:case 0:case 17:case 2:case 14:case 15:if(typeof I=="function")return I.displayName||I.name||null;if(typeof I=="string")return I}return null}function oZ(l){switch(typeof l){case"boolean":case"number":case"string":case"undefined":return l;case"object":return l;default:return""}}function Z6(l){var I=l.type;return(l=l.nodeName)&&l.toLowerCase()==="input"&&(I==="checkbox"||I==="radio")}function fyI(l){var I=Z6(l)?"checked":"value",e=Object.getOwnPropertyDescriptor(l.constructor.prototype,I),t=""+l[I];if(!l.hasOwnProperty(I)&&typeof e<"u"&&typeof e.get=="function"&&typeof e.set=="function"){var a=e.get,G=e.set;return Object.defineProperty(l,I,{configurable:!0,get:function(){return a.call(this)},set:function(c){t=""+c,G.call(this,c)}}),Object.defineProperty(l,I,{enumerable:e.enumerable}),{getValue:function(){return t},setValue:function(c){t=""+c},stopTracking:function(){l._valueTracker=null,delete l[I]}}}}function oH(l){l._valueTracker||(l._valueTracker=fyI(l))}function r6(l){if(!l)return!1;var I=l._valueTracker;if(!I)return!0;var e=I.getValue(),t="";return l&&(t=Z6(l)?l.checked?"true":"false":l.value),l=t,l!==e?(I.setValue(l),!0):!1}function MH(l){if(l=l||(typeof document<"u"?document:void 0),typeof l>"u")return null;try{return l.activeElement||l.body}catch{return l.body}}function cL(l,I){var e=I.checked;return Me({},I,{defaultChecked:void 0,defaultValue:void 0,value:void 0,checked:e??l._wrapperState.initialChecked})}function Gq(l,I){var e=I.defaultValue==null?"":I.defaultValue,t=I.checked!=null?I.checked:I.defaultChecked;e=oZ(I.value!=null?I.value:e),l._wrapperState={initialChecked:t,initialValue:e,controlled:I.type==="checkbox"||I.type==="radio"?I.checked!=null:I.value!=null}}function o6(l,I){I=I.checked,I!=null&&DL(l,"checked",I,!1)}function nL(l,I){o6(l,I);var e=oZ(I.value),t=I.type;if(e!=null)t==="number"?(e===0&&l.value===""||l.value!=e)&&(l.value=""+e):l.value!==""+e&&(l.value=""+e);else if(t==="submit"||t==="reset"){l.removeAttribute("value");return}I.hasOwnProperty("value")?dL(l,I.type,e):I.hasOwnProperty("defaultValue")&&dL(l,I.type,oZ(I.defaultValue)),I.checked==null&&I.defaultChecked!=null&&(l.defaultChecked=!!I.defaultChecked)}function cq(l,I,e){if(I.hasOwnProperty(
`).replace(j1I,"")}function HH(l,I,e){if(I=Eq(I),Eq(l)!==I&&e)throw Error(iI(425))}function _H(){}var VL=null,RL=null;function FL(l,I){return l==="textarea"||l==="noscript"||typeof I.children=="string"||typeof I.children=="number"||typeof I.dangerouslySetInnerHTML=="object"&&I.dangerouslySetInnerHTML!==null&&I.dangerouslySetInnerHTML.__html!=null}var XL=typeof setTimeout=="function"?setTimeout:void 0,K1I=typeof clearTimeout=="function"?clearTimeout:void 0,gq=typeof Promise=="function"?Promise:void 0,D1I=typeof queueMicrotask=="function"?queueMicrotask:typeof gq<"u"?function(l){return gq.resolve(null).then(l).catch(_1I)}:XL;function _1I(l){setTimeout(function(){throw l})}function SA(l,I){var e=I,t=0;do{var a=e.nextSibling;if(l.removeChild(e),a&&a.nodeType===8)if(e=a.data,e==="/$"){if(t===0){l.removeChild(a),hV(I);return}t--}else e!=="$"&&e!=="$?"&&e!=="$!"||t++;e=a}while(e);hV(I)}function bZ(l){for(;l!=null;l=l.nextSibling){var I=l.nodeType;if(I===1||I===3)break;if(I===8){if(I=l.data,I==="$"||I==="$!"||I==="$?")break;if(I==="/$")return null}}return l}function yq(l){l=l.previousSibling;for(var I=0;l;){if(l.nodeType===8){var e=l.data;if(e==="$"||e==="$!"||e==="$?"){if(I===0)return l;I--}else e==="/$"&&I++}l=l.previousSibling}return null}var ZN=Math.random().toString(36).slice(2),Kd="__reactFiber$"+ZN,XV="__reactProps$"+ZN,ws="__reactContainer$"+ZN,HL="__reactEvents$"+ZN,q1I="__reactListeners$"+ZN,P1I="__reactHandles$"+ZN;function yo(l){var I=l[Kd];if(I)return I;for(var e=l.parentNode;e;){if(I=e[ws]||e[Kd]){if(e=I.alternate,I.child!==null||e!==null&&e.child!==null)for(l=yq(l);l!==null;){if(e=l[Kd])return e;l=yq(l)}return I}l=e,e=l.parentNode}return null}function JV(l){return l=l[Kd]||l[ws],!l||l.tag!==5&&l.tag!==6&&l.tag!==13&&l.tag!==3?null:l}function Si(l){if(l.tag===5||l.tag===6)return l.stateNode;throw Error(iI(33))}function WQ(l){return l[XV]||null}var QL=[],Ti=-1;function iZ(l){return{current:l}}function Ye(l){0>Ti||(l.current=QL[Ti],QL[Ti]=null,Ti--)}function ue(l,I){Ti++,QL[Ti]=l.current,l.current=I}var uZ={},ya=iZ(uZ),xG=iZ(!1),ko=uZ;function GN(l,I){var e=l.type.contextTypes;if(!e)return uZ;var t=l.stateNode;if(t&&t.__reactInternalMemoizedUnmaskedChildContext===I)return t.__reactInternalMemoizedMaskedChildContext;var a={},G;for(G in e)a[G]=I[G];return t&&(l=l.stateNode,l.__reactInternalMemoizedUnmaskedChildContext=I,l.__reactInternalMemoizedMaskedChildContext=a),a}function fG(l){return l=l.childContextTypes,l!=null}function qH(){Ye(xG),Ye(ya)}function Cq(l,I,e){if(ya.current!==uZ)throw Error(iI(168));ue(ya,I),ue(xG,e)}function eP(l,I,e){var t=l.stateNode;if(I=I.childContextTypes,typeof t.getChildContext!="function")return e;t=t.getChildContext();for(var a in t)if(!(a in I))throw Error(iI(108,xyI(l)||"Unknown",a));return Me({},e,t)}function PH(l){return l=(l=l.stateNode)&&l.__reactInternalMemoizedMergedChildContext||uZ,ko=ya.current,ue(ya,l),ue(xG,xG.current),!0}function Jq(l,I,e){var t=l.stateNode;if(!t)throw Error(iI(169));e?(l=eP(l,I,ko),t.__reactInternalMemoizedMergedChildContext=l,Ye(xG),Ye(ya),ue(ya,l)):Ye(xG),ue(xG,e)}var Rs=null,iQ=!1,TA=!1;function tP(l){Rs===null?Rs=[l]:Rs.push(l)}function $1I(l){iQ=!0,tP(l)}function NZ(){if(!TA&&Rs!==null){TA=!0;var l=0,I=Dl;try{var e=Rs;for(Dl=1;l<e.length;l++){var t=e[l];do t=t(!0);while(t!==null)}Rs=null,iQ=!1}catch(a){throw Rs!==null&&(Rs=Rs.slice(l+1)),w6(I4,NZ),a}finally{Dl=I,TA=!1}}return null}var ji=[],Ki=0,$H=null,IQ=0,Dc=[],_c=0,xo=null,Fs=1,Xs="";function Eo(l,I){ji[Ki++]=IQ,ji[Ki++]=$H,$H=l,IQ=I}function aP(l,I,e){Dc[_c++]=Fs,Dc[_c++]=Xs,Dc[_c++]=xo,xo=l;var t=Fs;l=Xs;var a=32-Id(t)-1;t&=~(1<<a),e+=1;var G=32-Id(I)+a;if(30<G){var c=a-a%5;G=(t&(1<<c)-1).toString(32),t>>=c,a-=c,Fs=1<<32-Id(I)+a|e<<a|t,Xs=G+l}else Fs=1<<G|e<<a|t,Xs=l}function b4(l){l.return!==null&&(Eo(l,1),aP(l,1,0))}function s4(l){for(;l===$H;)$H=ji[--Ki],ji[Ki]=null,IQ=ji[--Ki],ji[Ki]=null;for(;l===xo;)xo=Dc[--_c],Dc[_c]=null,Xs=Dc[--_c],Dc[_c]=null,Fs=Dc[--_c],Dc[_c]=null}var uc=null,oc=null,Ee=!1,$n=null;function GP(l,I){var e=qc(5,null,null,0);e.elementType="DELETED",e.stateNode=I,e.return
Error generating stack: `+G.message+`
`+G.stack}return{value:l,source:I,stack:a,digest:null}}function qA(l,I,e){return{value:l,source:null,stack:e??null,digest:I??null}}function CL(l,I){try{console.error(I.value)}catch(e){setTimeout(function(){throw e})}}var dCI=typeof WeakMap=="function"?WeakMap:Map;function yP(l,I,e){e=Hs(-1,e),e.tag=3,e.payload={element:null};var t=I.value;return e.callback=function(){dQ||(dQ=!0,OL=t),CL(l,I)},e}function CP(l,I,e){e=Hs(-1,e),e.tag=3;var t=l.type.getDerivedStateFromError;if(typeof t=="function"){var a=I.value;e.payload=function(){return t(a)},e.callback=function(){CL(l,I)}}var G=l.stateNode;return G!==null&&typeof G.componentDidCatch=="function"&&(e.callback=function(){CL(l,I),typeof t!="function"&&(mZ===null?mZ=new Set([this]):mZ.add(this));var c=I.stack;this.componentDidCatch(I.value,{componentStack:c!==null?c:""})}),e}function Bq(l,I,e){var t=l.pingCache;if(t===null){t=l.pingCache=new dCI;var a=new Set;t.set(I,a)}else a=t.get(I),a===void 0&&(a=new Set,t.set(I,a));a.has(e)||(a.add(e),l=VCI.bind(null,l,I,e),I.then(l,l))}function Sq(l){do{var I;if((I=l.tag===13)&&(I=l.memoizedState,I=I!==null?I.dehydrated!==null:!0),I)return l;l=l.return}while(l!==null);return null}function Tq(l,I,e,t,a){return l.mode&1?(l.flags|=65536,l.lanes=a,l):(l===I?l.flags|=65536:(l.flags|=128,e.flags|=131072,e.flags&=-52805,e.tag===1&&(e.alternate===null?e.tag=17:(I=Hs(-1,1),I.tag=2,sZ(e,I,1))),e.lanes|=1),l)}var bCI=gs.ReactCurrentOwner,kG=!1;function GG(l,I,e,t){I.child=l===null?dP(I,null,e,t):nN(I,l.child,e,t)}function jq(l,I,e,t,a){e=e.render;var G=I.ref;return eN(I,a),t=Y4(l,I,e,t,G,a),e=V4(),l!==null&&!kG?(I.updateQueue=l.updateQueue,I.flags&=-2053,l.lanes&=~a,Es(l,I,a)):(Ee&&e&&b4(I),I.flags|=1,GG(l,I,t,a),I.child)}function Kq(l,I,e,t,a){if(l===null){var G=e.type;return typeof G=="function"&&!y4(G)&&G.defaultProps===void 0&&e.compare===null&&e.defaultProps===void 0?(I.tag=15,I.type=G,JP(l,I,G,t,a)):(l=UH(e.type,null,t,I,I.mode,a),l.ref=I.ref,l.return=I,I.child=l)}if(G=l.child,!(l.lanes&a)){var c=G.memoizedProps;if(e=e.compare,e=e!==null?e:VV,e(c,t)&&l.ref===I.ref)return Es(l,I,a)}return I.flags|=1,l=rZ(G,t),l.ref=I.ref,l.return=I,I.child=l}function JP(l,I,e,t,a){if(l!==null){var G=l.memoizedProps;if(VV(G,t)&&l.ref===I.ref)if(kG=!1,I.pendingProps=t=G,(l.lanes&a)!==0)l.flags&131072&&(kG=!0);else return I.lanes=l.lanes,Es(l,I,a)}return JL(l,I,e,t,a)}function AP(l,I,e){var t=I.pendingProps,a=t.children,G=l!==null?l.memoizedState:null;if(t.mode==="hidden")if(!(I.mode&1))I.memoizedState={baseLanes:0,cachePool:null,transitions:null},ue(qi,rc),rc|=e;else{if(!(e&1073741824))return l=G!==null?G.baseLanes|e:e,I.lanes=I.childLanes=1073741824,I.memoizedState={baseLanes:l,cachePool:null,transitions:null},I.updateQueue=null,ue(qi,rc),rc|=l,null;I.memoizedState={baseLanes:0,cachePool:null,transitions:null},t=G!==null?G.baseLanes:e,ue(qi,rc),rc|=t}else G!==null?(t=G.baseLanes|e,I.memoizedState=null):t=e,ue(qi,rc),rc|=t;return GG(l,I,a,e),I.child}function LP(l,I){var e=I.ref;(l===null&&e!==null||l!==null&&l.ref!==e)&&(I.flags|=512,I.flags|=2097152)}function JL(l,I,e,t,a){var G=fG(e)?ko:ya.current;return G=GN(I,G),eN(I,a),e=Y4(l,I,e,t,G,a),t=V4(),l!==null&&!kG?(I.updateQueue=l.updateQueue,I.flags&=-2053,l.lanes&=~a,Es(l,I,a)):(Ee&&t&&b4(I),I.flags|=1,GG(l,I,e,a),I.child)}function Dq(l,I,e,t,a){if(fG(e)){var G=!0;PH(I)}else G=!1;if(eN(I,a),I.stateNode===null)xH(l,I),gP(I,e,t),yL(I,e,t,a),t=!0;else if(l===null){var c=I.stateNode,n=I.memoizedProps;c.props=n;var d=c.context,b=e.contextType;typeof b=="object"&&b!==null?b=$c(b):(b=fG(e)?ko:ya.current,b=GN(I,b));var m=e.getDerivedStateFromProps,Z=typeof m=="function"||typeof c.getSnapshotBeforeUpdate=="function";Z||typeof c.UNSAFE_componentWillReceiveProps!="function"&&typeof c.componentWillReceiveProps!="function"||(n!==t||d!==b)&&Oq(I,c,t,b),lZ=!1;var r=I.memoizedState;c.state=r,tQ(I,t,c,a),d=I.memoizedState,n!==t||r!==d||xG.current||lZ?(typeof m=="function"&&(gL(I,e,m,t),d=I.memoizedState),(n=lZ||Mq(I,e,n,t,r,d,b))?(Z||typeof c.UNSAFE_componentWillMount!="function"&&typeof c.componentWillMount!="function"||(typeo
`+I.stack):new Error(I.message+`
`+I.stack):I},0)}}addListener(I){return this.listeners.push(I),()=>{this._removeListener(I)}}emit(I){this.listeners.forEach(e=>{e(I)})}_removeListener(I){this.listeners.splice(this.listeners.indexOf(I),1)}setUnexpectedErrorHandler(I){this.unexpectedErrorHandler=I}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(I){this.unexpectedErrorHandler(I),this.emit(I)}onUnexpectedExternalError(I){this.unexpectedErrorHandler(I)}};ba.ErrorHandler=EQ;ba.errorHandler=new EQ;function fCI(l){i8(l)||ba.errorHandler.onUnexpectedError(l)}ba.onUnexpectedError=fCI;var f4="Canceled";function i8(l){return l instanceof gQ?!0:l instanceof Error&&l.name===f4&&l.message===f4}ba.isCancellationError=i8;var gQ=class extends Error{constructor(){super(f4),this.name=this.message}};ba.CancellationError=gQ;var RZ=class extends Error{constructor(I){super(I),this.name="CodeExpectedError"}static fromError(I){if(I instanceof RZ)return I;let e=new RZ;return e.message=I.message,e.stack=I.stack,e}static isErrorNoTelemetry(I){return I.name==="CodeExpectedError"}};ba.ErrorNoTelemetry=RZ;var tR=class extends Error{constructor(I){super(I||"An unexpected bug occurred."),Object.setPrototypeOf(this,tR.prototype)}};ba.BugIndicatingError=tR});var qo=w(oN=>{"use strict";s();Object.defineProperty(oN,"__esModule",{value:!0});oN.OffsetRangeSet=oN.OffsetRange=void 0;var z4=rN(),hc=class{static addRange(I,e){let t=0;for(;t<e.length&&e[t].endExclusive<I.start;)t++;let a=t;for(;a<e.length&&e[a].start<=I.endExclusive;)a++;if(t===a)e.splice(t,0,I);else{let G=Math.min(I.start,e[t].start),c=Math.max(I.endExclusive,e[a-1].endExclusive);e.splice(t,a-t,new hc(G,c))}}static tryCreate(I,e){if(!(I>e))return new hc(I,e)}static ofLength(I){return new hc(0,I)}constructor(I,e){if(this.start=I,this.endExclusive=e,I>e)throw new z4.BugIndicatingError(`Invalid range: ${this.toString()}`)}get isEmpty(){return this.start===this.endExclusive}delta(I){return new hc(this.start+I,this.endExclusive+I)}deltaStart(I){return new hc(this.start+I,this.endExclusive)}deltaEnd(I){return new hc(this.start,this.endExclusive+I)}get length(){return this.endExclusive-this.start}toString(){return`[${this.start}, ${this.endExclusive})`}equals(I){return this.start===I.start&&this.endExclusive===I.endExclusive}containsRange(I){return this.start<=I.start&&I.endExclusive<=this.endExclusive}contains(I){return this.start<=I&&I<this.endExclusive}join(I){return new hc(Math.min(this.start,I.start),Math.max(this.endExclusive,I.endExclusive))}intersect(I){let e=Math.max(this.start,I.start),t=Math.min(this.endExclusive,I.endExclusive);if(e<=t)return new hc(e,t)}slice(I){return I.slice(this.start,this.endExclusive)}clip(I){if(this.isEmpty)throw new z4.BugIndicatingError(`Invalid clipping range: ${this.toString()}`);return Math.max(this.start,Math.min(this.endExclusive-1,I))}clipCyclic(I){if(this.isEmpty)throw new z4.BugIndicatingError(`Invalid clipping range: ${this.toString()}`);return I<this.start?this.endExclusive-(this.start-I)%this.length:I>=this.endExclusive?this.start+(I-this.start)%this.length:I}};oN.OffsetRange=hc;var aR=class{constructor(){this._sortedRanges=[]}addRange(I){let e=0;for(;e<this._sortedRanges.length&&this._sortedRanges[e].endExclusive<I.start;)e++;let t=e;for(;t<this._sortedRanges.length&&this._sortedRanges[t].start<=I.endExclusive;)t++;if(e===t)this._sortedRanges.splice(e,0,I);else{let a=Math.min(I.start,this._sortedRanges[e].start),G=Math.max(I.endExclusive,this._sortedRanges[t-1].endExclusive);this._sortedRanges.splice(e,t-e,new hc(a,G))}}toString(){return this._sortedRanges.map(I=>I.toString()).join(", ")}intersectsStrict(I){let e=0;for(;e<this._sortedRanges.length&&this._sortedRanges[e].endExclusive<=I.start;)e++;return e<this._sortedRanges.length&&this._sortedRanges[e].start<I.endExclusive}intersectWithRange(I){let e=new aR;for(let t of this._sortedRanges){let a=t.intersect(I);a&&e.addRange(a)}return e}intersectWithRangeLength(I){return this.intersectWithRange(I).length}get length(){return this._sortedRanges.reduce((I,e)=>I+e.length,0)}};oN.OffsetRangeSet=aR});var U4=w(
`).length<=10||V.push(X)}let Y=YN.createOfSorted(I,h=>h.originalRange.endLineNumberExclusive,Yc.numberComparator);return V=V.filter(h=>{let F=Y.findLastItemBeforeOrEqual(h.original.startLineNumber)||new an.LineRangeMapping(new Gn.LineRange(1,1),new Gn.LineRange(1,1),[]),X=h.modified.startLineNumber-F.modifiedRange.endLineNumberExclusive,H=h.original.startLineNumber-F.originalRange.endLineNumberExclusive;return X!==H}),V.map(h=>{let F=this.refineDiff(e,t,new rR.SequenceDiff(h.original.toOffsetRange(),h.modified.toOffsetRange()),c,n),X=ok(F.mappings,e,t,!0);return new an.MovedText(h,X)})}refineDiff(I,e,t,a,G){let c=new uR(I,t.seq1Range,G),n=new uR(e,t.seq2Range,G),d=c.length+n.length<500?this.dynamicProgrammingDiffing.compute(c,n,a):this.myersDiffingAlgorithm.compute(c,n,a),b=d.diffs;return b=(0,ZR.optimizeSequenceDiffs)(c,n,b),b=pJI(c,n,b),b=(0,ZR.smoothenSequenceDiffs)(c,n,b),b=(0,ZR.removeRandomMatches)(c,n,b),{mappings:b.map(Z=>new an.RangeMapping(c.translateRange(Z.seq1Range),n.translateRange(Z.seq2Range))),hitTimeout:d.hitTimeout}}};La.AdvancedLinesDiffComputer=rk;var YN=class{static create(I,e,t){return I.sort((a,G)=>t(e(a),e(G))),new YN(I,e,t)}static createOfSorted(I,e,t){return new YN(I,e,t)}constructor(I,e,t){this._items=I,this._itemToDomain=e,this._domainComparator=t,this._currentIdx=0,this._lastValue=void 0,this._hasLastValue=!1}findLastItemBeforeOrEqual(I){if(this._hasLastValue&&Yc.CompareResult.isLessThan(this._domainComparator(I,this._lastValue)))throw new uJI.BugIndicatingError;for(this._lastValue=I,this._hasLastValue=!0;this._currentIdx<this._items.length&&Yc.CompareResult.isLessThanOrEqual(this._domainComparator(this._itemToDomain(this._items[this._currentIdx]),I));)this._currentIdx++;return this._currentIdx===0?void 0:this._items[this._currentIdx-1]}};function NJI(l,I){let e=[],t=0,a=0;for(;t<l.length&&a<I.length;){let G=l[t],c=I[a],n=G.intersect(c);n&&!n.isEmpty&&e.push(n),G.endLineNumberExclusive<c.endLineNumberExclusive?t++:a++}return e}var Iw=class{constructor(){this._normalizedRanges=[]}addRange(I){let e=U8(this._normalizedRanges.findIndex(a=>a.endLineNumberExclusive>=I.startLineNumber),this._normalizedRanges.length),t=(0,Yc.findLastIndex)(this._normalizedRanges,a=>a.startLineNumber<=I.endLineNumberExclusive)+1;if(e===t)this._normalizedRanges.splice(e,0,I);else if(e===t-1){let a=this._normalizedRanges[e];this._normalizedRanges[e]=a.join(I)}else{let a=this._normalizedRanges[e].join(this._normalizedRanges[t-1]).join(I);this._normalizedRanges.splice(e,t-e,a)}}intersects(I){for(let e of this._normalizedRanges)if(e.intersectsStrict(I))return!0;return!1}subtractFrom(I){let e=U8(this._normalizedRanges.findIndex(c=>c.endLineNumberExclusive>=I.startLineNumber),this._normalizedRanges.length),t=(0,Yc.findLastIndex)(this._normalizedRanges,c=>c.startLineNumber<=I.endLineNumberExclusive)+1;if(e===t)return[I];let a=[],G=I.startLineNumber;for(let c=e;c<t;c++){let n=this._normalizedRanges[c];n.startLineNumber>G&&a.push(new Gn.LineRange(G,n.startLineNumber)),G=n.endLineNumberExclusive}return G<I.endLineNumberExclusive&&a.push(new Gn.LineRange(G,I.endLineNumberExclusive)),a}};function U8(l,I){return l===-1?I:l}function pJI(l,I,e){let t=[],a;function G(){if(!a)return;let n=a.s1Range.length-a.deleted,d=a.s2Range.length-a.added;Math.max(a.deleted,a.added)+(a.count-1)>n&&t.push(new rR.SequenceDiff(a.s1Range,a.s2Range)),a=void 0}for(let n of e){let d=function(o,u){if(!a||!a.s1Range.containsRange(o)||!a.s2Range.containsRange(u))if(a&&!(a.s1Range.endExclusive<o.start&&a.s2Range.endExclusive<u.start)){let Y=EZ.OffsetRange.tryCreate(a.s1Range.endExclusive,o.start),p=EZ.OffsetRange.tryCreate(a.s2Range.endExclusive,u.start);a.deleted+=Y?.length??0,a.added+=p?.length??0,a.s1Range=a.s1Range.join(o),a.s2Range=a.s2Range.join(u)}else G(),a={added:0,deleted:0,count:0,s1Range:o,s2Range:u};let N=o.intersect(n.seq1Range),V=u.intersect(n.seq2Range);a.count++,a.deleted+=N?.length??0,a.added+=V?.length??0},b=l.findWordContaining(n.seq1Range.start-1),m=I.findWordContaining(n.seq2Range.start-1),Z=l.findWordContaining(n.seq1Range.endExclusive
`)}isStronglyEqual(I,e){return this.lines[I]===this.lines[e]}};La.LineSequence=oR;function M8(l){let I=0;for(;I<l.length&&(l.charCodeAt(I)===32||l.charCodeAt(I)===9);)I++;return I}var uR=class{constructor(I,e,t){this.lines=I,this.considerWhitespaceChanges=t,this.elements=[],this.firstCharOffsetByLineMinusOne=[],this.additionalOffsetByLine=[];let a=!1;e.start>0&&e.endExclusive>=I.length&&(e=new EZ.OffsetRange(e.start-1,e.endExclusive),a=!0),this.lineRange=e;for(let G=this.lineRange.start;G<this.lineRange.endExclusive;G++){let c=I[G],n=0;if(a)n=c.length,c="",a=!1;else if(!t){let d=c.trimStart();n=c.length-d.length,c=d.trimEnd()}this.additionalOffsetByLine.push(n);for(let d=0;d<c.length;d++)this.elements.push(c.charCodeAt(d));G<I.length-1&&(this.elements.push(`
`.charCodeAt(0)),this.firstCharOffsetByLineMinusOne[G-this.lineRange.start]=this.elements.length)}this.additionalOffsetByLine.push(0)}toString(){return`Slice: "${this.text}"`}get text(){return this.getText(new EZ.OffsetRange(0,this.length))}getText(I){return this.elements.slice(I.start,I.endExclusive).map(e=>String.fromCharCode(e)).join("")}getElement(I){return this.elements[I]}get length(){return this.elements.length}getBoundaryScore(I){let e=B8(I>0?this.elements[I-1]:-1),t=B8(I<this.elements.length?this.elements[I]:-1);if(e===6&&t===7)return 0;let a=0;return e!==t&&(a+=10,t===1&&(a+=1)),a+=O8(e),a+=O8(t),a}translateOffset(I){if(this.lineRange.isEmpty)return new z8.Position(this.lineRange.start+1,1);let e=0,t=this.firstCharOffsetByLineMinusOne.length;for(;e<t;){let G=Math.floor((e+t)/2);this.firstCharOffsetByLineMinusOne[G]>I?t=G:e=G+1}let a=e===0?0:this.firstCharOffsetByLineMinusOne[e-1];return new z8.Position(this.lineRange.start+e+1,I-a+1+this.additionalOffsetByLine[e])}translateRange(I){return Zk.Range.fromPositions(this.translateOffset(I.start),this.translateOffset(I.endExclusive))}findWordContaining(I){if(I<0||I>=this.elements.length||!sk(this.elements[I]))return;let e=I;for(;e>0&&sk(this.elements[e-1]);)e--;let t=I;for(;t<this.elements.length&&sk(this.elements[t]);)t++;return new EZ.OffsetRange(e,t)}countLinesIn(I){return this.translateOffset(I.endExclusive).lineNumber-this.translateOffset(I.start).lineNumber}isStronglyEqual(I,e){return this.elements[I]===this.elements[e]}extendToFullLines(I){let e=j8(this.firstCharOffsetByLineMinusOne,a=>a<=I.start)??0,t=K8(this.firstCharOffsetByLineMinusOne,a=>I.endExclusive<=a)??this.elements.length;return new EZ.OffsetRange(e,t)}};La.LinesSliceCharSequence=uR;function VJI(l,I){let e=0,t=l.length;for(;e<t;){let a=Math.floor((e+t)/2);I(l[a])?e=a+1:t=a}return e-1}function j8(l,I){let e=VJI(l,I);return e===-1?void 0:l[e]}La.findLastMonotonous=j8;function RJI(l,I){let e=0,t=l.length;for(;e<t;){let a=Math.floor((e+t)/2);I(l[a])?t=a:e=a+1}return e}function K8(l,I){let e=RJI(l,I);return e===l.length?void 0:l[e]}La.findFirstMonotonous=K8;function sk(l){return l>=97&&l<=122||l>=65&&l<=90||l>=48&&l<=57}var FJI={[0]:0,[1]:0,[2]:0,[3]:10,[4]:2,[5]:3,[6]:10,[7]:10};function O8(l){return FJI[l]}function B8(l){return l===10?7:l===13?6:XJI(l)?5:l>=97&&l<=122?0:l>=65&&l<=90?1:l>=48&&l<=57?2:l===-1?3:4}function XJI(l){return l===32||l===9}var mk=new Map;function S8(l){let I=mk.get(l);return I===void 0&&(I=mk.size,mk.set(l,I)),I}var lw=class{constructor(I,e,t){this.range=I,this.lines=e,this.source=t,this.histogram=[];let a=0;for(let G=I.startLineNumber-1;G<I.endLineNumberExclusive-1;G++){let c=e[G];for(let d=0;d<c.length;d++){a++;let b=c[d],m=S8(b);this.histogram[m]=(this.histogram[m]||0)+1}a++;let n=S8(`
`);this.histogram[n]=(this.histogram[n]||0)+1}this.totalCount=a}computeSimilarity(I){let e=0,t=Math.max(this.histogram.length,I.histogram.length);for(let a=0;a<t;a++)e+=Math.abs((this.histogram[a]??0)-(I.histogram[a]??0));return 1-e/(this.totalCount+I.totalCount)}}});var _8=w(Gd=>{"use strict";s();var HJI=Gd&&Gd.__createBinding||(Object.create?function(l,I,e,t){t===void 0&&(t=e);var a=Object.getOwnPropertyDescriptor(I,e);(!a||("get"in a?!I.__esModule:a.writable||a.configurable))&&(a={enumerable:!0,get:function(){return I[e]}}),Object.defineProperty(l,t,a)}:function(l,I,e,t){t===void 0&&(t=e),l[t]=I[e]}),WR=Gd&&Gd.__exportStar||function(l,I){for(var e in l)e!=="default"&&!Object.prototype.hasOwnProperty.call(I,e)&&HJI(I,l,e)};Object.defineProperty(Gd,"__esModule",{value:!0});WR(xQ(),Gd);WR(D4(),Gd);WR(K4(),Gd);WR(w8(),Gd);WR(D8(),Gd)});var TII=w((QFl,SII)=>{s();var uLI="Expected a function",OII=NaN,WLI="[object Symbol]",iLI=/^\s+|\s+$/g,NLI=/^[-+]0x[0-9a-f]+$/i,pLI=/^0b[01]+$/i,hLI=/^0o[0-7]+$/i,YLI=parseInt,VLI=typeof global=="object"&&global&&global.Object===Object&&global,RLI=typeof self=="object"&&self&&self.Object===Object&&self,FLI=VLI||RLI||Function("return this")(),XLI=Object.prototype,HLI=XLI.toString,QLI=Math.max,wLI=Math.min,_3=function(){return FLI.Date.now()};function vLI(l,I,e){var t,a,G,c,n,d,b=0,m=!1,Z=!1,r=!0;if(typeof l!="function")throw new TypeError(uLI);I=BII(I)||0,q3(e)&&(m=!!e.leading,Z="maxWait"in e,G=Z?QLI(BII(e.maxWait)||0,I):G,r="trailing"in e?!!e.trailing:r);function o(H){var Q=t,E=a;return t=a=void 0,b=H,c=l.apply(E,Q),c}function u(H){return b=H,n=setTimeout(Y,I),m?o(H):c}function N(H){var Q=H-d,E=H-b,C=I-Q;return Z?wLI(C,G-E):C}function V(H){var Q=H-d,E=H-b;return d===void 0||Q>=I||Q<0||Z&&E>=G}function Y(){var H=_3();if(V(H))return p(H);n=setTimeout(Y,N(H))}function p(H){return n=void 0,r&&t?o(H):(t=a=void 0,c)}function h(){n!==void 0&&clearTimeout(n),b=0,t=d=a=n=void 0}function F(){return n===void 0?c:p(_3())}function X(){var H=_3(),Q=V(H);if(t=arguments,a=this,d=H,Q){if(n===void 0)return u(d);if(Z)return n=setTimeout(Y,I),o(d)}return n===void 0&&(n=setTimeout(Y,I)),c}return X.cancel=h,X.flush=F,X}function q3(l){var I=typeof l;return!!l&&(I=="object"||I=="function")}function ELI(l){return!!l&&typeof l=="object"}function gLI(l){return typeof l=="symbol"||ELI(l)&&HLI.call(l)==WLI}function BII(l){if(typeof l=="number")return l;if(gLI(l))return OII;if(q3(l)){var I=typeof l.valueOf=="function"?l.valueOf():l;l=q3(I)?I+"":I}if(typeof l!="string")return l===0?l:+l;l=l.replace(iLI,"");var e=pLI.test(l);return e||hLI.test(l)?YLI(l.slice(2),e?2:8):NLI.test(l)?OII:+l}SII.exports=vLI});var bx=w((J2,Ep)=>{s();var yLI=200,dx="__lodash_hash_undefined__",Mv=1,alI=2,GlI=9007199254740991,Av="[object Arguments]",lx="[object Array]",CLI="[object AsyncFunction]",clI="[object Boolean]",nlI="[object Date]",dlI="[object Error]",blI="[object Function]",JLI="[object GeneratorFunction]",Lv="[object Map]",slI="[object Number]",ALI="[object Null]",vp="[object Object]",jII="[object Promise]",LLI="[object Proxy]",mlI="[object RegExp]",kv="[object Set]",ZlI="[object String]",kLI="[object Symbol]",xLI="[object Undefined]",ex="[object WeakMap]",rlI="[object ArrayBuffer]",xv="[object DataView]",fLI="[object Float32Array]",zLI="[object Float64Array]",ULI="[object Int8Array]",MLI="[object Int16Array]",OLI="[object Int32Array]",BLI="[object Uint8Array]",SLI="[object Uint8ClampedArray]",TLI="[object Uint16Array]",jLI="[object Uint32Array]",KLI=/[\\^$.*+?()[\]{}|]/g,DLI=/^\[object .+?Constructor\]$/,_LI=/^(?:0|[1-9]\d*)$/,Re={};Re[fLI]=Re[zLI]=Re[ULI]=Re[MLI]=Re[OLI]=Re[BLI]=Re[SLI]=Re[TLI]=Re[jLI]=!0;Re[Av]=Re[lx]=Re[rlI]=Re[clI]=Re[xv]=Re[nlI]=Re[dlI]=Re[blI]=Re[Lv]=Re[slI]=Re[vp]=Re[mlI]=Re[kv]=Re[ZlI]=Re[ex]=!1;var olI=typeof global=="object"&&global&&global.Object===Object&&global,qLI=typeof self=="object"&&self&&self.Object===Object&&self,$s=olI||qLI||Function("return this")(),ulI=typeof J2=="object"&&J2&&!J2.nodeType&&J2,KII=ulI&&typeof Ep=="object"&&Ep&&!Ep.nodeType&&Ep,WlI=KII&&KII.exports===ulI,P3=WlI&&olI.process,DII=f
?|
|(?![\\s\\S])))+`,"m"),alias:G,inside:{line:{pattern:/(.)(?=[\s\S]).*(?:\r\n?|\n)?/,lookbehind:!0},prefix:{pattern:/[\s\S]/,alias:/\w+/.exec(t)[0]}}}}),Object.defineProperty(I.languages.diff,"PREFIXES",{value:e})})(l)}});var hG=w((NLl,fmI)=>{"use strict";s();fmI.exports=gU;gU.displayName="markupTemplating";gU.aliases=[];function gU(l){(function(I){function e(t,a){return"___"+t.toUpperCase()+a+"___"}Object.defineProperties(I.languages["markup-templating"]={},{buildPlaceholders:{value:function(t,a,G,c){if(t.language===a){var n=t.tokenStack=[];t.code=t.code.replace(G,function(d){if(typeof c=="function"&&!c(d))return d;for(var b=n.length,m;t.code.indexOf(m=e(a,b))!==-1;)++b;return n[b]=d,m}),t.grammar=I.languages.markup}}},tokenizePlaceholders:{value:function(t,a){if(t.language!==a||!t.tokenStack)return;t.grammar=I.languages[a];var G=0,c=Object.keys(t.tokenStack);function n(d){for(var b=0;b<d.length&&!(G>=c.length);b++){var m=d[b];if(typeof m=="string"||m.content&&typeof m.content=="string"){var Z=c[G],r=t.tokenStack[Z],o=typeof m=="string"?m:m.content,u=e(a,Z),N=o.indexOf(u);if(N>-1){++G;var V=o.substring(0,N),Y=new I.Token(a,I.tokenize(r,t.grammar),"language-"+a,r),p=o.substring(N+u.length),h=[];V&&h.push.apply(h,n([V])),h.push(Y),p&&h.push.apply(h,n([p])),typeof m=="string"?d.splice.apply(d,[b,1].concat(h)):m.content=h}}else m.content&&n(m.content)}return d}n(t.tokens)}}})})(l)}});var UmI=w((hLl,zmI)=>{"use strict";s();var HBI=hG();zmI.exports=yU;yU.displayName="django";yU.aliases=["jinja2"];function yU(l){l.register(HBI),function(I){I.languages.django={comment:/^\{#[\s\S]*?#\}$/,tag:{pattern:/(^\{%[+-]?\s*)\w+/,lookbehind:!0,alias:"keyword"},delimiter:{pattern:/^\{[{%][+-]?|[+-]?[}%]\}$/,alias:"punctuation"},string:{pattern:/("|')(?:\\.|(?!\1)[^\\\r\n])*\1/,greedy:!0},filter:{pattern:/(\|)\w+/,lookbehind:!0,alias:"function"},test:{pattern:/(\bis\s+(?:not\s+)?)(?!not\b)\w+/,lookbehind:!0,alias:"function"},function:/\b[a-z_]\w+(?=\s*\()/i,keyword:/\b(?:and|as|by|else|for|if|import|in|is|loop|not|or|recursive|with|without)\b/,operator:/[-+%=]=?|!=|\*\*?=?|\/\/?=?|<[<=>]?|>[=>]?|[&|^~]/,number:/\b\d+(?:\.\d+)?\b/,boolean:/[Ff]alse|[Nn]one|[Tt]rue/,variable:/\b\w+\b/,punctuation:/[{}[\](),.:;]/};var e=/\{\{[\s\S]*?\}\}|\{%[\s\S]*?%\}|\{#[\s\S]*?#\}/g,t=I.languages["markup-templating"];I.hooks.add("before-tokenize",function(a){t.buildPlaceholders(a,"django",e)}),I.hooks.add("after-tokenize",function(a){t.tokenizePlaceholders(a,"django")}),I.languages.jinja2=I.languages.django,I.hooks.add("before-tokenize",function(a){t.buildPlaceholders(a,"jinja2",e)}),I.hooks.add("after-tokenize",function(a){t.tokenizePlaceholders(a,"jinja2")})}(l)}});var OmI=w((VLl,MmI)=>{"use strict";s();MmI.exports=CU;CU.displayName="dnsZoneFile";CU.aliases=[];function CU(l){l.languages["dns-zone-file"]={comment:/;.*/,string:{pattern:/"(?:\\.|[^"\\\r\n])*"/,greedy:!0},variable:[{pattern:/(^\$ORIGIN[ \t]+)\S+/m,lookbehind:!0},{pattern:/(^|\s)@(?=\s|$)/,lookbehind:!0}],keyword:/^\$(?:INCLUDE|ORIGIN|TTL)(?=\s|$)/m,class:{pattern:/(^|\s)(?:CH|CS|HS|IN)(?=\s|$)/,lookbehind:!0,alias:"keyword"},type:{pattern:/(^|\s)(?:A|A6|AAAA|AFSDB|APL|ATMA|CAA|CDNSKEY|CDS|CERT|CNAME|DHCID|DLV|DNAME|DNSKEY|DS|EID|GID|GPOS|HINFO|HIP|IPSECKEY|ISDN|KEY|KX|LOC|MAILA|MAILB|MB|MD|MF|MG|MINFO|MR|MX|NAPTR|NB|NBSTAT|NIMLOC|NINFO|NS|NSAP|NSAP-PTR|NSEC|NSEC3|NSEC3PARAM|NULL|NXT|OPENPGPKEY|PTR|PX|RKEY|RP|RRSIG|RT|SIG|SINK|SMIMEA|SOA|SPF|SRV|SSHFP|TA|TKEY|TLSA|TSIG|TXT|UID|UINFO|UNSPEC|URI|WKS|X25)(?=\s|$)/,lookbehind:!0,alias:"keyword"},punctuation:/[()]/},l.languages["dns-zone"]=l.languages["dns-zone-file"]}});var SmI=w((FLl,BmI)=>{"use strict";s();BmI.exports=JU;JU.displayName="docker";JU.aliases=["dockerfile"];function JU(l){(function(I){var e=/\\[\r\n](?:\s|\\[\r\n]|#.*(?!.))*(?![\s#]|\\[\r\n])/.source,t=/(?:[ \t]+(?![ \t])(?:<SP_BS>)?|<SP_BS>)/.source.replace(/<SP_BS>/g,function(){return e}),a=/"(?:[^"\\\r\n]|\\(?:\r\n|[\s\S]))*"|'(?:[^'\\\r\n]|\\(?:\r\n|[\s\S]))*'/.source,G=/--[\w-]+=(?:<STR>|(?!["'])(?:[^\s\\]|\\.)+)/.source.replace(/<STR>/g,function(){return a}),c={pattern:RegExp(
]))(?:`+(/[^\s\\]/.source+'|[ ]+(?:(?![ "])|'+t+")|"+/\\[\r\n]+(?:[#;].*[\r\n]+)*(?![#;])/.source)+")*"),lookbehind:!0,greedy:!0,alias:"attr-value",inside:{comment:e,quoted:{pattern:RegExp(/(^|\s)/.source+t),lookbehind:!0,greedy:!0},punctuation:/\\$/m,boolean:{pattern:/^(?:false|no|off|on|true|yes)$/,greedy:!0}}},punctuation:/=/}})(l)}});var Pg=w((K9l,aNI)=>{"use strict";s();aNI.exports=DB;DB.displayName="t4Templating";DB.aliases=[];function DB(l){(function(I){function e(a,G,c){return{pattern:RegExp("<#"+a+"[\\s\\S]*?#>"),alias:"block",inside:{delimiter:{pattern:RegExp("^<#"+a+"|#>$"),alias:"important"},content:{pattern:/[\s\S]+/,inside:G,alias:c}}}}function t(a){var G=I.languages[a],c="language-"+a;return{block:{pattern:/<#[\s\S]+?#>/,inside:{directive:e("@",{"attr-value":{pattern:/=(?:("|')(?:\\[\s\S]|(?!\1)[^\\])*\1|[^\s'">=]+)/,inside:{punctuation:/^=|^["']|["']$/}},keyword:/\b\w+(?=\s)/,"attr-name":/\b\w+/}),expression:e("=",G,c),"class-feature":e("\\+",G,c),standard:e("",G,c)}}}}I.languages["t4-templating"]=Object.defineProperty({},"createT4",{value:t})})(l)}});var cNI=w((_9l,GNI)=>{"use strict";s();var dSI=Pg(),bSI=MF();GNI.exports=_B;_B.displayName="t4Cs";_B.aliases=[];function _B(l){l.register(dSI),l.register(bSI),l.languages.t4=l.languages["t4-cs"]=l.languages["t4-templating"].createT4("csharp")}});var PB=w((P9l,nNI)=>{"use strict";s();var sSI=Pz();nNI.exports=qB;qB.displayName="vbnet";qB.aliases=[];function qB(l){l.register(sSI),l.languages.vbnet=l.languages.extend("basic",{comment:[{pattern:/(?:!|REM\b).+/i,inside:{keyword:/^REM/i}},{pattern:/(^|[^\\:])'.*/,lookbehind:!0,greedy:!0}],string:{pattern:/(^|[^"])"(?:""|[^"])*"(?!")/,lookbehind:!0,greedy:!0},keyword:/(?:\b(?:ADDHANDLER|ADDRESSOF|ALIAS|AND|ANDALSO|AS|BEEP|BLOAD|BOOLEAN|BSAVE|BYREF|BYTE|BYVAL|CALL(?: ABSOLUTE)?|CASE|CATCH|CBOOL|CBYTE|CCHAR|CDATE|CDBL|CDEC|CHAIN|CHAR|CHDIR|CINT|CLASS|CLEAR|CLNG|CLOSE|CLS|COBJ|COM|COMMON|CONST|CONTINUE|CSBYTE|CSHORT|CSNG|CSTR|CTYPE|CUINT|CULNG|CUSHORT|DATA|DATE|DECIMAL|DECLARE|DEF(?: FN| SEG|DBL|INT|LNG|SNG|STR)|DEFAULT|DELEGATE|DIM|DIRECTCAST|DO|DOUBLE|ELSE|ELSEIF|END|ENUM|ENVIRON|ERASE|ERROR|EVENT|EXIT|FALSE|FIELD|FILES|FINALLY|FOR(?: EACH)?|FRIEND|FUNCTION|GET|GETTYPE|GETXMLNAMESPACE|GLOBAL|GOSUB|GOTO|HANDLES|IF|IMPLEMENTS|IMPORTS|IN|INHERITS|INPUT|INTEGER|INTERFACE|IOCTL|IS|ISNOT|KEY|KILL|LET|LIB|LIKE|LINE INPUT|LOCATE|LOCK|LONG|LOOP|LSET|ME|MKDIR|MOD|MODULE|MUSTINHERIT|MUSTOVERRIDE|MYBASE|MYCLASS|NAME|NAMESPACE|NARROWING|NEW|NEXT|NOT|NOTHING|NOTINHERITABLE|NOTOVERRIDABLE|OBJECT|OF|OFF|ON(?: COM| ERROR| KEY| TIMER)?|OPEN|OPERATOR|OPTION(?: BASE)?|OPTIONAL|OR|ORELSE|OUT|OVERLOADS|OVERRIDABLE|OVERRIDES|PARAMARRAY|PARTIAL|POKE|PRIVATE|PROPERTY|PROTECTED|PUBLIC|PUT|RAISEEVENT|READ|READONLY|REDIM|REM|REMOVEHANDLER|RESTORE|RESUME|RETURN|RMDIR|RSET|RUN|SBYTE|SELECT(?: CASE)?|SET|SHADOWS|SHARED|SHELL|SHORT|SINGLE|SLEEP|STATIC|STEP|STOP|STRING|STRUCTURE|SUB|SWAP|SYNCLOCK|SYSTEM|THEN|THROW|TIMER|TO|TROFF|TRON|TRUE|TRY|TRYCAST|TYPE|TYPEOF|UINTEGER|ULONG|UNLOCK|UNTIL|USHORT|USING|VIEW PRINT|WAIT|WEND|WHEN|WHILE|WIDENING|WITH|WITHEVENTS|WRITE|WRITEONLY|XOR)|\B(?:#CONST|#ELSE|#ELSEIF|#END|#IF))(?:\$|\b)/i,punctuation:/[,;:(){}]/})}});var bNI=w((Izl,dNI)=>{"use strict";s();var mSI=Pg(),ZSI=PB();dNI.exports=$B;$B.displayName="t4Vb";$B.aliases=[];function $B(l){l.register(mSI),l.register(ZSI),l.languages["t4-vb"]=l.languages["t4-templating"].createT4("vbnet")}});var lS=w((ezl,sNI)=>{"use strict";s();sNI.exports=IS;IS.displayName="yaml";IS.aliases=["yml"];function IS(l){(function(I){var e=/[*&][^\s[\]{},]+/,t=/!(?:<[\w\-%#;/?:@&=+$,.!~*'()[\]]+>|(?:[a-zA-Z\d-]*!)?[\w\-%#;/?:@&=+$.~*'()]+)?/,a="(?:"+t.source+"(?:[ ]+"+e.source+")?|"+e.source+"(?:[ ]+"+t.source+")?)",G=/(?:[^\s\x00-\x08\x0e-\x1f!"#%&'*,\-:>?@[\]`{|}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]|[?:-]<PLAIN>)(?:[ \t]*(?:(?![#:])<PLAIN>|:<PLAIN>))*/.source.replace(/<PLAIN>/g,function(){return/[^\s\x00-\x08\x0e-\x1f,[\]{}\x7f-\x84\x86-\x9f\ud800-\udfff\ufffe\uffff]/.source}),c=/"(?:[^"\\\r\n]|\\.)*"|'(?:[^'\\\r\n]|\\.)*'/.source;function n(d,b){b=(b||"").replace(/m/g,
`:`
`.charCodeAt(),e=typeof l=="string"?"\r":"\r".charCodeAt();return l[l.length-1]===I&&(l=l.slice(0,l.length-1)),l[l.length-1]===e&&(l=l.slice(0,l.length-1)),l}});var _VI=w((xTl,i0)=>{"use strict";s();var W0=require("path"),KVI=JT(),DVI=l=>{l={cwd:process.cwd(),path:process.env[KVI()],execPath:process.execPath,...l};let I,e=W0.resolve(l.cwd),t=[];for(;I!==e;)t.push(W0.join(e,"node_modules/.bin")),I=e,e=W0.resolve(e,"..");let a=W0.resolve(l.cwd,l.execPath,"..");return t.push(a),t.concat(l.path).join(W0.delimiter)};i0.exports=DVI;i0.exports.default=DVI;i0.exports.env=l=>{l={env:process.env,...l};let I={...l.env},e=KVI({env:I});return l.path=I[e],I[e]=i0.exports(l),I}});var PVI=w((zTl,OT)=>{"use strict";s();var qVI=(l,I)=>{for(let e of Reflect.ownKeys(I))Object.defineProperty(l,e,Object.getOwnPropertyDescriptor(I,e));return l};OT.exports=qVI;OT.exports.default=qVI});var IRI=w((MTl,Ly)=>{"use strict";s();var IDI=PVI(),Ay=new WeakMap,$VI=(l,I={})=>{if(typeof l!="function")throw new TypeError("Expected a function");let e,t=0,a=l.displayName||l.name||"<anonymous>",G=function(...c){if(Ay.set(G,++t),t===1)e=l.apply(this,c),l=null;else if(I.throw===!0)throw new Error(`Function \`${a}\` can only be called once`);return e};return IDI(G,l),Ay.set(G,t),G};Ly.exports=$VI;Ly.exports.default=$VI;Ly.exports.callCount=l=>{if(!Ay.has(l))throw new Error(`The given function \`${l.name}\` is not wrapped by the \`onetime\` package`);return Ay.get(l)}});var lRI=w(ky=>{"use strict";s();Object.defineProperty(ky,"__esModule",{value:!0});ky.SIGNALS=void 0;var lDI=[{name:"SIGHUP",number:1,action:"terminate",description:"Terminal closed",standard:"posix"},{name:"SIGINT",number:2,action:"terminate",description:"User interruption with CTRL-C",standard:"ansi"},{name:"SIGQUIT",number:3,action:"core",description:"User interruption with CTRL-\\",standard:"posix"},{name:"SIGILL",number:4,action:"core",description:"Invalid machine instruction",standard:"ansi"},{name:"SIGTRAP",number:5,action:"core",description:"Debugger breakpoint",standard:"posix"},{name:"SIGABRT",number:6,action:"core",description:"Aborted",standard:"ansi"},{name:"SIGIOT",number:6,action:"core",description:"Aborted",standard:"bsd"},{name:"SIGBUS",number:7,action:"core",description:"Bus error due to misaligned, non-existing address or paging error",standard:"bsd"},{name:"SIGEMT",number:7,action:"terminate",description:"Command should be emulated but is not implemented",standard:"other"},{name:"SIGFPE",number:8,action:"core",description:"Floating point arithmetic error",standard:"ansi"},{name:"SIGKILL",number:9,action:"terminate",description:"Forced termination",standard:"posix",forced:!0},{name:"SIGUSR1",number:10,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGSEGV",number:11,action:"core",description:"Segmentation fault",standard:"ansi"},{name:"SIGUSR2",number:12,action:"terminate",description:"Application-specific signal",standard:"posix"},{name:"SIGPIPE",number:13,action:"terminate",description:"Broken pipe or socket",standard:"posix"},{name:"SIGALRM",number:14,action:"terminate",description:"Timeout or timer",standard:"posix"},{name:"SIGTERM",number:15,action:"terminate",description:"Termination",standard:"ansi"},{name:"SIGSTKFLT",number:16,action:"terminate",description:"Stack is empty or overflowed",standard:"other"},{name:"SIGCHLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"posix"},{name:"SIGCLD",number:17,action:"ignore",description:"Child process terminated, paused or unpaused",standard:"other"},{name:"SIGCONT",number:18,action:"unpause",description:"Unpaused",standard:"posix",forced:!0},{name:"SIGSTOP",number:19,action:"pause",description:"Paused",standard:"posix",forced:!0},{name:"SIGTSTP",number:20,action:"pause",description:'Paused using CTRL-Z or "suspend"',standard:"posix"},{name:"SIGTTIN",number:21,action:"pause",description:"Background process cannot read terminal input",standard:"posix"},{name:"SIGBREAK",number:21,action:"terminate",description:"User interruption with CTRL-BREAK",st
${t.message}`:N,p=[Y,I,l].filter(Boolean).join(`
`);return V?(t.originalMessage=t.message,t.message=p):t=new Error(p),t.shortMessage=Y,t.command=c,t.escapedCommand=n,t.exitCode=G,t.signal=a,t.signalDescription=r,t.stdout=l,t.stderr=I,e!==void 0&&(t.all=e),"bufferedData"in t&&delete t.bufferedData,t.failed=!0,t.timedOut=Boolean(d),t.isCanceled=b,t.killed=m&&!d,t};nRI.exports=hDI});var sRI=w((Ijl,ST)=>{"use strict";s();var fy=["stdin","stdout","stderr"],YDI=l=>fy.some(I=>l[I]!==void 0),bRI=l=>{if(!l)return;let{stdio:I}=l;if(I===void 0)return fy.map(t=>l[t]);if(YDI(l))throw new Error(`It's not possible to provide \`stdio\` in combination with one of ${fy.map(t=>`\`${t}\``).join(", ")}`);if(typeof I=="string")return I;if(!Array.isArray(I))throw new TypeError(`Expected \`stdio\` to be of type \`string\` or \`Array\`, got \`${typeof I}\``);let e=Math.max(I.length,fy.length);return Array.from({length:e},(t,a)=>I[a])};ST.exports=bRI;ST.exports.node=l=>{let I=bRI(l);return I==="ipc"?"ipc":I===void 0||typeof I=="string"?[I,I,I,"ipc"]:I.includes("ipc")?I:[...I,"ipc"]}});var mRI=w((ejl,zy)=>{s();zy.exports=["SIGABRT","SIGALRM","SIGHUP","SIGINT","SIGTERM"];process.platform!=="win32"&&zy.exports.push("SIGVTALRM","SIGXCPU","SIGXFSZ","SIGUSR2","SIGTRAP","SIGSYS","SIGQUIT","SIGIOT");process.platform==="linux"&&zy.exports.push("SIGIO","SIGPOLL","SIGPWR","SIGSTKFLT","SIGUNUSED")});var WRI=w((ajl,Bh)=>{s();var ke=global.process,OW=function(l){return l&&typeof l=="object"&&typeof l.removeListener=="function"&&typeof l.emit=="function"&&typeof l.reallyExit=="function"&&typeof l.listeners=="function"&&typeof l.kill=="function"&&typeof l.pid=="number"&&typeof l.on=="function"};OW(ke)?(ZRI=require("assert"),Mh=mRI(),rRI=/^win/i.test(ke.platform),N0=require("events"),typeof N0!="function"&&(N0=N0.EventEmitter),ke.__signal_exit_emitter__?Dt=ke.__signal_exit_emitter__:(Dt=ke.__signal_exit_emitter__=new N0,Dt.count=0,Dt.emitted={}),Dt.infinite||(Dt.setMaxListeners(1/0),Dt.infinite=!0),Bh.exports=function(l,I){if(!OW(global.process))return function(){};ZRI.equal(typeof l,"function","a callback must be provided for exit handler"),Oh===!1&&TT();var e="exit";I&&I.alwaysLast&&(e="afterexit");var t=function(){Dt.removeListener(e,l),Dt.listeners("exit").length===0&&Dt.listeners("afterexit").length===0&&Uy()};return Dt.on(e,l),t},Uy=function(){!Oh||!OW(global.process)||(Oh=!1,Mh.forEach(function(I){try{ke.removeListener(I,My[I])}catch{}}),ke.emit=Oy,ke.reallyExit=jT,Dt.count-=1)},Bh.exports.unload=Uy,BW=function(I,e,t){Dt.emitted[I]||(Dt.emitted[I]=!0,Dt.emit(I,e,t))},My={},Mh.forEach(function(l){My[l]=function(){if(OW(global.process)){var e=ke.listeners(l);e.length===Dt.count&&(Uy(),BW("exit",null,l),BW("afterexit",null,l),rRI&&l==="SIGHUP"&&(l="SIGINT"),ke.kill(ke.pid,l))}}}),Bh.exports.signals=function(){return Mh},Oh=!1,TT=function(){Oh||!OW(global.process)||(Oh=!0,Dt.count+=1,Mh=Mh.filter(function(I){try{return ke.on(I,My[I]),!0}catch{return!1}}),ke.emit=uRI,ke.reallyExit=oRI)},Bh.exports.load=TT,jT=ke.reallyExit,oRI=function(I){OW(global.process)&&(ke.exitCode=I||0,BW("exit",ke.exitCode,null),BW("afterexit",ke.exitCode,null),jT.call(ke,ke.exitCode))},Oy=ke.emit,uRI=function(I,e){if(I==="exit"&&OW(global.process)){e!==void 0&&(ke.exitCode=e);var t=Oy.apply(this,arguments);return BW("exit",ke.exitCode,null),BW("afterexit",ke.exitCode,null),t}else return Oy.apply(this,arguments)}):Bh.exports=function(){return function(){}};var ZRI,Mh,rRI,N0,Dt,Uy,BW,My,Oh,TT,jT,oRI,Oy,uRI});var NRI=w((cjl,iRI)=>{"use strict";s();var VDI=require("os"),RDI=WRI(),FDI=1e3*5,XDI=(l,I="SIGTERM",e={})=>{let t=l(I);return HDI(l,I,e,t),t},HDI=(l,I,e,t)=>{if(!QDI(I,e,t))return;let a=vDI(e),G=setTimeout(()=>{l("SIGKILL")},a);G.unref&&G.unref()},QDI=(l,{forceKillAfterTimeout:I},e)=>wDI(l)&&I!==!1&&e,wDI=l=>l===VDI.constants.signals.SIGTERM||typeof l=="string"&&l.toUpperCase()==="SIGTERM",vDI=({forceKillAfterTimeout:l=!0})=>{if(l===!0)return FDI;if(!Number.isFinite(l)||l<0)throw new TypeError(`Expected the \`forceKillAfterTimeout\` option to be a non-negative integer, got \`${l}\` (${typeof l})`);return l},EDI=(l,I)=>{l.kill()&&(I
`).filter(t=>Boolean(t))){let[t,...a]=e.split("=");I[t]=a.join("=")}return I}});var ej,qRI,Ky,PRI,$RI,gd,kc,Y0,es,yd,Dy,H_I,Q_I,w_I,bo,v_I,I2I,jW,_y,l2I,E_I,g_I,y_I,tj,C_I,qy,J_I,Py,$y,I1,e2I,t2I,a2I,A_I,L_I,k_I,aj,x_I,Gj,f_I,cj,z_I,U_I,M_I,O_I,B_I,S_I,T_I,nj,j_I,l1,e1,t1,G2I,K_I,dj,D_I,__I,q_I,bj,a1,Ajl,P_I,$_I,c2I,IqI,lqI,eqI,tqI,aqI,GqI,cqI,nqI,dqI,bqI,sj,sqI,mqI,ZqI,rqI,Ljl,kjl,xjl,fjl,zjl,Ujl,TW,G1=tG(()=>{s();RG();ej="2024-11-05",qRI=[ej,"2024-10-07"],Ky="2.0",PRI=v.union([v.string(),v.number().int()]),$RI=v.string(),gd=v.object({_meta:v.optional(v.object({progressToken:v.optional(PRI)}).passthrough())}).passthrough(),kc=v.object({method:v.string(),params:v.optional(gd)}),Y0=v.object({_meta:v.optional(v.object({}).passthrough())}).passthrough(),es=v.object({method:v.string(),params:v.optional(Y0)}),yd=v.object({_meta:v.optional(v.object({}).passthrough())}).passthrough(),Dy=v.union([v.string(),v.number().int()]),H_I=v.object({jsonrpc:v.literal(Ky),id:Dy}).merge(kc).strict(),Q_I=v.object({jsonrpc:v.literal(Ky)}).merge(es).strict(),w_I=v.object({jsonrpc:v.literal(Ky),id:Dy,result:yd}).strict();(function(l){l[l.ConnectionClosed=-32e3]="ConnectionClosed",l[l.RequestTimeout=-32001]="RequestTimeout",l[l.ParseError=-32700]="ParseError",l[l.InvalidRequest=-32600]="InvalidRequest",l[l.MethodNotFound=-32601]="MethodNotFound",l[l.InvalidParams=-32602]="InvalidParams",l[l.InternalError=-32603]="InternalError"})(bo||(bo={}));v_I=v.object({jsonrpc:v.literal(Ky),id:Dy,error:v.object({code:v.number().int(),message:v.string(),data:v.optional(v.unknown())})}).strict(),I2I=v.union([H_I,Q_I,w_I,v_I]),jW=yd.strict(),_y=es.extend({method:v.literal("notifications/cancelled"),params:Y0.extend({requestId:Dy,reason:v.string().optional()})}),l2I=v.object({name:v.string(),version:v.string()}).passthrough(),E_I=v.object({experimental:v.optional(v.object({}).passthrough()),sampling:v.optional(v.object({}).passthrough()),roots:v.optional(v.object({listChanged:v.optional(v.boolean())}).passthrough())}).passthrough(),g_I=kc.extend({method:v.literal("initialize"),params:gd.extend({protocolVersion:v.string(),capabilities:E_I,clientInfo:l2I})}),y_I=v.object({experimental:v.optional(v.object({}).passthrough()),logging:v.optional(v.object({}).passthrough()),completions:v.optional(v.object({}).passthrough()),prompts:v.optional(v.object({listChanged:v.optional(v.boolean())}).passthrough()),resources:v.optional(v.object({subscribe:v.optional(v.boolean()),listChanged:v.optional(v.boolean())}).passthrough()),tools:v.optional(v.object({listChanged:v.optional(v.boolean())}).passthrough())}).passthrough(),tj=yd.extend({protocolVersion:v.string(),capabilities:y_I,serverInfo:l2I,instructions:v.optional(v.string())}),C_I=es.extend({method:v.literal("notifications/initialized")}),qy=kc.extend({method:v.literal("ping")}),J_I=v.object({progress:v.number(),total:v.optional(v.number())}).passthrough(),Py=es.extend({method:v.literal("notifications/progress"),params:Y0.merge(J_I).extend({progressToken:PRI})}),$y=kc.extend({params:gd.extend({cursor:v.optional($RI)}).optional()}),I1=yd.extend({nextCursor:v.optional($RI)}),e2I=v.object({uri:v.string(),mimeType:v.optional(v.string())}).passthrough(),t2I=e2I.extend({text:v.string()}),a2I=e2I.extend({blob:v.string().base64()}),A_I=v.object({uri:v.string(),name:v.string(),description:v.optional(v.string()),mimeType:v.optional(v.string())}).passthrough(),L_I=v.object({uriTemplate:v.string(),name:v.string(),description:v.optional(v.string()),mimeType:v.optional(v.string())}).passthrough(),k_I=$y.extend({method:v.literal("resources/list")}),aj=I1.extend({resources:v.array(A_I)}),x_I=$y.extend({method:v.literal("resources/templates/list")}),Gj=I1.extend({resourceTemplates:v.array(L_I)}),f_I=kc.extend({method:v.literal("resources/read"),params:gd.extend({uri:v.string()})}),cj=yd.extend({contents:v.array(v.union([t2I,a2I]))}),z_I=es.extend({method:v.literal("notifications/resources/list_changed")}),U_I=kc.extend({method:v.literal("resources/subscribe"),params:gd.extend({uri:v.string()})}),M_I=kc.extend({method:v.literal("resources/
`}var n1,Z2I=tG(()=>{s();G1();n1=class{append(I){this._buffer=this._buffer?Buffer.concat([this._buffer,I]):I}readMessage(){if(!this._buffer)return null;let I=this._buffer.indexOf(`
`);if(I===-1)return null;let e=this._buffer.toString("utf8",0,I).replace(/\r$/,"");return this._buffer=this._buffer.subarray(I+1),uqI(e)}clear(){this._buffer=void 0}}});var W2I={};pe(W2I,{DEFAULT_INHERITED_ENV_VARS:()=>o2I,StdioClientTransport:()=>Zj,getDefaultEnvironment:()=>u2I});function u2I(){let l={};for(let I of o2I){let e=V0.default.env[I];e!==void 0&&(e.startsWith("()")||(l[I]=e))}return l}function WqI(){return"type"in V0.default}var r2I,V0,o2I,Zj,i2I=tG(()=>{s();r2I=y(MT(),1),V0=y(require("node:process"),1);Z2I();o2I=V0.default.platform==="win32"?["APPDATA","HOMEDRIVE","HOMEPATH","LOCALAPPDATA","PATH","PROCESSOR_ARCHITECTURE","SYSTEMDRIVE","SYSTEMROOT","TEMP","USERNAME","USERPROFILE"]:["HOME","LOGNAME","PATH","SHELL","TERM","USER"];Zj=class{constructor(I){this._abortController=new AbortController,this._readBuffer=new n1,this._serverParams=I}async start(){if(this._process)throw new Error("StdioClientTransport already started! If using Client class, note that connect() calls start() automatically.");return new Promise((I,e)=>{var t,a,G,c,n,d;this._process=(0,r2I.default)(this._serverParams.command,(t=this._serverParams.args)!==null&&t!==void 0?t:[],{env:(a=this._serverParams.env)!==null&&a!==void 0?a:u2I(),stdio:["pipe","pipe",(G=this._serverParams.stderr)!==null&&G!==void 0?G:"inherit"],shell:!1,signal:this._abortController.signal,windowsHide:V0.default.platform==="win32"&&WqI(),cwd:this._serverParams.cwd}),this._process.on("error",b=>{var m,Z;if(b.name==="AbortError"){(m=this.onclose)===null||m===void 0||m.call(this);return}e(b),(Z=this.onerror)===null||Z===void 0||Z.call(this,b)}),this._process.on("spawn",()=>{I()}),this._process.on("close",b=>{var m;this._process=void 0,(m=this.onclose)===null||m===void 0||m.call(this)}),(c=this._process.stdin)===null||c===void 0||c.on("error",b=>{var m;(m=this.onerror)===null||m===void 0||m.call(this,b)}),(n=this._process.stdout)===null||n===void 0||n.on("data",b=>{this._readBuffer.append(b),this.processReadBuffer()}),(d=this._process.stdout)===null||d===void 0||d.on("error",b=>{var m;(m=this.onerror)===null||m===void 0||m.call(this,b)})})}get stderr(){var I,e;return(e=(I=this._process)===null||I===void 0?void 0:I.stderr)!==null&&e!==void 0?e:null}processReadBuffer(){for(var I,e;;)try{let t=this._readBuffer.readMessage();if(t===null)break;(I=this.onmessage)===null||I===void 0||I.call(this,t)}catch(t){(e=this.onerror)===null||e===void 0||e.call(this,t)}}async close(){this._abortController.abort(),this._process=void 0,this._readBuffer.clear()}send(I){return new Promise(e=>{var t;if(!(!((t=this._process)===null||t===void 0)&&t.stdin))throw new Error("Not connected");let a=m2I(I);this._process.stdin.write(a)?e():this._process.stdin.once("drain",e)})}}});var uPI,Oj,WPI,iPI,NPI,pPI,h0I,hPI,ei,g0,YPI,C1,Bj,M,DI,TI,ZI,Kh,ul,oo=tG(()=>{s();uPI=Object.create,Oj=Object.defineProperty,WPI=Object.getOwnPropertyDescriptor,iPI=Object.getOwnPropertyNames,NPI=Object.getPrototypeOf,pPI=Object.prototype.hasOwnProperty,h0I=l=>{throw TypeError(l)},hPI=(l,I)=>()=>(l&&(I=l(l=0)),I),ei=(l,I)=>()=>(I||l((I={exports:{}}).exports,I),I.exports),g0=(l,I)=>{for(var e in I)Oj(l,e,{get:I[e],enumerable:!0})},YPI=(l,I,e,t)=>{if(I&&typeof I=="object"||typeof I=="function")for(let a of iPI(I))!pPI.call(l,a)&&a!==e&&Oj(l,a,{get:()=>I[a],enumerable:!(t=WPI(I,a))||t.enumerable});return l},C1=(l,I,e)=>(e=l!=null?uPI(NPI(l)):{},YPI(I||!l||!l.__esModule?Oj(e,"default",{value:l,enumerable:!0}):e,l)),Bj=(l,I,e)=>I.has(l)||h0I("Cannot "+e),M=(l,I,e)=>(Bj(l,I,"read from private field"),e?e.call(l):I.get(l)),DI=(l,I,e)=>I.has(l)?h0I("Cannot add the same private member more than once"):I instanceof WeakSet?I.add(l):I.set(l,e),TI=(l,I,e,t)=>(Bj(l,I,"write to private field"),t?t.call(l,e):I.set(l,e),e),ZI=(l,I,e)=>(Bj(l,I,"access private method"),e),Kh=(l,I,e,t)=>({set _(a){TI(l,I,a,e)},get _(){return M(l,I,t)}}),ul=hPI(()=>{"use strict"})});async function R0I(l,I,e="pgdata",t="auto"){let a=HPI(l,I),[G,c]=await QPI(a,t),n=e+(c?".tar.gz":".tar"),d=c?"application/x-gzip":"application/x-tar";return typeof File<"u"?new File([G]
`),t=!1;try{I=JSON.parse(e[0])}catch{I={root:{type:"directory",lastModified:Date.now(),mode:iK.DIR,children:{}},pool:[]},M(this,qa).truncate(0),M(this,qa).write(new TextEncoder().encode(JSON.stringify(I)),{at:0}),t=!0}this.state=I;let a=e.slice(1).filter(Boolean).map(d=>JSON.parse(d));for(let d of a){let b=`_${d.opp}State`;if(typeof this[b]=="function")try{this[b].bind(this)(...d.args)}catch(m){console.warn("Error applying OPFS AHP WAL entry",d,m)}}let G=[],c=async d=>{if(d.type==="file")try{let b=await M(this,IY).getFileHandle(d.backingFilename),m=await b.createSyncAccessHandle();M(this,Wo).set(d.backingFilename,b),M(this,QG).set(d.backingFilename,m)}catch(b){console.error("Error opening file handle for node",d,b)}else for(let b of Object.values(d.children))G.push(c(b))};await c(this.state.root);let n=[];for(let d of this.state.pool)n.push(new Promise(async b=>{M(this,Wo).has(d)&&console.warn("File handle already exists for pool file",d);let m=await M(this,IY).getFileHandle(d),Z=await m.createSyncAccessHandle();M(this,Wo).set(d,m),M(this,QG).set(d,Z),b()}));await Promise.all([...G,...n]),await this.maintainPool(t?this.initialPoolSize:this.maintainedPoolSize)},ci=function(l,I){let e=ZI(this,cl,lY).call(this,l);try{I()}catch(t){throw M(this,qa).truncate(e),t}},lY=function(l){let I=JSON.stringify(l),e=new TextEncoder().encode(`
${I}`),t=M(this,qa).getSize();return M(this,qa).write(e,{at:t}),M(this,gm).add(M(this,qa)),t},cs=function(l){return l.split("/").filter(Boolean)},_a=function(l,I){let e=ZI(this,cl,cs).call(this,l),t=I||this.state.root;for(let a of e){if(t.type!=="directory")throw new yt("ENOTDIR","Not a directory");if(!Object.prototype.hasOwnProperty.call(t.children,a))throw new yt("ENOENT","No such file or directory");t=t.children[a]}return t},f0=function(l){let I=M(this,ni).get(l);if(!I)throw new yt("EBADF","Bad file descriptor");return I},kXI=function(){let l=++Kh(this,tC)._;for(;M(this,ni).has(l);)Kh(this,tC)._++;return l},WK=async function(l,I){let e=ZI(this,cl,cs).call(this,l),t=I?.from||M(this,lC);for(let a of e)t=await t.getDirectoryHandle(a,{create:I?.create});return t};yt=class extends Error{constructor(l,I){super(I),typeof l=="number"?this.code=l:typeof l=="string"&&(this.code=J1[l])}}});var eQI=w(VX=>{"use strict";s();var a5=VX&&VX.__assign||function(){return a5=Object.assign||function(l){for(var I,e=1,t=arguments.length;e<t;e++){I=arguments[e];for(var a in I)Object.prototype.hasOwnProperty.call(I,a)&&(l[a]=I[a])}return l},a5.apply(this,arguments)};Object.defineProperty(VX,"__esModule",{value:!0});var Dll={delayFirstAttempt:!1,jitter:"none",maxDelay:1/0,numOfAttempts:10,retry:function(){return!0},startingDelay:100,timeMultiple:2};function _ll(l){var I=a5(a5({},Dll),l);return I.numOfAttempts<1&&(I.numOfAttempts=1),I}VX.getSanitizedOptions=_ll});var tQI=w(BK=>{"use strict";s();Object.defineProperty(BK,"__esModule",{value:!0});function qll(l){var I=Math.random()*l;return Math.round(I)}BK.fullJitter=qll});var aQI=w(SK=>{"use strict";s();Object.defineProperty(SK,"__esModule",{value:!0});function Pll(l){return l}SK.noJitter=Pll});var GQI=w(TK=>{"use strict";s();Object.defineProperty(TK,"__esModule",{value:!0});var $ll=tQI(),Iel=aQI();function lel(l){switch(l.jitter){case"full":return $ll.fullJitter;case"none":default:return Iel.noJitter}}TK.JitterFactory=lel});var KK=w(jK=>{"use strict";s();Object.defineProperty(jK,"__esModule",{value:!0});var eel=GQI(),tel=function(){function l(I){this.options=I,this.attempt=0}return l.prototype.apply=function(){var I=this;return new Promise(function(e){return setTimeout(e,I.jitteredDelay)})},l.prototype.setAttemptNumber=function(I){this.attempt=I},Object.defineProperty(l.prototype,"jitteredDelay",{get:function(){var I=eel.JitterFactory(this.options);return I(this.delay)},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"delay",{get:function(){var I=this.options.startingDelay,e=this.options.timeMultiple,t=this.numOfDelayedAttempts,a=I*Math.pow(e,t);return Math.min(a,this.options.maxDelay)},enumerable:!0,configurable:!0}),Object.defineProperty(l.prototype,"numOfDelayedAttempts",{get:function(){return this.attempt},enumerable:!0,configurable:!0}),l}();jK.Delay=tel});var cQI=w(Lm=>{"use strict";s();var ael=Lm&&Lm.__extends||function(){var l=function(I,e){return l=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,a){t.__proto__=a}||function(t,a){for(var G in a)a.hasOwnProperty(G)&&(t[G]=a[G])},l(I,e)};return function(I,e){l(I,e);function t(){this.constructor=I}I.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}}(),Gel=Lm&&Lm.__awaiter||function(l,I,e,t){function a(G){return G instanceof e?G:new e(function(c){c(G)})}return new(e||(e=Promise))(function(G,c){function n(m){try{b(t.next(m))}catch(Z){c(Z)}}function d(m){try{b(t.throw(m))}catch(Z){c(Z)}}function b(m){m.done?G(m.value):a(m.value).then(n,d)}b((t=t.apply(l,I||[])).next())})},cel=Lm&&Lm.__generator||function(l,I){var e={label:0,sent:function(){if(G[0]&1)throw G[1];return G[1]},trys:[],ops:[]},t,a,G,c;return c={next:n(0),throw:n(1),return:n(2)},typeof Symbol=="function"&&(c[Symbol.iterator]=function(){return this}),c;function n(b){return function(m){return d([b,m])}}function d(b){if(t)throw new TypeError("Generator is already executing.");for(;e;)try{if(t=1,a&&(G=b[0]&2?a.return:b[0]?a.throw||((G=a.return)&&G.call(a),0):a.next)&&!(G=G.call(a,b[1])).done)return G;switch(a=0,G&&(b=[b[0]&2,G.value
`),c=I.split(`
`),n=a.computeDiff(G,c,t).changes,d=1;if(n.forEach(b=>{let m=b.originalRange.startLineNumber,Z=b.originalRange.endLineNumberExclusive,r=b.modifiedRange.startLineNumber,o=b.modifiedRange.endLineNumberExclusive;if(m>d){let V=G.slice(d-1,m-1).join(`
`);V.length>0&&e.push({type:"unchanged",value:V})}let u=G.slice(m-1,Z-1).join(`
`),N=c.slice(r-1,o-1).join(`
`);(u.length>0||N.length>0)&&e.push({type:"modified",originalValue:u.length>0?u:void 0,modifiedValue:N.length>0?N:void 0}),d=Z}),G.length>d-1){let b=G.slice(d-1).join(`
`);b.length>0&&e.push({type:"unchanged",value:b})}return e}var vl=y(K());function Wk({state:l,close:I}){let e=(0,uk.getIcon)("check"),t=(0,uk.getIcon)("x"),[a,G]=(0,kt.useState)(0),c=(0,kt.useRef)([]),n=(0,kt.useRef)(null),d=ee(),[b,m]=(0,kt.useState)(P8(l.originalContent,l.newContent)),Z=(0,kt.useMemo)(()=>b.reduce((X,H,Q)=>(H.type!=="unchanged"&&X.push(Q),X),[]),[b]),r=(0,kt.useCallback)(X=>{if(X>=0&&X<Z.length){let H=c.current[Z[X]];H&&(H.scrollIntoView({block:"start"}),G(X))}},[Z]),o=(0,kt.useCallback)(()=>{r(a-1)},[a,r]),u=(0,kt.useCallback)(()=>{r(a+1)},[a,r]),N=async()=>{let X=b.map(H=>H.type==="modified"?H.modifiedValue:H.value).join(`
`);await d.vault.modify(l.file,X),I()},V=async()=>{I()},Y=X=>{m(H=>{let Q=H[X];if(Q.type==="unchanged")return H;if(!Q.originalValue)return[...H.slice(0,X),...H.slice(X+1)];let E=Q.type==="modified"?{type:"unchanged",value:Q.originalValue}:Q;return[...H.slice(0,X),E,...H.slice(X+1)]})},p=X=>{m(H=>{let Q=H[X];if(Q.type==="unchanged")return H;if(!Q.modifiedValue)return[...H.slice(0,X),...H.slice(X+1)];let E=Q.type==="modified"?{type:"unchanged",value:Q.modifiedValue}:Q;return[...H.slice(0,X),E,...H.slice(X+1)]})},h=X=>{m(H=>{let Q=H[X];if(Q.type==="unchanged")return H;let E={type:"unchanged",value:[Q.originalValue,Q.modifiedValue].filter(Boolean).join(`
`)};return[...H.slice(0,X),E,...H.slice(X+1)]})},F=(0,kt.useCallback)(()=>{let X=n.current;if(!X)return;let Q=X.getBoundingClientRect().top,E=10;for(let C=0;C<Z.length;C++){let x=c.current[Z[C]];if(!x)continue;if(x.getBoundingClientRect().top-Q>=-E){G(C);break}}},[Z]);return(0,kt.useEffect)(()=>{let X=n.current;if(!X)return;let H=()=>{F()};return X.addEventListener("scroll",H),()=>X.removeEventListener("scroll",H)},[F]),(0,kt.useEffect)(()=>{Z.length>0&&r(0)},[]),(0,vl.jsxs)("div",{id:"smtcmp-apply-view",children:[(0,vl.jsx)("div",{className:"view-header",children:(0,vl.jsxs)("div",{className:"view-header-title-container mod-at-start",children:[(0,vl.jsxs)("div",{className:"view-header-title",children:["Applying: ",l?.file?.name??""]}),(0,vl.jsxs)("div",{className:"view-actions",children:[(0,vl.jsxs)("div",{className:"smtcmp-diff-navigation",children:[(0,vl.jsx)("button",{className:"clickable-icon",onClick:o,disabled:a<=0,"aria-label":"Previous diff",children:(0,vl.jsx)(dG,{size:14})}),(0,vl.jsx)("span",{children:Z.length>0?`${a+1} of ${Z.length}`:"0 of 0"}),(0,vl.jsx)("button",{className:"clickable-icon",onClick:u,disabled:a>=Z.length-1,"aria-label":"Next diff",children:(0,vl.jsx)(Vt,{size:14})})]}),(0,vl.jsxs)("button",{className:"clickable-icon view-action","aria-label":"Accept changes",onClick:N,children:[e&&(0,vl.jsx)(pc,{size:14}),"Accept"]}),(0,vl.jsxs)("button",{className:"clickable-icon view-action","aria-label":"Cancel apply",onClick:V,children:[t&&(0,vl.jsx)(ad,{size:14}),"Cancel"]})]})]})}),(0,vl.jsx)("div",{className:"view-content",children:(0,vl.jsx)("div",{className:"markdown-source-view cm-s-obsidian mod-cm6 node-insert-event is-readable-line-width is-live-preview is-folding show-properties",children:(0,vl.jsx)("div",{className:"cm-editor",children:(0,vl.jsx)("div",{className:"cm-scroller",ref:n,children:(0,vl.jsxs)("div",{className:"cm-sizer",children:[(0,vl.jsx)("div",{className:"smtcmp-inline-title",children:l?.file?.name?l.file.name.replace(/\.[^/.]+$/,""):""}),b.map((X,H)=>(0,vl.jsx)($8,{block:X,onAcceptIncoming:()=>p(H),onAcceptCurrent:()=>Y(H),onAcceptBoth:()=>h(H),ref:Q=>{c.current[H]=Q}},H))]})})})})})]})}var $8=(0,kt.forwardRef)(({block:l,onAcceptIncoming:I,onAcceptCurrent:e,onAcceptBoth:t},a)=>{if(l.type==="unchanged")return(0,vl.jsx)("div",{className:"smtcmp-diff-block",children:(0,vl.jsx)("div",{style:{width:"100%"},children:l.value})});if(l.type==="modified")return(0,vl.jsxs)("div",{className:"smtcmp-diff-block-container",ref:a,children:[l.originalValue&&l.originalValue.length>0&&(0,vl.jsx)("div",{className:"smtcmp-diff-block removed",children:(0,vl.jsx)("div",{style:{width:"100%"},children:l.originalValue})}),l.modifiedValue&&l.modifiedValue.length>0&&(0,vl.jsx)("div",{className:"smtcmp-diff-block added",children:(0,vl.jsx)("div",{style:{width:"100%"},children:l.modifiedValue})}),(0,vl.jsxs)("div",{className:"smtcmp-diff-block-actions",children:[(0,vl.jsx)("button",{onClick:I,className:"smtcmp-accept",children:"Accept Incoming"}),(0,vl.jsx)("button",{onClick:e,className:"smtcmp-exclude",children:"Accept Current"}),(0,vl.jsx)("button",{onClick:t,children:"Accept Both"})]})]})});$8.displayName="DiffBlockView";s();var Cs="smtcmp-chat-view",VN="smtcmp-apply-view",I7=".smtcmp_vector_db.tar.gz",l7="claude-sonnet-4.0",e7="gpt-4.1-mini",t7=["claude-sonnet-4.0","gpt-4.1"],a7=["gpt-4.1-mini"],G7=["openai/text-embedding-3-small"],xI={openai:{label:"OpenAI",defaultProviderId:"openai",requireApiKey:!0,requireBaseUrl:!1,supportEmbedding:!0,additionalSettings:[]},anthropic:{label:"Anthropic",defaultProviderId:"anthropic",requireApiKey:!0,requireBaseUrl:!1,supportEmbedding:!1,additionalSettings:[]},gemini:{label:"Gemini",defaultProviderId:"gemini",requireApiKey:!0,requireBaseUrl:!1,supportEmbedding:!0,additionalSettings:[]},groq:{label:"Groq",defaultProviderId:"groq",requireApiKey:!0,requireBaseUrl:!1,supportEmbedding:!1,additionalSettings:[]},openrouter:{label:"OpenRouter",defaultProviderId:"openrouter",requireApiKey:!0,requireBaseUrl:!1,supportEmbedding:!1,additionalSettings:[]},ollama:{label:"Ollama",d
`):[]}};Fc=new WeakMap;zs.NEWLINE_CHARS=new Set([`
`,"\r"]);zs.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function KJI(l,I){for(let a=I??0;a<l.length;a++){if(l[a]===10)return{preceding:a,index:a+1,carriage:!1};if(l[a]===13)return{preceding:a,index:a+1,carriage:!0}}return null}function r$(l){for(let t=0;t<l.length-1;t++){if(l[t]===10&&l[t+1]===10||l[t]===13&&l[t+1]===13)return t+2;if(l[t]===13&&l[t+1]===10&&t+3<l.length&&l[t+2]===13&&l[t+3]===10)return t+4}return-1}s();function KR(l){if(l[Symbol.asyncIterator])return l;let I=l.getReader();return{async next(){try{let e=await I.read();return e?.done&&I.releaseLock(),e}catch(e){throw I.releaseLock(),e}},async return(){let e=I.cancel();return I.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var mG=class{constructor(I,e){this.iterator=I,this.controller=e}static fromSSEResponse(I,e){let t=!1;async function*a(){if(t)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");t=!0;let G=!1;try{for await(let c of DJI(I,e)){if(c.event==="completion")try{yield JSON.parse(c.data)}catch(n){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),n}if(c.event==="message_start"||c.event==="message_delta"||c.event==="message_stop"||c.event==="content_block_start"||c.event==="content_block_delta"||c.event==="content_block_stop")try{yield JSON.parse(c.data)}catch(n){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),n}if(c.event!=="ping"&&c.event==="error")throw $e.generate(void 0,`SSE Error: ${c.data}`,c.data,Sk(I.headers))}G=!0}catch(c){if(c instanceof Error&&c.name==="AbortError")return;throw c}finally{G||e.abort()}}return new mG(a,e)}static fromReadableStream(I,e){let t=!1;async function*a(){let c=new zs,n=KR(I);for await(let d of n)for(let b of c.decode(d))yield b;for(let d of c.flush())yield d}async function*G(){if(t)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");t=!0;let c=!1;try{for await(let n of a())c||n&&(yield JSON.parse(n));c=!0}catch(n){if(n instanceof Error&&n.name==="AbortError")return;throw n}finally{c||e.abort()}}return new mG(G,e)}[Symbol.asyncIterator](){return this.iterator()}tee(){let I=[],e=[],t=this.iterator(),a=G=>({next:()=>{if(G.length===0){let c=t.next();I.push(c),e.push(c)}return G.shift()}});return[new mG(()=>a(I),this.controller),new mG(()=>a(e),this.controller)]}toReadableStream(){let I=this,e,t=new TextEncoder;return new Mk({async start(){e=I[Symbol.asyncIterator]()},async pull(a){try{let{value:G,done:c}=await e.next();if(c)return a.close();let n=t.encode(JSON.stringify(G)+`
`);a.enqueue(n)}catch(G){a.error(G)}},async cancel(){await e.return?.()}})}};async function*DJI(l,I){if(!l.body)throw I.abort(),new el("Attempted to iterate over a response with no body");let e=new Bk,t=new zs,a=KR(l.body);for await(let G of _JI(a))for(let c of t.decode(G)){let n=e.decode(c);n&&(yield n)}for(let G of t.flush()){let c=e.decode(G);c&&(yield c)}}async function*_JI(l){let I=new Uint8Array;for await(let e of l){if(e==null)continue;let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,a=new Uint8Array(I.length+t.length);a.set(I),a.set(t,I.length),I=a;let G;for(;(G=r$(I))!==-1;)yield I.slice(0,G),I=I.slice(G)}I.length>0&&(yield I)}var Bk=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(I){if(I.endsWith("\r")&&(I=I.substring(0,I.length-1)),!I){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push(I),I.startsWith(":"))return null;let[e,t,a]=qJI(I,":");return a.startsWith(" ")&&(a=a.substring(1)),e==="event"?this.event=a:e==="data"&&this.data.push(a),null}};function qJI(l,I){let e=l.indexOf(I);return e!==-1?[l.substring(0,e),I,l.substring(e+I.length)]:[l,"",""]}s();var PJI=l=>l!=null&&typeof l=="object"&&typeof l.url=="string"&&typeof l.blob=="function",$JI=l=>l!=null&&typeof l=="object"&&typeof l.name=="string"&&typeof l.lastModified=="number"&&DR(l),DR=l=>l!=null&&typeof l=="object"&&typeof l.size=="number"&&typeof l.type=="string"&&typeof l.text=="function"&&typeof l.slice=="function"&&typeof l.arrayBuffer=="function";async function o$(l,I,e){if(l=await l,$JI(l))return l;if(PJI(l)){let a=await l.blob();I||(I=new URL(l.url).pathname.split(/[\\/]/).pop()??"unknown_file");let G=DR(a)?[await a.arrayBuffer()]:[a];return new Ww(G,I,e)}let t=await I5I(l);if(I||(I=e5I(l)??"unknown_file"),!e?.type){let a=t[0]?.type;typeof a=="string"&&(e={...e,type:a})}return new Ww(t,I,e)}async function I5I(l){let I=[];if(typeof l=="string"||ArrayBuffer.isView(l)||l instanceof ArrayBuffer)I.push(l);else if(DR(l))I.push(await l.arrayBuffer());else if(t5I(l))for await(let e of l)I.push(e);else throw new Error(`Unexpected data type: ${typeof l}; constructor: ${l?.constructor?.name}; props: ${l5I(l)}`);return I}function l5I(l){return`[${Object.getOwnPropertyNames(l).map(e=>`"${e}"`).join(", ")}]`}function e5I(l){return Tk(l.name)||Tk(l.filename)||Tk(l.path)?.split(/[\\/]/).pop()}var Tk=l=>{if(typeof l=="string")return l;if(typeof Buffer<"u"&&l instanceof Buffer)return String(l)},t5I=l=>l!=null&&typeof l=="object"&&typeof l[Symbol.asyncIterator]=="function",jk=l=>l&&typeof l=="object"&&l.body&&l[Symbol.toStringTag]==="MultipartBody";var G5I=function(l,I,e,t,a){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!a:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?a.call(l,e):a?a.value=e:I.set(l,e),e},c5I=function(l,I,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!t:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(l):t?t.value:I.get(l)},Yw;async function p$(l){let{response:I}=l;if(l.options.stream)return BN("response",I.status,I.url,I.headers,I.body),l.options.__streamClass?l.options.__streamClass.fromSSEResponse(I,l.controller):mG.fromSSEResponse(I,l.controller);if(I.status===204)return null;if(l.options.__binaryResponse)return I;let e=I.headers.get("content-type");if(e?.includes("application/json")||e?.includes("application/vnd.api+json")){let G=await I.json();return BN("response",I.status,I.url,I.headers,G),h$(G,I)}let a=await I.text();return BN("response",I.status,I.url,I.headers,a),a}function h$(l,I){return!l||typeof l!="object"||Array.isArray(l)?l:Object.defineProperty(l,"_request_id",{value:I.headers.get("request-id"),enumerable:!1})}var SN=class extends Promise{constructor(I,e=p$){super(t=>{t(null)}),this.responsePromise=I,this.parseResponse=e}_thenUnwrap(I){return new SN(this.responsePromise,async e=>h$(I(await this.parseResponse(e),e),e.response))}asResponse(){return this.responsePromise.then(I=>I.response)}async withResponse(){let[I,e]=await Promise.all([this.parse(),this.asResponse()]);return{data:I,response:e,request_id:e.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(this.parseResponse)),this.parsedPromise}then(I,e){return this.parse().then(I,e)}catch(I){return this.parse().catch(I)}finally(I){return this.parse().finally(I)}},Rw=class{constructor({baseURL:I,maxRetries:e=2,timeout:t=6e5,httpAgent:a,fetch:G}){this.baseURL=I,this.maxRetries=Kk("maxRetries",e),this.timeout=Kk("timeout",t),this.httpAgent=a,this.fetch=G??Uk}auth
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages?beta=true",{body:a,timeout:this._client._options.timeout??(a.stream?6e5:this._client._calculateNonstreamingTimeout(a.max_tokens)),...e,headers:{...t?.toString()!=null?{"anthropic-beta":t?.toString()}:void 0,...e?.headers},stream:I.stream??!1})}stream(I,e){return ru.createMessage(this,I,e)}countTokens(I,e){let{betas:t,...a}=I;return this._client.post("/v1/messages/count_tokens?beta=true",{body:a,...e,headers:{"anthropic-beta":[...t??[],"token-counting-2024-11-01"].toString(),...e?.headers}})}};PZ.Batches=Zu;PZ.BetaMessageBatchesPage=jN;var db=class extends xt{constructor(){super(...arguments),this.models=new mu(this._client),this.messages=new PZ(this._client)}};db.Models=mu;db.BetaModelInfosPage=TN;db.Messages=PZ;s();var ou=class extends xt{create(I,e){return this._client.post("/v1/complete",{body:I,timeout:this._client._options.timeout??6e5,...e,stream:I.stream??!1})}};s();s();var uu=class extends xt{create(I,e){return this._client.post("/v1/messages/batches",{body:I,...e})}retrieve(I,e){return this._client.get(`/v1/messages/batches/${I}`,e)}list(I={},e){return dn(I)?this.list({},I):this._client.getAPIList("/v1/messages/batches",_N,{query:I,...e})}delete(I,e){return this._client.delete(`/v1/messages/batches/${I}`,e)}cancel(I,e){return this._client.post(`/v1/messages/batches/${I}/cancel`,e)}async results(I,e){let t=await this.retrieve(I);if(!t.results_url)throw new el(`No batch \`results_url\`; Has it finished processing? ${t.processing_status} - ${t.id}`);return this._client.get(t.results_url,{...e,headers:{Accept:"application/binary",...e?.headers},__binaryResponse:!0})._thenUnwrap((a,G)=>_Z.fromResponse(G.response,G.controller))}},_N=class extends nb{};uu.MessageBatchesPage=_N;s();var za=function(l,I,e,t,a){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!a:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?a.call(l,e):a?a.value=e:I.set(l,e),e},ol=function(l,I,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!t:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(l):t?t.value:I.get(l)},sn,$Z,e2,Cw,t2,a2,Jw,G2,Ms,c2,Aw,Lw,qN,kw,xw,l3,Q$,e3,t3,a3,G3,w$,v$="__json_buf",Wu=class{constructor(){sn.add(this),this.messages=[],this.receivedMessages=[],$Z.set(this,void 0),this.controller=new AbortController,e2.set(this,void 0),Cw.set(this,()=>{}),t2.set(this,()=>{}),a2.set(this,void 0),Jw.set(this,()=>{}),G2.set(this,()=>{}),Ms.set(this,{}),c2.set(this,!1),Aw.set(this,!1),Lw.set(this,!1),qN.set(this,!1),kw.set(this,void 0),xw.set(this,void 0),e3.set(this,I=>{if(za(this,Aw,!0,"f"),I instanceof Error&&I.name==="AbortError"&&(I=new ma),I instanceof ma)return za(this,Lw,!0,"f"),this._emit("abort",I);if(I instanceof el)return this._emit("error",I);if(I instanceof Error){let e=new el(I.message);return e.cause=I,this._emit("error",e)}return this._emit("error",new el(String(I)))}),za(this,e2,new Promise((I,e)=>{za(this,Cw,I,"f"),za(this,t2,e,"f")}),"f"),za(this,a2,new Promise((I,e)=>{za(this,Jw,I,"f"),za(this,G2,e,"f")}),"f"),ol(this,e2,"f").catch(()=>{}),ol(this,a2,"f").catch(()=>{})}get response(){return ol(this,kw,"f")}get request_id(){return ol(this,xw,"f")}async withResponse(){let I=await ol(this,e2,"f");if(!I)throw new Error("Could not resolve a `Response` object");return{data:this,response:I,request_id:I.headers.get("request-id")}}static fromReadableStream(I){let e=new Wu;return e._run(()=>e._fromReadableStream(I)),e}static createMessage(I,e,t){let a=new Wu;for(let G of e.messages)a._addMessageParam(G);return a._run(()=>a._createMessage(I,{...e,stream:!0},{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"stream"}})
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`),this._client.post("/v1/messages",{body:I,timeout:this._client._options.timeout??(I.stream?6e5:this._client._calculateNonstreamingTimeout(I.max_tokens)),...e,stream:I.stream??!1})}stream(I,e){return Wu.createMessage(this,I,e)}countTokens(I,e){return this._client.post("/v1/messages/count_tokens",{body:I,...e})}},E$={"claude-1.3":"November 6th, 2024","claude-1.3-100k":"November 6th, 2024","claude-instant-1.1":"November 6th, 2024","claude-instant-1.1-100k":"November 6th, 2024","claude-instant-1.2":"November 6th, 2024","claude-3-sonnet-20240229":"July 21st, 2025","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};Os.Batches=uu;Os.MessageBatchesPage=_N;s();var Ir=class extends xt{retrieve(I,e){return this._client.get(`/v1/models/${I}`,e)}list(I={},e){return dn(I)?this.list({},I):this._client.getAPIList("/v1/models",iu,{query:I,...e})}},iu=class extends nb{};Ir.ModelInfosPage=iu;var g$,Pl=class extends Rw{constructor({baseURL:I=Xw("ANTHROPIC_BASE_URL"),apiKey:e=Xw("ANTHROPIC_API_KEY")??null,authToken:t=Xw("ANTHROPIC_AUTH_TOKEN")??null,...a}={}){let G={apiKey:e,authToken:t,...a,baseURL:I||"https://api.anthropic.com"};if(!G.dangerouslyAllowBrowser&&V$())throw new el(`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 Anthropic({ apiKey, dangerouslyAllowBrowser: true });
`);super({baseURL:G.baseURL,timeout:G.timeout??6e5,httpAgent:G.httpAgent,maxRetries:G.maxRetries,fetch:G.fetch}),this.completions=new ou(this),this.messages=new Os(this),this.models=new Ir(this),this.beta=new db(this),this._options=G,this.apiKey=e,this.authToken=t}defaultQuery(){return this._options.defaultQuery}defaultHeaders(I){return{...super.defaultHeaders(I),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01",...this._options.defaultHeaders}}validateHeaders(I,e){if(!(this.apiKey&&I["x-api-key"])&&e["x-api-key"]!==null&&!(this.authToken&&I.authorization)&&e.authorization!==null)throw new Error('Could not resolve authentication method. Expected either apiKey or authToken to be set. Or for one of the "X-Api-Key" or "Authorization" headers to be explicitly omitted')}authHeaders(I){let e=this.apiKeyAuth(I),t=this.bearerAuth(I);return e!=null&&!_R(e)?e:t!=null&&!_R(t)?t:{}}apiKeyAuth(I){return this.apiKey==null?{}:{"X-Api-Key":this.apiKey}}bearerAuth(I){return this.authToken==null?{}:{Authorization:`Bearer ${this.authToken}`}}};g$=Pl;Pl.Anthropic=g$;Pl.HUMAN_PROMPT=`
Human:`;Pl.AI_PROMPT=`
Assistant:`;Pl.DEFAULT_TIMEOUT=6e5;Pl.AnthropicError=el;Pl.APIError=$e;Pl.APIConnectionError=DZ;Pl.APIConnectionTimeoutError=ON;Pl.APIUserAbortError=ma;Pl.NotFoundError=OR;Pl.ConflictError=BR;Pl.RateLimitError=TR;Pl.BadRequestError=zR;Pl.AuthenticationError=UR;Pl.InternalServerError=jR;Pl.PermissionDeniedError=MR;Pl.UnprocessableEntityError=SR;Pl.toFile=o$;Pl.fileFromPath=iw;Pl.Completions=ou;Pl.Messages=Os;Pl.Models=Ir;Pl.ModelInfosPage=iu;Pl.Beta=db;var{HUMAN_PROMPT:Mil,AI_PROMPT:Oil}=Pl,fw=Pl;s();function zw(l){let I=l.match(/^data:([^;]+);base64,(.+)/);if(!I)throw new Error("Invalid image data URL format");let[,e,t]=I;return{mimeType:e,base64Data:t}}async function PN(l){let I=await H5I(l);return{type:"image",name:l.name,mimeType:l.type,data:I}}function H5I(l){return new Promise((I,e)=>{let t=new FileReader;t.readAsDataURL(l),t.onload=()=>I(t.result),t.onerror=()=>e(new Error("Failed to read file"))})}s();var te=class{constructor(I){this.provider=I}};var Za=class extends te{constructor(e){super(e);this.client=new fw({apiKey:e.apiKey,baseURL:e.baseUrl?e.baseUrl.replace(/\/+$/,""):void 0,dangerouslyAllowBrowser:!0})}async generateResponse(e,t,a){if(e.providerType!=="anthropic")throw new Error("Model is not a Anthropic model");if(!this.client.apiKey)throw new Ve(`Provider ${this.provider.id} API key is missing. Please set it in settings menu.`);let G=Za.validateSystemMessages(t.messages);try{let c=await this.client.messages.create({model:t.model,messages:t.messages.map(n=>Za.parseRequestMessage(n)).filter(n=>n!==null),system:G,thinking:e.thinking?.enabled?{type:"enabled",budget_tokens:e.thinking.budget_tokens}:void 0,tools:t.tools?.map(n=>Za.parseRequestTool(n)),tool_choice:t.tool_choice?Za.parseRequestToolChoice(t.tool_choice):void 0,max_tokens:t.max_tokens??(e.thinking?.enabled?e.thinking?.budget_tokens+Za.DEFAULT_MAX_TOKENS:Za.DEFAULT_MAX_TOKENS),temperature:t.temperature,top_p:t.top_p},{signal:a?.signal});return Za.parseNonStreamingResponse(c)}catch(c){throw c instanceof fw.AuthenticationError?c.message.includes("CORS requests are not allowed for this Organization")?new Rt(`Provider ${this.provider.id} is experiencing a CORS issue. This is a known issue with new individual Anthropic accounts.
To resolve this issue:
1. Go to https://console.anthropic.com/settings/organization
2. Create a new organization
3. Your API key should work properly after creating an organization
For more information, please refer to the following issue:
https://github.com/glowingjade/obsidian-smart-composer/issues/286`,c):new Rt(`Provider ${this.provider.id} API key is invalid. Please update it in settings menu.`,c):c}}async streamResponse(e,t,a){if(e.providerType!=="anthropic")throw new Error("Model is not a Anthropic model");if(!this.client.apiKey)throw new Ve(`Provider ${this.provider.id} API key is missing. Please set it in settings menu.`);let G=Za.validateSystemMessages(t.messages);try{let c=await this.client.messages.create({model:t.model,messages:t.messages.map(n=>Za.parseRequestMessage(n)).filter(n=>n!==null),system:G,thinking:e.thinking?.enabled?{type:"enabled",budget_tokens:e.thinking.budget_tokens}:void 0,tools:t.tools?.map(n=>Za.parseRequestTool(n)),tool_choice:t.tool_choice?Za.parseRequestToolChoice(t.tool_choice):void 0,max_tokens:t.max_tokens??(e.thinking?.enabled?e.thinking?.budget_tokens+Za.DEFAULT_MAX_TOKENS:Za.DEFAULT_MAX_TOKENS),temperature:t.temperature,top_p:t.top_p,stream:!0},{signal:a?.signal});return this.streamResponseGenerator(c)}catch(c){throw c instanceof fw.AuthenticationError?c.message.includes("CORS requests are not allowed for this Organization")?new Rt(`Provider ${this.provider.id} is experiencing a CORS issue. This is a known issue with new individual Anthropic accounts.
To resolve this issue:
1. Go to https://console.anthropic.com/settings/organization
2. Create a new organization
3. Your API key should work properly after creating an organization
For more information, please refer to the following issue:
https://github.com/glowingjade/obsidian-smart-composer/issues/286`,c):new Rt(`Provider ${this.provider.id} API key is invalid. Please update it in settings menu.`,c):c}}async*streamResponseGenerator(e){let t="",a="",G={prompt_tokens:0,completion_tokens:0,total_tokens:0};for await(let c of e)if(c.type==="message_start")t=c.message.id,a=c.message.model,G={prompt_tokens:c.message.usage.input_tokens,completion_tokens:c.message.usage.output_tokens,total_tokens:c.message.usage.input_tokens+c.message.usage.output_tokens};else if(c.type==="content_block_start"||c.type==="content_block_delta"){let n=Za.parseStreamingResponseChunk(c,t,a);n!==null&&(yield n)}else c.type==="message_delta"&&(G={prompt_tokens:G.prompt_tokens,completion_tokens:G.completion_tokens+c.usage.output_tokens,total_tokens:G.total_tokens+c.usage.output_tokens});yield{id:t,choices:[],object:"chat.completion.chunk",model:a,usage:G}}static parseRequestMessage(e){switch(e.role){case"user":return Array.isArray(e.content)?{role:"user",content:e.content.map(a=>{switch(a.type){case"text":return{type:"text",text:a.text};case"image_url":{let{mimeType:G,base64Data:c}=zw(a.image_url.url);return Za.validateImageType(G),{type:"image",source:{data:c,media_type:G,type:"base64"}}}}})}:{role:"user",content:e.content};case"assistant":{let t=e.tool_calls?.map(G=>{let c=(()=>{if(G.arguments&&G.arguments.length>0)try{return JSON.parse(G.arguments)}catch{return{}}return{}})();return{type:"tool_use",id:G.id,name:G.name,input:c}}),a=[...e.content.trim()===""?[]:[{type:"text",text:e.content}],...t||[]];return a.length===0?null:{role:"assistant",content:a}}case"system":return null;case"tool":return{role:"user",content:[{type:"tool_result",tool_use_id:e.tool_call.id,content:e.content}]}}}static parseNonStreamingResponse(e){let t=e.content.filter(c=>c.type==="text").map(c=>c.text).join(""),a=e.content.filter(c=>c.type==="thinking").map(c=>c.thinking).join("")||void 0,G=e.content.filter(c=>c.type==="tool_use").map(c=>({id:c.id,type:"function",function:{name:c.name,arguments:JSON.stringify(c.input)}}));return{id:e.id,choices:[{finish_reason:e.stop_reason,message:{content:t,reasoning:a,tool_calls:G.length>0?G:void 0,role:e.role}}],model:e.model,object:"chat.completion",usage:{prompt_tokens:e.usage.input_tokens,completion_tokens:e.usage.output_tokens,total_tokens:e.usage.input_tokens+e.usage.output_tokens}}}static parseStreamingResponseChunk(e,t,a){if(e.type!=="content_block_start"&&e.type!=="content_block_delta")throw new Error("Unsupported chunk type");if(e.type==="content_block_start"&&e.content_block.type==="tool_use")return{id:t,choices:[{finish_reason:null,delta:{tool_calls:[{index:e.index,id:e.content_block.id,type:"function",function:{name:e.content_block.name}}]}}],object:"chat.completion.chunk",model:a};if(e.type==="content_block_delta"){if(e.delta.type==="text_delta")return{id:t,choices:[{finish_reason:null,delta:{content:e.delta.text}}],object:"chat.completion.chunk",model:a};if(e.delta.type==="thinking_delta")return{id:t,choices:[{finish_reason:null,delta:{reasoning:e.delta.thinking}}],object:"chat.completion.chunk",model:a};if(e.delta.type==="input_json_delta")return{id:t,choices:[{finish_reason:null,delta:{tool_calls:[{index:e.index,function:{arguments:e.delta.partial_json}}]}}],object:"chat.completion.chunk",model:a}}return null}static validateSystemMessages(e){let t=e.filter(G=>G.role==="system");if(t.length>1)throw new Error("Anthropic does not support more than one system message");let a=t.length>0?t[0].content:void 0;if(a&&typeof a!="string")throw new Error("Anthropic only supports string content for system messages");return a}static validateImageType(e){let t=["image/jpeg","image/png","image/gif","image/webp"];if(!t.includes(e))throw new Error(`Anthropic does not support image type ${e}. Supported types: ${t.join(", ")}`)}static parseRequestTool(e){return{name:e.function.name,input_schema:{...e.function.parameters,type:"object"},description:e.function.description}}static parseRequestToolChoice(e){if(e==="none")return{type:"none"};if(e==="auto")return{type:"auto"};if(e==="
`):[]}};Xc=new WeakMap;Yu.NEWLINE_CHARS=new Set([`
`,"\r"]);Yu.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function z5I(l,I){for(let a=I??0;a<l.length;a++){if(l[a]===10)return{preceding:a,index:a+1,carriage:!1};if(l[a]===13)return{preceding:a,index:a+1,carriage:!0}}return null}function U$(l){for(let t=0;t<l.length-1;t++){if(l[t]===10&&l[t+1]===10||l[t]===13&&l[t+1]===13)return t+2;if(l[t]===13&&l[t+1]===10&&t+3<l.length&&l[t+2]===13&&l[t+3]===10)return t+4}return-1}s();function i3(l){if(l[Symbol.asyncIterator])return l;let I=l.getReader();return{async next(){try{let e=await I.read();return e?.done&&I.releaseLock(),e}catch(e){throw I.releaseLock(),e}},async return(){let e=I.cancel();return I.releaseLock(),await e,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}var ZG=class{constructor(I,e){this.iterator=I,this.controller=e}static fromSSEResponse(I,e){let t=!1;async function*a(){if(t)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");t=!0;let G=!1;try{for await(let c of U5I(I,e))if(!G){if(c.data.startsWith("[DONE]")){G=!0;continue}if(c.event===null||c.event.startsWith("response.")||c.event.startsWith("transcript.")){let n;try{n=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(n&&n.error)throw new _e(void 0,n.error,void 0,p3(I.headers));yield n}else{let n;try{n=JSON.parse(c.data)}catch(d){throw console.error("Could not parse message into JSON:",c.data),console.error("From chunk:",c.raw),d}if(c.event=="error")throw new _e(void 0,n.error,n.message,void 0);yield{event:c.event,data:n}}}G=!0}catch(c){if(c instanceof Error&&c.name==="AbortError")return;throw c}finally{G||e.abort()}}return new ZG(a,e)}static fromReadableStream(I,e){let t=!1;async function*a(){let c=new Yu,n=i3(I);for await(let d of n)for(let b of c.decode(d))yield b;for(let d of c.flush())yield d}async function*G(){if(t)throw new Error("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");t=!0;let c=!1;try{for await(let n of a())c||n&&(yield JSON.parse(n));c=!0}catch(n){if(n instanceof Error&&n.name==="AbortError")return;throw n}finally{c||e.abort()}}return new ZG(G,e)}[Symbol.asyncIterator](){return this.iterator()}tee(){let I=[],e=[],t=this.iterator(),a=G=>({next:()=>{if(G.length===0){let c=t.next();I.push(c),e.push(c)}return G.shift()}});return[new ZG(()=>a(I),this.controller),new ZG(()=>a(e),this.controller)]}toReadableStream(){let I=this,e,t=new TextEncoder;return new Z3({async start(){e=I[Symbol.asyncIterator]()},async pull(a){try{let{value:G,done:c}=await e.next();if(c)return a.close();let n=t.encode(JSON.stringify(G)+`
`);a.enqueue(n)}catch(G){a.error(G)}},async cancel(){await e.return?.()}})}};async function*U5I(l,I){if(!l.body)throw I.abort(),new gI("Attempted to iterate over a response with no body");let e=new N3,t=new Yu,a=i3(l.body);for await(let G of M5I(a))for(let c of t.decode(G)){let n=e.decode(c);n&&(yield n)}for(let G of t.flush()){let c=e.decode(G);c&&(yield c)}}async function*M5I(l){let I=new Uint8Array;for await(let e of l){if(e==null)continue;let t=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?new TextEncoder().encode(e):e,a=new Uint8Array(I.length+t.length);a.set(I),a.set(t,I.length),I=a;let G;for(;(G=U$(I))!==-1;)yield I.slice(0,G),I=I.slice(G)}I.length>0&&(yield I)}var N3=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(I){if(I.endsWith("\r")&&(I=I.substring(0,I.length-1)),!I){if(!this.event&&!this.data.length)return null;let G={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],G}if(this.chunks.push(I),I.startsWith(":"))return null;let[e,t,a]=O5I(I,":");return a.startsWith(" ")&&(a=a.substring(1)),e==="event"?this.event=a:e==="data"&&this.data.push(a),null}};function O5I(l,I){let e=l.indexOf(I);return e!==-1?[l.substring(0,e),I,l.substring(e+I.length)]:[l,"",""]}s();var M$=l=>l!=null&&typeof l=="object"&&typeof l.url=="string"&&typeof l.blob=="function",O$=l=>l!=null&&typeof l=="object"&&typeof l.name=="string"&&typeof l.lastModified=="number"&&W2(l),W2=l=>l!=null&&typeof l=="object"&&typeof l.size=="number"&&typeof l.type=="string"&&typeof l.text=="function"&&typeof l.slice=="function"&&typeof l.arrayBuffer=="function",B5I=l=>O$(l)||M$(l)||u3(l);async function V3(l,I,e){if(l=await l,O$(l))return l;if(M$(l)){let a=await l.blob();I||(I=new URL(l.url).pathname.split(/[\\/]/).pop()??"unknown_file");let G=W2(a)?[await a.arrayBuffer()]:[a];return new Ow(G,I,e)}let t=await S5I(l);if(I||(I=j5I(l)??"unknown_file"),!e?.type){let a=t[0]?.type;typeof a=="string"&&(e={...e,type:a})}return new Ow(t,I,e)}async function S5I(l){let I=[];if(typeof l=="string"||ArrayBuffer.isView(l)||l instanceof ArrayBuffer)I.push(l);else if(W2(l))I.push(await l.arrayBuffer());else if(K5I(l))for await(let e of l)I.push(e);else throw new Error(`Unexpected data type: ${typeof l}; constructor: ${l?.constructor?.name}; props: ${T5I(l)}`);return I}function T5I(l){return`[${Object.getOwnPropertyNames(l).map(e=>`"${e}"`).join(", ")}]`}function j5I(l){return h3(l.name)||h3(l.filename)||h3(l.path)?.split(/[\\/]/).pop()}var h3=l=>{if(typeof l=="string")return l;if(typeof Buffer<"u"&&l instanceof Buffer)return String(l)},K5I=l=>l!=null&&typeof l=="object"&&typeof l[Symbol.asyncIterator]=="function",R3=l=>l&&typeof l=="object"&&l.body&&l[Symbol.toStringTag]==="MultipartBody";var mn=async l=>{let I=await B$(l.body);return r3(I,l)},B$=async l=>{let I=new m3;return await Promise.all(Object.entries(l||{}).map(([e,t])=>Y3(I,e,t))),I};var Y3=async(l,I,e)=>{if(e!==void 0){if(e==null)throw new TypeError(`Received null for "${I}"; to pass null in FormData, you must use the string 'null'`);if(typeof e=="string"||typeof e=="number"||typeof e=="boolean")l.append(I,String(e));else if(B5I(e)){let t=await V3(e);l.append(I,t)}else if(Array.isArray(e))await Promise.all(e.map(t=>Y3(l,I+"[]",t)));else if(typeof e=="object")await Promise.all(Object.entries(e).map(([t,a])=>Y3(l,`${I}[${t}]`,a)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${e} instead`)}};var _5I=function(l,I,e,t,a){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!a:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?a.call(l,e):a?a.value=e:I.set(l,e),e},q5I=function(l,I,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!t:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(l):t?t.value:I.get(l)},Kw;W3();async function _$(l){let{response:I}=l;if(l.options.stream)return Bs("response",I.status,I.url,I.headers,I.body),l.options.__streamClass?l.options.__streamClass.fromSSEResponse(I,l.controller):ZG.fromSSEResponse(I,l.controller);if(I.status===204)return null;if(l.options.__binaryResponse)return I;let t=I.headers.get("content-type")?.split(";")[0]?.trim();if(t?.includes("application/json")||t?.endsWith("+json")){let c=await I.json();return Bs("response",I.status,I.url,I.headers,c),q$(c,I)}let G=await I.text();return Bs("response",I.status,I.url,I.headers,G),G}function q$(l,I){return!l||typeof l!="object"||Array.isArray(l)?l:Object.defineProperty(l,"_request_id",{value:I.headers.get("x-request-id"),enumerable:!1})}var lp=class extends Promise{constructor(I,e=_$){super(t=>{t(null)}),this.response
\r `.includes(l[t]);)t++};return c()},x3=l=>uAI(l,ft.ALL^ft.NUM);var sp=function(l,I,e,t,a){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!a:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?a.call(l,e):a?a.value=e:I.set(l,e),e},Ge=function(l,I,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!t:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(l):t?t.value:I.get(l)},Xt,Ks,mp,Zr,f3,av,z3,U3,M3,Gv,O3,dII,Ds=class extends bp{constructor(I){super(),Xt.add(this),Ks.set(this,void 0),mp.set(this,void 0),Zr.set(this,void 0),sp(this,Ks,I,"f"),sp(this,mp,[],"f")}get currentChatCompletionSnapshot(){return Ge(this,Zr,"f")}static fromReadableStream(I){let e=new Ds(null);return e._run(()=>e._fromReadableStream(I)),e}static createChatCompletion(I,e,t){let a=new Ds(e);return a._run(()=>a._runChatCompletion(I,{...e,stream:!0},{...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"stream"}})),a}async _createChatCompletion(I,e,t){super._createChatCompletion;let a=t?.signal;a&&(a.aborted&&this.controller.abort(),a.addEventListener("abort",()=>this.controller.abort())),Ge(this,Xt,"m",f3).call(this);let G=await I.chat.completions.create({...e,stream:!0},{...t,signal:this.controller.signal});this._connected();for await(let c of G)Ge(this,Xt,"m",z3).call(this,c);if(G.controller.signal?.aborted)throw new ct;return this._addChatCompletion(Ge(this,Xt,"m",Gv).call(this))}async _fromReadableStream(I,e){let t=e?.signal;t&&(t.aborted&&this.controller.abort(),t.addEventListener("abort",()=>this.controller.abort())),Ge(this,Xt,"m",f3).call(this),this._connected();let a=ZG.fromReadableStream(I,this.controller),G;for await(let c of a)G&&G!==c.id&&this._addChatCompletion(Ge(this,Xt,"m",Gv).call(this)),Ge(this,Xt,"m",z3).call(this,c),G=c.id;if(a.controller.signal?.aborted)throw new ct;return this._addChatCompletion(Ge(this,Xt,"m",Gv).call(this))}[(Ks=new WeakMap,mp=new WeakMap,Zr=new WeakMap,Xt=new WeakSet,f3=function(){this.ended||sp(this,Zr,void 0,"f")},av=function(e){let t=Ge(this,mp,"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},Ge(this,mp,"f")[e.index]=t,t)},z3=function(e){if(this.ended)return;let t=Ge(this,Xt,"m",dII).call(this,e);this._emit("chunk",e,t);for(let a of e.choices){let G=t.choices[a.index];a.delta.content!=null&&G.message?.role==="assistant"&&G.message?.content&&(this._emit("content",a.delta.content,G.message.content),this._emit("content.delta",{delta:a.delta.content,snapshot:G.message.content,parsed:G.message.parsed})),a.delta.refusal!=null&&G.message?.role==="assistant"&&G.message?.refusal&&this._emit("refusal.delta",{delta:a.delta.refusal,snapshot:G.message.refusal}),a.logprobs?.content!=null&&G.message?.role==="assistant"&&this._emit("logprobs.content.delta",{content:a.logprobs?.content,snapshot:G.logprobs?.content??[]}),a.logprobs?.refusal!=null&&G.message?.role==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:a.logprobs?.refusal,snapshot:G.logprobs?.refusal??[]});let c=Ge(this,Xt,"m",av).call(this,G);G.finish_reason&&(Ge(this,Xt,"m",M3).call(this,G),c.current_tool_call_index!=null&&Ge(this,Xt,"m",U3).call(this,G,c.current_tool_call_index));for(let n of a.delta.tool_calls??[])c.current_tool_call_index!==n.index&&(Ge(this,Xt,"m",M3).call(this,G),c.current_tool_call_index!=null&&Ge(this,Xt,"m",U3).call(this,G,c.current_tool_call_index)),c.current_tool_call_index=n.index;for(let n of a.delta.tool_calls??[]){let d=G.message.tool_calls?.[n.index];d?.type&&(d?.type==="function"?this._emit("tool_calls.function.arguments.delta",{name:d.function?.name,index:n.index,arguments:d.function.arguments,parsed_arguments:d.function.parsed_arguments,arguments_delta:
${cv(l)}`);if(H==null)throw new gI(`missing choices[${Z}].tool_calls[${F}].type
${cv(l)}`);if(x==null)throw new gI(`missing choices[${Z}].tool_calls[${F}].function.name
${cv(l)}`);if(C==null)throw new gI(`missing choices[${Z}].tool_calls[${F}].function.arguments
${cv(l)}`);return{...E,id:Q,type:H,function:{...T,name:x,arguments:C}}})}}:{...o,message:{...Y,content:u,role:p,refusal:b.refusal??null},finish_reason:m,index:Z,logprobs:r}}),created:a,model:G,object:"chat.completion",...c?{system_fingerprint:c}:{}};return tII(d,I)}function cv(l){return JSON.stringify(l)}var _s=class extends Ds{static fromReadableStream(I){let e=new _s(null);return e._run(()=>e._fromReadableStream(I)),e}static runFunctions(I,e,t){let a=new _s(null),G={...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"runFunctions"}};return a._run(()=>a._runFunctions(I,e,G)),a}static runTools(I,e,t){let a=new _s(e),G={...t,headers:{...t?.headers,"X-Stainless-Helper-Method":"runTools"}};return a._run(()=>a._runTools(I,e,G)),a}};var F2=class extends QI{parse(I,e){return GII(I.tools),this._client.chat.completions.create(I,{...e,headers:{...e?.headers,"X-Stainless-Helper-Method":"beta.chat.completions.parse"}})._thenUnwrap(t=>R2(t,I))}runFunctions(I,e){return I.stream?_s.runFunctions(this._client,I,e):mr.runFunctions(this._client,I,e)}runTools(I,e){return I.stream?_s.runTools(this._client,I,e):mr.runTools(this._client,I,e)}stream(I,e){return Ds.createChatCompletion(this._client,I,e)}};var Zp=class extends QI{constructor(){super(...arguments),this.completions=new F2(this._client)}};(function(l){l.Completions=F2})(Zp||(Zp={}));s();s();var rp=class extends QI{create(I,e){return this._client.post("/realtime/sessions",{body:I,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}};s();var op=class extends QI{create(I,e){return this._client.post("/realtime/transcription_sessions",{body:I,...e,headers:{"OpenAI-Beta":"assistants=v2",...e?.headers}})}};var rr=class extends QI{constructor(){super(...arguments),this.sessions=new rp(this._client),this.transcriptionSessions=new op(this._client)}};rr.Sessions=rp;rr.TranscriptionSessions=op;s();s();var SI=function(l,I,e,t){if(e==="a"&&!t)throw new TypeError("Private accessor was defined without a getter");if(typeof I=="function"?l!==I||!t:!I.has(l))throw new TypeError("Cannot read private member from an object whose class did not declare it");return e==="m"?t:e==="a"?t.call(l):t?t.value:I.get(l)},Hc=function(l,I,e,t,a){if(t==="m")throw new TypeError("Private method is not writable");if(t==="a"&&!a)throw new TypeError("Private accessor was defined without a setter");if(typeof I=="function"?l!==I||!a:!I.has(l))throw new TypeError("Cannot write private member to an object whose class did not declare it");return t==="a"?a.call(l,e):a?a.value=e:I.set(l,e),e},ra,B3,Zb,nv,sd,Hu,up,Xu,sv,Qc,dv,bv,Q2,X2,H2,bII,sII,mII,ZII,rII,oII,uII,rG=class extends sr{constructor(){super(...arguments),ra.add(this),B3.set(this,[]),Zb.set(this,{}),nv.set(this,{}),sd.set(this,void 0),Hu.set(this,void 0),up.set(this,void 0),Xu.set(this,void 0),sv.set(this,void 0),Qc.set(this,void 0),dv.set(this,void 0),bv.set(this,void 0),Q2.set(this,void 0)}[(B3=new WeakMap,Zb=new WeakMap,nv=new WeakMap,sd=new WeakMap,Hu=new WeakMap,up=new WeakMap,Xu=new WeakMap,sv=new WeakMap,Qc=new WeakMap,dv=new WeakMap,bv=new WeakMap,Q2=new WeakMap,ra=new WeakSet,Symbol.asyncIterator)](){let I=[],e=[],t=!1;return this.on("event",a=>{let G=e.shift();G?G.resolve(a):I.push(a)}),this.on("end",()=>{t=!0;for(let a of e)a.resolve(void 0);e.length=0}),this.on("abort",a=>{t=!0;for(let G of e)G.reject(a);e.length=0}),this.on("error",a=>{t=!0;for(let G of e)G.reject(a);e.length=0}),{next:async()=>I.length?{value:I.shift(),done:!1}:t?{value:void 0,done:!0}:new Promise((G,c)=>e.push({resolve:G,reject:c})).then(G=>G?{value:G,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(I){let e=new rG;return e._run(()=>e._fromReadableStream(I)),e}async _fromReadableStream(I,e){let t=e?.signal;t&&(t.aborted&&this.controller.abort(),t.addEventListener("abort",()=>this.controller.abort())),this._connected();let a=ZG.fromReadableStream(I,this.controller);for await(let G of a)SI(this,ra,"m",X2).call(this,G);if(a.controller.signal?.aborted)throw new ct;return this._addRun(SI(this,ra,"m",H2).call(this
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
`);super({baseURL:c.baseURL,timeout:c.timeout??6e5,httpAgent:c.httpAgent,maxRetries:c.maxRetries,fetch:c.fetch}),this.completions=new vu(this),this.chat=new Ts(this),this.embeddings=new Eu(this),this.files=new or(this),this.images=new Cu(this),this.audio=new mb(this),this.moderations=new Au(this),this.models=new ur(this),this.fineTuning=new ub(this),this.vectorStores=new wc(this),this.beta=new md(this),this.batches=new dr(this),this.uploads=new pr(this),this.responses=new Nr(this),this._options=c,this.apiKey=e,this.organization=t,this.project=a}defaultQuery(){return this._options.defaultQuery}defaultHeaders(I){return{...super.defaultHeaders(I),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project,...this._options.defaultHeaders}}authHeaders(I){return{Authorization:`Bearer ${this.apiKey}`}}stringifyQuery(I){return b3(I,{arrayFormat:"brackets"})}};RII=bl;bl.OpenAI=RII;bl.DEFAULT_TIMEOUT=6e5;bl.OpenAIError=gI;bl.APIError=_e;bl.APIConnectionError=lr;bl.APIConnectionTimeoutError=er;bl.APIUserAbortError=ct;bl.NotFoundError=m2;bl.ConflictError=Z2;bl.RateLimitError=o2;bl.BadRequestError=d2;bl.AuthenticationError=b2;bl.InternalServerError=u2;bl.PermissionDeniedError=s2;bl.UnprocessableEntityError=r2;bl.toFile=V3;bl.fileFromPath=Bw;bl.Completions=vu;bl.Chat=Ts;bl.ChatCompletionsPage=nr;bl.Embeddings=Eu;bl.Files=or;bl.FileObjectsPage=gu;bl.Images=Cu;bl.Audio=mb;bl.Moderations=Au;bl.Models=ur;bl.ModelsPage=Ju;bl.FineTuning=ub;bl.VectorStores=wc;bl.VectorStoresPage=Lu;bl.VectorStoreSearchResponsesPage=ku;bl.Beta=md;bl.Batches=dr;bl.BatchesPage=Vu;bl.Uploads=pr;bl.Responses=Nr;var ov=class extends bl{constructor({baseURL:I=tr("OPENAI_BASE_URL"),apiKey:e=tr("AZURE_OPENAI_API_KEY"),apiVersion:t=tr("OPENAI_API_VERSION"),endpoint:a,deployment:G,azureADTokenProvider:c,dangerouslyAllowBrowser:n,...d}={}){if(!t)throw new gI("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 c=="function"&&(n=!0),!c&&!e)throw new gI("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(c&&e)throw new gI("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(e??(e=VII),d.defaultQuery={...d.defaultQuery,"api-version":t},I){if(a)throw new gI("baseURL and endpoint are mutually exclusive")}else{if(a||(a=process.env.AZURE_OPENAI_ENDPOINT),!a)throw new gI("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");I=`${a}/openai`}super({apiKey:e,baseURL:I,...d,...n!==void 0?{dangerouslyAllowBrowser:n}:{}}),this.apiVersion="",this._azureADTokenProvider=c,this.apiVersion=t,this.deploymentName=G}buildRequest(I,e={}){if(zAI.has(I.path)&&I.method==="post"&&I.body!==void 0){if(!ep(I.body))throw new Error("Expected request body to be an object");let t=this.deploymentName||I.body.model||I.__metadata?.model;t!==void 0&&!this.baseURL.includes("/deployments")&&(I.path=`/deployments/${t}${I.path}`)}return super.buildRequest(I,e)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){let I=await this._azureADTokenProvider();if(!I||typeof I!="string")throw new gI(`Expected 'azureADTokenProvider' argument to return a string but it returned ${I}`);return I}}authHeaders(I){return{}}async prepareOptions(I){if(I.headers?.["api-key"])return super.prepareOptions(I);let e=await this._getAzureADToken();if(I.headers??(I.headers={}),e)I.headers.Authorization=`Bearer ${e}`;else if(this.apiKey!==VII)I.headers["api-key"]=this.apiKey;else throw new gI("Unable to handle auth");return super.prepareOptions(I)}},zAI=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations"]),VII="<Missing Key>",Ma=bl;s();var ye=class{async generateResponse(I,e,t){let a=await I.chat.completions.create(this.buildChatCompletionCreateParams({
`):a}function Ps(l){let I=[],e=l.filter(a=>a.role==="system"),t=l.filter(a=>a.role!=="system");if(e.length>0){let a=e.map(G=>typeof G.content=="string"?G.content:"").filter(G=>G.trim().length>0).join(`
`);a.trim().length>0&&I.push({role:"system",content:a})}for(let a of t){let G=I[I.length-1];G&&G.role===a.role?G.content=UAI(G.content,a.content):I.push(a)}return I}s();var Wv=class extends ye{parseNonStreamingResponse(I){return{id:I.id,choices:I.choices.map(e=>({finish_reason:e.finish_reason,message:{content:e.message.content,reasoning:e.message.reasoning_content,role:e.message.role,tool_calls:e.message.tool_calls}})),created:I.created,model:I.model,object:"chat.completion",system_fingerprint:I.system_fingerprint,usage:I.usage}}parseStreamingResponseChunk(I){return{id:I.id,choices:I.choices.map(e=>({finish_reason:e.finish_reason??null,delta:{content:e.delta.content??null,reasoning:e.delta.reasoning_content,role:e.delta.role,tool_calls:e.delta.tool_calls}})),created:I.created,model:I.model,object:"chat.completion.chunk",system_fingerprint:I.system_fingerprint,usage:I.usage??void 0}}};var iv=class extends te{constructor(e){super(e);this.adapter=new Wv,this.client=new Ma({apiKey:e.apiKey??"",baseURL:e.baseUrl?e.baseUrl.replace(/\/+$/,""):"https://api.deepseek.com",dangerouslyAllowBrowser:!0})}async generateResponse(e,t,a){if(e.providerType!=="deepseek")throw new Error("Model is not a DeepSeek model");if(!this.client.apiKey)throw new Ve(`Provider ${this.provider.id} API key is missing. Please set it in settings menu.`);let G={...t,messages:Ps(t.messages)};return this.adapter.generateResponse(this.client,G,a)}async streamResponse(e,t,a){if(e.providerType!=="deepseek")throw new Error("Model is not a DeepSeek model");if(!this.client.apiKey)throw new Ve(`Provider ${this.provider.id} API key is missing. Please set it in settings menu.`);let G={...t,messages:Ps(t.messages)};return this.adapter.streamResponse(this.client,G,a)}async getEmbedding(e,t){throw new Error(`Provider ${this.provider.id} does not support embeddings. Please use a different provider.`)}};s();s();var pv;(function(l){l.STRING="string",l.NUMBER="number",l.INTEGER="integer",l.BOOLEAN="boolean",l.ARRAY="array",l.OBJECT="object"})(pv||(pv={}));var FII;(function(l){l.LANGUAGE_UNSPECIFIED="language_unspecified",l.PYTHON="python"})(FII||(FII={}));var XII;(function(l){l.OUTCOME_UNSPECIFIED="outcome_unspecified",l.OUTCOME_OK="outcome_ok",l.OUTCOME_FAILED="outcome_failed",l.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(XII||(XII={}));var HII=["user","model","function","system"],QII;(function(l){l.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",l.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",l.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",l.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",l.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT",l.HARM_CATEGORY_CIVIC_INTEGRITY="HARM_CATEGORY_CIVIC_INTEGRITY"})(QII||(QII={}));var wII;(function(l){l.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",l.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",l.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",l.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",l.BLOCK_NONE="BLOCK_NONE"})(wII||(wII={}));var vII;(function(l){l.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",l.NEGLIGIBLE="NEGLIGIBLE",l.LOW="LOW",l.MEDIUM="MEDIUM",l.HIGH="HIGH"})(vII||(vII={}));var EII;(function(l){l.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",l.SAFETY="SAFETY",l.OTHER="OTHER"})(EII||(EII={}));var w2;(function(l){l.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",l.STOP="STOP",l.MAX_TOKENS="MAX_TOKENS",l.SAFETY="SAFETY",l.RECITATION="RECITATION",l.LANGUAGE="LANGUAGE",l.BLOCKLIST="BLOCKLIST",l.PROHIBITED_CONTENT="PROHIBITED_CONTENT",l.SPII="SPII",l.MALFORMED_FUNCTION_CALL="MALFORMED_FUNCTION_CALL",l.OTHER="OTHER"})(w2||(w2={}));var gII;(function(l){l.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",l.RETRIEVAL_QUERY="RETRIEVAL_QUERY",l.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",l.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",l.CLASSIFICATION="CLASSIFICATION",l.CLUSTERING="CLUSTERING"})(gII||(gII={}));var yII;(function(l){l.MODE_UNSPECIFIED="MODE_UNSPECIFIED",l.AUTO="AUTO",l.ANY="ANY",l.NONE="NONE"})(yII||(yII={}));var CII;(function(l){l
`+c.executableCode.code+"\n```\n"),c.codeExecutionResult&&G.push("\n```\n"+c.codeExecutionResult.output+"\n```\n");return G.length>0?G.join(""):""}function JII(l){var I,e,t,a;let G=[];if(!((e=(I=l.candidates)===null||I===void 0?void 0:I[0].content)===null||e===void 0)&&e.parts)for(let c of(a=(t=l.candidates)===null||t===void 0?void 0:t[0].content)===null||a===void 0?void 0:a.parts)c.functionCall&&G.push(c.functionCall);if(G.length>0)return G}var ILI=[w2.RECITATION,w2.SAFETY,w2.LANGUAGE];function Nv(l){return!!l.finishReason&&ILI.includes(l.finishReason)}function Rr(l){var I,e,t;let a="";if((!l.candidates||l.candidates.length===0)&&l.promptFeedback)a+="Response was blocked",!((I=l.promptFeedback)===null||I===void 0)&&I.blockReason&&(a+=` due to ${l.promptFeedback.blockReason}`),!((e=l.promptFeedback)===null||e===void 0)&&e.blockReasonMessage&&(a+=`: ${l.promptFeedback.blockReasonMessage}`);else if(!((t=l.candidates)===null||t===void 0)&&t[0]){let G=l.candidates[0];Nv(G)&&(a+=`Candidate was blocked due to ${G.finishReason}`,G.finishMessage&&(a+=`: ${G.finishMessage}`))}return a}function v2(l){return this instanceof v2?(this.v=l,this):new v2(l)}function lLI(l,I,e){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var t=e.apply(l,I||[]),a,G=[];return a={},c("next"),c("throw"),c("return"),a[Symbol.asyncIterator]=function(){return this},a;function c(r){t[r]&&(a[r]=function(o){return new Promise(function(u,N){G.push([r,o,u,N])>1||n(r,o)})})}function n(r,o){try{d(t[r](o))}catch(u){Z(G[0][3],u)}}function d(r){r.value instanceof v2?Promise.resolve(r.value.v).then(b,m):Z(G[0][2],r)}function b(r){n("next",r)}function m(r){n("throw",r)}function Z(r,o){r(o),G.shift(),G.length&&n(G[0][0],G[0][1])}}var AII=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function eLI(l){let I=l.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),e=GLI(I),[t,a]=e.tee();return{stream:aLI(t),response:tLI(a)}}async function tLI(l){let I=[],e=l.getReader();for(;;){let{done:t,value:a}=await e.read();if(t)return D3(cLI(I));I.push(a)}}function aLI(l){return lLI(this,arguments,function*(){let e=l.getReader();for(;;){let{value:t,done:a}=yield v2(e.read());if(a)break;yield yield v2(D3(t))}})}function GLI(l){let I=l.getReader();return new ReadableStream({start(t){let a="";return G();function G(){return I.read().then(({value:c,done:n})=>{if(n){if(a.trim()){t.error(new zt("Failed to parse stream"));return}t.close();return}a+=c;let d=a.match(AII),b;for(;d;){try{b=JSON.parse(d[1])}catch{t.error(new zt(`Error parsing JSON response: "${d[1]}"`));return}t.enqueue(b),a=a.substring(d[0].length),d=a.match(AII)}return G()}).catch(c=>{let n=c;throw n.stack=c.stack,n.name==="AbortError"?n=new Yv("Request aborted when reading from the stream"):n=new zt("Error reading from the stream"),n})}}})}function cLI(l){let I=l[l.length-1],e={promptFeedback:I?.promptFeedback};for(let t of l){if(t.candidates){let a=0;for(let G of t.candidates)if(e.candidates||(e.candidates=[]),e.candidates[a]||(e.candidates[a]={index:a}),e.candidates[a].citationMetadata=G.citationMetadata,e.candidates[a].groundingMetadata=G.groundingMetadata,e.candidates[a].finishReason=G.finishReason,e.candidates[a].finishMessage=G.finishMessage,e.candidates[a].safetyRatings=G.safetyRatings,G.content&&G.content.parts){e.candidates[a].content||(e.candidates[a].content={role:G.content.role||"user",parts:[]});let c={};for(let n of G.content.parts)n.text&&(c.text=n.text),n.functionCall&&(c.functionCall=n.functionCall),n.executableCode&&(c.executableCode=n.executableCode),n.codeExecutionResult&&(c.codeExecutionResult=n.codeExecutionResult),Object.keys(c).length===0&&(c.text=""),e.candidates[a].content.parts.push(c)}a++}t.usageMetadata&&(e.usageMetadata=t.usageMetadata)}return e}async function zII(l,I,e,t){let a=await g2(I,xu.STREAM_GENERATE_CONTENT,l,!0,JSON.stringify(e),t);return eLI(a)}async function UII(l,I,e,t){let G=await(await g2(I,xu.GENERATE_CONTENT,l,!1,JSON.stringify(e),t)).json();return{response:D3(G)}}function MII(l){if(l!=null){if(typeof l=="string")return{role:"system",parts:[{text:l}
`):void 0;try{let d=await this.client.getGenerativeModel({model:t.model,generationConfig:{maxOutputTokens:t.max_tokens,temperature:t.temperature,topP:t.top_p,presencePenalty:t.presence_penalty,frequencyPenalty:t.frequency_penalty},systemInstruction:c}).generateContent({systemInstruction:c,contents:t.messages.map(m=>Zn.parseRequestMessage(m)).filter(m=>m!==null),tools:t.tools?.map(m=>Zn.parseRequestTool(m))},{signal:a?.signal}),b=crypto.randomUUID();return Zn.parseNonStreamingResponse(d,t.model,b)}catch(n){throw n.message?.includes("API_KEY_INVALID")||n.message?.includes("API key not valid")?new Rt(`Provider ${this.provider.id} API key is invalid. Please update it in settings menu.`,n):n}}async streamResponse(e,t,a){if(e.providerType!=="gemini")throw new Error("Model is not a Gemini model");if(!this.apiKey)throw new Ve(`Provider ${this.provider.id} API key is missing. Please set it in settings menu.`);let G=t.messages.filter(n=>n.role==="system"),c=G.length>0?G.map(n=>n.content).join(`
`):void 0;try{let d=await this.client.getGenerativeModel({model:t.model,generationConfig:{maxOutputTokens:t.max_tokens,temperature:t.temperature,topP:t.top_p,presencePenalty:t.presence_penalty,frequencyPenalty:t.frequency_penalty},systemInstruction:c}).generateContentStream({systemInstruction:c,contents:t.messages.map(m=>Zn.parseRequestMessage(m)).filter(m=>m!==null),tools:t.tools?.map(m=>Zn.parseRequestTool(m))},{signal:a?.signal}),b=crypto.randomUUID();return this.streamResponseGenerator(d,t.model,b)}catch(n){throw n.message?.includes("API_KEY_INVALID")||n.message?.includes("API key not valid")?new Rt("Gemini API key is invalid. Please update it in settings menu.",n):n}}async*streamResponseGenerator(e,t,a){for await(let G of e.stream)yield Zn.parseStreamingResponseChunk(G,t,a)}static parseRequestMessage(e){switch(e.role){case"system":return null;case"user":return{role:"user",parts:Array.isArray(e.content)?e.content.map(a=>{switch(a.type){case"text":return{text:a.text};case"image_url":{let{mimeType:G,base64Data:c}=zw(a.image_url.url);return Zn.validateImageType(G),{inlineData:{data:c,mimeType:G}}}}}):[{text:e.content}]};case"assistant":{let t=[...e.content===""?[]:[{text:e.content}],...e.tool_calls?.map(a=>{try{let G=JSON.parse(a.arguments??"{}");return{functionCall:{name:a.name,args:G}}}catch{return{functionCall:{name:a.name,args:{}}}}})??[]];return t.length===0?null:{role:"model",parts:t}}case"tool":return{role:"user",parts:[{functionResponse:{name:e.tool_call.name,response:{result:e.content}}}]}}}static parseNonStreamingResponse(e,t,a){return{id:a,choices:[{finish_reason:e.response.candidates?.[0]?.finishReason??null,message:{content:e.response.text(),role:"assistant",tool_calls:e.response.functionCalls()?.map(G=>({id:gl(),type:"function",function:{name:G.name,arguments:JSON.stringify(G.args)}}))}}],created:Date.now(),model:t,object:"chat.completion",usage:e.response.usageMetadata?{prompt_tokens:e.response.usageMetadata.promptTokenCount,completion_tokens:e.response.usageMetadata.candidatesTokenCount,total_tokens:e.response.usageMetadata.totalTokenCount}:void 0}}static parseStreamingResponseChunk(e,t,a){return{id:a,choices:[{finish_reason:e.candidates?.[0]?.finishReason??null,delta:{content:e.text(),tool_calls:e.functionCalls()?.map((G,c)=>({index:c,id:gl(),type:"function",function:{name:G.name,arguments:JSON.stringify(G.args)}}))}}],created:Date.now(),model:t,object:"chat.completion.chunk",usage:e.usageMetadata?{prompt_tokens:e.usageMetadata.promptTokenCount,completion_tokens:e.usageMetadata.candidatesTokenCount,total_tokens:e.usageMetadata.totalTokenCount}:void 0}}static removeAdditionalProperties(e){if(typeof e!="object"||e===null)return e;if(Array.isArray(e))return e.map(G=>this.removeAdditionalProperties(G));let{additionalProperties:t,...a}=e;return Object.fromEntries(Object.entries(a).map(([G,c])=>[G,this.removeAdditionalProperties(c)]))}static parseRequestTool(e){let t=this.removeAdditionalProperties(e.function.parameters);return{functionDeclarations:[{name:e.function.name,description:e.function.description,parameters:{type:pv.OBJECT,properties:t.properties??{}}}]}}static validateImageType(e){let t=["image/png","image/jpeg","image/webp","image/heic","image/heif"];if(!t.includes(e))throw new Error(`Gemini does not support image type ${e}. Supported types: ${t.join(", ")}`)}async getEmbedding(e,t){if(!this.apiKey)throw new Ve(`Provider ${this.provider.id} API key is missing. Please set it in settings menu.`);try{return(await this.client.getGenerativeModel({model:e}).embedContent(t)).embedding.values}catch(a){throw a.status===429?new KZ("Gemini API rate limit exceeded. Please try again later."):a}}};s();var Fv=class extends te{constructor(e){super(e);this.adapter=new ye,this.client=new Ma({apiKey:e.apiKey??"",baseURL:e.baseUrl?e.baseUrl?.replace(/\/+$/,""):"https://api.groq.com/openai/v1",dangerouslyAllowBrowser:!0})}async generateResponse(e,t,a){if(e.providerType!=="groq")throw new Error("Model is not a Groq model");return this.adapter.generateResponse(this.client,t,a)}async streamResponse(e,t,a){if(e.providerTy
`:"text"in l&&typeof l.text=="string"?l.text:""}s();var ce=l=>{switch(l.type){case"file":return{type:"file",file:l.file.path};case"folder":return{type:"folder",folder:l.folder.path};case"vault":return{type:"vault"};case"current-file":return{type:"current-file",file:l.file?.path??null};case"block":return{type:"block",content:l.content,file:l.file.path,startLine:l.startLine,endLine:l.endLine};case"url":return{type:"url",url:l.url};case"image":return{type:"image",name:l.name,mimeType:l.mimeType,data:l.data}}},Tv=(l,I)=>{try{switch(l.type){case"file":{let e=I.vault.getFileByPath(l.file);return e?{type:"file",file:e}:null}case"folder":{let e=I.vault.getFolderByPath(l.folder);return e?{type:"folder",folder:e}:null}case"vault":return{type:"vault"};case"current-file":return l.file?{type:"current-file",file:I.vault.getFileByPath(l.file)}:{type:"current-file",file:null};case"block":{let e=I.vault.getFileByPath(l.file);return e?{type:"block",content:l.content,file:e,startLine:l.startLine,endLine:l.endLine}:null}case"url":return{type:"url",url:l.url};case"image":return{type:"image",name:l.name,mimeType:l.mimeType,data:l.data}}}catch(e){return console.error("Error deserializing mentionable",e),null}};function We(l){switch(l.type){case"file":return`file:${l.file}`;case"folder":return`folder:${l.folder}`;case"vault":return"vault";case"current-file":return`current-file:${l.file??"current"}`;case"block":return`block:${l.file}:${l.startLine}:${l.endLine}:${l.content}`;case"url":return`url:${l.url}`;case"image":return`image:${l.name}:${l.data.length}:${l.data.slice(-32)}`}}function jv(l){switch(l.type){case"file":return l.file.name;case"folder":return l.folder.name;case"vault":return"Vault";case"current-file":return l.file?.name??"Current File";case"block":return`${l.file.name} (${l.startLine}:${l.endLine})`;case"url":return l.url;case"image":return l.name}}s();var Zx=y(dI());s();s();var Ou=require("obsidian"),Bu=y(sx()),Cp=class{constructor(I,e){this.app=I,this.dataDir=(0,Ou.normalizePath)(e),this.ensureDirectory()}async ensureDirectory(){await this.app.vault.adapter.exists(this.dataDir)||await this.app.vault.adapter.mkdir(this.dataDir)}async create(I){let e=this.generateFileName(I),t=(0,Ou.normalizePath)(Bu.default.join(this.dataDir,e)),a=JSON.stringify(I,null,2);if(await this.app.vault.adapter.exists(t))throw new Error(`File already exists: ${t}`);await this.app.vault.adapter.write(t,a)}async update(I,e){let t=this.generateFileName(I),a=this.generateFileName(e),G=JSON.stringify(e,null,2);if(t===a){let c=(0,Ou.normalizePath)(Bu.default.join(this.dataDir,t));await this.app.vault.adapter.write(c,G)}else{let c=(0,Ou.normalizePath)(Bu.default.join(this.dataDir,a));await this.app.vault.adapter.write(c,G),await this.delete(t)}}async listMetadata(){return(await this.app.vault.adapter.list(this.dataDir)).files.map(e=>Bu.default.basename(e)).filter(e=>e.endsWith(".json")).map(e=>{let t=this.parseFileName(e);return t?{...t,fileName:e}:null}).filter(e=>e!==null)}async read(I){let e=(0,Ou.normalizePath)(Bu.default.join(this.dataDir,I));if(!await this.app.vault.adapter.exists(e))return null;let t=await this.app.vault.adapter.read(e);return JSON.parse(t)}async delete(I){let e=(0,Ou.normalizePath)(Bu.default.join(this.dataDir,I));await this.app.vault.adapter.exists(e)&&await this.app.vault.adapter.remove(e)}};s();var Su=".smtcmp_json_db",ElI="templates",glI="chats",mx=".initial_migration_completed";s();var Tu=class extends Error{constructor(I){super(`Template with name "${I}" already exists`),this.name="DuplicateTemplateException"}},f2=class extends Error{constructor(){super("Template name cannot be empty"),this.name="EmptyTemplateNameException"}},z2=class extends Error{constructor(){super("Chat title cannot be empty"),this.name="EmptyChatTitleException"}};s();var Kv=1;var Jp=class extends Cp{constructor(I){super(I,`${Su}/${glI}`)}generateFileName(I){let e=encodeURIComponent(I.title);return`v${I.schemaVersion}_${e}_${I.updatedAt}_${I.id}.json`}parseFileName(I){let e=new RegExp(`^v${Kv}_(.+)_(\\d+)_([0-9a-f-]+)\\.json$`),t=I.match(e);if(!t)return null;
You will receive:
1. The content of the target markdown file.
2. A conversation history between the user and the assistant. This conversation may contain multiple markdown blocks suggesting changes to the file. Markdown blocks are indicated by the <smtcmp_block> tag. For example:
<smtcmp_block>
<!-- ... existing content ... -->
{{ edit_1 }}
<!-- ... existing content ... -->
{{ edit_2 }}
<!-- ... existing content ... -->
</smtcmp_block>
3. A single, specific markdown block extracted from the conversation history. This block contains the exact changes that should be applied to the target file.
Please rewrite the entire markdown file with ONLY the changes from the specified markdown block applied. DO NOT apply changes suggested by other parts of the conversation. Preserve all parts of the original file that are not related to the changes. Output only the file content, without any additional words or explanations.`,rkI=l=>{let e=l.mentionables.filter(G=>G.type==="file").map(G=>G.file).map(G=>`\`\`\`${G.path}
<!-- ... existing content ... -->
\`\`\`
`).join(""),a=l.mentionables.filter(G=>G.type==="block").map(({file:G,content:c})=>`\`\`\`${G.path}
${c}
\`\`\`
`).join("");return`${e}${a}
${l.content?lm(l.content):""}
`},okI=l=>l.content,ukI=l=>JSON.stringify(l.toolCalls.map(I=>({name:I.request.name,arguments:I.request.arguments??"",response:I.response}))),WkI=(l,I,e,t)=>`# Inputs
## Target File
Here is the file to apply changes to.
\`\`\`${I.path}
${e}
\`\`\`
## Conversation History
${t.slice(-mkI).map(a=>{if(a.role==="user")return`[User]: ${rkI(a)}`;if(a.role==="assistant")return`[Assistant]: ${okI(a)}`;if(a.role==="tool")return`[Tool]: ${ukI(a)}`}).join(`
`)}
## Changes to Apply
Here is the markdown block that indicates where content changes should be applied.
<smtcmp_block>
${l}
</smtcmp_block>
Now rewrite the entire file with the changes applied. Immediately start your response with \`\`\`${I.path}`,flI=async({blockToApply:l,currentFile:I,currentFileContent:e,chatMessages:t,providerClient:a,model:G})=>{let c=[{role:"system",content:ZkI},{role:"user",content:WkI(l,I,e,t)}],d=(await a.generateResponse(G,{model:G.model,messages:c,stream:!1,prediction:{type:"content",content:[{type:"text",text:e},{type:"text",text:l}]}})).choices[0].message.content;return d?ikI(d):null},ikI=l=>{let I=l.split(`
`);return I[0].startsWith("```")&&I.shift(),I[I.length-1].startsWith("```")&&I.pop(),I.join(`
`)};s();function zlI(l){return l.reduce((I,e)=>{if(e.role==="user")I.push(e);else{let t=I[I.length-1];Array.isArray(t)&&(e.role==="assistant"||e.role==="tool")?t.push(e):I.push([e])}return I},[])}s();var tE=require("obsidian");s();var M2=(e=>(e[e.Simple=0]="Simple",e[e.Default=1]="Default",e))(M2||{});s();s();s();var BlI=y(OlI(),1);var XkI=Object.defineProperty,HkI=(l,I,e)=>I in l?XkI(l,I,{enumerable:!0,configurable:!0,writable:!0,value:e}):l[I]=e,QkI=(l,I,e)=>(HkI(l,typeof I!="symbol"?I+"":I,e),e);function wkI(l,I){let e=Array.from({length:l.length},(t,a)=>({start:a,end:a+1}));for(;e.length>1;){let t=null;for(let a=0;a<e.length-1;a++){let G=l.slice(e[a].start,e[a+1].end),c=I.get(G.join(","));c!=null&&(t==null||c<t[0])&&(t=[c,a])}if(t!=null){let a=t[1];e[a]={start:e[a].start,end:e[a+1].end},e.splice(a+1,1)}else break}return e}function vkI(l,I){return l.length===1?[I.get(l.join(","))]:wkI(l,I).map(e=>I.get(l.slice(e.start,e.end).join(","))).filter(e=>e!=null)}function EkI(l){return l.replace(/[\\^$*+?.()|[\]{}]/g,"\\$&")}var ox=class{constructor(l,I){g(this,"specialTokens");g(this,"inverseSpecialTokens");g(this,"patStr");g(this,"textEncoder",new TextEncoder);g(this,"textDecoder",new TextDecoder("utf-8"));g(this,"rankMap",new Map);g(this,"textMap",new Map);this.patStr=l.pat_str;let e=l.bpe_ranks.split(`
`).filter(Boolean).reduce((t,a)=>{let[G,c,...n]=a.split(" "),d=Number.parseInt(c,10);return n.forEach((b,m)=>t[b]=d+m),t},{});for(let[t,a]of Object.entries(e)){let G=BlI.default.toByteArray(t);this.rankMap.set(G.join(","),a),this.textMap.set(a,G)}this.specialTokens={...l.special_tokens,...I},this.inverseSpecialTokens=Object.entries(this.specialTokens).reduce((t,[a,G])=>(t[G]=this.textEncoder.encode(a),t),{})}encode(l,I=[],e="all"){let t=new RegExp(this.patStr,"ug"),a=ox.specialTokenRegex(Object.keys(this.specialTokens)),G=[],c=new Set(I==="all"?Object.keys(this.specialTokens):I),n=new Set(e==="all"?Object.keys(this.specialTokens).filter(b=>!c.has(b)):e);if(n.size>0){let b=ox.specialTokenRegex([...n]),m=l.match(b);if(m!=null)throw new Error(`The text contains a special token that is not allowed: ${m[0]}`)}let d=0;for(;;){let b=null,m=d;for(;a.lastIndex=m,b=a.exec(l),!(b==null||c.has(b[0]));)m=b.index+1;let Z=b?.index??l.length;for(let o of l.substring(d,Z).matchAll(t)){let u=this.textEncoder.encode(o[0]),N=this.rankMap.get(u.join(","));if(N!=null){G.push(N);continue}G.push(...vkI(u,this.rankMap))}if(b==null)break;let r=this.specialTokens[b[0]];G.push(r),d=b.index+b[0].length}return G}decode(l){let I=[],e=0;for(let G=0;G<l.length;++G){let c=l[G],n=this.textMap.get(c)??this.inverseSpecialTokens[c];n!=null&&(I.push(n),e+=n.length)}let t=new Uint8Array(e),a=0;for(let G of I)t.set(G,a),a+=G.length;return this.textDecoder.decode(t)}},rd=ox;QkI(rd,"specialTokenRegex",l=>new RegExp(l.map(I=>EkI(I)).join("|"),"g"));var gkI={explicit_n_vocab:50257,pat_str:"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+",special_tokens:{"<|endoftext|>":50256},bpe_ranks:"! 0 IQ== Ig== Iw== JA== JQ== Jg== Jw== KA== KQ== Kg== Kw== LA== LQ== Lg== Lw== MA== MQ== Mg== Mw== NA== NQ== Ng== Nw== OA== OQ== Og== Ow== PA== PQ== Pg== Pw== QA== QQ== Qg== Qw== RA== RQ== Rg== Rw== SA== SQ== Sg== Sw== TA== TQ== Tg== Tw== UA== UQ== Ug== Uw== VA== VQ== Vg== Vw== WA== WQ== Wg== Ww== XA== XQ== Xg== Xw== YA== YQ== Yg== Yw== ZA== ZQ== Zg== Zw== aA== aQ== ag== aw== bA== bQ== bg== bw== cA== cQ== cg== cw== dA== dQ== dg== dw== eA== eQ== eg== ew== fA== fQ== fg== oQ== og== ow== pA== pQ== pg== pw== qA== qQ== qg== qw== rA== rg== rw== sA== sQ== sg== sw== tA== tQ== tg== tw== uA== uQ== ug== uw== vA== vQ== vg== vw== wA== wQ== wg== ww== xA== xQ== xg== xw== yA== yQ== yg== yw== zA== zQ== zg== zw== 0A== 0Q== 0g== 0w== 1A== 1Q== 1g== 1w== 2A== 2Q== 2g== 2w== 3A== 3Q== 3g== 3w== 4A== 4Q== 4g== 4w== 5A== 5Q== 5g== 5w== 6A== 6Q== 6g== 6w== 7A== 7Q== 7g== 7w== 8A== 8Q== 8g== 8w== 9A== 9Q== 9g== 9w== +A== +Q== +g== +w== /A== /Q== /g== /w== AA== AQ== Ag== Aw== BA== BQ== Bg== Bw== CA== CQ== Cg== Cw== DA== DQ== Dg== Dw== EA== EQ== Eg== Ew== FA== FQ== Fg== Fw== GA== GQ== Gg== Gw== HA== HQ== Hg== Hw== IA== fw== gA== gQ== gg== gw== hA== hQ== hg== hw== iA== iQ== ig== iw== jA== jQ== jg== jw== kA== kQ== kg== kw== lA== lQ== lg== lw== mA== mQ== mg== mw== nA== nQ== ng== nw== oA== rQ== IHQ= IGE= aGU= aW4= cmU= b24= IHRoZQ== ZXI= IHM= YXQ= IHc= IG8= ZW4= IGM= aXQ= aXM= YW4= b3I= ZXM= IGI= ZWQ= IGY= aW5n IHA= b3U= IGFu YWw= YXI= IHRv IG0= IG9m IGlu IGQ= IGg= IGFuZA== aWM= YXM= bGU= IHRo aW9u b20= bGw= ZW50 IG4= IGw= c3Q= IHJl dmU= IGU= cm8= bHk= IGJl IGc= IFQ= Y3Q= IFM= aWQ= b3Q= IEk= dXQ= ZXQ= IEE= IGlz IG9u aW0= YW0= b3c= YXk= YWQ= c2U= IHRoYXQ= IEM= aWc= IGZvcg== YWM= IHk= dmVy dXI= IHU= bGQ= IHN0 IE0= J3M= IGhl IGl0 YXRpb24= aXRo aXI= Y2U= IHlvdQ== aWw= IEI= IHdo b2w= IFA= IHdpdGg= IDE= dGVy Y2g= IGFz IHdl ICg= bmQ= aWxs IEQ= aWY= IDI= YWc= ZXJz a2U= ICI= IEg= ZW0= IGNvbg== IFc= IFI= aGVy IHdhcw== IHI= b2Q= IEY= dWw= YXRl IGF0 cmk= cHA= b3Jl IFRoZQ== IHNl dXM= IHBybw== IGhh dW0= IGFyZQ== IGRl YWlu YW5k IG9y aWdo ZXN0 aXN0 YWI= cm9t IE4= dGg= IGNvbQ== IEc= dW4= b3A= MDA= IEw= IG5vdA== ZXNz IGV4 IHY= cmVz IEU= ZXc= aXR5 YW50 IGJ5 ZWw= b3M= b3J0 b2M= cXU= IGZyb20= IGhhdmU= IHN1 aXZl b3VsZA== IHNo IHRoaXM= bnQ= cmE= cGU= aWdodA== YXJ0 bWVudA== IGFs dXN0 ZW5k LS0= YWxs IE8= YWNr IGNo IGxl aWVz cmVk YXJk 4oA= b3V0 IEo= IGFi ZWFy aXY= YWxseQ== b3Vy b3N0 Z2g= cHQ= IHBs YXN0 I
! 50257 ICA= ICAg ICAgIA== ICAgICA= ICAgICAg ICAgICAgIA== ICAgICAgICA= ICAgICAgICAg ICAgICAgICAgIA== ICAgICAgICAgICA= ICAgICAgICAgICAg ICAgICAgICAgICAgIA== ICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgIA==`},CkI={pat_str:"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+",special_tokens:{"<|endoftext|>":50256,"<|fim_prefix|>":50281,"<|fim_middle|>":50282,"<|fim_suffix|>":50283},bpe_ranks:`! 0 IQ== Ig== Iw== JA== JQ== Jg== Jw== KA== KQ== Kg== Kw== LA== LQ== Lg== Lw== MA== MQ== Mg== Mw== NA== NQ== Ng== Nw== OA== OQ== Og== Ow== PA== PQ== Pg== Pw== QA== QQ== Qg== Qw== RA== RQ== Rg== Rw== SA== SQ== Sg== Sw== TA== TQ== Tg== Tw== UA== UQ== Ug== Uw== VA== VQ== Vg== Vw== WA== WQ== Wg== Ww== XA== XQ== Xg== Xw== YA== YQ== Yg== Yw== ZA== ZQ== Zg== Zw== aA== aQ== ag== aw== bA== bQ== bg== bw== cA== cQ== cg== cw== dA== dQ== dg== dw== eA== eQ== eg== ew== fA== fQ== fg== oQ== og== ow== pA== pQ== pg== pw== qA== qQ== qg== qw== rA== rg== rw== sA== sQ== sg== sw== tA== tQ== tg== tw== uA== uQ== ug== uw== vA== vQ== vg== vw== wA== wQ== wg== ww== xA== xQ== xg== xw== yA== yQ== yg== yw== zA== zQ== zg== zw== 0A== 0Q== 0g== 0w== 1A== 1Q== 1g== 1w== 2A== 2Q== 2g== 2w== 3A== 3Q== 3g== 3w== 4A== 4Q== 4g== 4w== 5A== 5Q== 5g== 5w== 6A== 6Q== 6g== 6w== 7A== 7Q== 7g== 7w== 8A== 8Q== 8g== 8w== 9A== 9Q== 9g== 9w== +A== +Q== +g== +w== /A== /Q== /g== /w== AA== AQ== Ag== Aw== BA== BQ== Bg== Bw== CA== CQ== Cg== Cw== DA== DQ== Dg== Dw== EA== EQ== Eg== Ew== FA== FQ== Fg== Fw== GA== GQ== Gg== Gw== HA== HQ== Hg== Hw== IA== fw== gA== gQ== gg== gw== hA== hQ== hg== hw== iA== iQ== ig== iw== jA== jQ== jg== jw== kA== kQ== kg== kw== lA== lQ== lg== lw== mA== mQ== mg== mw== nA== nQ== ng== nw== oA== rQ== IHQ= IGE= aGU= aW4= cmU= b24= IHRoZQ== ZXI= IHM= YXQ= IHc= IG8= ZW4= IGM= aXQ= aXM= YW4= b3I= ZXM= IGI= ZWQ= IGY= aW5n IHA= b3U= IGFu YWw= YXI= IHRv IG0= IG9m IGlu IGQ= IGg= IGFuZA== aWM= YXM= bGU= IHRo aW9u b20= bGw= ZW50 IG4= IGw= c3Q= IHJl dmU= IGU= cm8= bHk= IGJl IGc= IFQ= Y3Q= IFM= aWQ= b3Q= IEk= dXQ= ZXQ= IEE= IGlz IG9u aW0= YW0= b3c= YXk= YWQ= c2U= IHRoYXQ= IEM= aWc= IGZvcg== YWM= IHk= dmVy dXI= IHU= bGQ= IHN0 IE0= J3M= IGhl IGl0 YXRpb24= aXRo aXI= Y2U= IHlvdQ== aWw= IEI= IHdo b2w= IFA= IHdpdGg= IDE= dGVy Y2g= IGFz IHdl ICg= bmQ= aWxs IEQ= aWY= IDI= YWc= ZXJz a2U= ICI= IEg= ZW0= IGNvbg== IFc= IFI= aGVy IHdhcw== IHI= b2Q= IEY= dWw= YXRl IGF0 cmk= cHA= b3Jl IFRoZQ== IHNl dXM= IHBybw== IGhh dW0= IGFyZQ== IGRl YWlu YW5k IG9y aWdo ZXN0 aXN0 YWI= cm9t IE4= dGg= IGNvbQ== IEc= dW4= b3A= MDA= IEw= IG5vdA== ZXNz IGV4 IHY= cmVz IEU= ZXc= aXR5 YW50 IGJ5 ZWw= b3M= b3J0 b2M= cXU= IGZyb20= IGhhdmU= IHN1 aXZl b3VsZA== IHNo IHRoaXM= bnQ= cmE= cGU= aWdodA== YXJ0 bWVudA== IGFs dXN0 ZW5k LS0= YWxs IE8= YWNr IGNo IGxl aWVz cmVk YXJk 4oA= b3V0 IEo= IGFi ZWFy aXY= YWxseQ== b3Vy b3N0 Z2g= cHQ= IHBs YXN0 IGNhbg== YWs= b21l dWQ= VGhl IGhpcw== IGRv IGdv IGhhcw== Z2U= J3Q= IFU= cm91 IHNh IGo= IGJ1dA== IHdvcg== IGFsbA== ZWN0 IGs= YW1l IHdpbGw= b2s= IHdoZQ== IHRoZXk= aWRl MDE= ZmY= aWNo cGw= dGhlcg== IHRy Li4= IGludA== aWU= dXJl YWdl IG5l aWFs YXA= aW5l aWNl IG1l IG91dA== YW5z b25l b25n aW9ucw== IHdobw== IEs= IHVw IHRoZWly IGFk IDM= IHVz YXRlZA== b3Vz IG1vcmU= dWU= b2c= IFN0 aW5k aWtl IHNv aW1l cGVy LiI= YmVy aXo= YWN0 IG9uZQ== IHNhaWQ= IC0= YXJl IHlvdXI= Y2M= IFRo IGNs ZXA= YWtl YWJsZQ== aXA= IGNvbnQ= IHdoaWNo aWE= IGlt IGFib3V0 IHdlcmU= dmVyeQ== dWI= IGhhZA== IGVu IGNvbXA= LCI= IElu IHVu IGFn aXJl YWNl YXU= YXJ5 IHdvdWxk YXNz cnk= IOKA Y2w= b29r ZXJl c28= IFY= aWdu aWI= IG9mZg== IHRl dmVu IFk= aWxl b3Nl aXRl b3Jt IDIwMQ== IHJlcw== IG1hbg== IHBlcg== IG90aGVy b3Jk dWx0 IGJlZW4= IGxpa2U= YXNl YW5jZQ== a3M= YXlz b3du ZW5jZQ== IGRpcw== Y3Rpb24= IGFueQ== IGFwcA== IHNw aW50 cmVzcw== YXRpb25z YWls IDQ= aWNhbA== IHRoZW0= IGhlcg== b3VudA== IENo IGFy IGlm IHRoZXJl IHBl IHllYXI= YXY= IG15 IHN
! 50257 ICA= ICAg ICAgIA== ICAgICA= ICAgICAg ICAgICAgIA== ICAgICAgICA= ICAgICAgICAg ICAgICAgICAgIA== ICAgICAgICAgICA= ICAgICAgICAgICAg ICAgICAgICAgICAgIA== ICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgIA== ICAgICAgICAgICAgICAgICAgICAgICA= ICAgICAgICAgICAgICAgICAgICAgICAg ICAgICAgICAgICAgICAgICAgICAgICAgIA==`},JkI={explicit_n_vocab:50257,pat_str:"'s|'t|'re|'ve|'m|'ll|'d| ?\\p{L}+| ?\\p{N}+| ?[^\\s\\p{L}\\p{N}]+|\\s+(?!\\S)|\\s+",special_tokens:{"<|endoftext|>":50256},bpe_ranks:"! 0 IQ== Ig== Iw== JA== JQ== Jg== Jw== KA== KQ== Kg== Kw== LA== LQ== Lg== Lw== MA== MQ== Mg== Mw== NA== NQ== Ng== Nw== OA== OQ== Og== Ow== PA== PQ== Pg== Pw== QA== QQ== Qg== Qw== RA== RQ== Rg== Rw== SA== SQ== Sg== Sw== TA== TQ== Tg== Tw== UA== UQ== Ug== Uw== VA== VQ== Vg== Vw== WA== WQ== Wg== Ww== XA== XQ== Xg== Xw== YA== YQ== Yg== Yw== ZA== ZQ== Zg== Zw== aA== aQ== ag== aw== bA== bQ== bg== bw== cA== cQ== cg== cw== dA== dQ== dg== dw== eA== eQ== eg== ew== fA== fQ== fg== oQ== og== ow== pA== pQ== pg== pw== qA== qQ== qg== qw== rA== rg== rw== sA== sQ== sg== sw== tA== tQ== tg== tw== uA== uQ== ug== uw== vA== vQ== vg== vw== wA== wQ== wg== ww== xA== xQ== xg== xw== yA== yQ== yg== yw== zA== zQ== zg== zw== 0A== 0Q== 0g== 0w== 1A== 1Q== 1g== 1w== 2A== 2Q== 2g== 2w== 3A== 3Q== 3g== 3w== 4A== 4Q== 4g== 4w== 5A== 5Q== 5g== 5w== 6A== 6Q== 6g== 6w== 7A== 7Q== 7g== 7w== 8A== 8Q== 8g== 8w== 9A== 9Q== 9g== 9w== +A== +Q== +g== +w== /A== /Q== /g== /w== AA== AQ== Ag== Aw== BA== BQ== Bg== Bw== CA== CQ== Cg== Cw== DA== DQ== Dg== Dw== EA== EQ== Eg== Ew== FA== FQ== Fg== Fw== GA== GQ== Gg== Gw== HA== HQ== Hg== Hw== IA== fw== gA== gQ== gg== gw== hA== hQ== hg== hw== iA== iQ== ig== iw== jA== jQ== jg== jw== kA== kQ== kg== kw== lA== lQ== lg== lw== mA== mQ== mg== mw== nA== nQ== ng== nw== oA== rQ== IHQ= IGE= aGU= aW4= cmU= b24= IHRoZQ== ZXI= IHM= YXQ= IHc= IG8= ZW4= IGM= aXQ= aXM= YW4= b3I= ZXM= IGI= ZWQ= IGY= aW5n IHA= b3U= IGFu YWw= YXI= IHRv IG0= IG9m IGlu IGQ= IGg= IGFuZA== aWM= YXM= bGU= IHRo aW9u b20= bGw= ZW50 IG4= IGw= c3Q= IHJl dmU= IGU= cm8= bHk= IGJl IGc= IFQ= Y3Q= IFM= aWQ= b3Q= IEk= dXQ= ZXQ= IEE= IGlz IG9u aW0= YW0= b3c= YXk= YWQ= c2U= IHRoYXQ= IEM= aWc= IGZvcg== YWM= IHk= dmVy dXI= IHU= bGQ= IHN0 IE0= J3M= IGhl IGl0 YXRpb24= aXRo aXI= Y2U= IHlvdQ== aWw= IEI= IHdo b2w= IFA= IHdpdGg= IDE= dGVy Y2g= IGFz IHdl ICg= bmQ= aWxs IEQ= aWY= IDI= YWc= ZXJz a2U= ICI= IEg= ZW0= IGNvbg== IFc= IFI= aGVy IHdhcw== IHI= b2Q= IEY= dWw= YXRl IGF0 cmk= cHA= b3Jl IFRoZQ== IHNl dXM= IHBybw== IGhh dW0= IGFyZQ== IGRl YWlu YW5k IG9y aWdo ZXN0 aXN0 YWI= cm9t IE4= dGg= IGNvbQ== IEc= dW4= b3A= MDA= IEw= IG5vdA== ZXNz IGV4 IHY= cmVz IEU= ZXc= aXR5 YW50 IGJ5 ZWw= b3M= b3J0 b2M= cXU= IGZyb20= IGhhdmU= IHN1 aXZl b3VsZA== IHNo IHRoaXM= bnQ= cmE= cGU= aWdodA== YXJ0 bWVudA== IGFs dXN0 ZW5k LS0= YWxs IE8= YWNr IGNo IGxl aWVz cmVk YXJk 4oA= b3V0 IEo= IGFi ZWFy aXY= YWxseQ== b3Vy b3N0 Z2g= cHQ= IHBs YXN0 IGNhbg== YWs= b21l dWQ= VGhl IGhpcw== IGRv IGdv IGhhcw== Z2U= J3Q= IFU= cm91 IHNh IGo= IGJ1dA== IHdvcg== IGFsbA== ZWN0 IGs= YW1l IHdpbGw= b2s= IHdoZQ== IHRoZXk= aWRl MDE= ZmY= aWNo cGw= dGhlcg== IHRy Li4= IGludA== aWU= dXJl YWdl IG5l aWFs YXA= aW5l aWNl IG1l IG91dA== YW5z b25l b25n aW9ucw== IHdobw== IEs= IHVw IHRoZWly IGFk IDM= IHVz YXRlZA== b3Vz IG1vcmU= dWU= b2c= IFN0 aW5k aWtl IHNv aW1l cGVy LiI= YmVy aXo= YWN0 IG9uZQ== IHNhaWQ= IC0= YXJl IHlvdXI= Y2M= IFRo IGNs ZXA= YWtl YWJsZQ== aXA= IGNvbnQ= IHdoaWNo aWE= IGlt IGFib3V0 IHdlcmU= dmVyeQ== dWI= IGhhZA== IGVu IGNvbXA= LCI= IElu IHVu IGFn aXJl YWNl YXU= YXJ5 IHdvdWxk YXNz cnk= IOKA Y2w= b29r ZXJl c28= IFY= aWdu aWI= IG9mZg== IHRl dmVu IFk= aWxl b3Nl aXRl b3Jt IDIwMQ== IHJlcw== IG1hbg== IHBlcg== IG90aGVy b3Jk dWx0 IGJlZW4= IGxpa2U= YXNl YW5jZQ== a3M= YXlz b3du ZW5jZQ== IGRpcw== Y3Rpb24= IGFueQ== IGFwcA== IHNw aW50 cmVzcw== YXRpb25z YWls IDQ= aWNhbA== IHRoZW0= IGhlcg== b3VudA== IENo IGFy IGlm IHRoZXJl IHBl IHllYXI= YXY= IG15 IHNvbWU= IHdoZW4= b3VnaA== YWNo IHRoYW4= cnU= b25
`).slice(a,G+1).join(`
`),file:e,startLine:a+1,endLine:G+1}}function KlI(l){try{return l.workspace.getLeavesOfType("markdown").map(e=>e.view.file).filter(e=>!!e)}catch{return[]}}function Nx(l,I){let e=l.path.split("/"),t=I.path.split("/");if(e[0]!==t[0])return null;let a=0,G=0;for(;G<e.length&&G<t.length&&e[G]===t[G];)G++;return a+=e.length-G,a+=t.length-G,a}function Hr(l,I,e){let t=l.vault.getFileByPath(I);if(!t)return;let a=l.workspace.getLeavesOfType("markdown").find(G=>G.view instanceof Ap.MarkdownView&&G.view.file?.path===t.path);a?(l.workspace.setActiveLeaf(a,{focus:!0}),e&&a.view.setEphemeralState({line:e-1})):l.workspace.getLeaf("tab").openFile(t,{eState:e?{line:e-1}:void 0})}s();var px=require("obsidian"),_lI=/(?:youtube\.com\/(?:[^/]+\/.+\/|(?:v|e(?:mbed)?)\/|.*[?&]v=)|youtu\.be\/)([^"&?/\s]{11})/i,DlI="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.83 Safari/537.36,gzip(gfe)",kkI=/<text start="([^"]*)" dur="([^"]*)">([^<]*)<\/text>/g;function qlI(l){return _lI.test(l)}var Qr=class extends Error{constructor(I){super(`[YoutubeTranscript] \u{1F6A8} ${I}`)}},hx=class extends Qr{constructor(){super("YouTube is receiving too many requests from this IP and now requires solving a captcha to continue")}},Yx=class extends Qr{constructor(I){super(`The video is no longer available (${I})`)}},Pv=class extends Qr{constructor(I){super(`Transcript is disabled on this video (${I})`)}},$v=class extends Qr{constructor(I){super(`No transcripts are available for this video (${I})`)}},Vx=class extends Qr{constructor(I,e,t){super(`No transcripts are available in ${I} this video (${t}). Available languages: ${e.join(", ")}`)}},IE=class{static async fetchTranscriptAndMetadata(I,e){let t=this.retrieveVideoId(I),G=(await(0,px.requestUrl)({url:`https://www.youtube.com/watch?v=${t}`,headers:{...e?.lang&&{"Accept-Language":e.lang},"User-Agent":DlI}})).text,c=G.match(/<title>(.*?)<\/title>/),n=c?c[1].replace(" - YouTube","").trim():"",d=G.split('"captions":');if(d.length<=1)throw G.includes('class="g-recaptcha"')?new hx:G.includes('"playabilityStatus":')?new Pv(I):new Yx(I);let b=(()=>{try{return JSON.parse(d[1].split(',"videoDetails')[0].replace(`
`,""))}catch{return}})()?.playerCaptionsTracklistRenderer;if(!b)throw new Pv(I);if(!("captionTracks"in b))throw new $v(I);if(e?.lang&&!b.captionTracks.some(u=>u.languageCode===e?.lang))throw new Vx(e?.lang,b.captionTracks.map(u=>u.languageCode),I);let m=(e?.lang?b.captionTracks.find(u=>u.languageCode===e?.lang):b.captionTracks[0]).baseUrl,Z=await(0,px.requestUrl)({url:m,headers:{...e?.lang&&{"Accept-Language":e.lang},"User-Agent":DlI}});if(Z.status!==200)throw new $v(I);let o=[...Z.text.matchAll(kkI)];return{title:n,transcript:o.map(u=>({text:u[3],duration:parseFloat(u[2]),offset:parseFloat(u[1]),lang:e?.lang??b.captionTracks[0].languageCode}))}}static retrieveVideoId(I){if(I.length===11)return I;let e=I.match(_lI);if(e?.length)return e[1];throw new Qr("Impossible to retrieve Youtube video ID.")}};var lE=class{constructor(I,e,t){this.MAX_CONTEXT_MESSAGES=20;this.getRagEngine=I,this.app=e,this.settings=t}async generateRequestMessages({messages:I}){if(I.length===0)throw new Error("No messages provided");let e=await Promise.all(I.map(async m=>{if(m.role==="user"&&!m.promptContent){let{promptContent:Z,similaritySearchResults:r}=await this.compileUserMessagePrompt({message:m});return{...m,promptContent:Z,similaritySearchResults:r}}return m})),t;for(let m=e.length-1;m>=0;--m)if(e[m].role==="user"){t=e[m];break}if(!t)throw new Error("No user messages found");let a=t.similaritySearchResults!==void 0,G=this.getSystemMessage(a),c=this.getCustomInstructionMessage(),n=t.mentionables.find(m=>m.type==="current-file")?.file,d=n&&this.settings.chatOptions.includeCurrentFileContent?await this.getCurrentFileMessage(n):void 0;return[G,...c?[c]:[],...d?[d]:[],...this.getChatHistoryMessages({messages:e}),...a&&this.getModelPromptLevel()==1?[this.getRagInstructionMessage()]:[]]}getChatHistoryMessages({messages:I}){let e=I.slice(-this.MAX_CONTEXT_MESSAGES).flatMap(a=>a.role==="user"?[{role:"user",content:a.promptContent??""}]:a.role==="assistant"?this.parseAssistantMessage({message:a}):this.parseToolMessage({message:a}));return e.map(a=>{switch(a.role){case"user":return a;case"assistant":{let G=a.tool_calls?.filter(c=>e.some(n=>n.role==="tool"&&n.tool_call.id===c.id));return{...a,tool_calls:G&&G.length>0?G:void 0}}case"tool":return e.find(c=>c.role==="assistant"&&c.tool_calls?.some(n=>n.id===a.tool_call.id))?a:null;default:return a}}).filter(a=>a!==null)}parseAssistantMessage({message:I}){let e=null;return I.annotations&&I.annotations.length>0&&(e=`Citations:
${I.annotations.map((t,a)=>{if(t.type==="url_citation"){let{url:G,title:c}=t.url_citation;return`[${a+1}] ${c?`${c}: `:""}${G}`}}).join(`
`)}`),[{role:"assistant",content:[I.content,...e?[e]:[]].join(`
`),tool_calls:I.toolCallRequests}]}parseToolMessage({message:I}){return I.toolCalls.map(e=>{switch(e.response.status){case"pending_approval":case"running":case"rejected":case"aborted":return{role:"tool",tool_call:e.request,content:`Tool call ${e.request.id} is ${e.response.status}`};case"success":return{role:"tool",tool_call:e.request,content:e.response.data.text};case"error":return{role:"tool",tool_call:e.request,content:`Error: ${e.response.error}`}}})}async compileUserMessagePrompt({message:I,useVaultSearch:e,onQueryProgressChange:t}){try{if(!I.content)return{promptContent:"",shouldUseRAG:!1};let a=lm(I.content),G;e=e||I.mentionables.some(h=>h.type==="vault"),t?.({type:"reading-mentionables"});let c=I.mentionables.filter(h=>h.type==="file").map(h=>h.file),n=I.mentionables.filter(h=>h.type==="folder").map(h=>h.folder),d=n.flatMap(h=>Wx(h,this.app.vault)),b=[...c,...d],m=await jlI(b,this.app.vault),r=e||await(async()=>{let h=0;for(let F of m){let X=await TlI(F);if(h+=X,h>this.settings.ragOptions.thresholdTokens)return!0}return!1})(),o;r?(G=e?await(await this.getRagEngine()).processQuery({query:a,onQueryProgressChange:t}):await(await this.getRagEngine()).processQuery({query:a,scope:{files:c.map(h=>h.path),folders:n.map(h=>h.path)},onQueryProgressChange:t}),o=`## Potentially Relevant Snippets from the current vault
${G.map(({path:h,content:F,metadata:X})=>{let H=this.getModelPromptLevel()==1?this.addLineNumbersToContent({content:F,startLine:X.startLine}):F;return`\`\`\`${h}
${H}
\`\`\`
`}).join("")}
`):o=b.map((h,F)=>`\`\`\`${h.path}
${m[F]}
\`\`\`
`).join("");let N=I.mentionables.filter(h=>h.type==="block").map(({file:h,content:F})=>`\`\`\`${h.path}
${F}
\`\`\`
`).join(""),V=I.mentionables.filter(h=>h.type==="url"),Y=V.length>0?`## Potentially Relevant Websearch Results
${(await Promise.all(V.map(async({url:h})=>`\`\`\`
Website URL: ${h}
Website Content:
${await this.getWebsiteContent(h)}
\`\`\``))).join(`
`)}
`:"",p=I.mentionables.filter(h=>h.type==="image").map(({data:h})=>h);return t?.({type:"idle"}),{promptContent:[...p.map(h=>({type:"image_url",image_url:{url:h}})),{type:"text",text:`${o}${N}${Y}
${a}
`}],shouldUseRAG:r,similaritySearchResults:G}}catch(a){throw console.error("Failed to compile user message",a),t?.({type:"idle"}),a}}getSystemMessage(I){let e=this.getModelPromptLevel(),t=`You are an intelligent assistant to help answer any questions that the user has${e==1?", particularly about editing and organizing markdown files in Obsidian":""}.
1. Please keep your response as concise as possible. Avoid being verbose.
2. Do not lie or make up facts.
3. Format your response in markdown.
${e==1?`4. Respond in the same language as the user's message.
5. When writing out new markdown blocks, also wrap them with <smtcmp_block> tags. For example:
<smtcmp_block language="markdown">
{{ content }}
</smtcmp_block>
6. When providing markdown blocks for an existing file, add the filename and language attributes to the <smtcmp_block> tags. Restate the relevant section or heading, so the user knows which part of the file you are editing. For example:
<smtcmp_block filename="path/to/file.md" language="markdown">
## Section Title
...
{{ content }}
...
</smtcmp_block>
7. When the user is asking for edits to their markdown, please provide a simplified version of the markdown block emphasizing only the changes. Use comments to show where unchanged content has been skipped. Wrap the markdown block with <smtcmp_block> tags. Add filename and language attributes to the <smtcmp_block> tags. For example:
<smtcmp_block filename="path/to/file.md" language="markdown">
<!-- ... existing content ... -->
{{ edit_1 }}
<!-- ... existing content ... -->
{{ edit_2 }}
<!-- ... existing content ... -->
</smtcmp_block>
The user has full access to the file, so they prefer seeing only the changes in the markdown. Often this will mean that the start/end of the file will be skipped, but that's okay! Rewrite the entire file only if specifically requested. Always provide a brief explanation of the updates, except when the user specifically asks for just the content.
`:""}`,a=`You are an intelligent assistant to help answer any questions that the user has${e==1?", particularly about editing and organizing markdown files in Obsidian":""}. You will be given your conversation history with them and potentially relevant blocks of markdown content from the current vault.
1. Do not lie or make up facts.
2. Format your response in markdown.
${e==1?`3. Respond in the same language as the user's message.
4. When referencing markdown blocks in your answer, keep the following guidelines in mind:
a. Never include line numbers in the output markdown.
b. Wrap the markdown block with <smtcmp_block> tags. Include language attribute. For example:
<smtcmp_block language="markdown">
{{ content }}
</smtcmp_block>
c. When providing markdown blocks for an existing file, also include the filename attribute to the <smtcmp_block> tags. For example:
<smtcmp_block filename="path/to/file.md" language="markdown">
{{ content }}
</smtcmp_block>
d. When referencing a markdown block the user gives you, only add the startLine and endLine attributes to the <smtcmp_block> tags. Write related content outside of the <smtcmp_block> tags. The content inside the <smtcmp_block> tags will be ignored and replaced with the actual content of the markdown block. For example:
<smtcmp_block filename="path/to/file.md" language="markdown" startLine="2" endLine="30"></smtcmp_block>`:""}`;return{role:"system",content:I?a:t}}getCustomInstructionMessage(){let I=this.settings.systemPrompt.trim();return I?{role:"user",content:`Here are additional instructions to follow in your responses when relevant. There's no need to explicitly acknowledge them:
<custom_instructions>
${I}
</custom_instructions>`}:null}async getCurrentFileMessage(I){let e=await Yb(I,this.app.vault);return{role:"user",content:`# Inputs
## Current File
Here is the file I'm looking at.
\`\`\`${I.path}
${e}
\`\`\`
`}}getRagInstructionMessage(){return{role:"user",content:`If you need to reference any of the markdown blocks I gave you, add the startLine and endLine attributes to the <smtcmp_block> tags without any content inside. For example:
<smtcmp_block filename="path/to/file.md" language="markdown" startLine="200" endLine="310"></smtcmp_block>
When writing out new markdown blocks, remember not to include "line_number|" at the beginning of each line.`}}addLineNumbersToContent({content:I,startLine:e}){return I.split(`
`).map((G,c)=>`${e+c}|${G}`).join(`
`)}async getWebsiteContent(I){if(qlI(I))try{let{title:t,transcript:a}=await IE.fetchTranscriptAndMetadata(I);return`Title: ${t}
Video Transcript:
${a.map(G=>`${G.offset}: ${G.text}`).join(`
`)}`}catch(t){console.error("Error fetching YouTube transcript",t)}let e=await(0,tE.requestUrl)({url:I});return(0,tE.htmlToMarkdown)(e.text)}getModelPromptLevel(){return this.settings.chatModels.find(e=>e.id===this.settings.chatModelId)?.promptLevel??1}};s();s();var PlI=require("obsidian"),$lI=y(LV()),IeI=y(K()),fl=class extends PlI.Modal{constructor({app:e,Component:t,props:a,options:G}){super(e);this.root=null;this.Component=t,this.props=a,this.options=G}onOpen(){this.options?.title&&this.titleEl.setText(this.options.title),this.root=(0,$lI.createRoot)(this.contentEl),this.root.render((0,IeI.jsx)(this.Component,{...this.props,onClose:()=>this.close()}))}onClose(){this.root&&(this.root.unmount(),this.root=null),this.contentEl.empty()}};var em=y(K()),od=class extends fl{constructor(I,e,t,a,G={}){super({app:I,Component:xkI,props:{app:I,message:t,log:a,options:G},options:{title:e}})}};function xkI({app:l,message:I,log:e,onClose:t,options:a}){return(0,em.jsxs)("div",{className:"smtcmp-error-modal-content",children:[(0,em.jsx)("div",{className:"smtcmp-error-modal-message",children:I}),e&&(0,em.jsx)("pre",{className:"smtcmp-error-modal-log",children:e}),(0,em.jsxs)("div",{className:"modal-button-container",children:[a.showReportBugButton&&(0,em.jsx)("button",{className:"mod-cta",onClick:()=>{t(),window.open("https://github.com/glowingjade/obsidian-smart-composer/issues","_blank")},children:"Report Bug"}),a.showSettingsButton&&(0,em.jsx)("button",{className:"mod-cta",onClick:()=>{t(),l.setting.open(),l.setting.openTabById("smart-composer")},children:"Open Settings"}),(0,em.jsx)("button",{className:"mod-cancel",onClick:t,children:"Cancel"})]})]})}s();s();var k9=require("obsidian"),Yn=y(dI());s();var teI=require("obsidian"),Rb=y(dI());s();var leI=require("obsidian"),vc=y(dI());s();function Rx(...l){return l.filter(Boolean).join(" ")}var Fx=y(K()),eeI=(0,vc.createContext)({setting:null});function MI({name:l,desc:I,heading:e,className:t,required:a,children:G}){let[c,n]=(0,vc.useState)(null),d=(0,vc.useRef)(null),b=(0,vc.useRef)(""),m=(0,vc.useRef)("");return(0,vc.useEffect)(()=>{if(!d.current)return;let Z=new leI.Setting(d.current);return n(Z),b.current=Z.settingEl.className,m.current=Z.nameEl.className,()=>{Z.clear()}},[]),(0,vc.useEffect)(()=>{c&&(c.setName(l??""),c.setDesc(I??""),e&&c.setHeading(),c.settingEl.setAttrs({class:Rx(b.current,t??"")}),c.nameEl.setAttrs({class:Rx(m.current,a?"smtcmp-settings-required":"")}))},[l,I,e,t,c,a]),(0,Fx.jsx)(eeI.Provider,{value:{setting:c},children:(0,Fx.jsx)("div",{ref:d,children:G})})}var Vb=()=>{let l=(0,vc.useContext)(eeI);if(!l)throw new Error("useObsidianSetting must be used within ObsidianSetting");return l};var aeI=y(K());function Al({text:l,icon:I,tooltip:e,onClick:t,cta:a,warning:G,disabled:c}){let n=(0,Rb.useRef)(null),{setting:d}=Vb(),[b,m]=(0,Rb.useState)(null),Z=(0,Rb.useRef)(t);return(0,Rb.useEffect)(()=>{if(d){let r=null;return d.addButton(o=>{r=o}),m(r),()=>{r?.buttonEl.remove()}}else if(n.current){let r=new teI.ButtonComponent(n.current);return m(r),()=>{r?.buttonEl.remove()}}},[d]),(0,Rb.useEffect)(()=>{Z.current=t},[t]),(0,Rb.useEffect)(()=>{b&&b.onClick(()=>Z.current())},[b]),(0,Rb.useEffect)(()=>{b&&(l&&b.setButtonText(l),I&&b.setIcon(I),e&&b.setTooltip(e),a&&b.setCta(),G&&b.setWarning(),b.setDisabled(!!c))},[b,l,I,e,a,G,c]),(0,aeI.jsx)("div",{ref:n})}s();var Ku=y(K()),Oa=class extends fl{constructor(I,e){super({app:I,Component:fkI,props:{message:e.message,ctaText:e.ctaText,onConfirm:e.onConfirm,onCancel:e.onCancel},options:{title:e.title}})}};function fkI({message:l,ctaText:I,onConfirm:e,onCancel:t,onClose:a}){return(0,Ku.jsxs)("div",{children:[(0,Ku.jsx)("div",{style:{whiteSpace:"pre-wrap"},children:l}),(0,Ku.jsxs)("div",{className:"modal-button-container",children:[(0,Ku.jsx)("button",{className:"mod-warning",onClick:()=>{a(),e()},children:I??"Confirm"}),(0,Ku.jsx)("button",{className:"mod-cancel",onClick:()=>{a(),t?.()},children:"Cancel"})]})]})}s();s();s();s();s();var vf={};pe(vf,{$addUpdateTag:()=>Q3I,$applyNodeReplacement:()=>mF,$cloneWithProperties:()=>QtI,$co
`,n3I=Cr?"\xA0":HE,dtI="\u0591-\u07FF\uFB1D-\uFDFD\uFE70-\uFEFC",btI="A-Za-z\xC0-\xD6\xD8-\xF6\xF8-\u02B8\u0300-\u0590\u0800-\u1FFF\u200E\u2C00-\uFB1C\uFE00-\uFE6F\uFEFD-\uFFFF",d3I=new RegExp("^[^"+btI+"]*["+dtI+"]"),b3I=new RegExp("^[^"+dtI+"]*["+btI+"]"),Xb={bold:1,code:16,highlight:XE,italic:2,strikethrough:eF,subscript:32,superscript:64,underline:tF},s3I={directionless:1,unmergeable:2},GeI={center:Zf,end:Wf,justify:of,left:mf,right:rf,start:uf},m3I={[Zf]:"center",[Wf]:"end",[of]:"justify",[mf]:"left",[rf]:"right",[uf]:"start"},Z3I={normal:0,segmented:2,token:1},r3I={[$kI]:"normal",[l3I]:"segmented",[I3I]:"token"};function o3I(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var FI=o3I(function(l){let I=new URLSearchParams;I.append("code",l);for(let e=1;e<arguments.length;e++)I.append("v",arguments[e]);throw Error(`Minified Lexical error #${l}; visit https://lexical.dev/docs/error?${I} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)});function sE(...l){let I=[];for(let e of l)if(e&&typeof e=="string")for(let[t]of e.matchAll(/\S+/g))I.push(t);return I}var u3I=100,fx=!1,Nf=0;function W3I(l){Nf=l.timeStamp}function Xx(l,I,e){return I.__lexicalLineBreak===l||l[`__lexicalKey_${e._key}`]!==void 0}function i3I(l,I,e){let t=Qb(e._window),a=null,G=null;t!==null&&t.anchorNode===l&&(a=t.anchorOffset,G=t.focusOffset);let c=l.nodeValue;c!==null&&Rf(I,c,a,G,!1)}function N3I(l,I,e){if(ll(l)){let t=l.anchor.getNode();if(t.is(e)&&l.format!==t.getFormat())return!1}return I.nodeType===fr&&e.isAttached()}function stI(l,I,e){fx=!0;let t=performance.now()-Nf>u3I;try{Ec(l,()=>{let a=Ze()||function(r){return r.getEditorState().read(()=>{let o=Ze();return o!==null?o.clone():null})}(l),G=new Map,c=l.getRootElement(),n=l._editorState,d=l._blockCursorElement,b=!1,m="";for(let r=0;r<I.length;r++){let o=I[r],u=o.type,N=o.target,V=sF(N,n);if(!(V===null&&N!==c||Ce(V))){if(u==="characterData")t&&zI(V)&&N3I(a,N,V)&&i3I(N,V,l);else if(u==="childList"){b=!0;let Y=o.addedNodes;for(let F=0;F<Y.length;F++){let X=Y[F],H=WtI(X),Q=X.parentNode;if(Q!=null&&X!==d&&H===null&&(X.nodeName!=="BR"||!Xx(X,Q,l))){if(Cr){let E=X.innerText||X.nodeValue;E&&(m+=E)}Q.removeChild(X)}}let p=o.removedNodes,h=p.length;if(h>0){let F=0;for(let X=0;X<h;X++){let H=p[X];(H.nodeName==="BR"&&Xx(H,N,l)||d===H)&&(N.appendChild(H),F++)}h!==F&&(N===c&&(V=NtI(n)),G.set(N,V))}}}}if(G.size>0)for(let[r,o]of G)if(NI(o)){let u=o.getChildrenKeys(),N=r.firstChild;for(let V=0;V<u.length;V++){let Y=u[V],p=l.getElementByKey(Y);p!==null&&(N==null?(r.appendChild(p),N=p):N!==p&&r.replaceChild(p,N),N=N.nextSibling)}}else zI(o)&&o.markDirty();let Z=e.takeRecords();if(Z.length>0){for(let r=0;r<Z.length;r++){let o=Z[r],u=o.addedNodes,N=o.target;for(let V=0;V<u.length;V++){let Y=u[V],p=Y.parentNode;p==null||Y.nodeName!=="BR"||Xx(Y,N,l)||p.removeChild(Y)}}e.takeRecords()}a!==null&&(b&&(a.dirty=!0,Hb(a)),Cr&&VtI(l)&&a.insertRawText(m))})}finally{fx=!1}}function mtI(l){let I=l._observer;I!==null&&stI(l,I.takeRecords(),I)}function ZtI(l){(function(I){Nf===0&&EE(I).addEventListener("textInput",W3I,!0)})(l),l._observer=new MutationObserver((I,e)=>{stI(l,I,e)})}function ceI(l,I){let e=l.__mode,t=l.__format,a=l.__style,G=I.__mode,c=I.__format,n=I.__style;return!(e!==null&&e!==G||t!==null&&t!==c||a!==null&&a!==n)}function neI(l,I){let e=l.mergeWithSibling(I),t=Je()._normalizedNodes;return t.add(l.__key),t.add(I.__key),e}function deI(l){let I,e,t=l;if(t.__text!==""||!t.isSimpleText()||t.isUnmergeable()){for(;(I=t.getPreviousSibling())!==null&&zI(I)&&I.isSimpleText()&&!I.isUnmergeable();){if(I.__text!==""){if(ceI(I,t)){t=neI(I,t);break}break}I.remove()}for(;(e=t.getNextSibling())!==null&&zI(e)&&e.isSimpleText()&&!e.isUnmergeable();){if(e.__text!==""){if(ceI(t,e)){t=neI(t,e);break}break}e.remove()}}else t.remove()}function rtI(l){return beI(l.anchor),beI(l.focus),l}function beI(l){for(;l.type==="element";){let I=l.getNode(),e=l.offset,t,a;if(e===I.getChildrenSize()?(t=I.getChildAtIndex(e-1),a=!0):(t=I.getChildAtIn
`)e.preventDefault(),vI(t,K2,!1);else if(d===cm)e.preventDefault(),vI(t,Lx,void 0);else if(d==null&&e.dataTransfer){let o=e.dataTransfer.getData("text/plain");e.preventDefault(),c.insertRawText(o)}else d!=null&&xtI(c,G,d,e.timeStamp,!0)?(e.preventDefault(),vI(t,fp,d)):kp=d;LtI=e.timeStamp}})}(l,I)]);var _2=0,AtI=null,LtI=0,kp=null,NE=new WeakMap,qx=!1,Px=!1,q2=!1,S2=!1,ktI=[0,"",0,"root",0];function xtI(l,I,e,t,a){let G=l.anchor,c=l.focus,n=G.getNode(),d=Je(),b=Qb(d._window),m=b!==null?b.anchorNode:null,Z=G.key,r=d.getElementByKey(Z),o=e.length;return Z!==c.key||!zI(n)||(!a&&(!bE||LtI<t+50)||n.isDirty()&&o<2||ptI(e))&&G.offset!==c.offset&&!n.isComposing()||_u(n)||n.isDirty()&&o>1||(a||!bE)&&r!==null&&!n.isComposing()&&m!==mE(r)||b!==null&&I!==null&&(!I.collapsed||I.startContainer!==b.anchorNode||I.startOffset!==b.anchorOffset)||n.getFormat()!==l.format||n.getStyle()!==l.style||R3I(l,n)}function peI(l,I){return l!==null&&l.nodeValue!==null&&l.nodeType===fr&&I!==0&&I!==l.nodeValue.length}function heI(l,I,e){let{anchorNode:t,anchorOffset:a,focusNode:G,focusOffset:c}=l;qx&&(qx=!1,peI(t,a)&&peI(G,c))||Ec(I,()=>{if(!e)return void Hb(null);if(!dF(I,t,G))return;let n=Ze();if(ll(n)){let d=n.anchor,b=d.getNode();if(n.isCollapsed()){l.type==="Range"&&l.anchorNode===l.focusNode&&(n.dirty=!0);let m=EE(I).event,Z=m?m.timeStamp:performance.now(),[r,o,u,N,V]=ktI,Y=gc(),p=I.isComposing()===!1&&Y.getTextContent()==="";if(Z<V+200&&d.offset===u&&d.key===N)n.format=r,n.style=o;else if(d.type==="text")zI(b)||FI(141),n.format=b.getFormat(),n.style=b.getStyle();else if(d.type==="element"&&!p){let h=d.getNode();n.style="",h instanceof dm&&h.getChildrenSize()===0?(n.format=h.getTextFormat(),n.style=h.getTextStyle()):n.format=0}}else{let m=d.key,Z=n.focus.key,r=n.getNodes(),o=r.length,u=n.isBackward(),N=u?c:a,V=u?a:c,Y=u?Z:m,p=u?m:Z,h=ntI,F=!1;for(let X=0;X<o;X++){let H=r[X],Q=H.getTextContentSize();if(zI(H)&&Q!==0&&!(X===0&&H.__key===Y&&N===Q||X===o-1&&H.__key===p&&V===0)&&(F=!0,h&=H.getFormat(),h===0))break}n.format=F?h:0}}vI(I,RE,void 0)})}function ftI(l){if(!l.getTargetRanges)return null;let I=l.getTargetRanges();return I.length===0?null:I[0]}function Ex(l,I){let e=l._compositionKey;if(Ut(null),e!==null&&I!=null){if(I===""){let t=ua(e),a=mE(l.getElementByKey(e));return void(a!==null&&a.nodeValue!==null&&zI(t)&&Rf(t,a.nodeValue,null,null,!0))}if(I[I.length-1]===`
`){let t=Ze();if(ll(t)){let a=t.focus;return t.anchor.set(a.key,a.offset,a.type),void vI(l,dE,null)}}}Vf(!0,l,I)}function ztI(l){let I=l.__lexicalEventHandles;return I===void 0&&(I=[],l.__lexicalEventHandles=I),I}var zp=new Map;function UtI(l){let I=l.target,e=Qb(I==null?null:I.nodeType===9?I.defaultView:I.ownerDocument.defaultView);if(e===null)return;let t=hf(e.anchorNode);if(t===null)return;Px&&(Px=!1,Ec(t,()=>{let b=jp(),m=e.anchorNode;if(m===null)return;let Z=m.nodeType;Z!==nF&&Z!==fr||Hb(JE(b,e,t,l))}));let a=Yf(t),G=a[a.length-1],c=G._key,n=zp.get(c),d=n||G;d!==t&&heI(e,d,!1),heI(e,t,!0),t!==G?zp.set(c,t):n&&zp.delete(c)}function YeI(l){l._lexicalHandled=!0}function VeI(l){return l._lexicalHandled===!0}function x3I(l){let I=l.ownerDocument,e=NE.get(I);e===void 0&&FI(162);let t=e-1;t>=0||FI(164),NE.set(I,t),t===0&&I.removeEventListener("selectionchange",UtI);let a=bF(l);QE(a)?(function(c){if(c._parentEditor!==null){let n=Yf(c),d=n[n.length-1]._key;zp.get(d)===c&&zp.delete(d)}else zp.delete(c._key)}(a),l.__lexicalEditor=null):a&&FI(198);let G=ztI(l);for(let c=0;c<G.length;c++)G[c]();l.__lexicalEventHandles=[]}function $x(l,I,e){oG();let t=l.__key,a=l.getParent();if(a===null)return;let G=function(n){let d=Ze();if(!ll(d)||!NI(n))return d;let{anchor:b,focus:m}=d,Z=b.getNode(),r=m.getNode();return oE(Z,n)&&b.set(n.__key,0,"element"),oE(r,n)&&m.set(n.__key,0,"element"),d}(l),c=!1;if(ll(G)&&I){let n=G.anchor,d=G.focus;n.key===t&&(hE(n,l,a,l.getPreviousSibling(),l.getNextSibling()),c=!0),d.key===t&&(hE(d,l,a,l.getPreviousSibling(),l.getNextSibling()),c=!0)}else ZF(G)&&I&&l.isSelected()&&l.selectPrevious();if(ll(G)&&I&&!c){let n=l.getIndexWithinParent();qu(l),pE(G,a,n,-1)}else qu(l);e||Jr(a)||a.canBeEmpty()||!a.isEmpty()||$x(a,I),I&&TG(a)&&a.isEmpty()&&a.selectEnd()}var Mp=class{static getType(){FI(64,this.name)}static clone(I){FI(65,this.name)}afterCloneFrom(I){this.__parent=I.__parent,this.__next=I.__next,this.__prev=I.__prev}constructor(I){this.__type=this.constructor.getType(),this.__parent=null,this.__prev=null,this.__next=null,utI(this,I)}getType(){return this.__type}isInline(){FI(137,this.constructor.name)}isAttached(){let I=this.__key;for(;I!==null;){if(I==="root")return!0;let e=ua(I);if(e===null)break;I=e.__parent}return!1}isSelected(I){let e=I||Ze();if(e==null)return!1;let t=e.getNodes().some(a=>a.__key===this.__key);if(zI(this))return t;if(ll(e)&&e.anchor.type==="element"&&e.focus.type==="element"){if(e.isCollapsed())return!1;let a=this.getParent();if(Ce(this)&&this.isInline()&&a){let G=e.isBackward()?e.focus:e.anchor,c=G.getNode();if(G.offset===c.getChildrenSize()&&c.is(a)&&c.getLastChildOrThrow().is(this))return!1}}return t}getKey(){return this.__key}getIndexWithinParent(){let I=this.getParent();if(I===null)return-1;let e=I.getFirstChild(),t=0;for(;e!==null;){if(this.is(e))return t;t++,e=e.getNextSibling()}return-1}getParent(){let I=this.getLatest().__parent;return I===null?null:ua(I)}getParentOrThrow(){let I=this.getParent();return I===null&&FI(66,this.__key),I}getTopLevelElement(){let I=this;for(;I!==null;){let e=I.getParent();if(Jr(e))return NI(I)||I===this&&Ce(I)||FI(194),I;I=e}return null}getTopLevelElementOrThrow(){let I=this.getTopLevelElement();return I===null&&FI(67,this.__key),I}getParents(){let I=[],e=this.getParent();for(;e!==null;)I.push(e),e=e.getParent();return I}getParentKeys(){let I=[],e=this.getParent();for(;e!==null;)I.push(e.__key),e=e.getParent();return I}getPreviousSibling(){let I=this.getLatest().__prev;return I===null?null:ua(I)}getPreviousSiblings(){let I=[],e=this.getParent();if(e===null)return I;let t=e.getFirstChild();for(;t!==null&&!t.is(this);)I.push(t),t=t.getNextSibling();return I}getNextSibling(){let I=this.getLatest().__next;return I===null?null:ua(I)}getNextSiblings(){let I=[],e=this.getNextSibling();for(;e!==null;)I.push(e),e=e.getNextSibling();return I}getCommonAncestor(I){let e=this.getParents(),t=I.getParents();NI(this)&&e.unshift(this),NI(I)&&t.unshift(I);let a=e.length,G=t.length;if(a===0||G===0||e[a-1]!==t[G-1])return null;let c=new Set(t);for(let n=0;n<a;n++){let d=e[n
`}createDOM(){return document.createElement("br")}updateDOM(){return!1}static importDOM(){return{br:I=>function(e){let t=e.parentElement;if(t!==null&&Mx(t)){let a=t.firstChild;if(a===e||a.nextSibling===e&&aE(a)){let G=t.lastChild;if(G===e||G.previousSibling===e&&aE(G))return!0}}return!1}(I)||function(e){let t=e.parentElement;if(t!==null&&Mx(t)){let a=t.firstChild;if(a===e||a.nextSibling===e&&aE(a))return!1;let G=t.lastChild;if(G===e||G.previousSibling===e&&aE(G))return!0}return!1}(I)?null:{conversion:f3I,priority:0}}}static importJSON(I){return Op()}exportJSON(){return{type:"linebreak",version:1}}};function f3I(l){return{node:Op()}}function Op(){return mF(new Lr)}function Pu(l){return l instanceof Lr}function aE(l){return l.nodeType===fr&&/^( |\t|\r?\n)+$/.test(l.textContent||"")}function gx(l,I){return 16&I?"code":I&XE?"mark":32&I?"sub":64&I?"sup":null}function yx(l,I){return 1&I?"strong":2&I?"em":"span"}function MtI(l,I,e,t,a){let G=t.classList,c=D2(a,"base");c!==void 0&&G.add(...c),c=D2(a,"underlineStrikethrough");let n=!1,d=I&tF&&I&eF;c!==void 0&&(e&tF&&e&eF?(n=!0,d||G.add(...c)):d&&G.remove(...c));for(let b in Xb){let m=Xb[b];if(c=D2(a,b),c!==void 0)if(e&m){if(n&&(b==="underline"||b==="strikethrough")){I&m&&G.remove(...c);continue}I&m&&(!d||b!=="underline")&&b!=="strikethrough"||G.add(...c)}else I&m&&G.remove(...c)}}function OtI(l,I,e){let t=I.firstChild,a=e.isComposing(),G=l+(a?HE:"");if(t==null)I.textContent=G;else{let c=t.nodeValue;if(c!==G)if(a||Cr){let[n,d,b]=function(m,Z){let r=m.length,o=Z.length,u=0,N=0;for(;u<r&&u<o&&m[u]===Z[u];)u++;for(;N+u<r&&N+u<o&&m[r-N-1]===Z[o-N-1];)N++;return[u,r-u-N,Z.slice(u,o-N)]}(c,G);d!==0&&t.deleteData(n,d),t.insertData(n,b)}else t.nodeValue=G}}function ReI(l,I,e,t,a,G){OtI(a,l,I);let c=G.theme.text;c!==void 0&&MtI(0,0,t,l,c)}function GE(l,I){let e=document.createElement(I);return e.appendChild(l),e}var nm=class extends Mp{static getType(){return"text"}static clone(I){return new nm(I.__text,I.__key)}afterCloneFrom(I){super.afterCloneFrom(I),this.__format=I.__format,this.__style=I.__style,this.__mode=I.__mode,this.__detail=I.__detail}constructor(I,e){super(e),this.__text=I,this.__format=0,this.__style="",this.__mode=0,this.__detail=0}getFormat(){return this.getLatest().__format}getDetail(){return this.getLatest().__detail}getMode(){let I=this.getLatest();return r3I[I.__mode]}getStyle(){return this.getLatest().__style}isToken(){return this.getLatest().__mode===1}isComposing(){return this.__key===gr()}isSegmented(){return this.getLatest().__mode===2}isDirectionless(){return!!(1&this.getLatest().__detail)}isUnmergeable(){return!!(2&this.getLatest().__detail)}hasFormat(I){let e=Xb[I];return!!(this.getFormat()&e)}isSimpleText(){return this.__type==="text"&&this.__mode===0}getTextContent(){return this.getLatest().__text}getFormatFlags(I,e){return zx(this.getLatest().__format,I,e)}canHaveFormat(){return!0}createDOM(I,e){let t=this.__format,a=gx(0,t),G=yx(0,t),c=a===null?G:a,n=document.createElement(c),d=n;this.hasFormat("code")&&n.setAttribute("spellcheck","false"),a!==null&&(d=document.createElement(G),n.appendChild(d)),ReI(d,this,0,t,this.__text,I);let b=this.__style;return b!==""&&(n.style.cssText=b),n}updateDOM(I,e,t){let a=this.__text,G=I.__format,c=this.__format,n=gx(0,G),d=gx(0,c),b=yx(0,G),m=yx(0,c);if((n===null?b:n)!==(d===null?m:d))return!0;if(n===d&&b!==m){let N=e.firstChild;N==null&&FI(48);let V=document.createElement(m);return ReI(V,this,0,c,a,t),e.replaceChild(V,N),!1}let Z=e;d!==null&&n!==null&&(Z=e.firstChild,Z==null&&FI(49)),OtI(a,Z,this);let r=t.theme.text;r!==void 0&&G!==c&&MtI(0,G,c,Z,r);let o=I.__style,u=this.__style;return o!==u&&(e.style.cssText=u),!1}static importDOM(){return{"#text":()=>({conversion:O3I,priority:0}),b:()=>({conversion:U3I,priority:0}),code:()=>({conversion:wr,priority:0}),em:()=>({conversion:wr,priority:0}),i:()=>({conversion:wr,priority:0}),s:()=>({conversion:wr,priority:0}),span:()=>({conversion:z3I,priority:0}),strong:()=>({conversion:wr,priority:0}),sub:()=>({conversion:wr,priority:0}),sup:()=>({conversion:wr,priority:0}),u:()=>({conversi
`||n===`\r
`?a.push(Op()):n===" "?a.push(CE()):n!==""&&a.push(oa(n))}return{node:a}}if(e=e.replace(/\r/g,"").replace(/[ \t\n]+/g," "),e==="")return{node:null};if(e[0]===" "){let t=I,a=!0;for(;t!==null&&(t=XeI(t,!1))!==null;){let G=t.textContent||"";if(G.length>0){/[ \t\n]$/.test(G)&&(e=e.slice(1)),a=!1;break}}a&&(e=e.slice(1))}if(e[e.length-1]===" "){let t=I,a=!0;for(;t!==null&&(t=XeI(t,!0))!==null;)if((t.textContent||"").replace(/^( |\t|\r?\n)+/,"").length>0){a=!1;break}a&&(e=e.slice(0,e.length-1))}return e===""?{node:null}:{node:oa(e)}}function XeI(l,I){let e=l;for(;;){let t;for(;(t=I?e.nextSibling:e.previousSibling)===null;){let G=e.parentElement;if(G===null)return null;e=G}if(e=t,e.nodeType===nF){let G=e.style.display;if(G===""&&!XtI(e)||G!==""&&!G.startsWith("inline"))return null}let a=e;for(;(a=I?e.firstChild:e.lastChild)!==null;)e=a;if(e.nodeType===fr)return e;if(e.nodeName==="BR")return null}}var B3I={code:"code",em:"italic",i:"italic",s:"strikethrough",strong:"bold",sub:"subscript",sup:"superscript",u:"underline"};function wr(l){let I=B3I[l.nodeName.toLowerCase()];return I===void 0?{node:null}:{forChild:Hf(l.style,I),node:null}}function oa(l=""){return mF(new nm(l))}function zI(l){return l instanceof nm}function Hf(l,I){let e=l.fontWeight,t=l.textDecoration.split(" "),a=e==="700"||e==="bold",G=t.includes("line-through"),c=l.fontStyle==="italic",n=t.includes("underline"),d=l.verticalAlign;return b=>(zI(b)&&(a&&!b.hasFormat("bold")&&b.toggleFormat("bold"),G&&!b.hasFormat("strikethrough")&&b.toggleFormat("strikethrough"),c&&!b.hasFormat("italic")&&b.toggleFormat("italic"),n&&!b.hasFormat("underline")&&b.toggleFormat("underline"),d!=="sub"||b.hasFormat("subscript")||b.toggleFormat("subscript"),d!=="super"||b.hasFormat("superscript")||b.toggleFormat("superscript"),I&&!b.hasFormat(I)&&b.toggleFormat(I)),b)}var kr=class extends nm{static getType(){return"tab"}static clone(I){return new kr(I.__key)}afterCloneFrom(I){super.afterCloneFrom(I),this.__text=I.__text}constructor(I){super(" ",I),this.__detail=2}static importDOM(){return null}static importJSON(I){let e=CE();return e.setFormat(I.format),e.setStyle(I.style),e}exportJSON(){return{...super.exportJSON(),type:"tab",version:1}}setTextContent(I){FI(126)}setDetail(I){FI(127)}setMode(I){FI(128)}canInsertTextBefore(){return!1}canInsertTextAfter(){return!1}};function CE(){return mF(new kr)}function BtI(l){return l instanceof kr}var If=class{constructor(I,e,t){this._selection=null,this.key=I,this.offset=e,this.type=t}is(I){return this.key===I.key&&this.offset===I.offset&&this.type===I.type}isBefore(I){let e=this.getNode(),t=I.getNode(),a=this.offset,G=I.offset;if(NI(e)){let c=e.getDescendantByIndex(a);e=c??e}if(NI(t)){let c=t.getDescendantByIndex(G);t=c??t}return e===t?a<G:e.isBefore(t)}getNode(){let I=ua(this.key);return I===null&&FI(20),I}set(I,e,t){let a=this._selection,G=this.key;this.key=I,this.offset=e,this.type=t,Kp()||(gr()===G&&Ut(I),a!==null&&(a.setCachedNodes(null),a.dirty=!0))}};function Nd(l,I,e){return new If(l,I,e)}function Cx(l,I){let e=I.__key,t=l.offset,a="element";if(zI(I)){a="text";let G=I.getTextContentSize();t>G&&(t=G)}else if(!NI(I)){let G=I.getNextSibling();if(zI(G))e=G.__key,t=0,a="text";else{let c=I.getParent();c&&(e=c.__key,t=I.getIndexWithinParent()+1)}}l.set(e,t,a)}function HeI(l,I){if(NI(I)){let e=I.getLastDescendant();NI(e)||zI(e)?Cx(l,e):Cx(l,I)}else Cx(l,I)}function vr(l,I,e,t){l.key=I,l.offset=e,l.type=t}var Bp=class{constructor(I){this._cachedNodes=null,this._nodes=I,this.dirty=!1}getCachedNodes(){return this._cachedNodes}setCachedNodes(I){this._cachedNodes=I}is(I){if(!ZF(I))return!1;let e=this._nodes,t=I._nodes;return e.size===t.size&&Array.from(e).every(a=>t.has(a))}isCollapsed(){return!1}isBackward(){return!1}getStartEndPoints(){return null}add(I){this.dirty=!0,this._nodes.add(I),this._cachedNodes=null}delete(I){this.dirty=!0,this._nodes.delete(I),this._cachedNodes=null}clear(){this.dirty=!0,this._nodes.clear(),this._cachedNodes=null}has(I){return this._nodes.has(I)}clone(){return new Bp(new Set(this._nodes))}extract(){return this.getNodes()}inser
`),m=!r.isEmpty();else if(m=!1,zI(r)){let o=r.getTextContent();r===e?r===t?a.type==="element"&&G.type==="element"&&G.offset!==a.offset||(o=n<d?o.slice(n,d):o.slice(d,n)):o=c?o.slice(n):o.slice(d):r===t&&(o=c?o.slice(0,d):o.slice(0,n)),b+=o}else!Ce(r)&&!Pu(r)||r===t&&this.isCollapsed()||(b+=r.getTextContent())}return b}applyDOMRange(I){let e=Je(),t=e.getEditorState()._selection,a=TtI(I.startContainer,I.startOffset,I.endContainer,I.endOffset,e,t);if(a===null)return;let[G,c]=a;vr(this.anchor,G.key,G.offset,G.type),vr(this.focus,c.key,c.offset,c.type),this._cachedNodes=null}clone(){let I=this.anchor,e=this.focus;return new wb(Nd(I.key,I.offset,I.type),Nd(e.key,e.offset,e.type),this.format,this.style)}toggleFormat(I){this.format=zx(this.format,I,null),this.dirty=!0}setStyle(I){this.style=I,this.dirty=!0}hasFormat(I){let e=Xb[I];return!!(this.format&e)}insertRawText(I){let e=I.split(/(\r?\n|\t)/),t=[],a=e.length;for(let G=0;G<a;G++){let c=e[G];c===`
`||c===`\r
`?t.push(Op()):c===" "?t.push(CE()):t.push(oa(c))}this.insertNodes(t)}insertText(I){let e=this.anchor,t=this.focus,a=this.format,G=this.style,c=e,n=t;!this.isCollapsed()&&t.isBefore(e)&&(c=t,n=e),c.type==="element"&&function(V,Y,p,h){let F=V.getNode(),X=F.getChildAtIndex(V.offset),H=oa(),Q=TG(F)?Gm().append(H):H;H.setFormat(p),H.setStyle(h),X===null?F.append(Q):X.insertBefore(Q),V.is(Y)&&Y.set(H.__key,0,"text"),V.set(H.__key,0,"text")}(c,n,a,G);let d=c.offset,b=n.offset,m=this.getNodes(),Z=m.length,r=m[0];zI(r)||FI(26);let o=r.getTextContent().length,u=r.getParentOrThrow(),N=m[Z-1];if(Z===1&&n.type==="element"&&(b=o,n.set(c.key,b,"text")),this.isCollapsed()&&d===o&&(r.isSegmented()||r.isToken()||!r.canInsertTextAfter()||!u.canInsertTextAfter()&&r.getNextSibling()===null)){let V=r.getNextSibling();if(zI(V)&&V.canInsertTextBefore()&&!_u(V)||(V=oa(),V.setFormat(a),V.setStyle(G),u.canInsertTextAfter()?r.insertAfter(V):u.insertAfter(V)),V.select(0,0),r=V,I!=="")return void this.insertText(I)}else if(this.isCollapsed()&&d===0&&(r.isSegmented()||r.isToken()||!r.canInsertTextBefore()||!u.canInsertTextBefore()&&r.getPreviousSibling()===null)){let V=r.getPreviousSibling();if(zI(V)&&!_u(V)||(V=oa(),V.setFormat(a),u.canInsertTextBefore()?r.insertBefore(V):u.insertBefore(V)),V.select(),r=V,I!=="")return void this.insertText(I)}else if(r.isSegmented()&&d!==o){let V=oa(r.getTextContent());V.setFormat(a),r.replace(V),r=V}else if(!this.isCollapsed()&&I!==""){let V=N.getParent();if(!u.canInsertTextBefore()||!u.canInsertTextAfter()||NI(V)&&(!V.canInsertTextBefore()||!V.canInsertTextAfter()))return this.insertText(""),StI(this.anchor,this.focus,null),void this.insertText(I)}if(Z===1){if(r.isToken()){let h=oa(I);return h.select(),void r.replace(h)}let V=r.getFormat(),Y=r.getStyle();if(d!==b||V===a&&Y===G){if(BtI(r)){let h=oa(I);return h.setFormat(a),h.setStyle(G),h.select(),void r.replace(h)}}else{if(r.getTextContent()!==""){let h=oa(I);if(h.setFormat(a),h.setStyle(G),h.select(),d===0)r.insertBefore(h,!1);else{let[F]=r.splitText(d);F.insertAfter(h,!1)}return void(h.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=I.length))}r.setFormat(a),r.setStyle(G)}let p=b-d;r=r.spliceText(d,p,I,!0),r.getTextContent()===""?r.remove():this.anchor.type==="text"&&(r.isComposing()?this.anchor.offset-=I.length:(this.format=V,this.style=Y))}else{let V=new Set([...r.getParentKeys(),...N.getParentKeys()]),Y=NI(r)?r:r.getParentOrThrow(),p=NI(N)?N:N.getParentOrThrow(),h=N;if(!Y.is(p)&&p.isInline())do h=p,p=p.getParentOrThrow();while(p.isInline());if(n.type==="text"&&(b!==0||N.getTextContent()==="")||n.type==="element"&&N.getIndexWithinParent()<b)if(zI(N)&&!N.isToken()&&b!==N.getTextContentSize()){if(N.isSegmented()){let E=oa(N.getTextContent());N.replace(E),N=E}TG(n.getNode())||n.type!=="text"||(N=N.spliceText(0,b,"")),V.add(N.__key)}else{let E=N.getParentOrThrow();E.canBeEmpty()||E.getChildrenSize()!==1?N.remove():E.remove()}else V.add(N.__key);let F=p.getChildren(),X=new Set(m),H=Y.is(p),Q=Y.isInline()&&r.getNextSibling()===null?Y:r;for(let E=F.length-1;E>=0;E--){let C=F[E];if(C.is(r)||NI(C)&&C.isParentOf(r))break;C.isAttached()&&(!X.has(C)||C.is(h)?H||Q.insertAfter(C,!1):C.remove())}if(!H){let E=p,C=null;for(;E!==null;){let x=E.getChildren(),T=x.length;(T===0||x[T-1].is(C))&&(V.delete(E.__key),C=E),E=E.getParent()}}if(r.isToken())if(d===o)r.select();else{let E=oa(I);E.select(),r.replace(E)}else r=r.spliceText(d,o-d,I,!0),r.getTextContent()===""?r.remove():r.isComposing()&&this.anchor.type==="text"&&(this.anchor.offset-=I.length);for(let E=1;E<Z;E++){let C=m[E],x=C.__key;V.has(x)||C.remove()}}}removeText(){this.insertText("")}formatText(I){if(this.isCollapsed())return this.toggleFormat(I),void Ut(null);let e=this.getNodes(),t=[];for(let p of e)zI(p)&&t.push(p);let a=t.length;if(a===0)return this.toggleFormat(I),void Ut(null);let G=this.anchor,c=this.focus,n=this.isBackward(),d=n?c:G,b=n?G:c,m=0,Z=t[0],r=d.type==="element"?0:d.offset;if(d.type==="text"&&r===Z.getTextContentSize()&&(m=1,Z=t[1],r=0),Z==null)return;let o=Z.getFormatFlags(I,null),u=a-1
`);let d=n.length;if(!nl(t)||a>=d){let b=t.getParent();t.remove(),b==null||b.getChildrenSize()!==0||eW(b)||b.remove(),a-=d+c,t=G}else{let b=t.getKey(),m=l.getEditorState().read(()=>{let o=taI(b);return nl(o)&&o.isSimpleText()?o.getTextContent():null}),Z=d-a,r=n.slice(0,Z);if(m!==null&&m!==n){let o=uF(),u=t;if(t.isSimpleText())t.setTextContent(m);else{let N=Wn(m);t.replace(N),u=N}if(KI(o)&&o.isCollapsed()){let N=o.anchor.offset;u.select(N,N)}}else if(t.isSimpleText()){let o=I.key===b,u=I.offset;u<a&&(u=d);let N=o?u-a:0,V=o?u:Z;if(o&&N===0){let[Y]=t.splitText(N,V);Y.remove()}else{let[,Y]=t.splitText(N,V);Y.remove()}}else{let o=Wn(r);t.replace(o)}a=0}}}function ZxI(l){let I=l.getStyle(),e=TaI(I);jE.set(I,e)}function $p(l,I){let e=KE("getStyle"in l?l.getStyle():l.style),t=Object.entries(I).reduce((G,[c,n])=>(typeof n=="function"?G[c]=n(e[c],l):n===null?delete G[c]:G[c]=n,G),{...e}),a=function(G){let c="";for(let n in G)n&&(c+=`${n}: ${G[n]};`);return c}(t);l.setStyle(a),jE.set(a,t)}function rxI(l,I){let e=l.getNodes(),t=e.length,a=l.getStartEndPoints();if(a===null)return;let[G,c]=a,n=t-1,d=e[0],b=e[n];if(l.isCollapsed()&&KI(l))return void $p(l,I);let m=d.getTextContent().length,Z=c.offset,r=G.offset,o=G.isBefore(c),u=o?r:Z,N=o?Z:r,V=o?G.type:c.type,Y=o?c.type:G.type,p=o?c.key:G.key;if(nl(d)&&u===m){let h=d.getNextSibling();nl(h)&&(r=0,u=0,d=h)}if(e.length===1){if(nl(d)&&d.canHaveFormat()){if(u=V==="element"?0:r>Z?Z:r,N=Y==="element"?m:r>Z?r:Z,u===N)return;if(xE(d)||u===0&&N===m)$p(d,I),d.select(u,N);else{let h=d.splitText(u,N),F=u===0?h[0]:h[1];$p(F,I),F.select(0,N-u)}}}else{if(nl(d)&&u<d.getTextContentSize()&&d.canHaveFormat()&&(u===0||xE(d)||(d=d.splitText(u)[1],u=0,o?G.set(d.getKey(),u,"text"):c.set(d.getKey(),u,"text")),$p(d,I)),nl(b)&&b.canHaveFormat()){let h=b.getTextContent().length;b.__key!==p&&N!==0&&(N=h),N===h||xE(b)||([b]=b.splitText(N)),N===0&&Y!=="element"||$p(b,I)}for(let h=1;h<n;h++){let F=e[h],X=F.getKey();nl(F)&&F.canHaveFormat()&&X!==d.getKey()&&X!==b.getKey()&&!F.isToken()&&$p(F,I)}}}function oxI(l,I){if(l===null)return;let e=l.getStartEndPoints(),t=e?e[0]:null;if(t!==null&&t.key==="root"){let c=I(),n=Bt(),d=n.getFirstChild();return void(d?d.replace(c,!0):n.append(c))}let a=l.getNodes(),G=t!==null&&function(c,n){let d=c;for(;d!==null&&d.getParent()!==null&&!n(d);)d=d.getParentOrThrow();return n(d)?d:null}(t.getNode(),SaI);G&&a.indexOf(G)===-1&&a.push(G);for(let c=0;c<a.length;c++){let n=a[c];if(!SaI(n))continue;hl(n)||xf(178);let d=I();d.setFormat(n.getFormatType()),d.setIndent(n.getIndent()),n.replace(d,!0)}}function BaI(l){return l.getNode().isAttached()}function uxI(l){let I=l;for(;I!==null&&!gb(I);){let e=I.getLatest(),t=I.getParent();e.getChildrenSize()===0&&I.remove(!0),I=t}}function WxI(l,I,e=null){let t=l.getStartEndPoints(),a=t?t[0]:null,G=l.getNodes(),c=G.length;if(a!==null&&(c===0||c===1&&a.type==="element"&&a.getNode().getChildrenSize()===0)){let b=a.type==="text"?a.getNode().getParentOrThrow():a.getNode(),m=b.getChildren(),Z=I();return Z.setFormat(b.getFormatType()),Z.setIndent(b.getIndent()),m.forEach(r=>Z.append(r)),e&&(Z=e.append(Z)),void b.replace(Z)}let n=null,d=[];for(let b=0;b<c;b++){let m=G[b];gb(m)?(kf(l,d,d.length,I,e),d=[],n=m):n===null||n!==null&&aaI(m,n)?d.push(m):(kf(l,d,d.length,I,e),d=[m])}kf(l,d,d.length,I,e)}function kf(l,I,e,t,a=null){if(I.length===0)return;let G=I[0],c=new Map,n=[],d=hl(G)?G:G.getParentOrThrow();d.isInline()&&(d=d.getParentOrThrow());let b=!1;for(;d!==null;){let u=d.getPreviousSibling();if(u!==null){d=u,b=!0;break}if(d=d.getParentOrThrow(),gb(d))break}let m=new Set;for(let u=0;u<e;u++){let N=I[u];hl(N)&&N.getChildrenSize()===0&&m.add(N.getKey())}let Z=new Set;for(let u=0;u<e;u++){let N=I[u],V=N.getParent();if(V!==null&&V.isInline()&&(V=V.getParent()),V!==null&&GaI(N)&&!Z.has(N.getKey())){let Y=V.getKey();if(c.get(Y)===void 0){let p=t();p.setFormat(V.getFormatType()),p.setIndent(V.getIndent()),n.push(p),c.set(Y,p),V.getChildren().forEach(h=>{p.append(h),Z.add(h.getKey()),hl(h)&&h.getChildrenKeys().forEach(F=>Z.add(F))}),uxI(V)}}else if(m.has(N.getKey())){h
`||b===`\r
`?d.insertParagraph():b===" "?d.insertNodes([AE()]):d.insertText(b)}}}else I.insertRawText(G)}function Kf(l,I,e){l.dispatchCommand(CaI,{nodes:I,selection:e})||e.insertNodes(I)}function WGI(l,I,e,t=[]){let a=I===null||e.isSelected(I),G=hl(e)&&e.excludeFromCopy("html"),c=e;if(I!==null){let b=zr(e);b=nl(b)&&I!==null?DE(I,b):b,c=b}let n=hl(c)?c.getChildren():[],d=function(b){let m=b.exportJSON(),Z=b.constructor;if(m.type!==Z.getType()&&_E(58,Z.name),hl(b)){let r=m.children;Array.isArray(r)||_E(59,Z.name)}return m}(c);if(nl(c)){let b=c.__text;b.length>0?d.text=b:a=!1}for(let b=0;b<n.length;b++){let m=n[b],Z=WGI(l,I,m,d.children);!a&&hl(e)&&Z&&e.extractWithChild(m,I,"clone")&&(a=!0)}if(a&&!G)t.push(d);else if(Array.isArray(d.children))for(let b=0;b<d.children.length;b++){let m=d.children[b];t.push(m)}return a}function iGI(l,I){let e=[],t=Bt().getChildren();for(let a=0;a<t.length;a++)WGI(l,I,t[a],e);return{namespace:l._config.namespace,nodes:e}}function NGI(l){let I=[];for(let e=0;e<l.length;e++){let t=l[e],a=fE(t);nl(a)&&_aI(a),I.push(a)}return I}var Ih=null;async function ZfI(l,I,e){if(Ih!==null)return!1;if(I!==null)return new Promise((d,b)=>{l.update(()=>{d(ZGI(l,I,e))})});let t=l.getRootElement(),a=l._window==null?window.document:l._window.document,G=rGI(l._window);if(t===null||G===null)return!1;let c=a.createElement("span");c.style.cssText="position: fixed; top: -1000px;",c.append(a.createTextNode("#")),t.append(c);let n=new Range;return n.setStart(c,0),n.setEnd(c,1),G.removeAllRanges(),G.addRange(n),new Promise((d,b)=>{let m=l.registerCommand(ME,Z=>(bm(Z,ClipboardEvent)&&(m(),Ih!==null&&(window.clearTimeout(Ih),Ih=null),d(ZGI(l,Z,e))),!0),raI);Ih=window.setTimeout(()=>{m(),Ih=null,d(!1)},50),a.execCommand("copy"),c.remove()})}function ZGI(l,I,e){if(e===void 0){let a=rGI(l._window);if(!a)return!1;let G=a.anchorNode,c=a.focusNode;if(G!==null&&c!==null&&!UaI(l,G,c))return!1;let n=PI();if(n===null)return!1;e=pGI(n)}I.preventDefault();let t=I.clipboardData;return t!==null&&(hGI(t,e),!0)}var rfI=[["text/html",oGI],["application/x-lexical-editor",uGI]];function pGI(l=PI()){let I={"text/plain":l?l.getTextContent():""};if(l){let e=eaI();for(let[t,a]of rfI){let G=a(e,l);G!==null&&(I[t]=G)}}return I}function hGI(l,I){for(let e in I){let t=I[e];t!==void 0&&l.setData(e,t)}}var Cb=Df,YGI=Cb.$generateJSONFromSelectedNodes,_f=Cb.$generateNodesFromSerializedNodes,wQl=Cb.$getClipboardDataFromSelection,vQl=Cb.$getHtmlContent,EQl=Cb.$getLexicalContent,gQl=Cb.$insertDataTransferForPlainText,qf=Cb.$insertDataTransferForRichText,yQl=Cb.$insertGeneratedNodes,Pf=Cb.copyToClipboard,CQl=Cb.setLexicalClipboardDataTransfer;var nW=require("obsidian"),fb=y(dI());s();s();s();var $f={};pe($f,{LexicalComposerContext:()=>VGI,createLexicalComposerContext:()=>WfI,useLexicalComposerContext:()=>ifI});s();var qE=y(dI(),1);function ofI(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var ufI=ofI(function(l){let I=new URLSearchParams;I.append("code",l);for(let e=1;e<arguments.length;e++)I.append("v",arguments[e]);throw Error(`Minified Lexical error #${l}; visit https://lexical.dev/docs/error?${I} for the full message or use the non-minified dev environment for full errors and additional helpful warnings.`)}),VGI=(0,qE.createContext)(null);function WfI(l,I){let e=null;return l!=null&&(e=l[1]),{getTheme:function(){return I??(e!=null?e.getTheme():null)}}}function ifI(){let l=(0,qE.useContext)(VGI);return l==null&&ufI(8),l}var I9=$f,RGI=I9.LexicalComposerContext,FGI=I9.createLexicalComposerContext,Fl=I9.useLexicalComposerContext;var l9={};pe(l9,{LexicalComposer:()=>pfI});s();var lh=y(dI(),1),XGI=y(K(),1),HGI=typeof window<"u"&&window.document!==void 0&&window.document.createElement!==void 0,NfI=HGI?lh.useLayoutEffect:lh.useEffect,PE={tag:"history-merge"};function pfI({initialConfig:l,children:I}){let e=(0,lh.useMemo)(()=>{let{theme:t,namespace:a,nodes:G,onError:c,editorState:n,html:d}=l,b=FGI(null,t),m=LaI({editable:l.editable,html:d,namespace:a,nodes:G,onError:Z=>c(Z,m),theme:t});return function(Z,r){if(r!==null){if(r===void
${l}
\`\`\``,scale:e})})}var Mb=y(K()),dMI=(0,Ob.memo)(function({reasoning:I}){let[e,t]=(0,Ob.useState)(!1),[a,G]=(0,Ob.useState)(!1),c=(0,Ob.useRef)(I),n=(0,Ob.useRef)(!1);return(0,Ob.useEffect)(()=>{if(c.current!==I&&c.current!==""){G(!0),n.current||t(!0);let b=setTimeout(()=>{G(!1)},1e3);return()=>clearTimeout(b)}c.current=I},[I]),(0,Mb.jsxs)("div",{className:"smtcmp-assistant-message-metadata",children:[(0,Mb.jsxs)("div",{className:"smtcmp-assistant-message-metadata-toggle",onClick:()=>{n.current=!0,t(!e)},children:[(0,Mb.jsxs)("span",{children:["Reasoning ",a&&(0,Mb.jsx)(Tr,{})]}),e?(0,Mb.jsx)(dG,{className:"smtcmp-assistant-message-metadata-toggle-icon"}):(0,Mb.jsx)(Vt,{className:"smtcmp-assistant-message-metadata-toggle-icon"})]}),e&&(0,Mb.jsx)("div",{className:"smtcmp-assistant-message-metadata-content",children:(0,Mb.jsx)(Hd,{content:I,scale:"xs"})})]})}),Cg=dMI;s();var TF=y(dI());s();var Kr=y(dI());var wnI=y(K()),HnI=(0,Kr.createContext)(void 0);function QnI({children:l}){let[I,e]=(0,Kr.useState)(!1),t=ee();return(0,Kr.useEffect)(()=>{let a=()=>{e(document.body.classList.contains("theme-dark"))};return a(),t.workspace.on("css-change",a),()=>t.workspace.off("css-change",a)},[]),(0,wnI.jsx)(HnI.Provider,{value:{isDarkMode:I},children:l})}function Jg(){let l=(0,Kr.useContext)(HnI);if(l===void 0)throw new Error("useDarkModeContext must be used within a DarkModeProvider");return l}s();var RpI=y(dI());s();s();s();s();function Ag(l,I){if(l==null)return{};var e={};for(var t in l)if({}.hasOwnProperty.call(l,t)){if(I.includes(t))continue;e[t]=l[t]}return e}function vnI(l,I){if(l==null)return{};var e,t,a=Ag(l,I);if(Object.getOwnPropertySymbols){var G=Object.getOwnPropertySymbols(l);for(t=0;t<G.length;t++)e=G[t],I.includes(e)||{}.propertyIsEnumerable.call(l,e)&&(a[e]=l[e])}return a}s();s();s();function kF(l,I){(I==null||I>l.length)&&(I=l.length);for(var e=0,t=Array(I);e<I;e++)t[e]=l[e];return t}function EnI(l){if(Array.isArray(l))return kF(l)}s();function gnI(l){if(typeof Symbol<"u"&&l[Symbol.iterator]!=null||l["@@iterator"]!=null)return Array.from(l)}s();function ynI(l,I){if(l){if(typeof l=="string")return kF(l,I);var e={}.toString.call(l).slice(8,-1);return e==="Object"&&l.constructor&&(e=l.constructor.name),e==="Map"||e==="Set"?Array.from(l):e==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(e)?kF(l,I):void 0}}s();function CnI(){throw new TypeError(`Invalid attempt to spread non-iterable instance.
In order to be iterable, non-array objects must have a [Symbol.iterator]() method.`)}function JnI(l){return EnI(l)||gnI(l)||ynI(l)||CnI()}s();s();s();function mW(l){return mW=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(I){return typeof I}:function(I){return I&&typeof Symbol=="function"&&I.constructor===Symbol&&I!==Symbol.prototype?"symbol":typeof I},mW(l)}s();function AnI(l,I){if(mW(l)!="object"||!l)return l;var e=l[Symbol.toPrimitive];if(e!==void 0){var t=e.call(l,I||"default");if(mW(t)!="object")return t;throw new TypeError("@@toPrimitive must return a primitive value.")}return(I==="string"?String:Number)(l)}function LnI(l){var I=AnI(l,"string");return mW(I)=="symbol"?I:I+""}function Lg(l,I,e){return(I=LnI(I))in l?Object.defineProperty(l,I,{value:e,enumerable:!0,configurable:!0,writable:!0}):l[I]=e,l}var Dr=y(dI());s();s();function sh(){return sh=Object.assign?Object.assign.bind():function(l){for(var I=1;I<arguments.length;I++){var e=arguments[I];for(var t in e)({}).hasOwnProperty.call(e,t)&&(l[t]=e[t])}return l},sh.apply(null,arguments)}var fnI=y(dI());function knI(l,I){var e=Object.keys(l);if(Object.getOwnPropertySymbols){var t=Object.getOwnPropertySymbols(l);I&&(t=t.filter(function(a){return Object.getOwnPropertyDescriptor(l,a).enumerable})),e.push.apply(e,t)}return e}function mh(l){for(var I=1;I<arguments.length;I++){var e=arguments[I]!=null?arguments[I]:{};I%2?knI(Object(e),!0).forEach(function(t){Lg(l,t,e[t])}):Object.getOwnPropertyDescriptors?Object.defineProperties(l,Object.getOwnPropertyDescriptors(e)):knI(Object(e)).forEach(function(t){Object.defineProperty(l,t,Object.getOwnPropertyDescriptor(e,t))})}return l}function bMI(l){var I=l.length;if(I===0||I===1)return l;if(I===2)return[l[0],l[1],"".concat(l[0],".").concat(l[1]),"".concat(l[1],".").concat(l[0])];if(I===3)return[l[0],l[1],l[2],"".concat(l[0],".").concat(l[1]),"".concat(l[0],".").concat(l[2]),"".concat(l[1],".").concat(l[0]),"".concat(l[1],".").concat(l[2]),"".concat(l[2],".").concat(l[0]),"".concat(l[2],".").concat(l[1]),"".concat(l[0],".").concat(l[1],".").concat(l[2]),"".concat(l[0],".").concat(l[2],".").concat(l[1]),"".concat(l[1],".").concat(l[0],".").concat(l[2]),"".concat(l[1],".").concat(l[2],".").concat(l[0]),"".concat(l[2],".").concat(l[0],".").concat(l[1]),"".concat(l[2],".").concat(l[1],".").concat(l[0])];if(I>=4)return[l[0],l[1],l[2],l[3],"".concat(l[0],".").concat(l[1]),"".concat(l[0],".").concat(l[2]),"".concat(l[0],".").concat(l[3]),"".concat(l[1],".").concat(l[0]),"".concat(l[1],".").concat(l[2]),"".concat(l[1],".").concat(l[3]),"".concat(l[2],".").concat(l[0]),"".concat(l[2],".").concat(l[1]),"".concat(l[2],".").concat(l[3]),"".concat(l[3],".").concat(l[0]),"".concat(l[3],".").concat(l[1]),"".concat(l[3],".").concat(l[2]),"".concat(l[0],".").concat(l[1],".").concat(l[2]),"".concat(l[0],".").concat(l[1],".").concat(l[3]),"".concat(l[0],".").concat(l[2],".").concat(l[1]),"".concat(l[0],".").concat(l[2],".").concat(l[3]),"".concat(l[0],".").concat(l[3],".").concat(l[1]),"".concat(l[0],".").concat(l[3],".").concat(l[2]),"".concat(l[1],".").concat(l[0],".").concat(l[2]),"".concat(l[1],".").concat(l[0],".").concat(l[3]),"".concat(l[1],".").concat(l[2],".").concat(l[0]),"".concat(l[1],".").concat(l[2],".").concat(l[3]),"".concat(l[1],".").concat(l[3],".").concat(l[0]),"".concat(l[1],".").concat(l[3],".").concat(l[2]),"".concat(l[2],".").concat(l[0],".").concat(l[1]),"".concat(l[2],".").concat(l[0],".").concat(l[3]),"".concat(l[2],".").concat(l[1],".").concat(l[0]),"".concat(l[2],".").concat(l[1],".").concat(l[3]),"".concat(l[2],".").concat(l[3],".").concat(l[0]),"".concat(l[2],".").concat(l[3],".").concat(l[1]),"".concat(l[3],".").concat(l[0],".").concat(l[1]),"".concat(l[3],".").concat(l[0],".").concat(l[2]),"".concat(l[3],".").concat(l[1],".").concat(l[0]),"".concat(l[3],".").concat(l[1],".").concat(l[2]),"".concat(l[3],".").concat(l[2],".").concat(l[0]),"".concat(l[3],".").concat(l[2],".").concat(l[1]),"".concat(l[0],".").concat(l[1],".").concat(l[2],".").concat(l[3]),"".concat(l[0],".").concat(l[1],".").concat(
`))})}function iMI(l){var I=l.codeString,e=l.codeStyle,t=l.containerStyle,a=t===void 0?{float:"left",paddingRight:"10px"}:t,G=l.numberStyle,c=G===void 0?{}:G,n=l.startingLineNumber;return Dr.default.createElement("code",{style:Object.assign({},e,a)},WMI({lines:I.replace(/\n$/,"").split(`
`),style:c,startingLineNumber:n}))}function NMI(l){return"".concat(l.toString().length,".25em")}function MnI(l,I){return{type:"element",tagName:"span",properties:{key:"line-number--".concat(l),className:["comment","linenumber","react-syntax-highlighter-line-number"],style:I},children:[{type:"text",value:l}]}}function OnI(l,I,e){var t={display:"inline-block",minWidth:NMI(e),paddingRight:"1em",textAlign:"right",userSelect:"none"},a=typeof l=="function"?l(I):l,G=Bb(Bb({},t),a);return G}function xg(l){var I=l.children,e=l.lineNumber,t=l.lineNumberStyle,a=l.largestLineNumber,G=l.showInlineLineNumbers,c=l.lineProps,n=c===void 0?{}:c,d=l.className,b=d===void 0?[]:d,m=l.showLineNumbers,Z=l.wrapLongLines,r=typeof n=="function"?n(e):n;if(r.className=b,e&&G){var o=OnI(t,e,a);I.unshift(MnI(e,o))}return Z&m&&(r.style=Bb(Bb({},r.style),{},{display:"flex"})),{type:"element",tagName:"span",properties:r,children:I}}function BnI(l){for(var I=arguments.length>1&&arguments[1]!==void 0?arguments[1]:[],e=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[],t=0;t<l.length;t++){var a=l[t];if(a.type==="text")e.push(xg({children:[a],className:JnI(new Set(I))}));else if(a.children){var G=I.concat(a.properties.className);BnI(a.children,G).forEach(function(c){return e.push(c)})}}return e}function pMI(l,I,e,t,a,G,c,n,d){var b,m=BnI(l.value),Z=[],r=-1,o=0;function u(X,H){var Q=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return xg({children:X,lineNumber:H,lineNumberStyle:n,largestLineNumber:c,showInlineLineNumbers:a,lineProps:e,className:Q,showLineNumbers:t,wrapLongLines:d})}function N(X,H){if(t&&H&&a){var Q=OnI(n,H,c);X.unshift(MnI(H,Q))}return X}function V(X,H){var Q=arguments.length>2&&arguments[2]!==void 0?arguments[2]:[];return I||Q.length>0?u(X,H,Q):N(X,H)}for(var Y=function(){var H=m[o],Q=H.children[0].value,E=uMI(Q);if(E){var C=Q.split(`
`);C.forEach(function(x,T){var S=t&&Z.length+G,B={type:"text",value:"".concat(x,`
`)};if(T===0){var O=m.slice(r+1,o).concat(xg({children:[B],className:H.properties.className})),_=V(O,S);Z.push(_)}else if(T===C.length-1){var P=m[o+1]&&m[o+1].children&&m[o+1].children[0],tI={type:"text",value:"".concat(x)};if(P){var mI=xg({children:[tI],className:H.properties.className});m.splice(o+1,0,mI)}else{var $=[tI],hI=V($,S,H.properties.className);Z.push(hI)}}else{var VI=[B],BI=V(VI,S,H.properties.className);Z.push(BI)}}),r=o}o++};o<m.length;)Y();if(r!==m.length-1){var p=m.slice(r+1,m.length);if(p&&p.length){var h=t&&Z.length+G,F=V(p,h);Z.push(F)}}return I?Z:(b=[]).concat.apply(b,Z)}function hMI(l){var I=l.rows,e=l.stylesheet,t=l.useInlineStyles;return I.map(function(a,G){return kg({node:a,stylesheet:e,useInlineStyles:t,key:"code-segement".concat(G)})})}function SnI(l){return l&&typeof l.highlightAuto<"u"}function YMI(l){var I=l.astGenerator,e=l.language,t=l.code,a=l.defaultCodeValue;if(SnI(I)){var G=znI(I,e);return e==="text"?{value:a,language:"text"}:G?I.highlight(e,t):I.highlightAuto(t)}try{return e&&e!=="text"?{value:I.highlight(t,e)}:{value:a}}catch{return{value:a}}}function TnI(l,I){return function(t){var a=t.language,G=t.children,c=t.style,n=c===void 0?I:c,d=t.customStyle,b=d===void 0?{}:d,m=t.codeTagProps,Z=m===void 0?{className:a?"language-".concat(a):void 0,style:Bb(Bb({},n['code[class*="language-"]']),n['code[class*="language-'.concat(a,'"]')])}:m,r=t.useInlineStyles,o=r===void 0?!0:r,u=t.showLineNumbers,N=u===void 0?!1:u,V=t.showInlineLineNumbers,Y=V===void 0?!0:V,p=t.startingLineNumber,h=p===void 0?1:p,F=t.lineNumberContainerStyle,X=t.lineNumberStyle,H=X===void 0?{}:X,Q=t.wrapLines,E=t.wrapLongLines,C=E===void 0?!1:E,x=t.lineProps,T=x===void 0?{}:x,S=t.renderer,B=t.PreTag,O=B===void 0?"pre":B,_=t.CodeTag,P=_===void 0?"code":_,tI=t.code,mI=tI===void 0?(Array.isArray(G)?G[0]:G)||"":tI,$=t.astGenerator,hI=vnI(t,rMI);$=$||l;var VI=N?Dr.default.createElement(iMI,{containerStyle:F,codeStyle:Z.style||{},numberStyle:H,startingLineNumber:h,codeString:mI}):null,BI=n.hljs||n['pre[class*="language-"]']||{backgroundColor:"#fff"},aI=SnI($)?"hljs":"prismjs",q=o?Object.assign({},hI,{style:Object.assign({},BI,b)}):Object.assign({},hI,{className:hI.className?"".concat(aI," ").concat(hI.className):aI,style:Object.assign({},b)});if(C?Z.style=Bb(Bb({},Z.style),{},{whiteSpace:"pre-wrap"}):Z.style=Bb(Bb({},Z.style),{},{whiteSpace:"pre"}),!$)return Dr.default.createElement(O,q,VI,Dr.default.createElement(P,Z,mI));(Q===void 0&&S||C)&&(Q=!0),S=S||hMI;var j=[{type:"text",value:mI}],eI=YMI({astGenerator:$,language:a,code:mI,defaultCodeValue:j});eI.language===null&&(eI.value=j);var lI=eI.value.length+h,GI=pMI(eI,Q,T,N,Y,h,lI,H,C);return Dr.default.createElement(O,q,Dr.default.createElement(P,Z,!Y&&VI,S({rows:GI,stylesheet:n,useInlineStyles:o})))}}s();var jnI=["abap","abnf","actionscript","ada","agda","al","antlr4","apacheconf","apex","apl","applescript","aql","arduino","arff","asciidoc","asm6502","asmatmel","aspnet","autohotkey","autoit","avisynth","avro-idl","bash","basic","batch","bbcode","bicep","birb","bison","bnf","brainfuck","brightscript","bro","bsl","c","cfscript","chaiscript","cil","clike","clojure","cmake","cobol","coffeescript","concurnas","coq","cpp","crystal","csharp","cshtml","csp","css-extras","css","csv","cypher","d","dart","dataweave","dax","dhall","diff","django","dns-zone-file","docker","dot","ebnf","editorconfig","eiffel","ejs","elixir","elm","erb","erlang","etlua","excel-formula","factor","false","firestore-security-rules","flow","fortran","fsharp","ftl","gap","gcode","gdscript","gedcom","gherkin","git","glsl","gml","gn","go-module","go","graphql","groovy","haml","handlebars","haskell","haxe","hcl","hlsl","hoon","hpkp","hsts","http","ichigojam","icon","icu-message-format","idris","iecst","ignore","inform7","ini","io","j","java","javadoc","javadoclike","javascript","javastacktrace","jexl","jolie","jq","js-extras","js-templates","jsdoc","json","json5","jsonp","jsstacktrace","jsx","julia","keepalived","keyman","kotlin","kumir","kusto","latex","latte","less","lilypond","liquid","lisp","livescript","llvm","log",
`).slice(I-1,e).join(`
`);b(N)}r()},[l,I,e,a.vault]);let Z=()=>{Hr(a,l,I)};return d&&(0,Qd.jsxs)("div",{className:yc("smtcmp-code-block",l&&"has-filename"),children:[(0,Qd.jsxs)("div",{className:"smtcmp-code-block-header",children:[l&&(0,Qd.jsx)("div",{className:"smtcmp-code-block-header-filename",onClick:Z,children:l}),(0,Qd.jsx)("div",{className:"smtcmp-code-block-header-button-container",children:(0,Qd.jsxs)("button",{className:"clickable-icon smtcmp-code-block-header-button",onClick:()=>{n(!c)},children:[(0,Qd.jsx)(td,{size:12}),c?"View Raw Text":"View Formatted"]})})]}),c?(0,Qd.jsx)("div",{className:"smtcmp-code-block-obsidian-markdown",children:(0,Qd.jsx)(Hd,{content:d,scale:"sm"})}):(0,Qd.jsx)($g,{isDarkMode:G,language:t,hasFilename:!!l,wrapLines:m,children:d})]})}var Sb=y(K());function fS({content:l,contextMessages:I,handleApply:e,isApplying:t}){let a=(0,Wh.useCallback)(G=>{e(G,I)},[e,I]);return(0,Sb.jsx)(pSI,{onApply:a,isApplying:t,children:l})}var pSI=Wh.default.memo(function({onApply:I,isApplying:e,children:t}){let a=(0,Wh.useMemo)(()=>hnI(t),[t]);return(0,Sb.jsx)(Sb.Fragment,{children:a.map((G,c)=>G.type==="string"?(0,Sb.jsx)("div",{children:(0,Sb.jsx)(Hd,{content:G.content,scale:"sm"})},c):G.type==="think"?(0,Sb.jsx)(Cg,{reasoning:G.content},c):G.startLine&&G.endLine&&G.filename?(0,Sb.jsx)(xS,{filename:G.filename,startLine:G.startLine,endLine:G.endLine},c):(0,Sb.jsx)(kS,{onApply:I,isApplying:e,language:G.language,filename:G.filename,children:G.content},c))})});s();s();var sl=y(dI(),1);s();function qI(l,I,{checkForDefaultPrevented:e=!0}={}){return function(a){if(l?.(a),e===!1||!a.defaultPrevented)return I?.(a)}}s();var XpI=y(dI(),1);function hSI(l,I){typeof l=="function"?l(I):l!=null&&(l.current=I)}function uW(...l){return I=>l.forEach(e=>hSI(e,I))}function re(...l){return XpI.useCallback(uW(...l),l)}s();var om=y(dI(),1),HpI=y(K(),1);function $r(l,I=[]){let e=[];function t(G,c){let n=om.createContext(c),d=e.length;e=[...e,c];let b=Z=>{let{scope:r,children:o,...u}=Z,N=r?.[l]?.[d]||n,V=om.useMemo(()=>u,Object.values(u));return(0,HpI.jsx)(N.Provider,{value:V,children:o})};b.displayName=G+"Provider";function m(Z,r){let o=r?.[l]?.[d]||n,u=om.useContext(o);if(u)return u;if(c!==void 0)return c;throw new Error(`\`${Z}\` must be used within \`${G}\``)}return[b,m]}let a=()=>{let G=e.map(c=>om.createContext(c));return function(n){let d=n?.[l]||G;return om.useMemo(()=>({[`__scope${l}`]:{...n,[l]:d}}),[n,d])}};return a.scopeName=l,[t,YSI(a,...I)]}function YSI(...l){let I=l[0];if(l.length===1)return I;let e=()=>{let t=l.map(a=>({useScope:a(),scopeName:a.scopeName}));return function(G){let c=t.reduce((n,{useScope:d,scopeName:b})=>{let Z=d(G)[`__scope${b}`];return{...n,...Z}},{});return om.useMemo(()=>({[`__scope${I.scopeName}`]:c}),[c])}};return e.scopeName=I.scopeName,e}s();var Be=y(dI(),1);s();var QpI=y(dI(),1),wpI=y(pZ(),1);s();var ia=y(dI(),1);var ih=y(K(),1),Tb=ia.forwardRef((l,I)=>{let{children:e,...t}=l,a=ia.Children.toArray(e),G=a.find(VSI);if(G){let c=G.props.children,n=a.map(d=>d===G?ia.Children.count(c)>1?ia.Children.only(null):ia.isValidElement(c)?c.props.children:null:d);return(0,ih.jsx)(zS,{...t,ref:I,children:ia.isValidElement(c)?ia.cloneElement(c,void 0,n):null})}return(0,ih.jsx)(zS,{...t,ref:I,children:e})});Tb.displayName="Slot";var zS=ia.forwardRef((l,I)=>{let{children:e,...t}=l;if(ia.isValidElement(e)){let a=FSI(e);return ia.cloneElement(e,{...RSI(t,e.props),ref:I?uW(I,a):a})}return ia.Children.count(e)>1?ia.Children.only(null):null});zS.displayName="SlotClone";var US=({children:l})=>(0,ih.jsx)(ih.Fragment,{children:l});function VSI(l){return ia.isValidElement(l)&&l.type===US}function RSI(l,I){let e={...I};for(let t in I){let a=l[t],G=I[t];/^on[A-Z]/.test(t)?a&&G?e[t]=(...n)=>{G(...n),a(...n)}:a&&(e[t]=a):t==="style"?e[t]={...a,...G}:t==="className"&&(e[t]=[a,G].filter(Boolean).join(" "))}return{...l,...e}}function FSI(l){let I=Object.getOwnPropertyDescriptor(l.props,"ref")?.get,e=I&&"isReactWarning"in I&&I.isReactWarning;return e?l.ref:(I=Object.getOwnPropertyDescriptor(l,"ref")?.get,e=I&&"isReactWarning"in I&&I.isReactWarni
.`.concat(mT,` {
overflow: hidden `).concat(t,`;
padding-right: `).concat(n,"px ").concat(t,`;
}
body[`).concat(Hh,`] {
overflow: hidden `).concat(t,`;
overscroll-behavior: contain;
`).concat([I&&"position: relative ".concat(t,";"),e==="margin"&&`
padding-left: `.concat(a,`px;
padding-top: `).concat(G,`px;
padding-right: `).concat(c,`px;
margin-left:0;
margin-top:0;
margin-right: `).concat(n,"px ").concat(t,`;
`),e==="padding"&&"padding-right: ".concat(n,"px ").concat(t,";")].filter(Boolean).join(""),`
}
.`).concat(HW,` {
right: `).concat(n,"px ").concat(t,`;
}
.`).concat(QW,` {
margin-right: `).concat(n,"px ").concat(t,`;
}
.`).concat(HW," .").concat(HW,` {
right: 0 `).concat(t,`;
}
.`).concat(QW," .").concat(QW,` {
margin-right: 0 `).concat(t,`;
}
body[`).concat(Hh,`] {
`).concat(ZT,": ").concat(n,`px;
}
`)},FYI=function(){var l=parseInt(document.body.getAttribute(Hh)||"0",10);return isFinite(l)?l:0},PTI=function(){Qh.useEffect(function(){return document.body.setAttribute(Hh,(FYI()+1).toString()),function(){var l=FYI()-1;l<=0?document.body.removeAttribute(Hh):document.body.setAttribute(Hh,l.toString())}},[])},YT=function(l){var I=l.noRelative,e=l.noImportant,t=l.gapMode,a=t===void 0?"margin":t;PTI();var G=Qh.useMemo(function(){return hT(a)},[a]);return Qh.createElement(_TI,{styles:qTI(G,!I,a,e?"":"!important")})};s();var VT=!1;if(typeof window<"u")try{n0=Object.defineProperty({},"passive",{get:function(){return VT=!0,!0}}),window.addEventListener("test",n0,n0),window.removeEventListener("test",n0,n0)}catch{VT=!1}var n0,wW=VT?{passive:!1}:!1;s();var $TI=function(l){return l.tagName==="TEXTAREA"},XYI=function(l,I){if(!(l instanceof Element))return!1;var e=window.getComputedStyle(l);return e[I]!=="hidden"&&!(e.overflowY===e.overflowX&&!$TI(l)&&e[I]==="visible")},IjI=function(l){return XYI(l,"overflowY")},ljI=function(l){return XYI(l,"overflowX")},RT=function(l,I){var e=I.ownerDocument,t=I;do{typeof ShadowRoot<"u"&&t instanceof ShadowRoot&&(t=t.host);var a=HYI(l,t);if(a){var G=QYI(l,t),c=G[1],n=G[2];if(c>n)return!0}t=t.parentNode}while(t&&t!==e.body);return!1},ejI=function(l){var I=l.scrollTop,e=l.scrollHeight,t=l.clientHeight;return[I,e,t]},tjI=function(l){var I=l.scrollLeft,e=l.scrollWidth,t=l.clientWidth;return[I,e,t]},HYI=function(l,I){return l==="v"?IjI(I):ljI(I)},QYI=function(l,I){return l==="v"?ejI(I):tjI(I)},ajI=function(l,I){return l==="h"&&I==="rtl"?-1:1},wYI=function(l,I,e,t,a){var G=ajI(l,window.getComputedStyle(I).direction),c=G*t,n=e.target,d=I.contains(n),b=!1,m=c>0,Z=0,r=0;do{var o=QYI(l,n),u=o[0],N=o[1],V=o[2],Y=N-V-G*u;(u||Y)&&HYI(l,n)&&(Z+=Y,r+=u),n instanceof ShadowRoot?n=n.host:n=n.parentNode}while(!d&&n!==document.body||d&&(I.contains(n)||I===n));return(m&&(a&&Math.abs(Z)<1||!a&&c>Z)||!m&&(a&&Math.abs(r)<1||!a&&-c>r))&&(b=!0),b};var Hy=function(l){return"changedTouches"in l?[l.changedTouches[0].clientX,l.changedTouches[0].clientY]:[0,0]},vYI=function(l){return[l.deltaX,l.deltaY]},EYI=function(l){return l&&"current"in l?l.current:l},GjI=function(l,I){return l[0]===I[0]&&l[1]===I[1]},cjI=function(l){return`
.block-interactivity-`.concat(l,` {pointer-events: none;}
.allow-interactivity-`).concat(l,` {pointer-events: all;}
`)},njI=0,wh=[];function gYI(l){var I=He.useRef([]),e=He.useRef([0,0]),t=He.useRef(),a=He.useState(njI++)[0],G=He.useState(c0)[0],c=He.useRef(l);He.useEffect(function(){c.current=l},[l]),He.useEffect(function(){if(l.inert){document.body.classList.add("block-interactivity-".concat(a));var N=uYI([l.lockRef.current],(l.shards||[]).map(EYI),!0).filter(Boolean);return N.forEach(function(V){return V.classList.add("allow-interactivity-".concat(a))}),function(){document.body.classList.remove("block-interactivity-".concat(a)),N.forEach(function(V){return V.classList.remove("allow-interactivity-".concat(a))})}}},[l.inert,l.lockRef.current,l.shards]);var n=He.useCallback(function(N,V){if("touches"in N&&N.touches.length===2||N.type==="wheel"&&N.ctrlKey)return!c.current.allowPinchZoom;var Y=Hy(N),p=e.current,h="deltaX"in N?N.deltaX:p[0]-Y[0],F="deltaY"in N?N.deltaY:p[1]-Y[1],X,H=N.target,Q=Math.abs(h)>Math.abs(F)?"h":"v";if("touches"in N&&Q==="h"&&H.type==="range")return!1;var E=RT(Q,H);if(!E)return!0;if(E?X=Q:(X=Q==="v"?"h":"v",E=RT(Q,H)),!E)return!1;if(!t.current&&"changedTouches"in N&&(h||F)&&(t.current=X),!X)return!0;var C=t.current||X;return wYI(C,V,N,C==="h"?h:F,!0)},[]),d=He.useCallback(function(N){var V=N;if(!(!wh.length||wh[wh.length-1]!==G)){var Y="deltaY"in V?vYI(V):Hy(V),p=I.current.filter(function(X){return X.name===V.type&&(X.target===V.target||V.target===X.shadowParent)&&GjI(X.delta,Y)})[0];if(p&&p.should){V.cancelable&&V.preventDefault();return}if(!p){var h=(c.current.shards||[]).map(EYI).filter(Boolean).filter(function(X){return X.contains(V.target)}),F=h.length>0?n(V,h[0]):!c.current.noIsolation;F&&V.cancelable&&V.preventDefault()}}},[]),b=He.useCallback(function(N,V,Y,p){var h={name:N,delta:V,target:Y,should:p,shadowParent:djI(Y)};I.current.push(h),setTimeout(function(){I.current=I.current.filter(function(F){return F!==h})},1)},[]),m=He.useCallback(function(N){e.current=Hy(N),t.current=void 0},[]),Z=He.useCallback(function(N){b(N.type,vYI(N),N.target,n(N,l.lockRef.current))},[]),r=He.useCallback(function(N){b(N.type,Hy(N),N.target,n(N,l.lockRef.current))},[]);He.useEffect(function(){return wh.push(G),l.setCallbacks({onScrollCapture:Z,onWheelCapture:Z,onTouchMoveCapture:r}),document.addEventListener("wheel",d,wW),document.addEventListener("touchmove",d,wW),document.addEventListener("touchstart",m,wW),function(){wh=wh.filter(function(N){return N!==G}),document.removeEventListener("wheel",d,wW),document.removeEventListener("touchmove",d,wW),document.removeEventListener("touchstart",m,wW)}},[]);var o=l.removeScrollBar,u=l.inert;return He.createElement(He.Fragment,null,u?He.createElement(G,{styles:cjI(a)}):null,o?He.createElement(YT,{gapMode:l.gapMode}):null)}function djI(l){for(var I=null;l!==null;)l instanceof ShadowRoot&&(I=l.host,l=l.host),l=l.parentNode;return I}var yYI=uT(Xy,gYI);var CYI=Qy.forwardRef(function(l,I){return Qy.createElement(G0,PG({},l,{ref:I,sideCar:yYI}))});CYI.classNames=G0.classNames;var d0=CYI;var mt=y(K(),1),FT="Popover",[JYI,PSl]=$r(FT,[pm]),b0=pm(),[bjI,ao]=JYI(FT),AYI=l=>{let{__scopePopover:I,children:e,open:t,defaultOpen:a,onOpenChange:G,modal:c=!1}=l,n=b0(I),d=Le.useRef(null),[b,m]=Le.useState(!1),[Z=!1,r]=eo({prop:t,defaultProp:a,onChange:G});return(0,mt.jsx)(RW,{...n,children:(0,mt.jsx)(bjI,{scope:I,contentId:Qn(),triggerRef:d,open:Z,onOpenChange:r,onOpenToggle:Le.useCallback(()=>r(o=>!o),[r]),hasCustomAnchor:b,onCustomAnchorAdd:Le.useCallback(()=>m(!0),[]),onCustomAnchorRemove:Le.useCallback(()=>m(!1),[]),modal:c,children:e})})};AYI.displayName=FT;var LYI="PopoverAnchor",sjI=Le.forwardRef((l,I)=>{let{__scopePopover:e,...t}=l,a=ao(LYI,e),G=b0(e),{onCustomAnchorAdd:c,onCustomAnchorRemove:n}=a;return Le.useEffect(()=>(c(),()=>n()),[c,n]),(0,mt.jsx)(FW,{...G,...t,ref:I})});sjI.displayName=LYI;var kYI="PopoverTrigger",xYI=Le.forwardRef((l,I)=>{let{__scopePopover:e,...t}=l,a=ao(kYI,e),G=b0(e),c=re(I,a.triggerRef),n=(0,mt.jsx)(Tl.button,{type:"button","aria-haspopup":"dialog","aria-expanded":a.open,"aria-controls":a.contentId,"data-state":OYI(a.open),...t,ref:c,onClick:qI(l.onClick,a.onOpenTo
`)}).join(`
`),g6I=(0,xc.memo)(function({message:I,conversationId:e,onMessageUpdate:t}){return(0,yl.jsx)("div",{className:"smtcmp-toolcall-container",children:I.toolCalls.map((a,G)=>(0,yl.jsx)("div",{className:yc(G>0&&"smtcmp-toolcall-border-top"),children:(0,yl.jsx)(y6I,{request:a.request,response:a.response,conversationId:e,onResponseUpdate:c=>t({...I,toolCalls:I.toolCalls.map(n=>n.request.id===a.request.id?{...n,response:c}:n)})})},a.request.id))})});function y6I({request:l,response:I,conversationId:e,onResponseUpdate:t}){let{handleToolCall:a,handleAllowForConversation:G,handleAllowAutoExecution:c,handleReject:n,handleAbort:d}=C6I(l,e,t),[b,m]=(0,xc.useState)(I.status==="pending_approval"),{serverName:Z,toolName:r}=(0,xc.useMemo)(()=>{try{return DW(l.name)}catch(u){if(u instanceof _b)return{serverName:null,toolName:l.name};throw u}},[l.name]),o=(0,xc.useMemo)(()=>{if(!l.arguments)return"No parameters";try{return JSON.stringify(JSON.parse(l.arguments),null,2)}catch{return l.arguments}},[l.arguments]);return(0,yl.jsxs)("div",{className:"smtcmp-toolcall",children:[(0,yl.jsxs)("div",{onClick:()=>m(!b),className:"smtcmp-toolcall-header",children:[(0,yl.jsx)("div",{className:"smtcmp-toolcall-header-icon",children:b?(0,yl.jsx)(Vt,{size:16}):(0,yl.jsx)(Bo,{size:16})}),(0,yl.jsxs)("div",{className:"smtcmp-toolcall-header-content",children:[(0,yl.jsx)("span",{children:wFI[I.status]||"Unknown"}),(0,yl.jsx)("span",{children:"\xA0\xA0"}),(0,yl.jsx)("span",{className:"smtcmp-toolcall-header-tool-name",children:Z?`${Z}:${r}`:r})]}),(0,yl.jsx)("div",{className:"smtcmp-toolcall-header-icon smtcmp-toolcall-header-icon--status",children:(0,yl.jsx)(J6I,{status:I.status})})]}),b&&(0,yl.jsxs)("div",{className:"smtcmp-toolcall-content",children:[(0,yl.jsxs)("div",{className:"smtcmp-toolcall-content-section",children:[(0,yl.jsx)("div",{children:"Parameters:"}),(0,yl.jsx)(yg,{language:"json",content:o})]}),I.status==="success"&&(0,yl.jsxs)("div",{className:"smtcmp-toolcall-content-section",children:[(0,yl.jsx)("div",{children:"Result:"}),(0,yl.jsx)(yg,{content:I.data.text})]}),I.status==="error"&&(0,yl.jsxs)("div",{className:"smtcmp-toolcall-content-section",children:[(0,yl.jsx)("div",{children:"Error:"}),(0,yl.jsx)(yg,{content:I.error})]})]}),(I.status==="pending_approval"||I.status==="running")&&(0,yl.jsxs)("div",{className:"smtcmp-toolcall-footer",children:[I.status==="pending_approval"&&(0,yl.jsxs)("div",{className:"smtcmp-toolcall-footer-actions",children:[(0,yl.jsx)(QFI,{primaryText:"Allow",onPrimaryClick:()=>{a(),m(!1)},menuOptions:[{label:"Always allow this tool",onClick:()=>{a(),c(),m(!1)}},{label:"Allow for this chat",onClick:()=>{a(),G(),m(!1)}}]}),(0,yl.jsx)("button",{onClick:()=>{n(),m(!1)},children:"Reject"})]}),I.status==="running"&&(0,yl.jsx)("div",{className:"smtcmp-toolcall-footer-actions",children:(0,yl.jsx)("button",{onClick:d,children:"Abort"})})]})]})}function C6I(l,I,e){let{settings:t,setSettings:a}=ql(),{getMcpManager:G}=SZ(),c=(0,xc.useCallback)(async()=>{let Z=await G();e({status:"running"});let r=await Z.callTool({name:l.name,args:l.arguments,id:l.id});e(r)},[l,e,G]),n=(0,xc.useCallback)(async()=>{(await G()).allowToolForConversation(l.name,I)},[l,I,G]),d=(0,xc.useCallback)(async()=>{let{serverName:Z,toolName:r}=DW(l.name),o=t.mcp.servers.find(N=>N.id===Z);if(!o)throw new Error(`Server ${Z} not found`);let u={...o.toolOptions};u[r]||(u[r]={allowAutoExecution:!1,disabled:!1}),u[r]={...u[r],allowAutoExecution:!0},a({...t,mcp:{...t.mcp,servers:t.mcp.servers.map(N=>N.id===o.id?{...N,toolOptions:u}:N)}})},[l,t,a]),b=(0,xc.useCallback)(async()=>{e({status:"rejected"})},[e]),m=(0,xc.useCallback)(async()=>{(await G()).abortToolCall(l.id),e({status:"aborted"})},[l,e,G]);return{handleToolCall:c,handleAllowForConversation:n,handleAllowAutoExecution:d,handleReject:b,handleAbort:m}}function J6I({status:l}){switch(l){case"pending_approval":return null;case"rejected":case"aborted":case"error":return(0,yl.jsx)(ad,{size:16,style:{color:"var(--text-error)"}});case"running":return(0,yl.jsx)(UG,{size:16,className:"spinner"});case"success":return(
`),[l]);return(0,Zt.jsx)($F,{delayDuration:0,children:(0,Zt.jsxs)(I0,{children:[(0,Zt.jsx)(l0,{asChild:!0,children:(0,Zt.jsx)("button",{onClick:I?void 0:async()=>{await navigator.clipboard.writeText(t),e(!0),setTimeout(()=>{e(!1)},1500)},className:"clickable-icon",children:I?(0,Zt.jsx)(pc,{size:12}):(0,Zt.jsx)(So,{size:12})})}),(0,Zt.jsx)(e0,{children:(0,Zt.jsx)(t0,{className:"smtcmp-tooltip-content",children:"Copy message"})})]})})}function L6I({messages:l}){let I=(0,qW.useMemo)(()=>l.reduce((a,G)=>G.role==="assistant"&&G.metadata?.usage?a?{prompt_tokens:a.prompt_tokens+G.metadata.usage.prompt_tokens,completion_tokens:a.completion_tokens+G.metadata.usage.completion_tokens,total_tokens:a.total_tokens+G.metadata.usage.total_tokens}:G.metadata.usage:a,null),[l]),e=(0,qW.useMemo)(()=>l.find(G=>G.role==="assistant"&&!!G.metadata?.model)?.metadata?.model,[l]),t=(0,qW.useMemo)(()=>!e||!I?null:GYI({model:e,usage:I}),[e,I]);return(0,Zt.jsx)($F,{delayDuration:0,children:(0,Zt.jsxs)(I0,{children:[(0,Zt.jsx)(l0,{asChild:!0,children:(0,Zt.jsx)("div",{children:(0,Zt.jsx)(HT,{usage:I,estimatedPrice:t,model:e?.model??null})})}),(0,Zt.jsx)(e0,{children:(0,Zt.jsx)(t0,{className:"smtcmp-tooltip-content",children:"View details"})})]})})}function wj({messages:l}){return(0,Zt.jsxs)("div",{className:"smtcmp-assistant-message-actions",children:[(0,Zt.jsx)(L6I,{messages:l}),(0,Zt.jsx)(A6I,{messages:l})]})}var ts=y(K());function vj({messages:l,contextMessages:I,conversationId:e,isApplying:t,onApply:a,onToolMessageUpdate:G}){return(0,ts.jsxs)("div",{className:"smtcmp-assistant-tool-message-group",children:[l.map(c=>c.role==="assistant"?c.reasoning||c.annotations||c.content?(0,ts.jsxs)("div",{className:"smtcmp-chat-messages-assistant",children:[c.reasoning&&(0,ts.jsx)(Cg,{reasoning:c.reasoning}),c.annotations&&(0,ts.jsx)(vcI,{annotations:c.annotations}),(0,ts.jsx)(fS,{content:c.content,contextMessages:I,handleApply:a,isApplying:t})]},c.id):null:(0,ts.jsx)("div",{children:(0,ts.jsx)(EFI,{message:c,conversationId:e,onMessageUpdate:G})},c.id)),l.length>0&&(0,ts.jsx)(wj,{messages:l})]})}s();var ha=y(dI());s();var PW=y(K());function gFI({onUpload:l}){return(0,PW.jsxs)("label",{className:"smtcmp-chat-user-input-submit-button",children:[(0,PW.jsx)("input",{type:"file",accept:"image/*",multiple:!0,onChange:e=>{let t=Array.from(e.target.files??[]);t.length>0&&l(t)},style:{display:"none"}}),(0,PW.jsx)("div",{className:"smtcmp-chat-user-input-submit-button-icons",children:(0,PW.jsx)(Do,{size:12})}),(0,PW.jsx)("div",{children:"Image"})]})}s();var yFI=y(dI());var Gl=y(K());function $W({children:l,onDelete:I,onClick:e,isFocused:t}){return(0,Gl.jsxs)("div",{className:`smtcmp-chat-user-input-file-badge ${t?"smtcmp-chat-user-input-file-badge-focused":""}`,onClick:e,children:[l,(0,Gl.jsx)("div",{className:"smtcmp-chat-user-input-file-badge-delete",onClick:a=>{a.stopPropagation(),I()},children:(0,Gl.jsx)(ad,{size:12})})]})}function k6I({mentionable:l,onDelete:I,onClick:e,isFocused:t}){let a=Ab(l);return(0,Gl.jsx)($W,{onDelete:I,onClick:e,isFocused:t,children:(0,Gl.jsxs)("div",{className:"smtcmp-chat-user-input-file-badge-name",children:[a&&(0,Gl.jsx)(a,{size:12,className:"smtcmp-chat-user-input-file-badge-name-icon"}),(0,Gl.jsx)("span",{children:l.file.name})]})})}function x6I({mentionable:l,onDelete:I,onClick:e,isFocused:t}){let a=Ab(l);return(0,Gl.jsx)($W,{onDelete:I,onClick:e,isFocused:t,children:(0,Gl.jsxs)("div",{className:"smtcmp-chat-user-input-file-badge-name",children:[a&&(0,Gl.jsx)(a,{size:12,className:"smtcmp-chat-user-input-file-badge-name-icon"}),(0,Gl.jsx)("span",{children:l.folder.name})]})})}function f6I({mentionable:l,onDelete:I,onClick:e,isFocused:t}){let a=Ab(l);return(0,Gl.jsx)($W,{onDelete:I,onClick:e,isFocused:t,children:(0,Gl.jsxs)("div",{className:"smtcmp-chat-user-input-file-badge-name",children:[a&&(0,Gl.jsx)(a,{size:12,className:"smtcmp-chat-user-input-file-badge-name-icon"}),(0,Gl.jsx)("span",{children:"Vault"})]})})}function z6I({mentionable:l,onDelete:I,onClick:e,isFocused:t}){let{settings:a,setSettings:G}=ql(),c=(0,yFI.useCallback)(d=
`);b(N)}else b(u instanceof Error?u.message:"Invalid parameters")}},[]);return(0,ro.useEffect)(()=>{r(c)},[c,r]),(0,lc.jsxs)(lc.Fragment,{children:[(0,lc.jsx)(MI,{name:"Name",desc:"The name of the MCP server",required:!0,children:(0,lc.jsx)(Ae,{value:a,onChange:o=>G(o),placeholder:"e.g. 'github'"})}),(0,lc.jsx)(MI,{name:"Parameters",desc:`JSON configuration that defines how to run the MCP server. Format must include:
- "command": The executable name (e.g., "npx", "node")
- "args": (Optional) Array of command-line arguments
- "env": (Optional) Key-value pairs of environment variables`,className:"smtcmp-settings-textarea-header smtcmp-settings-description-preserve-whitespace",required:!0}),(0,lc.jsx)(PFI,{value:c,placeholder:m,onChange:o=>n(o.target.value),className:"smtcmp-mcp-server-modal-textarea",maxRows:20,minRows:m.split(`
`).length}),d!==null?(0,lc.jsx)("div",{className:"smtcmp-mcp-server-modal-validation smtcmp-mcp-server-modal-validation--error",children:d}):(0,lc.jsx)("div",{className:"smtcmp-mcp-server-modal-validation smtcmp-mcp-server-modal-validation--success",children:"Valid parameters"}),(0,lc.jsxs)(MI,{children:[(0,lc.jsx)(Al,{text:"Save",onClick:Z,cta:!0}),(0,lc.jsx)(Al,{text:"Cancel",onClick:I})]})]})}var fI=y(K());function F1({app:l,plugin:I}){let[e,t]=(0,Jd.useState)(null),[a,G]=(0,Jd.useState)([]);return(0,Jd.useEffect)(()=>{(async()=>{let n=await I.getMcpManager();t(n),G(n.getServers())})()},[I]),(0,Jd.useEffect)(()=>{if(e){let c=e.subscribeServersChange(n=>{G(n)});return()=>{c()}}},[e]),(0,fI.jsxs)("div",{className:"smtcmp-settings-section",children:[(0,fI.jsx)("div",{className:"smtcmp-settings-header",children:"MCP (Model Context Pool)"}),(0,fI.jsxs)("div",{className:"smtcmp-settings-desc smtcmp-settings-callout",children:[(0,fI.jsx)("strong",{children:"Warning:"})," When using tools, the tool response is passed to the language model (LLM). If the tool result contains a large amount of content, this can significantly increase LLM usage and associated costs. Please be mindful when enabling or using tools that may return long outputs."]}),e?.disabled?(0,fI.jsx)("div",{className:"smtcmp-settings-sub-header-container",children:(0,fI.jsx)("div",{className:"smtcmp-settings-sub-header",children:"MCP is not supported on mobile devices"})}):(0,fI.jsxs)(fI.Fragment,{children:[(0,fI.jsxs)("div",{className:"smtcmp-settings-sub-header-container",children:[(0,fI.jsx)("div",{className:"smtcmp-settings-sub-header",children:"MCP Servers"}),(0,fI.jsx)(Al,{text:"Add MCP Server",onClick:()=>new V1(l,I).open()})]}),(0,fI.jsxs)("div",{className:"smtcmp-mcp-servers-container",children:[(0,fI.jsxs)("div",{className:"smtcmp-mcp-servers-header",children:[(0,fI.jsx)("div",{children:"Server"}),(0,fI.jsx)("div",{children:"Status"}),(0,fI.jsx)("div",{children:"Enabled"}),(0,fI.jsx)("div",{children:"Actions"})]}),a.length>0?a.map(c=>(0,fI.jsx)(ePI,{server:c,app:l,plugin:I},c.name)):(0,fI.jsx)("div",{className:"smtcmp-mcp-servers-empty",children:"No MCP servers found"})]})]})]})}function ePI({server:l,app:I,plugin:e}){let{settings:t,setSettings:a}=ql(),[G,c]=(0,Jd.useState)(!1),n=(0,Jd.useCallback)(()=>{new R1(I,e,l.name).open()},[l.name,I,e]),d=(0,Jd.useCallback)(()=>{let m=`Are you sure you want to delete MCP server "${l.name}"?`;new Oa(I,{title:"Delete MCP Server",message:m,ctaText:"Delete",onConfirm:async()=>{await a({...t,mcp:{...t.mcp,servers:t.mcp.servers.filter(Z=>Z.id!==l.name)}})}}).open()},[l.name,t,a,I]),b=(0,Jd.useCallback)(m=>{a({...t,mcp:{...t.mcp,servers:t.mcp.servers.map(Z=>Z.id===l.name?{...Z,enabled:m}:Z)}})},[t,a,l.name]);return(0,fI.jsxs)("div",{className:"smtcmp-mcp-server",children:[(0,fI.jsxs)("div",{className:"smtcmp-mcp-server-row",children:[(0,fI.jsx)("div",{className:"smtcmp-mcp-server-name",children:l.name}),(0,fI.jsx)("div",{className:"smtcmp-mcp-server-status",children:(0,fI.jsx)(aPI,{status:l.status})}),(0,fI.jsx)("div",{className:"smtcmp-mcp-server-toggle",children:(0,fI.jsx)(Ic,{value:l.config.enabled,onChange:b})}),(0,fI.jsxs)("div",{className:"smtcmp-mcp-server-actions",children:[(0,fI.jsx)("button",{onClick:n,className:"clickable-icon","aria-label":"Edit",children:(0,fI.jsx)(Ca,{size:16})}),(0,fI.jsx)("button",{onClick:d,className:"clickable-icon","aria-label":"Delete",children:(0,fI.jsx)(da,{size:16})}),(0,fI.jsx)("button",{onClick:()=>c(!G),className:"clickable-icon","aria-label":G?"Collapse":"Expand",children:G?(0,fI.jsx)(dG,{size:16}):(0,fI.jsx)(Vt,{size:16})})]})]}),G&&(0,fI.jsx)(tPI,{server:l})]})}function tPI({server:l}){return l.status==="disconnected"||l.status==="connecting"?null:(0,fI.jsxs)("div",{className:"smtcmp-server-expanded-info",children:[l.status==="connected"&&(0,fI.jsxs)("div",{children:[(0,fI.jsx)("div",{className:"smtcmp-server-expanded-info-header",children:"Tools"}),(0,fI.jsx)("div",{className:"smtcmp-server-tools-container",children:l.tools.map(I=>(0,fI.jsx)(GPI,{tool:I,server:l},I.name))
`).slice(t.startLine-1,t.endLine).join(`
`):null:null}),G=(0,ha.useMemo)(()=>t?.type==="image"?t:null,[t]);return a?(0,vt.jsx)("div",{className:"smtcmp-chat-user-input-file-content-preview",children:(0,vt.jsx)(Hd,{content:a,scale:"xs"})}):G?(0,vt.jsx)("div",{className:"smtcmp-chat-user-input-file-content-preview",children:(0,vt.jsx)("img",{src:G.data,alt:G.name})}):null}e0I.displayName="ChatUserInput";var H1=e0I;s();var ec=y(dI()),Et=y(K());function dPI({title:l,onSubmit:I}){let[e,t]=(0,ec.useState)(l),a=(0,ec.useRef)(null);return(0,ec.useEffect)(()=>{a.current&&(a.current.select(),a.current.scrollLeft=0)},[]),(0,Et.jsx)("input",{ref:a,type:"text",value:e,className:"smtcmp-chat-list-dropdown-item-title-input",onClick:G=>G.stopPropagation(),onChange:G=>t(G.target.value),onKeyDown:G=>{G.stopPropagation(),G.key==="Enter"&&I(e)},autoFocus:!0,maxLength:100})}function bPI({title:l,isFocused:I,isEditing:e,onMouseEnter:t,onSelect:a,onDelete:G,onStartEdit:c,onFinishEdit:n}){let d=(0,ec.useRef)(null);return(0,ec.useEffect)(()=>{I&&d.current&&d.current.scrollIntoView({block:"nearest"})},[I]),(0,Et.jsxs)("li",{ref:d,onClick:a,onMouseEnter:t,className:I?"selected":"",children:[e?(0,Et.jsx)(dPI,{title:l,onSubmit:n}):(0,Et.jsx)("div",{className:"smtcmp-chat-list-dropdown-item-title",children:l}),(0,Et.jsxs)("div",{className:"smtcmp-chat-list-dropdown-item-actions",children:[(0,Et.jsx)("button",{onClick:b=>{b.stopPropagation(),c()},className:"clickable-icon smtcmp-chat-list-dropdown-item-icon",children:(0,Et.jsx)(qV,{})}),(0,Et.jsx)("button",{onClick:async b=>{b.stopPropagation(),await G()},className:"clickable-icon smtcmp-chat-list-dropdown-item-icon",children:(0,Et.jsx)(da,{})})]})]})}function t0I({chatList:l,currentConversationId:I,onSelect:e,onDelete:t,onUpdateTitle:a,children:G}){let[c,n]=(0,ec.useState)(!1),[d,b]=(0,ec.useState)(0),[m,Z]=(0,ec.useState)(null);(0,ec.useEffect)(()=>{if(c){let o=l.findIndex(u=>u.id===I);b(o===-1?0:o),Z(null)}},[c,l,I]);let r=(0,ec.useCallback)(o=>{o.key==="ArrowUp"?b(Math.max(0,d-1)):o.key==="ArrowDown"?b(Math.min(l.length-1,d+1)):o.key==="Enter"&&(e(l[d].id),n(!1))},[l,d,b,e]);return(0,Et.jsxs)(wy,{open:c,onOpenChange:n,children:[(0,Et.jsx)(vy,{asChild:!0,children:(0,Et.jsx)("button",{className:"clickable-icon","aria-label":"Chat History",children:G})}),(0,Et.jsx)(BYI,{children:(0,Et.jsx)(s0,{className:"smtcmp-popover smtcmp-chat-list-dropdown-content",onKeyDown:r,children:(0,Et.jsx)("ul",{children:l.length===0?(0,Et.jsx)("li",{className:"smtcmp-chat-list-dropdown-empty",children:"No conversations"}):l.map((o,u)=>(0,Et.jsx)(bPI,{title:o.title,isFocused:d===u,isEditing:m===o.id,onMouseEnter:()=>{b(u)},onSelect:async()=>{await e(o.id),n(!1)},onDelete:async()=>{await t(o.id)},onStartEdit:()=>{Z(o.id)},onFinishEdit:async N=>{await a(o.id,N),Z(null)}},o.id))})})})]})}s();var gt=y(K());function kj({state:l}){switch(l.type){case"idle":return null;case"reading-mentionables":return(0,gt.jsx)("div",{className:"smtcmp-query-progress",children:(0,gt.jsxs)("p",{children:["Reading mentioned files",(0,gt.jsx)(Tr,{})]})});case"indexing":return(0,gt.jsxs)("div",{className:"smtcmp-query-progress",children:[(0,gt.jsxs)("p",{children:[`Indexing ${l.indexProgress.totalFiles} file`,(0,gt.jsx)(Tr,{})]}),(0,gt.jsx)("p",{className:"smtcmp-query-progress-detail",children:`${l.indexProgress.completedChunks}/${l.indexProgress.totalChunks} chunks indexed`}),l.indexProgress.waitingForRateLimit&&(0,gt.jsx)("p",{className:"smtcmp-query-progress-detail",children:"Waiting for rate limit to reset..."})]});case"querying":return(0,gt.jsx)("div",{className:"smtcmp-query-progress",children:(0,gt.jsxs)("p",{children:["Querying the vault",(0,gt.jsx)(Tr,{})]})});case"querying-done":return(0,gt.jsxs)("div",{className:"smtcmp-query-progress",children:[(0,gt.jsxs)("p",{children:["Reading related files",(0,gt.jsx)(Tr,{})]}),l.queryResult.map(I=>(0,gt.jsxs)("div",{children:[(0,gt.jsx)("p",{children:I.path}),(0,gt.jsx)("p",{children:I.similarity})]},I.path))]})}}s();var vm=y(dI()),sPI=50,mPI=20;function a0I({scrollContainerRef:l}){let I=(0,vm.useRef)(!1),e=(0,vm.useRef)(0);(0,vm.useEff
SELECT b.oid, b.typarray
FROM pg_catalog.pg_type a
LEFT JOIN pg_catalog.pg_type b ON b.oid = a.typelem
WHERE a.typcategory = 'A'
GROUP BY b.oid, b.typarray
ORDER BY b.oid
`);for(let I of l.rows)this.serializers[I.typarray]=e=>D1(e,this.serializers[I.oid],I.typarray),this.parsers[I.typarray]=e=>rK(e,this.parsers[I.oid],I.typarray)}async query(l,I,e){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await ZI(this,lt,P1).call(this,l,I,e))}async sql(l,...I){let{query:e,params:t}=Tj(l,...I);return await this.query(e,t)}async exec(l,I){return await this._checkReady(),await this._runExclusiveTransaction(async()=>await ZI(this,lt,ti).call(this,l,I))}async transaction(l){return await this._checkReady(),await this._runExclusiveTransaction(async()=>{await ZI(this,lt,ti).call(this,"BEGIN"),TI(this,ai,!0);let I=!1,e=()=>{if(I)throw new Error("Transaction is closed")},t={query:async(a,G,c)=>(e(),await ZI(this,lt,P1).call(this,a,G,c)),sql:async(a,...G)=>{let{query:c,params:n}=Tj(a,...G);return await ZI(this,lt,P1).call(this,c,n)},exec:async(a,G)=>(e(),await ZI(this,lt,ti).call(this,a,G)),rollback:async()=>{e(),await ZI(this,lt,ti).call(this,"ROLLBACK"),I=!0},get closed(){return I}};try{let a=await l(t);return I||(I=!0,await ZI(this,lt,ti).call(this,"COMMIT")),TI(this,ai,!1),a}catch(a){throw I||await ZI(this,lt,ti).call(this,"ROLLBACK"),TI(this,ai,!1),a}})}};q1=new WeakMap,ai=new WeakMap,lt=new WeakSet,Em=async function(l,I={}){return await this.execProtocol(l,{...I,syncToFs:!1})},P1=async function(l,I=[],e){return await this._runExclusiveQuery(async()=>{ZI(this,lt,uK).call(this,"runQuery",l,I,e),await this._handleBlob(e?.blob);let t;try{let G=await ZI(this,lt,Em).call(this,xn.parse({text:l,types:e?.paramTypes}),e),c=oK((await ZI(this,lt,Em).call(this,xn.describe({type:"S"}),e)).map(([d])=>d)),n=I.map((d,b)=>{let m=c[b];if(d==null)return null;let Z=this.serializers[m];return Z?Z(d):d.toString()});t=[...G,...await ZI(this,lt,Em).call(this,xn.bind({values:n}),e),...await ZI(this,lt,Em).call(this,xn.describe({type:"P"}),e),...await ZI(this,lt,Em).call(this,xn.execute({}),e)]}finally{await ZI(this,lt,Em).call(this,xn.sync(),e)}await this._cleanupBlob(),M(this,ai)||await this.syncToFs();let a=await this._getWrittenBlob();return _1(t.map(([G])=>G),this.parsers,e,a)[0]})},ti=async function(l,I){return await this._runExclusiveQuery(async()=>{ZI(this,lt,uK).call(this,"runExec",l,I),await this._handleBlob(I?.blob);let e;try{e=await ZI(this,lt,Em).call(this,xn.query(l),I)}finally{await ZI(this,lt,Em).call(this,xn.sync(),I)}this._cleanupBlob(),M(this,ai)||await this.syncToFs();let t=await this._getWrittenBlob();return _1(e.map(([a])=>a),this.parsers,I,t)})},uK=function(...l){this.debug>0&&console.log(...l)};oo();s();var HG={},a7I=(()=>{var _scriptName=W;return async function(moduleArg={}){var moduleRtn,Module=moduleArg,readyPromiseResolve,readyPromiseReject,readyPromise=new Promise((l,I)=>{readyPromiseResolve=l,readyPromiseReject=I}),ENVIRONMENT_IS_WEB=typeof window=="object",ENVIRONMENT_IS_WORKER=typeof importScripts=="function",ENVIRONMENT_IS_NODE=typeof HG=="object"&&typeof HG.versions=="object"&&typeof HG.versions.node=="string"&&HG.type!="renderer",ENVIRONMENT_IS_SHELL=!ENVIRONMENT_IS_WEB&&!ENVIRONMENT_IS_NODE&&!ENVIRONMENT_IS_WORKER;if(ENVIRONMENT_IS_NODE){let{createRequire:l}=await import("module"),I=W;I.startsWith("data:")&&(I="/");var require=l(I)}Module.expectedDataFileDownloads||(Module.expectedDataFileDownloads=0),Module.expectedDataFileDownloads++,(()=>{var l=typeof ENVIRONMENT_IS_PTHREAD<"u"&&ENVIRONMENT_IS_PTHREAD,I=typeof ENVIRONMENT_IS_WASM_WORKER<"u"&&ENVIRONMENT_IS_WASM_WORKER;if(l||I)return;function e(t){var a="";typeof window=="object"?a=window.encodeURIComponent(window.location.pathname.toString().substring(0,window.location.pathname.toString().lastIndexOf("/"))+"/"):typeof HG>"u"&&typeof location<"u"&&(a=encodeURIComponent(location.pathname.toString().substring(0,location.pathname.toString().lastIndexOf("/"))+"/"));var G="postgres.data",c="postgres.data";typeof Module.locateFilePackage=="function"&&!Module.locateFile&&(Module.locateFile=Module.locateFilePackage,err("warning: you defined Module.locateFilePackage, that has been renamed to Module.locateFile (using
`));if(!l)return null;FS_stdin_getChar_buffer=intArrayFromString(l,!0)}return FS_stdin_getChar_buffer.shift()},TTY={ttys:[],init(){},shutdown(){},register(l,I){TTY.ttys[l]={input:[],output:[],ops:I},FS.registerDevice(l,TTY.stream_ops)},stream_ops:{open(l){var I=TTY.ttys[l.node.rdev];if(!I)throw new FS.ErrnoError(43);l.tty=I,l.seekable=!1},close(l){l.tty.ops.fsync(l.tty)},fsync(l){l.tty.ops.fsync(l.tty)},read(l,I,e,t,a){if(!l.tty||!l.tty.ops.get_char)throw new FS.ErrnoError(60);for(var G=0,c=0;c<t;c++){var n;try{n=l.tty.ops.get_char(l.tty)}catch{throw new FS.ErrnoError(29)}if(n===void 0&&G===0)throw new FS.ErrnoError(6);if(n==null)break;G++,I[e+c]=n}return G&&(l.node.timestamp=Date.now()),G},write(l,I,e,t,a){if(!l.tty||!l.tty.ops.put_char)throw new FS.ErrnoError(60);try{for(var G=0;G<t;G++)l.tty.ops.put_char(l.tty,I[e+G])}catch{throw new FS.ErrnoError(29)}return t&&(l.node.timestamp=Date.now()),G}},default_tty_ops:{get_char(l){return FS_stdin_getChar()},put_char(l,I){I===null||I===10?(out(UTF8ArrayToString(l.output,0)),l.output=[]):I!=0&&l.output.push(I)},fsync(l){l.output&&l.output.length>0&&(out(UTF8ArrayToString(l.output,0)),l.output=[])},ioctl_tcgets(l){return{c_iflag:25856,c_oflag:5,c_cflag:191,c_lflag:35387,c_cc:[3,28,127,21,4,0,1,0,17,19,26,0,18,15,23,22,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]}},ioctl_tcsets(l,I,e){return 0},ioctl_tiocgwinsz(l){return[24,80]}},default_tty1_ops:{put_char(l,I){I===null||I===10?(err(UTF8ArrayToString(l.output,0)),l.output=[]):I!=0&&l.output.push(I)},fsync(l){l.output&&l.output.length>0&&(err(UTF8ArrayToString(l.output,0)),l.output=[])}}},zeroMemory=(l,I)=>(HEAPU8.fill(0,l,l+I),l),mmapAlloc=l=>{l=alignMemory(l,65536);var I=_emscripten_builtin_memalign(65536,l);return I?zeroMemory(I,l):0},MEMFS={ops_table:null,mount(l){return MEMFS.createNode(null,"/",16895,0)},createNode(l,I,e,t){if(FS.isBlkdev(e)||FS.isFIFO(e))throw new FS.ErrnoError(63);MEMFS.ops_table||(MEMFS.ops_table={dir:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,lookup:MEMFS.node_ops.lookup,mknod:MEMFS.node_ops.mknod,rename:MEMFS.node_ops.rename,unlink:MEMFS.node_ops.unlink,rmdir:MEMFS.node_ops.rmdir,readdir:MEMFS.node_ops.readdir,symlink:MEMFS.node_ops.symlink},stream:{llseek:MEMFS.stream_ops.llseek}},file:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:{llseek:MEMFS.stream_ops.llseek,read:MEMFS.stream_ops.read,write:MEMFS.stream_ops.write,allocate:MEMFS.stream_ops.allocate,mmap:MEMFS.stream_ops.mmap,msync:MEMFS.stream_ops.msync}},link:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr,readlink:MEMFS.node_ops.readlink},stream:{}},chrdev:{node:{getattr:MEMFS.node_ops.getattr,setattr:MEMFS.node_ops.setattr},stream:FS.chrdev_stream_ops}});var a=FS.createNode(l,I,e,t);return FS.isDir(a.mode)?(a.node_ops=MEMFS.ops_table.dir.node,a.stream_ops=MEMFS.ops_table.dir.stream,a.contents={}):FS.isFile(a.mode)?(a.node_ops=MEMFS.ops_table.file.node,a.stream_ops=MEMFS.ops_table.file.stream,a.usedBytes=0,a.contents=null):FS.isLink(a.mode)?(a.node_ops=MEMFS.ops_table.link.node,a.stream_ops=MEMFS.ops_table.link.stream):FS.isChrdev(a.mode)&&(a.node_ops=MEMFS.ops_table.chrdev.node,a.stream_ops=MEMFS.ops_table.chrdev.stream),a.timestamp=Date.now(),l&&(l.contents[I]=a,l.timestamp=a.timestamp),a},getFileDataAsTypedArray(l){return l.contents?l.contents.subarray?l.contents.subarray(0,l.usedBytes):new Uint8Array(l.contents):new Uint8Array(0)},expandFileStorage(l,I){var e=l.contents?l.contents.length:0;if(!(e>=I)){var t=1024*1024;I=Math.max(I,e*(e<t?2:1.125)>>>0),e!=0&&(I=Math.max(I,256));var a=l.contents;l.contents=new Uint8Array(I),l.usedBytes>0&&l.contents.set(a.subarray(0,l.usedBytes),0)}},resizeFileStorage(l,I){if(l.usedBytes!=I)if(I==0)l.contents=null,l.usedBytes=0;else{var e=l.contents;l.contents=new Uint8Array(I),e&&l.contents.set(e.subarray(0,Math.min(I,l.usedBytes))),l.usedBytes=I}},node_ops:{getattr(l){var I={};return I.dev=FS.isChrdev(l.mode)?l.id:1,I.ino=l.id,I.mode=l.mode,I.nlink=1,I.uid=0,I.gid=0,I.rdev=l.rdev,FS.isDir(l.mode)?I.size=4096:FS.isFile(l.mode)?I.size=l.usedBytes:
${d}`),0}},__dlopen_js=l=>dlopenInternal(l,{loadAsync:!1});__dlopen_js.sig="pp";var __dlsym_js=(l,I,e)=>{I=UTF8ToString(I);var t,a,G=LDSO.loadedLibsByHandle[l];if(!G.exports.hasOwnProperty(I)||G.exports[I].stub)return dlSetError(`Tried to lookup unknown symbol "${I}" in dynamic lib: ${G.name}`),0;if(a=Object.keys(G.exports).indexOf(I),t=G.exports[I],typeof t=="function"){var c=getFunctionAddress(t);c?t=c:(t=addFunction(t,t.sig),HEAPU32[e>>2]=a)}return t};__dlsym_js.sig="pppp";var nowIsMonotonic=1,__emscripten_get_now_is_monotonic=()=>nowIsMonotonic;__emscripten_get_now_is_monotonic.sig="i";var __emscripten_runtime_keepalive_clear=()=>{noExitRuntime=!1,runtimeKeepaliveCounter=0};__emscripten_runtime_keepalive_clear.sig="v";var __emscripten_system=l=>{if(ENVIRONMENT_IS_NODE){if(!l)return 1;var I=UTF8ToString(l);if(!I.length)return 0;var e=require("child_process"),t=e.spawnSync(I,[],{shell:!0,stdio:"inherit"}),a=(c,n)=>c<<8|n;if(t.status===null){var G=c=>{switch(c){case"SIGHUP":return 1;case"SIGQUIT":return 3;case"SIGFPE":return 8;case"SIGKILL":return 9;case"SIGALRM":return 14;case"SIGTERM":return 15;default:return 2}};return a(0,G(t.signal))}return a(t.status,0)}return l?-52:0};__emscripten_system.sig="ip";var __emscripten_throw_longjmp=()=>{throw 1/0};__emscripten_throw_longjmp.sig="v";function __gmtime_js(l,I){l=bigintToI53Checked(l);var e=new Date(l*1e3);HEAP32[I>>2]=e.getUTCSeconds(),HEAP32[I+4>>2]=e.getUTCMinutes(),HEAP32[I+8>>2]=e.getUTCHours(),HEAP32[I+12>>2]=e.getUTCDate(),HEAP32[I+16>>2]=e.getUTCMonth(),HEAP32[I+20>>2]=e.getUTCFullYear()-1900,HEAP32[I+24>>2]=e.getUTCDay();var t=Date.UTC(e.getUTCFullYear(),0,1,0,0,0,0),a=(e.getTime()-t)/(1e3*60*60*24)|0;HEAP32[I+28>>2]=a}__gmtime_js.sig="vjp";var isLeapYear=l=>l%4===0&&(l%100!==0||l%400===0),MONTH_DAYS_LEAP_CUMULATIVE=[0,31,60,91,121,152,182,213,244,274,305,335],MONTH_DAYS_REGULAR_CUMULATIVE=[0,31,59,90,120,151,181,212,243,273,304,334],ydayFromDate=l=>{var I=isLeapYear(l.getFullYear()),e=I?MONTH_DAYS_LEAP_CUMULATIVE:MONTH_DAYS_REGULAR_CUMULATIVE,t=e[l.getMonth()]+l.getDate()-1;return t};function __localtime_js(l,I){l=bigintToI53Checked(l);var e=new Date(l*1e3);HEAP32[I>>2]=e.getSeconds(),HEAP32[I+4>>2]=e.getMinutes(),HEAP32[I+8>>2]=e.getHours(),HEAP32[I+12>>2]=e.getDate(),HEAP32[I+16>>2]=e.getMonth(),HEAP32[I+20>>2]=e.getFullYear()-1900,HEAP32[I+24>>2]=e.getDay();var t=ydayFromDate(e)|0;HEAP32[I+28>>2]=t,HEAP32[I+36>>2]=-(e.getTimezoneOffset()*60);var a=new Date(e.getFullYear(),0,1),G=new Date(e.getFullYear(),6,1).getTimezoneOffset(),c=a.getTimezoneOffset(),n=(G!=c&&e.getTimezoneOffset()==Math.min(c,G))|0;HEAP32[I+32>>2]=n}__localtime_js.sig="vjp";function __mmap_js(l,I,e,t,a,G,c){a=bigintToI53Checked(a);try{if(isNaN(a))return 61;var n=SYSCALLS.getStreamFromFD(t),d=FS.mmap(n,l,a,I,e),b=d.ptr;return HEAP32[G>>2]=d.allocated,HEAPU32[c>>2]=b,0}catch(m){if(typeof FS>"u"||m.name!=="ErrnoError")throw m;return-m.errno}}__mmap_js.sig="ipiiijpp";function __munmap_js(l,I,e,t,a,G){G=bigintToI53Checked(G);try{var c=SYSCALLS.getStreamFromFD(a);e&2&&SYSCALLS.doMsync(l,c,I,t,G)}catch(n){if(typeof FS>"u"||n.name!=="ErrnoError")throw n;return-n.errno}}__munmap_js.sig="ippiiij";var timers={},handleException=l=>{if(l instanceof ExitStatus||l=="unwind")return EXITSTATUS;quit_(1,l)},runtimeKeepaliveCounter=0,keepRuntimeAlive=()=>noExitRuntime||runtimeKeepaliveCounter>0,_proc_exit=l=>{EXITSTATUS=l,keepRuntimeAlive()||(Module.onExit?.(l),ABORT=!0),quit_(l,new ExitStatus(l))};_proc_exit.sig="vi";var exitJS=(l,I)=>{EXITSTATUS=l,_proc_exit(l)},_exit=exitJS;_exit.sig="vi";var maybeExit=()=>{if(!keepRuntimeAlive())try{_exit(EXITSTATUS)}catch(l){handleException(l)}},callUserCallback=l=>{if(!ABORT)try{l(),maybeExit()}catch(I){handleException(I)}},_emscripten_get_now=()=>performance.now();_emscripten_get_now.sig="d";var __setitimer_js=(l,I)=>{if(timers[l]&&(clearTimeout(timers[l].id),delete timers[l]),!I)return 0;var e=setTimeout(()=>{delete timers[l],callUserCallback(()=>__emscripten_timeout(l,_emscripten_get_now()))},I);return timers[l]={id:e,timeout_ms:I},0};__setitimer_js.sig="iid";var __tz
CREATE TABLE IF NOT EXISTS ${U.identifier(G)}.${U.identifier(a)} (
id SERIAL PRIMARY KEY,
hash text NOT NULL,
created_at bigint
)
`;await e.execute(U`CREATE SCHEMA IF NOT EXISTS ${U.identifier(G)}`),await e.execute(c);let d=(await e.all(U`select id, hash, created_at from ${U.identifier(G)}.${U.identifier(a)} order by created_at desc limit 1`))[0];await e.transaction(async b=>{for await(let m of I)if(!d||Number(d.created_at)<m.folderMillis){for(let Z of m.sql)await b.execute(U.raw(Z));await b.execute(U`insert into ${U.identifier(G)}.${U.identifier(a)} ("hash", "created_at") values(${m.hash}, ${m.folderMillis})`)}})}escapeName(I){return`"${I}"`}escapeParam(I){return`$${I+1}`}escapeString(I){return`'${I.replace(/'/g,"''")}'`}buildWithCTE(I){if(!I?.length)return;let e=[U`with `];for(let[t,a]of I.entries())e.push(U`${U.identifier(a._.alias)} as (${a._.sql})`),t<I.length-1&&e.push(U`, `);return e.push(U` `),U.join(e)}buildDeleteQuery({table:I,where:e,returning:t,withList:a}){let G=this.buildWithCTE(a),c=t?U` returning ${this.buildSelection(t,{isSingleTable:!0})}`:void 0,n=e?U` where ${e}`:void 0;return U`${G}delete from ${I}${n}${c}`}buildUpdateSet(I,e){let t=I[RI.Symbol.Columns],a=Object.keys(t).filter(c=>e[c]!==void 0||t[c]?.onUpdateFn!==void 0),G=a.length;return U.join(a.flatMap((c,n)=>{let d=t[c],b=e[c]??U.param(d.onUpdateFn(),d),m=U`${U.identifier(this.casing.getColumnCasing(d))} = ${b}`;return n<G-1?[m,U.raw(", ")]:[m]}))}buildUpdateQuery({table:I,set:e,where:t,returning:a,withList:G,from:c,joins:n}){let d=this.buildWithCTE(G),b=I[ut.Symbol.Name],m=I[ut.Symbol.Schema],Z=I[ut.Symbol.OriginalName],r=b===Z?void 0:b,o=U`${m?U`${U.identifier(m)}.`:void 0}${U.identifier(Z)}${r&&U` ${U.identifier(r)}`}`,u=this.buildUpdateSet(I,e),N=c&&U.join([U.raw(" from "),this.buildFromTable(c)]),V=this.buildJoins(n),Y=a?U` returning ${this.buildSelection(a,{isSingleTable:!c})}`:void 0,p=t?U` where ${t}`:void 0;return U`${d}update ${o} set ${u}${N}${V}${p}${Y}`}buildSelection(I,{isSingleTable:e=!1}={}){let t=I.length,a=I.flatMap(({field:G},c)=>{let n=[];if(sI(G,yI.Aliased)&&G.isSelectionField)n.push(U.identifier(G.fieldAlias));else if(sI(G,yI.Aliased)||sI(G,yI)){let d=sI(G,yI.Aliased)?G.sql:G;e?n.push(new yI(d.queryChunks.map(b=>sI(b,YI)?U.identifier(this.casing.getColumnCasing(b)):b))):n.push(d),sI(G,yI.Aliased)&&n.push(U` as ${U.identifier(G.fieldAlias)}`)}else sI(G,$l)&&(e?n.push(U.identifier(this.casing.getColumnCasing(G))):n.push(G));return c<t-1&&n.push(U`, `),n});return U.join(a)}buildJoins(I){if(!I||I.length===0)return;let e=[];for(let[t,a]of I.entries()){t===0&&e.push(U` `);let G=a.table,c=a.lateral?U` lateral`:void 0;if(sI(G,ut)){let n=G[ut.Symbol.Name],d=G[ut.Symbol.Schema],b=G[ut.Symbol.OriginalName],m=n===b?void 0:a.alias;e.push(U`${U.raw(a.joinType)} join${c} ${d?U`${U.identifier(d)}.`:void 0}${U.identifier(b)}${m&&U` ${U.identifier(m)}`} on ${a.on}`)}else if(sI(G,Pa)){let n=G[we].name,d=G[we].schema,b=G[we].originalName,m=n===b?void 0:a.alias;e.push(U`${U.raw(a.joinType)} join${c} ${d?U`${U.identifier(d)}.`:void 0}${U.identifier(b)}${m&&U` ${U.identifier(m)}`} on ${a.on}`)}else e.push(U`${U.raw(a.joinType)} join${c} ${G} on ${a.on}`);t<I.length-1&&e.push(U` `)}return U.join(e)}buildFromTable(I){if(sI(I,RI)&&I[RI.Symbol.OriginalName]!==I[RI.Symbol.Name]){let e=U`${U.identifier(I[RI.Symbol.OriginalName])}`;return I[RI.Symbol.Schema]&&(e=U`${U.identifier(I[RI.Symbol.Schema])}.${e}`),U`${e} ${U.identifier(I[RI.Symbol.Name])}`}return I}buildSelectQuery({withList:I,fields:e,fieldsFlat:t,where:a,having:G,table:c,joins:n,orderBy:d,groupBy:b,limit:m,offset:Z,lockingClause:r,distinct:o,setOperators:u}){let N=t??fn(e);for(let O of N)if(sI(O.field,$l)&&ac(O.field.table)!==(sI(c,et)?c._.alias:sI(c,ui)?c[we].name:sI(c,yI)?void 0:ac(c))&&!(_=>n?.some(({alias:P})=>P===(_[RI.Symbol.IsAlias]?ac(_):_[RI.Symbol.BaseName])))(O.field.table)){let _=ac(O.field.table);throw new Error(`Your "${O.path.join("->")}" field references a column "${_}"."${O.field.name}", but the table "${_}" is not part of the query! Did you forget to join it?`)}let V=!n||n.length===0,Y=this.buildWithCTE(I),p;o&&(p=o===!0?U` distinct`:U` distinct on (${U.join(o.on,U`, `)})`);let h=this.buildSelection
CREATE EXTENSION IF NOT EXISTS vector;`],bps:!0,folderMillis:1729509950412,hash:"6c20ce195f8fc8f8ccb136af42a856f90c3e62e0727ad2e9cd1f01e59efc3a86"},{sql:[`CREATE TABLE IF NOT EXISTS "vector_data_text_embedding_3_small" (
"id" serial PRIMARY KEY NOT NULL,
"path" text NOT NULL,
"mtime" bigint NOT NULL,
"content" text NOT NULL,
"embedding" vector(1536),
"metadata" jsonb NOT NULL
);
`,`
CREATE TABLE IF NOT EXISTS "vector_data_text_embedding_3_large" (
"id" serial PRIMARY KEY NOT NULL,
"path" text NOT NULL,
"mtime" bigint NOT NULL,
"content" text NOT NULL,
"embedding" vector(3072),
"metadata" jsonb NOT NULL
);
`,`
CREATE INDEX IF NOT EXISTS "embeddingIndex_text_embedding_3_small" ON "vector_data_text_embedding_3_small" USING hnsw ("embedding" vector_cosine_ops);`],bps:!0,folderMillis:1729509994653,hash:"30520313039892c9c07b13185b6e4aa0b0f9a09b851db96e0f6e400303560aec"},{sql:[`CREATE TABLE IF NOT EXISTS "vector_data_nomic_embed_text" (
"id" serial PRIMARY KEY NOT NULL,
"path" text NOT NULL,
"mtime" bigint NOT NULL,
"content" text NOT NULL,
"embedding" vector(768),
"metadata" jsonb NOT NULL
);
`,`
CREATE INDEX IF NOT EXISTS "embeddingIndex_nomic_embed_text" ON "vector_data_nomic_embed_text" USING hnsw ("embedding" vector_cosine_ops);`],bps:!0,folderMillis:1729890971064,hash:"2041cd1e2808ad7ceea75ab34088b1dae1d563286b35d36586129ab6467fb627"},{sql:[`CREATE TABLE IF NOT EXISTS "vector_data_mxbai_embed_large" (
"id" serial PRIMARY KEY NOT NULL,
"path" text NOT NULL,
"mtime" bigint NOT NULL,
"content" text NOT NULL,
"embedding" vector(1024),
"metadata" jsonb NOT NULL
);
`,`
CREATE INDEX IF NOT EXISTS "embeddingIndex_mxbai_embed_large" ON "vector_data_mxbai_embed_large" USING hnsw ("embedding" vector_cosine_ops);`],bps:!0,folderMillis:1729928816942,hash:"4dd533fe5e978bc0ad79708c073fc3ce973702b7c6eed71f0e4818b1063212fb"},{sql:[`CREATE TABLE IF NOT EXISTS "vector_data_bge_m3" (
"id" serial PRIMARY KEY NOT NULL,
"path" text NOT NULL,
"mtime" bigint NOT NULL,
"content" text NOT NULL,
"embedding" vector(1024),
"metadata" jsonb NOT NULL
);
`,`
CREATE INDEX IF NOT EXISTS "embeddingIndex_bge_m3" ON "vector_data_bge_m3" USING hnsw ("embedding" vector_cosine_ops);`],bps:!0,folderMillis:1730085029605,hash:"e41dde00d7d98da74596c60e796aa78d5cbfec57208347c72f16a6fa11c24ef1"},{sql:[`CREATE TABLE IF NOT EXISTS "template" (
"id" uuid PRIMARY KEY DEFAULT gen_random_uuid() NOT NULL,
"name" text NOT NULL,
"content" jsonb NOT NULL,
"created_at" timestamp DEFAULT now() NOT NULL,
"updated_at" timestamp DEFAULT now() NOT NULL,
CONSTRAINT "template_name_unique" UNIQUE("name")
);
`],bps:!0,folderMillis:1730443763982,hash:"eddf72b8d40619c170b3c12f3d3ce280385b1fc05717f211ab6077c6bea691bf"},{sql:['ALTER TABLE "vector_data_text_embedding_3_small" RENAME TO "vector_data_openai_text_embedding_3_small";',`
ALTER TABLE "vector_data_text_embedding_3_large" RENAME TO "vector_data_openai_text_embedding_3_large";`,`
ALTER TABLE "vector_data_nomic_embed_text" RENAME TO "vector_data_ollama_nomic_embed_text";`,`
ALTER TABLE "vector_data_mxbai_embed_large" RENAME TO "vector_data_ollama_mxbai_embed_large";`,`
ALTER TABLE "vector_data_bge_m3" RENAME TO "vector_data_ollama_bge_m3";`,`
ALTER INDEX IF EXISTS "embeddingIndex_text_embedding_3_small" RENAME TO "embeddingIndex_openai_text_embedding_3_small";`,`
ALTER INDEX IF EXISTS "embeddingIndex_nomic_embed_text" RENAME TO "embeddingIndex_ollama_nomic_embed_text";`,`
ALTER INDEX IF EXISTS "embeddingIndex_mxbai_embed_large" RENAME TO "embeddingIndex_ollama_mxbai_embed_large";`,`
ALTER INDEX IF EXISTS "embeddingIndex_bge_m3" RENAME TO "embeddingIndex_ollama_bge_m3";`,""],bps:!0,folderMillis:1732064682864,hash:"3dad96e7f1c939c5da3cae4792782e7a35488d39da418e6a9e6f60eafd637f55"},{sql:[`CREATE TABLE IF NOT EXISTS "vector_data_gemini_text_embedding_004" (
"id" serial PRIMARY KEY NOT NULL,
"path" text NOT NULL,
"mtime" bigint NOT NULL,
"content" text NOT NULL,
"embedding" vector(768),
"metadata" jsonb NOT NULL
);
`,`
CREATE INDEX IF NOT EXISTS "embeddingIndex_gemini_text_embedding_004" ON "vector_data_gemini_text_embedding_004" USING hnsw ("embedding" vector_cosine_ops);`],bps:!0,folderMillis:1732189839252,hash:"9eef3295787aab3582954d7b8fbdeda90de062f43e09a0a53d839c601c00fe0f"},{sql:[`CREATE TABLE "embeddings" (
"id" serial PRIMARY KEY NOT NULL,
"path" text NOT NULL,
"mtime" bigint NOT NULL,
"content" text NOT NULL,
"model" text NOT NULL,
"dimension" smallint NOT NULL,
"embedding" vector,
"metadata" jsonb NOT NULL
);
`,`
CREATE INDEX "embeddings_path_index" ON "embeddings" USING btree ("path");`,`
CREATE INDEX "embeddings_model_index" ON "embeddings" USING btree ("model");`,`
CREATE INDEX "embeddings_dimension_index" ON "embeddings" USING btree ("dimension");`,`
CREATE INDEX "embeddings_embedding_768_index" ON "embeddings" USING hnsw ((embedding::vector(768)) vector_cosine_ops) WHERE dimension = 768;`,`
CREATE INDEX "embeddings_embedding_1024_index" ON "embeddings" USING hnsw ((embedding::vector(1024)) vector_cosine_ops) WHERE dimension = 1024;`,`
CREATE INDEX "embeddings_embedding_1536_index" ON "embeddings" USING hnsw ((embedding::vector(1536)) vector_cosine_ops) WHERE dimension = 1536;`,`
-- Migrate data from openai-text-embedding-3-small
INSERT INTO "embeddings" ("path", "mtime", "content", "model", "dimension", "embedding", "metadata")
SELECT "path", "mtime", "content", 'openai/text-embedding-3-small', 1536, "embedding", "metadata"
FROM "vector_data_openai_text_embedding_3_small";`,`
-- Migrate data from openai-text-embedding-3-large
INSERT INTO "embeddings" ("path", "mtime", "content", "model", "dimension", "embedding", "metadata")
SELECT "path", "mtime", "content", 'openai/text-embedding-3-large', 3072, "embedding", "metadata"
FROM "vector_data_openai_text_embedding_3_large";`,`
-- Migrate data from gemini-text-embedding-004
INSERT INTO "embeddings" ("path", "mtime", "content", "model", "dimension", "embedding", "metadata")
SELECT "path", "mtime", "content", 'gemini/text-embedding-004', 768, "embedding", "metadata"
FROM "vector_data_gemini_text_embedding_004";`,`
-- Migrate data from nomic-embed-text
INSERT INTO "embeddings" ("path", "mtime", "content", "model", "dimension", "embedding", "metadata")
SELECT "path", "mtime", "content", 'ollama/nomic-embed-text', 768, "embedding", "metadata"
FROM "vector_data_ollama_nomic_embed_text";`,`
-- Migrate data from mxbai-embed-large
INSERT INTO "embeddings" ("path", "mtime", "content", "model", "dimension", "embedding", "metadata")
SELECT "path", "mtime", "content", 'ollama/mxbai-embed-large', 1024, "embedding", "metadata"
FROM "vector_data_ollama_mxbai_embed_large";`,`
-- Migrate data from bge-m3
INSERT INTO "embeddings" ("path", "mtime", "content", "model", "dimension", "embedding", "metadata")
SELECT "path", "mtime", "content", 'ollama/bge-m3', 1024, "embedding", "metadata"
FROM "vector_data_ollama_bge_m3";`,`
DROP TABLE "vector_data_openai_text_embedding_3_small" CASCADE;`,`
DROP TABLE "vector_data_openai_text_embedding_3_large" CASCADE;`,`
DROP TABLE "vector_data_gemini_text_embedding_004" CASCADE;`,`
DROP TABLE "vector_data_ollama_nomic_embed_text" CASCADE;`,`
DROP TABLE "vector_data_ollama_mxbai_embed_large" CASCADE;`,`
DROP TABLE "vector_data_ollama_bge_m3" CASCADE;
`],bps:!0,folderMillis:1738138268694,hash:"01ff79bbbba4e3a9dda7a5dc47faf9b649b1fef812897ef714dbf99cdc787efb"},{sql:['CREATE INDEX "embeddings_embedding_128_index" ON "embeddings" USING hnsw ((embedding::vector(128)) vector_cosine_ops) WHERE dimension = 128;',`
CREATE INDEX "embeddings_embedding_256_index" ON "embeddings" USING hnsw ((embedding::vector(256)) vector_cosine_ops) WHERE dimension = 256;`,`
CREATE INDEX "embeddings_embedding_384_index" ON "embeddings" USING hnsw ((embedding::vector(384)) vector_cosine_ops) WHERE dimension = 384;`,`
CREATE INDEX "embeddings_embedding_512_index" ON "embeddings" USING hnsw ((embedding::vector(512)) vector_cosine_ops) WHERE dimension = 512;`,`
CREATE INDEX "embeddings_embedding_1280_index" ON "embeddings" USING hnsw ((embedding::vector(1280)) vector_cosine_ops) WHERE dimension = 1280;`,`
CREATE INDEX "embeddings_embedding_1792_index" ON "embeddings" USING hnsw ((embedding::vector(1792)) vector_cosine_ops) WHERE dimension = 1792; `],bps:!0,folderMillis:1738720225813,hash:"18a862af0fda7dc9e56e7122a65964a760410272de2188e777e2e0f035d7814f"}];s();var lQI=y(_v());s();s();RG();var Kll=xC({dataType(){return"vector"},toDriver(l){return JSON.stringify(l)},fromDriver(l){if(typeof l!="string")throw new Error("Invalid vector value from pg driver");return v.array(v.number()).parse(JSON.parse(l))}}),e5=[128,256,384,512,768,1024,1280,1536,1792],de=fK("embeddings",{id:NJ("id").primaryKey(),path:oi("path").notNull(),mtime:XC("mtime",{mode:"number"}).notNull(),content:oi("content").notNull(),model:oi("model").notNull(),dimension:YJ("dimension").notNull(),embedding:Kll("embedding"),metadata:IX("metadata").notNull().$type()},l=>[oX("embeddings_path_index").on(l.path),oX("embeddings_model_index").on(l.model),oX("embeddings_dimension_index").on(l.dimension),...e5.map(I=>oX(`embeddings_embedding_${I}_index`).using("hnsw",U.raw(`(${l.embedding.name}::vector(${I})) vector_cosine_ops`)).where(U.raw(`${l.dimension.name} = ${I}`)))]),Am=fK("template",{id:EJ("id").defaultRandom().primaryKey(),name:oi("name").notNull().unique(),content:IX("content").notNull().$type(),createdAt:lX("created_at").defaultNow().notNull(),updatedAt:lX("updated_at").defaultNow().notNull()});var t5=class{constructor(I,e){this.app=I,this.db=e}async create(I){if(!this.db)throw new Ra;let[e]=await this.db.insert(Am).values(I).returning();return e}async findAll(){if(!this.db)throw new Ra;return await this.db.select().from(Am)}async findByName(I){if(!this.db)throw new Ra;let[e]=await this.db.select().from(Am).where($t(Am.name,I));return e??null}async update(I,e){if(!this.db)throw new Ra;let[t]=await this.db.update(Am).set({...e,updatedAt:new Date}).where($t(Am.id,I)).returning();return t}async delete(I){if(!this.db)throw new Ra;let[e]=await this.db.delete(Am).where($t(Am.id,I)).returning();return!!e}};var YX=class{constructor(I,e){this.saveCallback=null;this.vacuumCallback=null;this.app=I,this.repository=new t5(I,e)}async requestSave(){this.saveCallback&&await this.saveCallback()}async requestVacuum(){this.vacuumCallback&&await this.vacuumCallback()}setSaveCallback(I){this.saveCallback=I}setVacuumCallback(I){this.vacuumCallback=I}async createTemplate(I){if(await this.repository.findByName(I.name))throw new XY(I.name);let t=await this.repository.create(I);return await this.requestSave(),t}async findAllTemplates(){return await this.repository.findAll()}async searchTemplates(I){let e=await this.findAllTemplates();return lQI.default.go(I,e,{keys:["name"],threshold:.2,limit:20,all:!0}).map(a=>a.obj)}async deleteTemplate(I){let e=await this.repository.delete(I);return await this.requestSave(),e}};s();var hgI=y(bQI());s();s();s();s();s();s();s();s();var G5=class{constructor(I){Object.defineProperty(this,"pageContent",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.pageContent=I.pageContent!==void 0?I.pageContent.toString():"",this.metadata=I.metadata??{},this.id=I.id}};s();s();RG();var n_=y(d5(),1);s();s();s();s();s();s();s();var XQI=y(d5(),1),o5=y(r5(),1);s();var Cel=(...l)=>fetch(...l),Jel=Symbol.for("ls:fetch_implementation");var jI=()=>globalThis[Jel]??Cel;var Ael=[400,401,403,404,405,406,407,408],Lel=[409],XX=class{constructor(I){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"onFailedResponseHook",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=I.maxConcurrency??1/0,this.maxRetries=I.maxRetries??6,"default"in o5.default?this.queue=new o5.default.default({concurrency:thi
Status: ${G.status}
Message: ${c.detail.join(`
`)}`):new Error(`Failed to list shared examples: ${G.status} ${G.statusText}`);return c.map(n=>({...n,_hostUrl:this.getHostUrl()}))}async createProject({projectName:I,description:e=null,metadata:t=null,upsert:a=!1,projectExtra:G=null,referenceDatasetId:c=null}){let n=a?"?upsert=true":"",d=`${this.apiUrl}/sessions${n}`,b=G||{};t&&(b.metadata=t);let m={name:I,extra:b,description:e};c!==null&&(m.reference_dataset_id=c);let Z=await this.caller.call(jI(),d,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(m),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(Z,"create project"),await Z.json()}async updateProject(I,{name:e=null,description:t=null,metadata:a=null,projectExtra:G=null,endTime:c=null}){let n=`${this.apiUrl}/sessions/${I}`,d=G;a&&(d={...d||{},metadata:a});let b={name:e,extra:d,description:t,end_time:c?new Date(c).toISOString():null},m=await this.caller.call(jI(),n,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(b),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(m,"update project"),await m.json()}async hasProject({projectId:I,projectName:e}){let t="/sessions",a=new URLSearchParams;if(I!==void 0&&e!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(I!==void 0)Yl(I),t+=`/${I}`;else if(e!==void 0)a.append("name",e);else throw new Error("Must provide projectName or projectId");let G=await this.caller.call(jI(),`${this.apiUrl}${t}?${a}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});try{let c=await G.json();return G.ok?Array.isArray(c)?c.length>0:!0:!1}catch{return!1}}async readProject({projectId:I,projectName:e,includeStats:t}){let a="/sessions",G=new URLSearchParams;if(I!==void 0&&e!==void 0)throw new Error("Must provide either projectName or projectId, not both");if(I!==void 0)Yl(I),a+=`/${I}`;else if(e!==void 0)G.append("name",e);else throw new Error("Must provide projectName or projectId");t!==void 0&&G.append("include_stats",t.toString());let c=await this._get(a,G),n;if(Array.isArray(c)){if(c.length===0)throw new Error(`Project[id=${I}, name=${e}] not found`);n=c[0]}else n=c;return n}async getProjectUrl({projectId:I,projectName:e}){if(I===void 0&&e===void 0)throw new Error("Must provide either projectName or projectId");let t=await this.readProject({projectId:I,projectName:e}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/projects/p/${t.id}`}async getDatasetUrl({datasetId:I,datasetName:e}){if(I===void 0&&e===void 0)throw new Error("Must provide either datasetName or datasetId");let t=await this.readDataset({datasetId:I,datasetName:e}),a=await this._getTenantId();return`${this.getHostUrl()}/o/${a}/datasets/${t.id}`}async _getTenantId(){if(this._tenantId!==null)return this._tenantId;let I=new URLSearchParams({limit:"1"});for await(let e of this._getPaginated("/sessions",I))return this._tenantId=e[0].tenant_id,e[0].tenant_id;throw new Error("No projects found to resolve tenant.")}async*listProjects({projectIds:I,name:e,nameContains:t,referenceDatasetId:a,referenceDatasetName:G,referenceFree:c,metadata:n}={}){let d=new URLSearchParams;if(I!==void 0)for(let b of I)d.append("id",b);if(e!==void 0&&d.append("name",e),t!==void 0&&d.append("name_contains",t),a!==void 0)d.append("reference_dataset",a);else if(G!==void 0){let b=await this.readDataset({datasetName:G});d.append("reference_dataset",b.id)}c!==void 0&&d.append("reference_free",c.toString()),n!==void 0&&d.append("metadata",JSON.stringify(n));for await(let b of this._getPaginated("/sessions",d))yield*b}async deleteProject({projectId:I,projectName:e}){let t;if(I===void 0&&e===void 0)throw new Error("Must provide projectName or projectId");if(I!==void 0&&e!==void 0)throw new Error("Must provide either projectName or projectId, not both");I===void 0?t=(await this.readProject({projectName:e})).id:t=I,Yl(t);let a=await this.caller.call(jI(),`${this.apiUrl}/sessions/${t}`,{method:"DELETE",headers:this.headers,
`).map(n=>JSON.parse(n))}async*listDatasets({limit:I=100,offset:e=0,datasetIds:t,datasetName:a,datasetNameContains:G,metadata:c}={}){let n="/datasets",d=new URLSearchParams({limit:I.toString(),offset:e.toString()});if(t!==void 0)for(let b of t)d.append("id",b);a!==void 0&&d.append("name",a),G!==void 0&&d.append("name_contains",G),c!==void 0&&d.append("metadata",JSON.stringify(c));for await(let b of this._getPaginated(n,d))yield*b}async updateDataset(I){let{datasetId:e,datasetName:t,...a}=I;if(!e&&!t)throw new Error("Must provide either datasetName or datasetId");let G=e??(await this.readDataset({datasetName:t})).id;Yl(G);let c=await this.caller.call(jI(),`${this.apiUrl}/datasets/${G}`,{method:"PATCH",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(a),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(c,"update dataset"),await c.json()}async deleteDataset({datasetId:I,datasetName:e}){let t="/datasets",a=I;if(I!==void 0&&e!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");if(e!==void 0&&(a=(await this.readDataset({datasetName:e})).id),a!==void 0)Yl(a),t+=`/${a}`;else throw new Error("Must provide datasetName or datasetId");let G=await this.caller.call(jI(),this.apiUrl+t,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await il(G,`delete ${t}`),await G.json()}async indexDataset({datasetId:I,datasetName:e,tag:t}){let a=I;if(!a&&!e)throw new Error("Must provide either datasetName or datasetId");if(a&&e)throw new Error("Must provide either datasetName or datasetId, not both");a||(a=(await this.readDataset({datasetName:e})).id),Yl(a);let G={tag:t},c=await this.caller.call(jI(),`${this.apiUrl}/datasets/${a}/index`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(G),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await il(c,"index dataset"),await c.json()}async similarExamples(I,e,t,{filter:a}={}){let G={limit:t,inputs:I};a!==void 0&&(G.filter=a),Yl(e);let c=await this.caller.call(jI(),`${this.apiUrl}/datasets/${e}/search`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(G),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(c,"fetch similar examples"),(await c.json()).examples}async createExample(I,e,{datasetId:t,datasetName:a,createdAt:G,exampleId:c,metadata:n,split:d,sourceRunId:b}){let m=t;if(m===void 0&&a===void 0)throw new Error("Must provide either datasetName or datasetId");if(m!==void 0&&a!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");m===void 0&&(m=(await this.readDataset({datasetName:a})).id);let Z=G||new Date,r={dataset_id:m,inputs:I,outputs:e,created_at:Z?.toISOString(),id:c,metadata:n,split:d,source_run_id:b},o=await this.caller.call(jI(),`${this.apiUrl}/examples`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(r),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(o,"create example"),await o.json()}async createExamples(I){let{inputs:e,outputs:t,metadata:a,sourceRunIds:G,exampleIds:c,datasetId:n,datasetName:d}=I,b=n;if(b===void 0&&d===void 0)throw new Error("Must provide either datasetName or datasetId");if(b!==void 0&&d!==void 0)throw new Error("Must provide either datasetName or datasetId, not both");b===void 0&&(b=(await this.readDataset({datasetName:d})).id);let m=e.map((o,u)=>({dataset_id:b,inputs:o,outputs:t?t[u]:void 0,metadata:a?a[u]:void 0,split:I.splits?I.splits[u]:void 0,id:c?c[u]:void 0,source_run_id:G?G[u]:void 0})),Z=await this.caller.call(jI(),`${this.apiUrl}/examples/bulk`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(m),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(Z,"create examples"),await Z.json()}async createLLMExample(I,e,t){return this.createExample({input:I},{output:e},t)}async createChatExample(I,e,t){le
Current tenant: ${t.tenant_handle}
Requested tenant: ${e}`)}async _getLatestCommitHash(I){let e=await this.caller.call(jI(),`${this.apiUrl}/commits/${I}/?limit=${1}&offset=${0}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions}),t=await e.json();if(!e.ok){let a=typeof t.detail=="string"?t.detail:JSON.stringify(t.detail),G=new Error(`Error ${e.status}: ${e.statusText}
${a}`);throw G.statusCode=e.status,G}if(t.commits.length!==0)return t.commits[0].commit_hash}async _likeOrUnlikePrompt(I,e){let[t,a,G]=xm(I),c=await this.caller.call(jI(),`${this.apiUrl}/likes/${t}/${a}`,{method:"POST",body:JSON.stringify({like:e}),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(c,`${e?"like":"unlike"} prompt`),await c.json()}async _getPromptUrl(I){let[e,t,a]=xm(I);if(await this._currentTenantIsOwner(e)){let G=await this._getSettings();return a!=="latest"?`${this.getHostUrl()}/prompts/${t}/${a.substring(0,8)}?organizationId=${G.id}`:`${this.getHostUrl()}/prompts/${t}?organizationId=${G.id}`}else return a!=="latest"?`${this.getHostUrl()}/hub/${e}/${t}/${a.substring(0,8)}`:`${this.getHostUrl()}/hub/${e}/${t}`}async promptExists(I){return!!await this.getPrompt(I)}async likePrompt(I){return this._likeOrUnlikePrompt(I,!0)}async unlikePrompt(I){return this._likeOrUnlikePrompt(I,!1)}async*listCommits(I){for await(let e of this._getPaginated(`/commits/${I}/`,new URLSearchParams,t=>t.commits))yield*e}async*listPrompts(I){let e=new URLSearchParams;e.append("sort_field",I?.sortField??"updated_at"),e.append("sort_direction","desc"),e.append("is_archived",(!!I?.isArchived).toString()),I?.isPublic!==void 0&&e.append("is_public",I.isPublic.toString()),I?.query&&e.append("query",I.query);for await(let t of this._getPaginated("/repos",e,a=>a.repos))yield*t}async getPrompt(I){let[e,t,a]=xm(I),G=await this.caller.call(jI(),`${this.apiUrl}/repos/${e}/${t}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});if(G.status===404)return null;await il(G,"get prompt");let c=await G.json();return c.repo?c.repo:null}async createPrompt(I,e){let t=await this._getSettings();if(e?.isPublic&&!t.tenant_handle)throw new Error(`Cannot create a public prompt without first
creating a LangChain Hub handle.
You can add a handle by creating a public prompt at:
https://smith.langchain.com/prompts`);let[a,G,c]=xm(I);if(!await this._currentTenantIsOwner(a))throw await this._ownerConflictError("create a prompt",a);let n={repo_handle:G,...e?.description&&{description:e.description},...e?.readme&&{readme:e.readme},...e?.tags&&{tags:e.tags},is_public:!!e?.isPublic},d=await this.caller.call(jI(),`${this.apiUrl}/repos/`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(n),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await il(d,"create prompt");let{repo:b}=await d.json();return b}async createCommit(I,e,t){if(!await this.promptExists(I))throw new Error("Prompt does not exist, you must create it first.");let[a,G,c]=xm(I),n=t?.parentCommitHash==="latest"||!t?.parentCommitHash?await this._getLatestCommitHash(`${a}/${G}`):t?.parentCommitHash,d={manifest:JSON.parse(JSON.stringify(e)),parent_commit:n},b=await this.caller.call(jI(),`${this.apiUrl}/commits/${a}/${G}`,{method:"POST",headers:{...this.headers,"Content-Type":"application/json"},body:JSON.stringify(d),signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await il(b,"create commit");let m=await b.json();return this._getPromptUrl(`${a}/${G}${m.commit_hash?`:${m.commit_hash}`:""}`)}async updatePrompt(I,e){if(!await this.promptExists(I))throw new Error("Prompt does not exist, you must create it first.");let[t,a]=xm(I);if(!await this._currentTenantIsOwner(t))throw await this._ownerConflictError("update a prompt",t);let G={};if(e?.description!==void 0&&(G.description=e.description),e?.readme!==void 0&&(G.readme=e.readme),e?.tags!==void 0&&(G.tags=e.tags),e?.isPublic!==void 0&&(G.is_public=e.isPublic),e?.isArchived!==void 0&&(G.is_archived=e.isArchived),Object.keys(G).length===0)throw new Error("No valid update options provided");let c=await this.caller.call(jI(),`${this.apiUrl}/repos/${t}/${a}`,{method:"PATCH",body:JSON.stringify(G),headers:{...this.headers,"Content-Type":"application/json"},signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});return await il(c,"update prompt"),c.json()}async deletePrompt(I){if(!await this.promptExists(I))throw new Error("Prompt does not exist, you must create it first.");let[e,t,a]=xm(I);if(!await this._currentTenantIsOwner(e))throw await this._ownerConflictError("delete a prompt",e);return await(await this.caller.call(jI(),`${this.apiUrl}/repos/${e}/${t}`,{method:"DELETE",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions})).json()}async pullPromptCommit(I,e){let[t,a,G]=xm(I),c=await this._getServerInfo(),n=NvI(c.version,"0.5.23"),d=G;if(!n&&G==="latest"){let Z=await this._getLatestCommitHash(`${t}/${a}`);if(Z)d=Z;else throw new Error("No commits found")}let b=await this.caller.call(jI(),`${this.apiUrl}/commits/${t}/${a}/${d}${e?.includeModel?"?include_model=true":""}`,{method:"GET",headers:this.headers,signal:AbortSignal.timeout(this.timeout_ms),...this.fetchOptions});await il(b,"pull prompt commit");let m=await b.json();return{owner:t,repo:a,commit_hash:m.commit_hash,manifest:m.manifest,examples:m.examples}}async _pullPrompt(I,e){let t=await this.pullPromptCommit(I,{includeModel:e?.includeModel});return JSON.stringify(t.manifest)}async pushPrompt(I,e){return await this.promptExists(I)?e&&Object.keys(e).some(a=>a!=="object")&&await this.updatePrompt(I,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}):await this.createPrompt(I,{description:e?.description,readme:e?.readme,tags:e?.tags,isPublic:e?.isPublic}),e?.object?await this.createCommit(I,e?.object,{parentCommitHash:e?.parentCommitHash}):await this._getPromptUrl(I)}async clonePublicDataset(I,e={}){let{sourceApiUrl:t=this.apiUrl,datasetName:a}=e,[G,c]=this.parseTokenOrUrl(I,t),n=new Zs({apiUrl:G,apiKey:"placeholder"}),d=await n.readSharedDataset(c),b=a||d.name;try{if(await this.hasDataset({datasetId:b})){console.log(`Dataset ${b} already exists in your tenant. Skipping.`);return}}catch{}let m=await n.listSharedExamples(c),Z=await this.createDataset(b,{description:d.description,dataType:
`));return l};var Zme=Symbol.for("langsmith:traceable:root");function E5(l){return typeof l=="function"&&"langsmith:traceable"in l}s();s();var CD={};pe(CD,{JsonPatchError:()=>qe,_areEquals:()=>JX,applyOperation:()=>Fi,applyPatch:()=>Xi,applyReducer:()=>lcl,deepClone:()=>$Gl,getValueByPointer:()=>J5,validate:()=>EvI,validator:()=>A5});s();s();var PGl=Object.prototype.hasOwnProperty;function wvI(l,I){return PGl.call(l,I)}function vvI(l){if(Array.isArray(l)){let e=new Array(l.length);for(let t=0;t<e.length;t++)e[t]=""+t;return e}if(Object.keys)return Object.keys(l);let I=[];for(let e in l)wvI(l,e)&&I.push(e);return I}function On(l){switch(typeof l){case"object":return JSON.parse(JSON.stringify(l));case"undefined":return null;default:return l}}function y5(l){let I=0,e=l.length,t;for(;I<e;){if(t=l.charCodeAt(I),t>=48&&t<=57){I++;continue}return!1}return!0}function C5(l){return l.indexOf("/")===-1&&l.indexOf("~")===-1?l:l.replace(/~/g,"~0").replace(/\//g,"~1")}function CX(l){return l.replace(/~1/g,"/").replace(/~0/g,"~")}function g5(l){if(l===void 0)return!0;if(l){if(Array.isArray(l)){for(let e=0,t=l.length;e<t;e++)if(g5(l[e]))return!0}else if(typeof l=="object"){let e=vvI(l),t=e.length;for(var I=0;I<t;I++)if(g5(l[e[I]]))return!0}}return!1}function QvI(l,I){let e=[l];for(let t in I){let a=typeof I[t]=="object"?JSON.stringify(I[t],null,2):I[t];typeof a<"u"&&e.push(`${t}: ${a}`)}return e.join(`
`)}var Ri=class extends Error{constructor(I,e,t,a,G){super(QvI(I,{name:e,index:t,operation:a,tree:G})),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"index",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"operation",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"tree",{enumerable:!0,configurable:!0,writable:!0,value:G}),Object.setPrototypeOf(this,new.target.prototype),this.message=QvI(I,{name:e,index:t,operation:a,tree:G})}};var qe=Ri,$Gl=On,yY={add:function(l,I,e){return l[I]=this.value,{newDocument:e}},remove:function(l,I,e){var t=l[I];return delete l[I],{newDocument:e,removed:t}},replace:function(l,I,e){var t=l[I];return l[I]=this.value,{newDocument:e,removed:t}},move:function(l,I,e){let t=J5(e,this.path);t&&(t=On(t));let a=Fi(e,{op:"remove",path:this.from}).removed;return Fi(e,{op:"add",path:this.path,value:a}),{newDocument:e,removed:t}},copy:function(l,I,e){let t=J5(e,this.from);return Fi(e,{op:"add",path:this.path,value:On(t)}),{newDocument:e}},test:function(l,I,e){return{newDocument:e,test:JX(l[I],this.value)}},_get:function(l,I,e){return this.value=l[I],{newDocument:e}}},Icl={add:function(l,I,e){return y5(I)?l.splice(I,0,this.value):l[I]=this.value,{newDocument:e,index:I}},remove:function(l,I,e){var t=l.splice(I,1);return{newDocument:e,removed:t[0]}},replace:function(l,I,e){var t=l[I];return l[I]=this.value,{newDocument:e,removed:t}},move:yY.move,copy:yY.copy,test:yY.test,_get:yY._get};function J5(l,I){if(I=="")return l;var e={op:"_get",path:I};return Fi(l,e),e.value}function Fi(l,I,e=!1,t=!0,a=!0,G=0){if(e&&(typeof e=="function"?e(I,0,l,I.path):A5(I,0)),I.path===""){let c={newDocument:l};if(I.op==="add")return c.newDocument=I.value,c;if(I.op==="replace")return c.newDocument=I.value,c.removed=l,c;if(I.op==="move"||I.op==="copy")return c.newDocument=J5(l,I.from),I.op==="move"&&(c.removed=l),c;if(I.op==="test"){if(c.test=JX(l,I.value),c.test===!1)throw new qe("Test operation failed","TEST_OPERATION_FAILED",G,I,l);return c.newDocument=l,c}else{if(I.op==="remove")return c.removed=l,c.newDocument=null,c;if(I.op==="_get")return I.value=l,c;if(e)throw new qe("Operation `op` property is not one of operations defined in RFC-6902","OPERATION_OP_INVALID",G,I,l);return c}}else{t||(l=On(l));let n=(I.path||"").split("/"),d=l,b=1,m=n.length,Z,r,o;for(typeof e=="function"?o=e:o=A5;;){if(r=n[b],r&&r.indexOf("~")!=-1&&(r=CX(r)),a&&(r=="__proto__"||r=="prototype"&&b>0&&n[b-1]=="constructor"))throw new TypeError("JSON-Patch: modifying `__proto__` or `constructor/prototype` prop is banned for security reasons, if this was on purpose, please set `banPrototypeModifications` flag false and pass it to this function. More info in fast-json-patch README");if(e&&Z===void 0&&(d[r]===void 0?Z=n.slice(0,b).join("/"):b==m-1&&(Z=I.path),Z!==void 0&&o(I,0,l,Z)),b++,Array.isArray(d)){if(r==="-")r=d.length;else{if(e&&!y5(r))throw new qe("Expected an unsigned base-10 integer value, making the new referenced value the array element with the zero-based index","OPERATION_PATH_ILLEGAL_ARRAY_INDEX",G,I,l);y5(r)&&(r=~~r)}if(b>=m){if(e&&I.op==="add"&&r>d.length)throw new qe("The specified index MUST NOT be greater than the number of elements in the array","OPERATION_VALUE_OUT_OF_BOUNDS",G,I,l);let u=Icl[I.op].call(I,d,r,l);if(u.test===!1)throw new qe("Test operation failed","TEST_OPERATION_FAILED",G,I,l);return u}}else if(b>=m){let u=yY[I.op].call(I,d,r,l);if(u.test===!1)throw new qe("Test operation failed","TEST_OPERATION_FAILED",G,I,l);return u}if(d=d[r],e&&b<m&&(!d||typeof d!="object"))throw new qe("Cannot perform operation at the desired path","OPERATION_PATH_UNRESOLVABLE",G,I,l)}}}function Xi(l,I,e,t=!0,a=!0){if(e&&!Array.isArray(I))throw new qe("Patch sequence must be an array","SEQUENCE_NOT_AN_ARRAY");t||(l=On(l));let G=new Array(I.length);for(let c=0,n=I.length;c<n;c++)G[c]=Fi(l,I[c],e,!0,a,c),l=G[c].newDocument;return G.newDocument=l,G}function lcl(l,I,e){let t=Fi(l,I);if(t.test===!1)throw new qe("Test operation f
${I.stack}`:""):typeof I=="string"?I:`${I}`}_addChildRun(I,e){I.child_runs.push(e)}_addRunToRunMap(I){let e=Wcl(I.start_time,I.id,I.execution_order),t={...I};if(t.parent_run_id!==void 0){let a=this.runMap.get(t.parent_run_id);a&&(this._addChildRun(a,t),a.child_execution_order=Math.max(a.child_execution_order,t.child_execution_order),t.trace_id=a.trace_id,a.dotted_order!==void 0&&(t.dotted_order=[a.dotted_order,e].join(".")))}else t.trace_id=t.id,t.dotted_order=e;return this.runMap.set(t.id,t),t}async _endTrace(I){let e=I.parent_run_id!==void 0&&this.runMap.get(I.parent_run_id);e?e.child_execution_order=Math.max(e.child_execution_order,I.child_execution_order):await this.persistRun(I),this.runMap.delete(I.id),await this.onRunUpdate?.(I)}_getExecutionOrder(I){let e=I!==void 0&&this.runMap.get(I);return e?e.child_execution_order+1:1}_createRunForLLMStart(I,e,t,a,G,c,n,d){let b=this._getExecutionOrder(a),m=Date.now(),Z=n?{...G,metadata:n}:G,r={id:t,name:d??I.id[I.id.length-1],parent_run_id:a,start_time:m,serialized:I,events:[{name:"start",time:new Date(m).toISOString()}],inputs:{prompts:e},execution_order:b,child_runs:[],child_execution_order:b,run_type:"llm",extra:Z??{},tags:c||[]};return this._addRunToRunMap(r)}async handleLLMStart(I,e,t,a,G,c,n,d){let b=this.runMap.get(t)??this._createRunForLLMStart(I,e,t,a,G,c,n,d);return await this.onRunCreate?.(b),await this.onLLMStart?.(b),b}_createRunForChatModelStart(I,e,t,a,G,c,n,d){let b=this._getExecutionOrder(a),m=Date.now(),Z=n?{...G,metadata:n}:G,r={id:t,name:d??I.id[I.id.length-1],parent_run_id:a,start_time:m,serialized:I,events:[{name:"start",time:new Date(m).toISOString()}],inputs:{messages:e},execution_order:b,child_runs:[],child_execution_order:b,run_type:"llm",extra:Z??{},tags:c||[]};return this._addRunToRunMap(r)}async handleChatModelStart(I,e,t,a,G,c,n,d){let b=this.runMap.get(t)??this._createRunForChatModelStart(I,e,t,a,G,c,n,d);return await this.onRunCreate?.(b),await this.onLLMStart?.(b),b}async handleLLMEnd(I,e){let t=this.runMap.get(e);if(!t||t?.run_type!=="llm")throw new Error("No LLM run to end.");return t.end_time=Date.now(),t.outputs=I,t.events.push({name:"end",time:new Date(t.end_time).toISOString()}),await this.onLLMEnd?.(t),await this._endTrace(t),t}async handleLLMError(I,e){let t=this.runMap.get(e);if(!t||t?.run_type!=="llm")throw new Error("No LLM run to end.");return t.end_time=Date.now(),t.error=this.stringifyError(I),t.events.push({name:"error",time:new Date(t.end_time).toISOString()}),await this.onLLMError?.(t),await this._endTrace(t),t}_createRunForChainStart(I,e,t,a,G,c,n,d){let b=this._getExecutionOrder(a),m=Date.now(),Z={id:t,name:d??I.id[I.id.length-1],parent_run_id:a,start_time:m,serialized:I,events:[{name:"start",time:new Date(m).toISOString()}],inputs:e,execution_order:b,child_execution_order:b,run_type:n??"chain",child_runs:[],extra:c?{metadata:c}:{},tags:G||[]};return this._addRunToRunMap(Z)}async handleChainStart(I,e,t,a,G,c,n,d){let b=this.runMap.get(t)??this._createRunForChainStart(I,e,t,a,G,c,n,d);return await this.onRunCreate?.(b),await this.onChainStart?.(b),b}async handleChainEnd(I,e,t,a,G){let c=this.runMap.get(e);if(!c)throw new Error("No chain run to end.");return c.end_time=Date.now(),c.outputs=xD(I,"output"),c.events.push({name:"end",time:new Date(c.end_time).toISOString()}),G?.inputs!==void 0&&(c.inputs=xD(G.inputs,"input")),await this.onChainEnd?.(c),await this._endTrace(c),c}async handleChainError(I,e,t,a,G){let c=this.runMap.get(e);if(!c)throw new Error("No chain run to end.");return c.end_time=Date.now(),c.error=this.stringifyError(I),c.events.push({name:"error",time:new Date(c.end_time).toISOString()}),G?.inputs!==void 0&&(c.inputs=xD(G.inputs,"input")),await this.onChainError?.(c),await this._endTrace(c),c}_createRunForToolStart(I,e,t,a,G,c,n){let d=this._getExecutionOrder(a),b=Date.now(),m={id:t,name:n??I.id[I.id.length-1],parent_run_id:a,start_time:b,serialized:I,events:[{name:"start",time:new Date(b).toISOString()}],inputs:{input:e},execution_order:d,child_execution_order:d,run_type:"tool",child_runs:[],extra:c?{metada
`&&!a?G="\\n":G==="\\"?a=!a:a=!1;else if(G==='"')t=!0,a=!1;else if(G==="{")e.push("}");else if(G==="[")e.push("]");else if(G==="}"||G==="]")if(e&&e[e.length-1]===G)e.pop();else return null;I+=G}t&&(I+='"');for(let G=e.length-1;G>=0;G-=1)I+=e[G];try{return JSON.parse(I)}catch{return null}}s();function Hi(l,I){return typeof l=="string"?typeof I=="string"?l+I:[{type:"text",text:l},...I]:Array.isArray(I)?k5(l,I)??[...l,...I]:[...l,{type:"text",text:I}]}function Ncl(l,I){function e(t,a){if(typeof t!="object"||t===null||t===void 0)return t;if(a>=I)return Array.isArray(t)?"[Array]":"[Object]";if(Array.isArray(t))return t.map(c=>e(c,a+1));let G={};for(let c of Object.keys(t))G[c]=e(t[c],a+1);return G}return JSON.stringify(e(l,0),null,2)}var Mm=class extends zd{get lc_aliases(){return{additional_kwargs:"additional_kwargs",response_metadata:"response_metadata"}}get text(){return typeof this.content=="string"?this.content:""}getType(){return this._getType()}constructor(I,e){typeof I=="string"&&(I={content:I,additional_kwargs:e,response_metadata:{}}),I.additional_kwargs||(I.additional_kwargs={}),I.response_metadata||(I.response_metadata={}),super(I),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","messages"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"content",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"additional_kwargs",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"response_metadata",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"id",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=I.name,this.content=I.content,this.additional_kwargs=I.additional_kwargs,this.response_metadata=I.response_metadata,this.id=I.id}toDict(){return{type:this._getType(),data:this.toJSON().kwargs}}static lc_name(){return"BaseMessage"}get _printableFields(){return{id:this.id,content:this.content,name:this.name,additional_kwargs:this.additional_kwargs,response_metadata:this.response_metadata}}_updateId(I){this.id=I,this.lc_kwargs.id=I}get[Symbol.toStringTag](){return this.constructor.lc_name()}[Symbol.for("nodejs.util.inspect.custom")](I){if(I===null)return this;let e=Ncl(this._printableFields,Math.max(4,I));return`${this.constructor.lc_name()} ${e}`}};function os(l,I){let e={...l};for(let[t,a]of Object.entries(I))if(e[t]==null)e[t]=a;else{if(a==null)continue;if(typeof e[t]!=typeof a||Array.isArray(e[t])!==Array.isArray(a))throw new Error(`field[${t}] already exists in the message chunk, but with a different type.`);if(typeof e[t]=="string"){if(t==="type")continue;e[t]+=a}else if(typeof e[t]=="object"&&!Array.isArray(e[t]))e[t]=os(e[t],a);else if(Array.isArray(e[t]))e[t]=k5(e[t],a);else{if(e[t]===a)continue;console.warn(`field[${t}] already exists in this message chunk and value has unsupported type.`)}}return e}function k5(l,I){if(!(l===void 0&&I===void 0)){if(l===void 0||I===void 0)return l||I;{let e=[...l];for(let t of I)if(typeof t=="object"&&"index"in t&&typeof t.index=="number"){let a=e.findIndex(G=>G.index===t.index);a!==-1?e[a]=os(e[a],t):e.push(t)}else{if(typeof t=="object"&&"text"in t&&t.text==="")continue;e.push(t)}return e}}}var Om=class extends Mm{};s();var Bm=class extends Om{constructor(I){let e;if(typeof I=="string")e={content:I,tool_calls:[],invalid_tool_calls:[],tool_call_chunks:[]};else if(I.tool_call_chunks===void 0)e={...I,tool_calls:I.tool_calls??[],invalid_tool_calls:[],tool_call_chunks:[],usage_metadata:I.usage_metadata!==void 0?I.usage_metadata:void 0};else{let t=[],a=[];for(let G of I.tool_call_chunks){let c={};try{if(c=qvI(G.args||"{}"),c===null||typeof c!="object"||Array.isArray(c))throw new Error("Malformed tool call chunk args.");t.push({name:G.name??"",args:c,id:G.id,type:"tool_call"})}catch{a.push({name:G.name,args:G.args,id:G.id,error:"Malformed args.",ty
`)}s();s();var Yo=class extends Bn{constructor(I={}){super(I),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:"langchain_tracer"}),Object.defineProperty(this,"projectName",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"exampleId",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"client",{enumerable:!0,configurable:!0,writable:!0,value:void 0});let{exampleId:e,projectName:t,client:a}=I;this.projectName=t??rs("LANGCHAIN_PROJECT")??rs("LANGCHAIN_SESSION"),this.exampleId=e,this.client=a??new Zs({});let G=Yo.getTraceableRunTree();G&&this.updateFromRunTree(G)}async _convertToCreate(I,e=void 0){return{...I,extra:{...I.extra,runtime:await SvI()},child_runs:void 0,session_name:this.projectName,reference_example_id:I.parent_run_id?void 0:e}}async persistRun(I){}async onRunCreate(I){let e=await this._convertToCreate(I,this.exampleId);await this.client.createRun(e)}async onRunUpdate(I){let e={end_time:I.end_time,error:I.error,outputs:I.outputs,events:I.events,inputs:I.inputs,trace_id:I.trace_id,dotted_order:I.dotted_order,parent_run_id:I.parent_run_id};await this.client.updateRun(I.id,e)}getRun(I){return this.runMap.get(I)}updateFromRunTree(I){let e=I,t=new Set;for(;e.parent_run&&!(t.has(e.id)||(t.add(e.id),!e.parent_run));)e=e.parent_run;t.clear();let a=[e];for(;a.length>0;){let G=a.shift();!G||t.has(G.id)||(t.add(G.id),this.runMap.set(G.id,G),G.child_runs&&a.push(...G.child_runs))}this.client=I.client??this.client,this.projectName=I.project_name??this.projectName,this.exampleId=I.reference_example_id??this.exampleId}convertToRunTree(I){let e={},t=[];for(let[a,G]of this.runMap){let c=new Ia({...G,child_runs:[],parent_run:void 0,client:this.client,project_name:this.projectName,reference_example_id:this.exampleId,tracingEnabled:!0});e[a]=c,t.push([a,G.dotted_order])}t.sort((a,G)=>!a[1]||!G[1]?0:a[1].localeCompare(G[1]));for(let[a]of t){let G=this.runMap.get(a),c=e[a];if(!(!G||!c)&&G.parent_run_id){let n=e[G.parent_run_id];n&&(n.child_runs.push(c),c.parent_run=n)}}return e[I]}static getTraceableRunTree(){try{return HvI()}catch{return}}};s();var x5=y(r5(),1),UD;function pcl(){let l="default"in x5.default?x5.default.default:x5.default;return new l({autoStart:!0,concurrency:1})}async function Wt(l,I){I===!0?await l():(typeof UD>"u"&&(UD=pcl()),UD.add(l))}s();var $vI=l=>l!==void 0?l:!!["LANGSMITH_TRACING_V2","LANGCHAIN_TRACING_V2","LANGSMITH_TRACING","LANGCHAIN_TRACING"].find(e=>rs(e)==="true");var MD=class{setHandler(I){return this.setHandlers([I])}},JY=class{constructor(I,e,t,a,G,c,n,d){Object.defineProperty(this,"runId",{enumerable:!0,configurable:!0,writable:!0,value:I}),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:e}),Object.defineProperty(this,"inheritableHandlers",{enumerable:!0,configurable:!0,writable:!0,value:t}),Object.defineProperty(this,"tags",{enumerable:!0,configurable:!0,writable:!0,value:a}),Object.defineProperty(this,"inheritableTags",{enumerable:!0,configurable:!0,writable:!0,value:G}),Object.defineProperty(this,"metadata",{enumerable:!0,configurable:!0,writable:!0,value:c}),Object.defineProperty(this,"inheritableMetadata",{enumerable:!0,configurable:!0,writable:!0,value:n}),Object.defineProperty(this,"_parentRunId",{enumerable:!0,configurable:!0,writable:!0,value:d})}get parentRunId(){return this._parentRunId}async handleText(I){await Promise.all(this.handlers.map(e=>Wt(async()=>{try{await e.handleText?.(I,this.runId,this._parentRunId,this.tags)}catch(t){if((e.raiseError?console.error:console.warn)(`Error in handler ${e.constructor.name}, handleText: ${t}`),e.raiseError)throw t}},e.awaitHandlers)))}async handleCustomEvent(I,e,t,a,G){await Promise.all(this.handlers.map(c=>Wt(async()=>{try{await c.handleCustomEvent?.(I,e,this.runId,this.tags,this.metadata)}catch(n){if((c.raiseError?console.error:console.warn)(`Error in handler ${c.constructor.name}, handleCustomEvent: ${n}`),c.raiseError)throw n}},c.awaitHandlers)))}},OD=class extends JY{getChild(I){let e=new dc(this.run
]))`;continue}else if(t[d]==="$"){a+=`($|(?=[\r
]))`;continue}}if(e.s&&t[d]==="."){a+=c?`${t[d]}\r
`:`[${t[d]}\r
]`;continue}a+=t[d],t[d]==="\\"?G=!0:c&&t[d]==="]"?c=!1:!c&&t[d]==="["&&(c=!0)}try{new RegExp(a)}catch{return console.warn(`Could not convert regex pattern at ${I.currentPath.join("/")} to a flag-independent form! Falling back to the flag-ignorant source`),l.source}return a}function j5(l,I){if(I.target==="openAi"&&console.warn("Warning: OpenAI may not support records in schemas! Try an array of key-value pairs instead."),I.target==="openApi3"&&l.keyType?._def.typeName===WI.ZodEnum)return{type:"object",required:l.keyType._def.values,properties:l.keyType._def.values.reduce((t,a)=>({...t,[a]:$I(l.valueType._def,{...I,currentPath:[...I.currentPath,"properties",a]})??{}}),{}),additionalProperties:I.rejectedAdditionalProperties};let e={type:"object",additionalProperties:$I(l.valueType._def,{...I,currentPath:[...I.currentPath,"additionalProperties"]})??I.allowedAdditionalProperties};if(I.target==="openApi3")return e;if(l.keyType?._def.typeName===WI.ZodString&&l.keyType._def.checks?.length){let{type:t,...a}=T5(l.keyType._def,I);return{...e,propertyNames:a}}else{if(l.keyType?._def.typeName===WI.ZodEnum)return{...e,propertyNames:{enum:l.keyType._def.values}};if(l.keyType?._def.typeName===WI.ZodBranded&&l.keyType._def.type._def.typeName===WI.ZodString&&l.keyType._def.type._def.checks?.length){let{type:t,...a}=S5(l.keyType._def,I);return{...e,propertyNames:a}}}return e}function VEI(l,I){if(I.mapStrategy==="record")return j5(l,I);let e=$I(l.keyType._def,{...I,currentPath:[...I.currentPath,"items","items","0"]})||{},t=$I(l.valueType._def,{...I,currentPath:[...I.currentPath,"items","items","1"]})||{};return{type:"array",maxItems:125,items:{type:"array",items:[e,t],minItems:2,maxItems:2}}}s();function REI(l){let I=l.values,t=Object.keys(l.values).filter(G=>typeof I[I[G]]!="number").map(G=>I[G]),a=Array.from(new Set(t.map(G=>typeof G)));return{type:a.length===1?a[0]==="string"?"string":"number":["string","number"],enum:t}}s();function FEI(){return{not:{}}}s();function XEI(l){return l.target==="openApi3"?{enum:["null"],nullable:!0}:{type:"null"}}s();s();var UX={ZodString:"string",ZodNumber:"number",ZodBigInt:"integer",ZodBoolean:"boolean",ZodNull:"null"};function QEI(l,I){if(I.target==="openApi3")return HEI(l,I);let e=l.options instanceof Map?Array.from(l.options.values()):l.options;if(e.every(t=>t._def.typeName in UX&&(!t._def.checks||!t._def.checks.length))){let t=e.reduce((a,G)=>{let c=UX[G._def.typeName];return c&&!a.includes(c)?[...a,c]:a},[]);return{type:t.length>1?t:t[0]}}else if(e.every(t=>t._def.typeName==="ZodLiteral"&&!t.description)){let t=e.reduce((a,G)=>{let c=typeof G._def.value;switch(c){case"string":case"number":case"boolean":return[...a,c];case"bigint":return[...a,"integer"];case"object":if(G._def.value===null)return[...a,"null"];case"symbol":case"undefined":case"function":default:return a}},[]);if(t.length===e.length){let a=t.filter((G,c,n)=>n.indexOf(G)===c);return{type:a.length>1?a:a[0],enum:e.reduce((G,c)=>G.includes(c._def.value)?G:[...G,c._def.value],[])}}}else if(e.every(t=>t._def.typeName==="ZodEnum"))return{type:"string",enum:e.reduce((t,a)=>[...t,...a._def.values.filter(G=>!t.includes(G))],[])};return HEI(l,I)}var HEI=(l,I)=>{let e=(l.options instanceof Map?Array.from(l.options.values()):l.options).map((t,a)=>$I(t._def,{...I,currentPath:[...I.currentPath,"anyOf",`${a}`]})).filter(t=>!!t&&(!I.strictUnions||typeof t=="object"&&Object.keys(t).length>0));return e.length?{anyOf:e}:void 0};function wEI(l,I){if(["ZodString","ZodNumber","ZodBigInt","ZodBoolean","ZodNull"].includes(l.innerType._def.typeName)&&(!l.innerType._def.checks||!l.innerType._def.checks.length))return I.target==="openApi3"?{type:UX[l.innerType._def.typeName],nullable:!0}:{type:[UX[l.innerType._def.typeName],"null"]};if(I.target==="openApi3"){let t=$I(l.innerType._def,{...I,currentPath:[...I.currentPath]});return t&&"$ref"in t?{allOf:[t],nullable:!0}:t&&{...t,nullable:!0}}let e=$I(l.innerType._def,{...I,currentPath:[...I.currentPath,"anyOf","0"]});return e&&{anyOf:[e,{type:"null"}]}}s();function vEI(l,I){let e={type:"number"};if(!l.checks)return
`;return I}function zEI(l,I,e){let{firstNode:t,lastNode:a,nodeColors:G,withStyles:c=!0,curveStyle:n="linear",wrapLabelNWords:d=9}=e??{},b=c?`%%{init: {'flowchart': {'curve': '${n}'}}}%%
graph TD;
`:`graph TD;
`;if(c){let o="default",u={[o]:"{0}({1})"};t!==void 0&&(u[t]="{0}([{1}]):::first"),a!==void 0&&(u[a]="{0}([{1}]):::last");for(let[N,V]of Object.entries(l)){let Y=V.name.split(":").pop()??"",h=Jcl.some(X=>Y.startsWith(X)&&Y.endsWith(X))?`<p>${Y}</p>`:Y;Object.keys(V.metadata??{}).length&&(h+=`<hr/><small><em>${Object.entries(V.metadata??{}).map(([X,H])=>`${X} = ${H}`).join(`
`)}</em></small>`);let F=(u[N]??u[o]).replace("{0}",t_(N)).replace("{1}",h);b+=` ${F}
`}}let m={};for(let o of I){let u=o.source.split(":"),N=o.target.split(":"),V=u.filter((Y,p)=>Y===N[p]).join(":");m[V]||(m[V]=[]),m[V].push(o)}let Z=new Set;function r(o,u){let N=o.length===1&&o[0].source===o[0].target;if(u&&!N){let V=u.split(":").pop();if(Z.has(V))throw new Error(`Found duplicate subgraph '${V}' -- this likely means that you're reusing a subgraph node with the same name. Please adjust your graph to have subgraph nodes with unique names.`);Z.add(V),b+=` subgraph ${V}
`}for(let V of o){let{source:Y,target:p,data:h,conditional:F}=V,X="";if(h!==void 0){let H=h,Q=H.split(" ");Q.length>d&&(H=Array.from({length:Math.ceil(Q.length/d)},(E,C)=>Q.slice(C*d,(C+1)*d).join(" ")).join("&nbsp;<br>&nbsp;")),X=F?` -. &nbsp;${H}&nbsp; .-> `:` -- &nbsp;${H}&nbsp; --> `}else X=F?" -.-> ":" --> ";b+=` ${t_(Y)}${X}${t_(p)};
`}for(let V in m)V.startsWith(`${u}:`)&&V!==u&&r(m[V],V);u&&!N&&(b+=` end
`)}r(m[""]??[],"");for(let o in m)!o.includes(":")&&o!==""&&r(m[o],o);return c&&(b+=Acl(G??{})),b}async function UEI(l,I){let{backgroundColor:e="white"}=I??{},t=btoa(l);e!==void 0&&(/^#(?:[0-9a-fA-F]{3}){1,2}$/.test(e)||(e=`!${e}`));let a=`https://mermaid.ink/img/${t}?bgColor=${e}`,G=await fetch(a);if(!G.ok)throw new Error(["Failed to render the graph using the Mermaid.INK API.",`Status code: ${G.status}`,`Status text: ${G.statusText}`].join(`
`));return await G.blob()}function Lcl(l,I){if(l!==void 0&&!OZ(l))return l;if(zX(I))try{let e=I.getName();return e=e.startsWith("Runnable")?e.slice(8):e,e}catch{return I.getName()}else return I.name??"UnknownSchema"}function kcl(l){return zX(l.data)?{type:"runnable",data:{id:l.data.lc_id,name:l.data.getName()}}:{type:"schema",data:{...e_(l.data.schema),title:l.data.name}}}var wi=class{constructor(I){Object.defineProperty(this,"nodes",{enumerable:!0,configurable:!0,writable:!0,value:{}}),Object.defineProperty(this,"edges",{enumerable:!0,configurable:!0,writable:!0,value:[]}),this.nodes=I?.nodes??this.nodes,this.edges=I?.edges??this.edges}toJSON(){let I={};return Object.values(this.nodes).forEach((e,t)=>{I[e.id]=OZ(e.id)?t:e.id}),{nodes:Object.values(this.nodes).map(e=>({id:I[e.id],...kcl(e)})),edges:this.edges.map(e=>{let t={source:I[e.source],target:I[e.target]};return typeof e.data<"u"&&(t.data=e.data),typeof e.conditional<"u"&&(t.conditional=e.conditional),t})}}addNode(I,e,t){if(e!==void 0&&this.nodes[e]!==void 0)throw new Error(`Node with id ${e} already exists`);let a=e??gl(),G={id:a,data:I,name:Lcl(e,I),metadata:t};return this.nodes[a]=G,G}removeNode(I){delete this.nodes[I.id],this.edges=this.edges.filter(e=>e.source!==I.id&&e.target!==I.id)}addEdge(I,e,t,a){if(this.nodes[I.id]===void 0)throw new Error(`Source node ${I.id} not in graph`);if(this.nodes[e.id]===void 0)throw new Error(`Target node ${e.id} not in graph`);let G={source:I.id,target:e.id,data:t,conditional:a};return this.edges.push(G),G}firstNode(){return MEI(this)}lastNode(){return OEI(this)}extend(I,e=""){let t=e;Object.values(I.nodes).map(b=>b.id).every(OZ)&&(t="");let G=b=>t?`${t}:${b}`:b;Object.entries(I.nodes).forEach(([b,m])=>{this.nodes[G(b)]={...m,id:G(b)}});let c=I.edges.map(b=>({...b,source:G(b.source),target:G(b.target)}));this.edges=[...this.edges,...c];let n=I.firstNode(),d=I.lastNode();return[n?{id:G(n.id),data:n.data}:void 0,d?{id:G(d.id),data:d.data}:void 0]}trimFirstNode(){let I=this.firstNode();I&&MEI(this,[I.id])&&this.removeNode(I)}trimLastNode(){let I=this.lastNode();I&&OEI(this,[I.id])&&this.removeNode(I)}reid(){let I=Object.fromEntries(Object.values(this.nodes).map(a=>[a.id,a.name])),e=new Map;Object.values(I).forEach(a=>{e.set(a,(e.get(a)||0)+1)});let t=a=>{let G=I[a];return OZ(a)&&e.get(G)===1?G:a};return new wi({nodes:Object.fromEntries(Object.entries(this.nodes).map(([a,G])=>[t(a),{...G,id:t(a)}])),edges:this.edges.map(a=>({...a,source:t(a.source),target:t(a.target)}))})}drawMermaid(I){let{withStyles:e,curveStyle:t,nodeColors:a={default:"fill:#f2f0ff,line-height:1.2",first:"fill-opacity:0",last:"fill:#bfb6fc"},wrapLabelNWords:G}=I??{},c=this.reid(),n=c.firstNode(),d=c.lastNode();return zEI(c.nodes,c.edges,{firstNode:n?.id,lastNode:d?.id,withStyles:e,curveStyle:t,nodeColors:a,wrapLabelNWords:G})}async drawMermaidPng(I){let e=this.drawMermaid(I);return UEI(e,{backgroundColor:I?.backgroundColor})}};function MEI(l,I=[]){let e=new Set(l.edges.filter(a=>!I.includes(a.source)).map(a=>a.target)),t=[];for(let a of Object.values(l.nodes))!I.includes(a.id)&&!e.has(a.id)&&t.push(a);return t.length===1?t[0]:void 0}function OEI(l,I=[]){let e=new Set(l.edges.filter(a=>!I.includes(a.target)).map(a=>a.source)),t=[];for(let a of Object.values(l.nodes))!I.includes(a.id)&&!e.has(a.id)&&t.push(a);return t.length===1?t[0]:void 0}s();function BEI(l){let I=new TextEncoder,e=new ReadableStream({async start(t){for await(let a of l)t.enqueue(I.encode(`event: data
data: ${JSON.stringify(a)}
`));t.enqueue(I.encode(`event: end
`)),t.close()}});return Ct.fromReadableStream(e)}s();function a_(l){return typeof l=="object"&&l!==null&&typeof l[Symbol.iterator]=="function"&&typeof l.next=="function"}var SEI=l=>l!=null&&typeof l=="object"&&"next"in l&&typeof l.next=="function";function K5(l){return typeof l=="object"&&l!==null&&typeof l[Symbol.asyncIterator]=="function"}function*G_(l,I){for(;;){let{value:e,done:t}=Ud.runWithConfig(l,I.next.bind(I),!0);if(t)break;yield e}}async function*c_(l,I){let e=I[Symbol.asyncIterator]();for(;;){let{value:t,done:a}=await Ud.runWithConfig(l,e.next.bind(I),!0);if(a)break;yield t}}function la(l,I){return l&&!Array.isArray(l)&&!(l instanceof Date)&&typeof l=="object"?l:{[I]:l}}var ea=class extends zd{constructor(){super(...arguments),Object.defineProperty(this,"lc_runnable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0})}getName(I){let e=this.name??this.constructor.lc_name()??this.constructor.name;return I?`${e}${I}`:e}bind(I){return new jm({bound:this,kwargs:I,config:{}})}map(){return new AY({bound:this})}withRetry(I){return new d_({bound:this,kwargs:{},config:{},maxAttemptNumber:I?.stopAfterAttempt,...I})}withConfig(I){return new jm({bound:this,config:I,kwargs:{}})}withFallbacks(I){let e=Array.isArray(I)?I:I.fallbacks;return new b_({runnable:this,fallbacks:e})}_getOptionsList(I,e=0){if(Array.isArray(I)&&I.length!==e)throw new Error(`Passed "options" must be an array with the same length as the inputs, but got ${I.length} options for ${e} inputs`);if(Array.isArray(I))return I.map(Ie);if(e>1&&!Array.isArray(I)&&I.runId){console.warn("Provided runId will be used only for the first element of the batch.");let t=Object.fromEntries(Object.entries(I).filter(([a])=>a!=="runId"));return Array.from({length:e},(a,G)=>Ie(G===0?I:t))}return Array.from({length:e},()=>Ie(I))}async batch(I,e,t){let a=this._getOptionsList(e??{},I.length),G=a[0]?.maxConcurrency??t?.maxConcurrency,c=new xX({maxConcurrency:G,onFailedAttempt:d=>{throw d}}),n=I.map((d,b)=>c.call(async()=>{try{return await this.invoke(d,a[b])}catch(m){if(t?.returnExceptions)return m;throw m}}));return Promise.all(n)}async*_streamIterator(I,e){yield this.invoke(I,e)}async stream(I,e){let t=Ie(e),a=new Sm({generator:this._streamIterator(I,t),config:t});return await a.setup,Ct.fromAsyncGenerator(a)}_separateRunnableConfigFromCallOptions(I){let e;I===void 0?e=Ie(I):e=Ie({callbacks:I.callbacks,tags:I.tags,metadata:I.metadata,runName:I.runName,configurable:I.configurable,recursionLimit:I.recursionLimit,maxConcurrency:I.maxConcurrency,runId:I.runId,timeout:I.timeout,signal:I.signal});let t={...I};return delete t.callbacks,delete t.tags,delete t.metadata,delete t.runName,delete t.configurable,delete t.recursionLimit,delete t.maxConcurrency,delete t.runId,delete t.timeout,delete t.signal,[e,t]}async _callWithConfig(I,e,t){let a=Ie(t),c=await(await Tn(a))?.handleChainStart(this.toJSON(),la(e,"input"),a.runId,a?.runType,void 0,void 0,a?.runName??this.getName());delete a.runId;let n;try{let d=I.call(this,e,a,c);n=await us(d,t?.signal)}catch(d){throw await c?.handleChainError(d),d}return await c?.handleChainEnd(la(n,"output")),n}async _batchWithConfig(I,e,t,a){let G=this._getOptionsList(t??{},e.length),c=await Promise.all(G.map(Tn)),n=await Promise.all(c.map(async(b,m)=>{let Z=await b?.handleChainStart(this.toJSON(),la(e[m],"input"),G[m].runId,G[m].runType,void 0,void 0,G[m].runName??this.getName());return delete G[m].runId,Z})),d;try{let b=I.call(this,e,G,n,a);d=await us(b,G?.[0]?.signal)}catch(b){throw await Promise.all(n.map(m=>m?.handleChainError(b))),b}return await Promise.all(n.map(b=>b?.handleChainEnd(la(d,"output")))),d}async*_transformStreamWithConfig(I,e,t){let a,G=!0,c,n=!0,d=Ie(t),b=await Tn(d);async function*m(){for await(let r of I){if(G)if(a===void 0)a=r;else try{a=Ws(a,r)}catch{a=void 0,G=!1}yield r}}let Z;try{let r=await lEI(e.bind(this),m(),async()=>b?.handleChainStart(this.toJSON(),{input:""},d.runId,d.runType,void 0,void 0,d.runName??this.getName()),t?.signal,d);dele
Instead got an unsupported type.`)}var s_=class extends ea{static lc_name(){return"RunnableAssign"}constructor(I){I instanceof Ei&&(I={mapper:I}),super(I),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"mapper",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.mapper=I.mapper}async invoke(I,e){let t=await this.mapper.invoke(I,e);return{...I,...t}}async*_transform(I,e,t){let a=this.mapper.getStepsKeys(),[G,c]=_D(I),n=this.mapper.transform(c,Fa(t,{callbacks:e?.getChild()})),d=n.next();for await(let b of G){if(typeof b!="object"||Array.isArray(b))throw new Error(`RunnableAssign can only be used with objects as input, got ${typeof b}`);let m=Object.fromEntries(Object.entries(b).filter(([Z])=>!a.includes(Z)));Object.keys(m).length>0&&(yield m)}yield(await d).value;for await(let b of n)yield b}transform(I,e){return this._transformStreamWithConfig(I,this._transform.bind(this),e)}async stream(I,e){async function*t(){yield I}let a=Ie(e),G=new Sm({generator:this.transform(t(),a),config:a});return await G.setup,Ct.fromAsyncGenerator(G)}},m_=class extends ea{static lc_name(){return"RunnablePick"}constructor(I){(typeof I=="string"||Array.isArray(I))&&(I={keys:I}),super(I),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","runnables"]}),Object.defineProperty(this,"lc_serializable",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.defineProperty(this,"keys",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.keys=I.keys}async _pick(I){if(typeof this.keys=="string")return I[this.keys];{let e=this.keys.map(t=>[t,I[t]]).filter(t=>t[1]!==void 0);return e.length===0?void 0:Object.fromEntries(e)}}async invoke(I,e){return this._callWithConfig(this._pick.bind(this),I,e)}async*_transform(I){for await(let e of I){let t=await this._pick(e);t!==void 0&&(yield t)}}transform(I,e){return this._transformStreamWithConfig(I,this._transform.bind(this),e)}async stream(I,e){async function*t(){yield I}let a=Ie(e),G=new Sm({generator:this.transform(t(),a),config:a});return await G.setup,Ct.fromAsyncGenerator(G)}},D5=class extends jm{constructor(I){let e=Tm.from([LY.from(async t=>{let a;if(zD(t))try{a=await this.schema.parseAsync(t.args)}catch{throw new L5("Received tool input did not match expected schema",JSON.stringify(t.args))}else a=t;return a}).withConfig({runName:`${I.name}:parse_input`}),I.bound]).withConfig({runName:I.name});super({bound:e,config:I.config??{}}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"description",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"schema",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.name=I.name,this.description=I.description,this.schema=I.schema}static lc_name(){return"RunnableToolLike"}};function fcl(l,I){let e=I.name??l.getName(),t=I.description??I.schema?.description;return I.schema.constructor===v.ZodString?new D5({name:e,description:t,schema:v.object({input:v.string()}).transform(a=>a.input),bound:l}):new D5({name:e,description:t,schema:I.schema,bound:l})}var _5=class extends ea{constructor(){super(...arguments),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain_core","documents","transformers"]})}invoke(I,e){return this.transformDocuments(I)}};s();s();s();var Z_=class extends _5{constructor(I){if(super(I),Object.defineProperty(this,"lc_namespace",{enumerable:!0,configurable:!0,writable:!0,value:["langchain","document_transformers","text_splitters"]}),Object.defineProperty(this,"chunkSize",{enumerable:!0,configurable:!0,writable:!0,value:1e3}),Object.defineProperty(this,"chunkOverlap",{enumerable:!0,configurable:!0,writable:!0,value:200}),Object.defineProperty(this,"keepSeparator",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Objec
which is longer than the specified ${this.chunkSize}`),a.length>0)){let b=this.joinDocs(a,e);for(b!==null&&t.push(b);G>this.chunkOverlap||G+d+a.length*e.length>this.chunkSize&&G>0;)G-=await this.lengthFunction(a[0]),a.shift()}a.push(n),G+=d}let c=this.joinDocs(a,e);return c!==null&&t.push(c),t}};var gi=class extends Z_{static lc_name(){return"RecursiveCharacterTextSplitter"}constructor(I){super(I),Object.defineProperty(this,"separators",{enumerable:!0,configurable:!0,writable:!0,value:[`
`,`
`," ",""]}),this.separators=I?.separators??this.separators,this.keepSeparator=I?.keepSeparator??!0}async _splitText(I,e){let t=[],a=e[e.length-1],G;for(let b=0;b<e.length;b+=1){let m=e[b];if(m===""){a=m;break}if(I.includes(m)){a=m,G=e.slice(b+1);break}}let c=this.splitOnSeparator(I,a),n=[],d=this.keepSeparator?"":a;for(let b of c)if(await this.lengthFunction(b)<this.chunkSize)n.push(b);else{if(n.length){let m=await this.mergeSplits(n,d);t.push(...m),n=[]}if(!G)t.push(b);else{let m=await this._splitText(b,G);t.push(...m)}}if(n.length){let b=await this.mergeSplits(n,d);t.push(...b)}return t}async splitText(I){return this._splitText(I,this.separators)}static fromLanguage(I,e){return new gi({...e,separators:gi.getSeparatorsForLanguage(I)})}static getSeparatorsForLanguage(I){if(I==="cpp")return[`
class `,`
void `,`
int `,`
float `,`
double `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(I==="go")return[`
func `,`
var `,`
const `,`
type `,`
if `,`
for `,`
switch `,`
case `,`
`,`
`," ",""];if(I==="java")return[`
class `,`
public `,`
protected `,`
private `,`
static `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
`,`
`," ",""];if(I==="js")return[`
function `,`
const `,`
let `,`
var `,`
class `,`
if `,`
for `,`
while `,`
switch `,`
case `,`
default `,`
`,`
`," ",""];if(I==="php")return[`
function `,`
class `,`
if `,`
foreach `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(I==="proto")return[`
message `,`
service `,`
enum `,`
option `,`
import `,`
syntax `,`
`,`
`," ",""];if(I==="python")return[`
class `,`
def `,`
def `,`
`,`
`," ",""];if(I==="rst")return[`
===
`,`
---
`,`
***
`,`
.. `,`
`,`
`," ",""];if(I==="ruby")return[`
def `,`
class `,`
if `,`
unless `,`
while `,`
for `,`
do `,`
begin `,`
rescue `,`
`,`
`," ",""];if(I==="rust")return[`
fn `,`
const `,`
let `,`
if `,`
while `,`
for `,`
loop `,`
match `,`
const `,`
`,`
`," ",""];if(I==="scala")return[`
class `,`
object `,`
def `,`
val `,`
var `,`
if `,`
for `,`
while `,`
match `,`
case `,`
`,`
`," ",""];if(I==="swift")return[`
func `,`
class `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do `,`
switch `,`
case `,`
`,`
`," ",""];if(I==="markdown")return[`
## `,`
### `,`
#### `,`
##### `,`
###### `,"```\n\n",`
***
`,`
---
`,`
___
`,`
`,`
`," ",""];if(I==="latex")return[`
\\chapter{`,`
\\section{`,`
\\subsection{`,`
\\subsubsection{`,`
\\begin{enumerate}`,`
\\begin{itemize}`,`
\\begin{description}`,`
\\begin{list}`,`
\\begin{quote}`,`
\\begin{quotation}`,`
\\begin{verse}`,`
\\begin{verbatim}`,`
\\begin{align}`,"$$","$",`
`,`
`," ",""];if(I==="html")return["<body>","<div>","<p>","<br>","<li>","<h1>","<h2>","<h3>","<h4>","<h5>","<h6>","<span>","<table>","<tr>","<td>","<th>","<ul>","<ol>","<header>","<footer>","<nav>","<head>","<style>","<script>","<meta>","<title>"," ",""];if(I==="sol")return[`
pragma `,`
using `,`
contract `,`
interface `,`
library `,`
constructor `,`
type `,`
function `,`
event `,`
modifier `,`
error `,`
struct `,`
enum `,`
if `,`
for `,`
while `,`
do while `,`
assembly `,`
`,`
`," ",""];throw new Error(`Language ${I} is not supported.`)}};s();var ogI=y(agI(),1);s();var BX=l=>{if(typeof l!="string")throw new TypeError("invalid pattern");if(l.length>65536)throw new TypeError("pattern is too long")};s();s();var jcl={"[:alnum:]":["\\p{L}\\p{Nl}\\p{Nd}",!0],"[:alpha:]":["\\p{L}\\p{Nl}",!0],"[:ascii:]":["\\x00-\\x7f",!1],"[:blank:]":["\\p{Zs}\\t",!0],"[:cntrl:]":["\\p{Cc}",!0],"[:digit:]":["\\p{Nd}",!0],"[:graph:]":["\\p{Z}\\p{C}",!0,!0],"[:lower:]":["\\p{Ll}",!0],"[:print:]":["\\p{C}",!0],"[:punct:]":["\\p{P}",!0],"[:space:]":["\\p{Z}\\t\\r\\n\\v\\f",!0],"[:upper:]":["\\p{Lu}",!0],"[:word:]":["\\p{L}\\p{Nl}\\p{Nd}\\p{Pc}",!0],"[:xdigit:]":["A-Fa-f0-9",!1]},SX=l=>l.replace(/[[\]\\-]/g,"\\$&"),Kcl=l=>l.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),GgI=l=>l.join(""),cgI=(l,I)=>{let e=I;if(l.charAt(e)!=="[")throw new Error("not in a brace expression");let t=[],a=[],G=e+1,c=!1,n=!1,d=!1,b=!1,m=e,Z="";I:for(;G<l.length;){let N=l.charAt(G);if((N==="!"||N==="^")&&G===e+1){b=!0,G++;continue}if(N==="]"&&c&&!d){m=G+1;break}if(c=!0,N==="\\"&&!d){d=!0,G++;continue}if(N==="["&&!d){for(let[V,[Y,p,h]]of Object.entries(jcl))if(l.startsWith(V,G)){if(Z)return["$.",!1,l.length-e,!0];G+=V.length,h?a.push(Y):t.push(Y),n=n||p;continue I}}if(d=!1,Z){N>Z?t.push(SX(Z)+"-"+SX(N)):N===Z&&t.push(SX(N)),Z="",G++;continue}if(l.startsWith("-]",G+1)){t.push(SX(N+"-")),G+=2;continue}if(l.startsWith("-",G+1)){Z=N,G+=2;continue}t.push(SX(N)),G++}if(m<G)return["",!1,0,!1];if(!t.length&&!a.length)return["$.",!1,l.length-e,!0];if(a.length===0&&t.length===1&&/^\\?.$/.test(t[0])&&!b){let N=t[0].length===2?t[0].slice(-1):t[0];return[Kcl(N),!1,m-e,!1]}let r="["+(b?"^":"")+GgI(t)+"]",o="["+(b?"":"^")+GgI(a)+"]";return[t.length&&a.length?"("+r+"|"+o+")":t.length?r:o,n,m-e,!0]};s();var Ro=(l,{windowsPathsNoEscape:I=!1}={})=>I?l.replace(/\[([^\/\\])\]/g,"$1"):l.replace(/((?!\\).|^)\[([^\/\\])\]/g,"$1$2").replace(/\\([^\/])/g,"$1");var Dcl=new Set(["!","?","+","*","@"]),ngI=l=>Dcl.has(l),_cl="(?!(?:^|/)\\.\\.?(?:$|/))",q5="(?!\\.)",qcl=new Set(["[","."]),Pcl=new Set(["..","."]),$cl=new Set("().*{}+?[]^$\\!"),Inl=l=>l.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,"\\$&"),W_="[^/]",dgI=W_+"*?",bgI=W_+"+?",Jt,ta,Km,xe,it,Fo,yi,Xo,is,Ci,TX,$5,sgI,kY,P5,jX,u_,IA,mgI,bc=class{constructor(I,e,t={}){pI(this,$5);pI(this,jX);g(this,"type");pI(this,Jt,void 0);pI(this,ta,void 0);pI(this,Km,!1);pI(this,xe,[]);pI(this,it,void 0);pI(this,Fo,void 0);pI(this,yi,void 0);pI(this,Xo,!1);pI(this,is,void 0);pI(this,Ci,void 0);pI(this,TX,!1);this.type=I,I&&rI(this,ta,!0),rI(this,it,e),rI(this,Jt,A(this,it)?A(A(this,it),Jt):this),rI(this,is,A(this,Jt)===this?t:A(A(this,Jt),is)),rI(this,yi,A(this,Jt)===this?[]:A(A(this,Jt),yi)),I==="!"&&!A(A(this,Jt),Xo)&&A(this,yi).push(this),rI(this,Fo,A(this,it)?A(A(this,it),xe).length:0)}get hasMagic(){if(A(this,ta)!==void 0)return A(this,ta);for(let I of A(this,xe))if(typeof I!="string"&&(I.type||I.hasMagic))return rI(this,ta,!0);return A(this,ta)}toString(){return A(this,Ci)!==void 0?A(this,Ci):this.type?rI(this,Ci,this.type+"("+A(this,xe).map(I=>String(I)).join("|")+")"):rI(this,Ci,A(this,xe).map(I=>String(I)).join(""))}push(...I){for(let e of I)if(e!==""){if(typeof e!="string"&&!(e instanceof bc&&A(e,it)===this))throw new Error("invalid part: "+e);A(this,xe).push(e)}}toJSON(){let I=this.type===null?A(this,xe).slice().map(e=>typeof e=="string"?e:e.toJSON()):[this.type,...A(this,xe).map(e=>e.toJSON())];return this.isStart()&&!this.type&&I.unshift([]),this.isEnd()&&(this===A(this,Jt)||A(A(this,Jt),Xo)&&A(this,it)?.type==="!")&&I.push({}),I}isStart(){if(A(this,Jt)===this)return!0;if(!A(this,it)?.isStart())return!1;if(A(this,Fo)===0)return!0;let I=A(this,it);for(let e=0;e<A(this,Fo);e++){let t=A(I,xe)[e];if(!(t instanceof bc&&t.type==="!"))return!1}return!0}isEnd(){if(A(this,Jt)===this||A(this,it)?.type==="!")return!0;if(!A(this,it)?.isEnd())return!1;if(!this.type)return A(this,it)?.isEnd();let I=A(this,it)?A(A(this,it),xe).length:0;return A(this,Fo)===I-1}copyIn(I){typeof I=="string"?this.push(I):this.push(I.clone(this))}clone(I){let e=new bc(th
globstar while`,I,r,e,o,u),this.matchOne(I.slice(r),e.slice(o),t))return this.debug("globstar found match!",r,d,u),!0;if(u==="."||u===".."||!a.dot&&u.charAt(0)==="."){this.debug("dot detected!",I,r,e,o);break}this.debug("globstar swallow a segment, and continue"),r++}return!!(t&&(this.debug(`
>>> no match, partial?`,I,r,e,o),r===d))}let N;if(typeof m=="string"?(N=Z===m,this.debug("string match",m,Z,N)):(N=m.test(Z),this.debug("pattern match",m,Z,N)),!N)return!1}if(c===d&&n===b)return!0;if(c===d)return t;if(n===b)return c===d-1&&I[c]==="";throw new Error("wtf?")}braceExpand(){return NgI(this.pattern,this.options)}parse(I){BX(I);let e=this.options;if(I==="**")return Kn;if(I==="")return"";let t,a=null;(t=I.match(mnl))?a=e.dot?rnl:Znl:(t=I.match(lnl))?a=(e.nocase?e.dot?Gnl:anl:e.dot?tnl:enl)(t[1]):(t=I.match(onl))?a=(e.nocase?e.dot?Wnl:unl:e.dot?inl:Nnl)(t):(t=I.match(cnl))?a=e.dot?dnl:nnl:(t=I.match(bnl))&&(a=snl);let G=Ho.fromGlob(I,this.options).toMMPattern();return a&&typeof G=="object"&&Reflect.defineProperty(G,"test",{value:a}),G}makeRe(){if(this.regexp||this.regexp===!1)return this.regexp;let I=this.set;if(!I.length)return this.regexp=!1,this.regexp;let e=this.options,t=e.noglobstar?Ynl:e.dot?Vnl:Rnl,a=new Set(e.nocase?["i"]:[]),G=I.map(d=>{let b=d.map(m=>{if(m instanceof RegExp)for(let Z of m.flags.split(""))a.add(Z);return typeof m=="string"?wnl(m):m===Kn?Kn:m._src});return b.forEach((m,Z)=>{let r=b[Z+1],o=b[Z-1];m!==Kn||o===Kn||(o===void 0?r!==void 0&&r!==Kn?b[Z+1]="(?:\\/|"+t+"\\/)?"+r:b[Z]=t:r===void 0?b[Z-1]=o+"(?:\\/|"+t+")?":r!==Kn&&(b[Z-1]=o+"(?:\\/|\\/"+t+"\\/)"+r,b[Z+1]=Kn))}),b.filter(m=>m!==Kn).join("/")}).join("|"),[c,n]=I.length>1?["(?:",")"]:["",""];G="^"+c+G+n+"$",this.negate&&(G="^(?!"+G+").+$");try{this.regexp=new RegExp(G,[...a].join(""))}catch{this.regexp=!1}return this.regexp}slashSplit(I){return this.preserveMultipleSlashes?I.split("/"):this.isWindows&&/^\/\/[^\/]+/.test(I)?["",...I.split(/\/+/)]:I.split(/\/+/)}match(I,e=this.partial){if(this.debug("match",I,this.pattern),this.comment)return!1;if(this.empty)return I==="";if(I==="/"&&e)return!0;let t=this.options;this.isWindows&&(I=I.split("\\").join("/"));let a=this.slashSplit(I);this.debug(this.pattern,"split",a);let G=this.set;this.debug(this.pattern,"set",G);let c=a[a.length-1];if(!c)for(let n=a.length-2;!c&&n>=0;n--)c=a[n];for(let n=0;n<G.length;n++){let d=G[n],b=a;if(t.matchBase&&d.length===1&&(b=[c]),this.matchOne(b,d,e))return t.flipNegate?!0:!this.negate}return t.flipNegate?!1:this.negate}static defaults(I){return Nt.defaults(I).Minimatch}};Nt.AST=Ho;Nt.Minimatch=xY;Nt.escape=i_;Nt.unescape=Ro;s();function pgI(l,I){let e=[];for(let t=0;t<l.length;t+=I){let a=l.slice(t,t+I);e.push(a)}return e}s();var lA=class{constructor(I,e){this.app=I,this.db=e}async getIndexedFilePaths(I){if(!this.db)throw new Ra;return(await this.db.select({path:de.path}).from(de).where($t(de.model,I.id))).map(t=>t.path)}async getVectorsByFilePath(I,e){if(!this.db)throw new Ra;return await this.db.select().from(de).where(ms($t(de.path,I),$t(de.model,e.id)))}async deleteVectorsForSingleFile(I,e){if(!this.db)throw new Ra;await this.db.delete(de).where(ms($t(de.path,I),$t(de.model,e.id)))}async deleteVectorsForMultipleFiles(I,e){if(!this.db)throw new Ra;await this.db.delete(de).where(ms(aX(de.path,I),$t(de.model,e.id)))}async clearAllVectors(I){if(!this.db)throw new Ra;await this.db.delete(de).where($t(de.model,I.id))}async insertVectors(I){if(!this.db)throw new Ra;await this.db.insert(de).values(I)}async performSimilaritySearch(I,e,t){if(!this.db)throw new Ra;let a=U`1 - (${$HI(de.embedding,I)})`,G=MJ(a,t.minSimilarity),n=(()=>{if(!t.scope)return;let b=[];if(t.scope.files.length>0&&b.push(aX(de.path,t.scope.files)),t.scope.folders.length>0&&b.push(tX(...t.scope.folders.map(m=>OJ(de.path,`${m}/%`)))),b.length!==0)return tX(...b)})();return await this.db.select({...(()=>{let{embedding:b,...m}=hC(de);return m})(),similarity:a}).from(de).where(ms(G,n,$t(de.model,e.id),$t(de.dimension,e.dimension))).orderBy(b=>BJ(b.similarity)).limit(t.limit)}async getEmbeddingStats(){if(!this.db)throw new Ra;return await this.db.select({model:de.model,rowCount:qHI(),totalDataBytes:PHI(U`pg_column_size(${de}.*)`).mapWith(Number)}).from(de).groupBy(de.model).orderBy(de.model)}};var KX=class{constructor(I,e){this.saveCallback=null;this.vacuumCallback=null;this.app=I,this.repositor
`+c.map(({path:r,error:o})=>`File: ${r}
Error: ${o}`).join(`
`);new od(this.app,"Error: chunk embedding failed","Some files failed to process. Please report this issue to the developer if it persists.",`[Error Log]
${Z}`,{showReportBugButton:!0}).open()}if(n.length===0)throw new Error("All files failed to process. Stopping indexing process.");t?.({completedChunks:0,totalChunks:n.length,totalFiles:a.length});let d=0,b=pgI(n,100),m=[];try{for(let Z of b){let o=(await Promise.all(Z.map(async u=>{try{return await(0,hgI.backOff)(async()=>{if(u.content.length===0)throw new Error(`Chunk content is empty in file: ${u.path}`);if(u.content.includes("\0"))throw new Error(`Chunk content contains null bytes in file: ${u.path}`);let N=await I.getEmbedding(u.content);return d+=1,t?.({completedChunks:d,totalChunks:n.length,totalFiles:a.length}),{path:u.path,mtime:u.mtime,content:u.content,model:I.id,dimension:I.dimension,embedding:N,metadata:u.metadata}},{numOfAttempts:8,startingDelay:2e3,timeMultiple:2,maxDelay:6e4,retry:N=>N instanceof KZ||N.status===429?(t?.({completedChunks:d,totalChunks:n.length,totalFiles:a.length,waitingForRateLimit:!0}),!0):!1})}catch(N){return m.push({path:u.path,metadata:u.metadata,error:N instanceof Error?N.message:"Unknown error"}),null}}))).filter(u=>u!==null);if(o.length===0&&Z.length>0)throw new Error("All chunks in batch failed to embed. Stopping indexing process.");await this.repository.insertVectors(o)}}catch(Z){if(Z instanceof Ve||Z instanceof Rt||Z instanceof dd)new od(this.app,"Error",Z.message,void 0,{showSettingsButton:!0}).open();else{let r=`Failed to process ${m.length} file(s):
`+m.map(o=>`File: ${o.path}
Error: ${o.error}`).join(`
`);new od(this.app,"Error: embedding failed",`The indexing process was interrupted because several files couldn't be processed.
Please report this issue to the developer if it persists.`,`[Error Log]
${r}`,{showReportBugButton:!0}).open()}}finally{await this.requestSave()}}async clearAllVectors(I){await this.repository.clearAllVectors(I),await this.requestVacuum(),await this.requestSave()}async deleteVectorsForDeletedFiles(I){let e=await this.repository.getIndexedFilePaths(I);for(let t of e)this.app.vault.getAbstractFileByPath(t)||await this.repository.deleteVectorsForMultipleFiles([t],I)}async getFilesToIndex({embeddingModel:I,excludePatterns:e,includePatterns:t,reindexAll:a}){let G=this.app.vault.getMarkdownFiles();return G=G.filter(c=>!e.some(n=>Nt(c.path,n))),t.length>0&&(G=G.filter(c=>t.some(n=>Nt(c.path,n)))),a||(G=await Promise.all(G.map(async c=>{let n=await this.repository.getVectorsByFilePath(c.path,I);return n.length===0?(await this.app.vault.cachedRead(c)).length===0?null:c:c.stat.mtime>n[0].mtime?c:null})).then(c=>c.filter(Boolean))),G}async getEmbeddingStats(){return await this.repository.getEmbeddingStats()}};var Dm=class{constructor(I,e){this.pgClient=null;this.db=null;this.app=I,this.dbPath=e}static async create(I){let e=new Dm(I,(0,_X.normalizePath)(I7));e.db=await e.loadExistingDatabase(),e.db||(e.db=await e.createNewDatabase()),await e.migrateDatabase(),await e.save();let t={vectorManager:new KX(I,e.db),templateManager:new YX(I,e.db)},a=e.save.bind(e),G=e.vacuum.bind(e);return t.vectorManager.setSaveCallback(a),t.vectorManager.setVacuumCallback(G),t.templateManager.setSaveCallback(a),t.templateManager.setVacuumCallback(G),Dm.managers.set(e,t),console.log("Smart composer database initialized.",e),e}getDb(){return this.db}getVectorManager(){let I=Dm.managers.get(this)??{};if(!I.vectorManager)if(this.db)I.vectorManager=new KX(this.app,this.db),Dm.managers.set(this,I);else throw new Error("Database is not initialized");return I.vectorManager}getTemplateManager(){let I=Dm.managers.get(this)??{};if(!I.templateManager)if(this.db)I.templateManager=new YX(this.app,this.db),Dm.managers.set(this,I);else throw new Error("Database is not initialized");return I.templateManager}async vacuum(){this.pgClient&&await this.pgClient.query("VACUUM FULL;")}async createNewDatabase(){try{let{fsBundle:I,wasmModule:e,vectorExtensionBundlePath:t}=await this.loadPGliteResources();return this.pgClient=await bi.create({fsBundle:I,wasmModule:e,extensions:{vector:t}}),pX(this.pgClient)}catch(I){throw console.log("createNewDatabase error",I),I instanceof Error&&I.message.includes("Aborted(). Build with -sASSERTIONS for more info.")?new Ni:I}}async loadExistingDatabase(){try{if(!await this.app.vault.adapter.exists(this.dbPath))return null;let e=await this.app.vault.adapter.readBinary(this.dbPath),t=new Blob([e],{type:"application/x-gzip"}),{fsBundle:a,wasmModule:G,vectorExtensionBundlePath:c}=await this.loadPGliteResources();return this.pgClient=await bi.create({loadDataDir:t,fsBundle:a,wasmModule:G,extensions:{vector:c}}),pX(this.pgClient)}catch(I){if(console.log("loadExistingDatabase error",I),I instanceof Error&&I.message.includes("Aborted(). Build with -sASSERTIONS for more info."))throw new Ni;return null}}async migrateDatabase(){try{await this.db.dialect.migrate(IQI,this.db.session,{migrationsTable:"drizzle_migrations"})}catch(I){throw console.error("Error migrating database:",I),I}}async save(){if(this.pgClient)try{let I=await this.pgClient.dumpDataDir("gzip");await this.app.vault.adapter.writeBinary(this.dbPath,Buffer.from(await I.arrayBuffer()))}catch(I){console.error("Error saving database:",I)}}async cleanup(){await this.save(),Dm.managers.delete(this),await this.pgClient?.close(),this.pgClient=null,this.db=null}async loadPGliteResources(){try{let I="0.2.12",[e,t]=await Promise.all([(0,_X.requestUrl)(`https://unpkg.com/@electric-sql/pglite@${I}/dist/postgres.data`),(0,_X.requestUrl)(`https://unpkg.com/@electric-sql/pglite@${I}/dist/postgres.wasm`)]),a=new Blob([e.arrayBuffer],{type:"application/octet-stream"}),G=await WebAssembly.compile(t.arrayBuffer),c=new URL(`https://unpkg.com/@electric-sql/pglite@${I}/dist/vector.tar.gz`);return{fsBundle:a,wasmModule:G,vectorExtensionBundlePath:c}}catch(I){throw console.error("Erro
`));return}await l.setSettings({...l.settings,chatModels:[...l.settings.chatModels,e]}),I()};return(0,lG.jsxs)(lG.Fragment,{children:[(0,lG.jsx)(MI,{name:"ID",desc:"Choose an ID to identify this model in your settings. This is just for your reference.",required:!0,children:(0,lG.jsx)(Ae,{value:e.id,placeholder:"my-custom-model",onChange:G=>t(c=>({...c,id:G}))})}),(0,lG.jsx)(MI,{name:"Provider ID",required:!0,children:(0,lG.jsx)(JG,{value:e.providerId,options:Object.fromEntries(l.settings.providers.map(G=>[G.id,G.id])),onChange:G=>{let c=l.settings.providers.find(n=>n.id===G);if(!c){new IH.Notice(`Provider with ID ${G} not found`);return}t(n=>({...n,providerId:G,providerType:c.type}))}})}),(0,lG.jsx)(MI,{name:"Model Name",required:!0,children:(0,lG.jsx)(Ae,{value:e.model,placeholder:"Enter the model name",onChange:G=>t(c=>({...c,model:G}))})}),(0,lG.jsx)(MI,{name:"Prompt Level",desc:'Choose how complex the system prompt should be. Select "simple" for small models that ignore user questions and just repeat back instructions.',required:!0,children:(0,lG.jsx)(JG,{value:(e.promptLevel??1).toString(),options:{[1]:"default",[0]:"simple"},onChange:G=>t(c=>({...c,promptLevel:Number(G)}))})}),(0,lG.jsxs)(MI,{children:[(0,lG.jsx)(Al,{text:"Add",onClick:a,cta:!0}),(0,lG.jsx)(Al,{text:"Cancel",onClick:I})]})]})}s();var Li=require("obsidian"),zY=y(dI());var le=y(K()),dA=class extends fl{constructor(I,e,t){let a=SgI(I);super({app:e,Component:a?a.SettingsComponent:()=>(0,le.jsx)("div",{children:"No settings available for this model"}),props:{model:I,plugin:t},options:{title:`Edit Chat Model: ${I.id}`}})}},ldl=[{check:l=>l.providerType==="openai",SettingsComponent:l=>{let{model:I,plugin:e,onClose:t}=l,a=I,[G,c]=(0,zY.useState)(a.reasoning?.enabled??!1),[n,d]=(0,zY.useState)(a.reasoning?.reasoning_effort??"medium");return(0,le.jsxs)(le.Fragment,{children:[(0,le.jsx)(MI,{name:"Reasoning",desc:"Enable reasoning for the model. Available for o-series models (e.g., o3, o4-mini) and GPT-5 models.",children:(0,le.jsx)(Ic,{value:G,onChange:m=>c(m)})}),G&&(0,le.jsx)(MI,{name:"Reasoning Effort",desc:'Controls how much thinking the model does before responding. Default is "medium".',className:"smtcmp-setting-item--nested",required:!0,children:(0,le.jsx)(JG,{value:n,options:{low:"low",medium:"medium",high:"high"},onChange:m=>d(m)})}),(0,le.jsxs)(MI,{children:[(0,le.jsx)(Al,{text:"Save",onClick:async()=>{if(!["low","medium","high"].includes(n)){new Li.Notice('Reasoning effort must be one of "low", "medium", "high"');return}let m={...a,reasoning:{enabled:G,reasoning_effort:n}},Z=Ji.safeParse(m);if(!Z.success){new Li.Notice(Z.error.issues.map(r=>r.message).join(`
`));return}await e.setSettings({...e.settings,chatModels:e.settings.chatModels.map(r=>r.id===I.id?m:r)}),t()},cta:!0}),(0,le.jsx)(Al,{text:"Cancel",onClick:t})]})]})}},{check:l=>l.providerType==="anthropic",SettingsComponent:l=>{let{model:e,plugin:t,onClose:a}=l,G=e,[c,n]=(0,zY.useState)(G.thinking?.enabled??!1),[d,b]=(0,zY.useState)((G.thinking?.budget_tokens??8192).toString());return(0,le.jsxs)(le.Fragment,{children:[(0,le.jsx)(MI,{name:"Extended Thinking",desc:"Enable extended thinking for Claude. Available for Claude Sonnet 3.7+ and Claude Opus 4.0+.",children:(0,le.jsx)(Ic,{value:c,onChange:Z=>n(Z)})}),c&&(0,le.jsx)(MI,{name:"Budget Tokens",desc:"The maximum number of tokens that Claude can use for thinking. Must be at least 1024.",className:"smtcmp-setting-item--nested",required:!0,children:(0,le.jsx)(Ae,{value:d,placeholder:"Number of tokens",onChange:Z=>b(Z),type:"number"})}),(0,le.jsxs)(MI,{children:[(0,le.jsx)(Al,{text:"Save",onClick:async()=>{let Z=parseInt(d,10);if(isNaN(Z)){new Li.Notice("Please enter a valid number");return}if(Z<1024){new Li.Notice("Budget tokens must be at least 1024");return}let r={...G,thinking:{enabled:c,budget_tokens:Z}},o=Ji.safeParse(r);if(!o.success){new Li.Notice(o.error.issues.map(u=>u.message).join(`
`));return}await t.setSettings({...t.settings,chatModels:t.settings.chatModels.map(u=>u.id===e.id?r:u)}),a()},cta:!0}),(0,le.jsx)(Al,{text:"Cancel",onClick:a})]})]})}},{check:l=>l.providerType==="perplexity"&&["sonar","sonar-pro","sonar-deep-research","sonar-reasoning","sonar-reasoning-pro"].includes(l.model),SettingsComponent:l=>{let{model:I,plugin:e,onClose:t}=l,a=I,[G,c]=(0,zY.useState)(a.web_search_options?.search_context_size??"low");return(0,le.jsxs)(le.Fragment,{children:[(0,le.jsx)(MI,{name:"Search Context Size",desc:'Determines how much search context is retrieved for the model. Choose "low" for minimal context and lower costs, "medium" for a balanced approach, or "high" for maximum context at higher cost. Default is "low".',children:(0,le.jsx)(JG,{value:G,options:{low:"low",medium:"medium",high:"high"},onChange:d=>c(d)})}),(0,le.jsxs)(MI,{children:[(0,le.jsx)(Al,{text:"Save",onClick:async()=>{if(!["low","medium","high"].includes(G)){new Li.Notice('Search context size must be one of "low", "medium", "high"');return}let d={...a,web_search_options:{...a.web_search_options,search_context_size:G}};await e.setSettings({...e.settings,chatModels:e.settings.chatModels.map(b=>b.id===I.id?d:b)}),t()},cta:!0}),(0,le.jsx)(Al,{text:"Cancel",onClick:t})]})]})}}];function SgI(l){return ldl.find(I=>I.check(l))}function TgI(l){return!!SgI(l)}var Vl=y(K()),edl=l=>l??!0;function jgI({app:l,plugin:I}){let{settings:e,setSettings:t}=ql(),a=async c=>{if(c===e.chatModelId||c===e.applyModelId){new V_.Notice("Cannot remove model that is currently selected as Chat Model or Apply Model");return}let n=`Are you sure you want to delete model "${c}"?`;new Oa(l,{title:"Delete Chat Model",message:n,ctaText:"Delete",onConfirm:async()=>{await t({...e,chatModels:[...e.chatModels].filter(d=>d.id!==c)})}}).open()},G=async(c,n)=>{if(!n&&(c===e.chatModelId||c===e.applyModelId)){new V_.Notice("Cannot disable model that is currently selected as Chat Model or Apply Model"),await t({...e,chatModels:[...e.chatModels].map(d=>d.id===c?{...d,enable:!0}:d)});return}await t({...e,chatModels:[...e.chatModels].map(d=>d.id===c?{...d,enable:n}:d)})};return(0,Vl.jsxs)("div",{children:[(0,Vl.jsx)("div",{className:"smtcmp-settings-sub-header",children:"Chat Models"}),(0,Vl.jsx)("div",{className:"smtcmp-settings-desc",children:"Models used for chat and apply"}),(0,Vl.jsx)("div",{className:"smtcmp-settings-table-container",children:(0,Vl.jsxs)("table",{className:"smtcmp-settings-table",children:[(0,Vl.jsxs)("colgroup",{children:[(0,Vl.jsx)("col",{}),(0,Vl.jsx)("col",{}),(0,Vl.jsx)("col",{}),(0,Vl.jsx)("col",{width:60}),(0,Vl.jsx)("col",{width:60})]}),(0,Vl.jsx)("thead",{children:(0,Vl.jsxs)("tr",{children:[(0,Vl.jsx)("th",{children:"ID"}),(0,Vl.jsx)("th",{children:"Provider ID"}),(0,Vl.jsx)("th",{children:"Model"}),(0,Vl.jsx)("th",{children:"Enable"}),(0,Vl.jsx)("th",{children:"Actions"})]})}),(0,Vl.jsx)("tbody",{children:e.chatModels.map(c=>(0,Vl.jsxs)("tr",{children:[(0,Vl.jsx)("td",{children:c.id}),(0,Vl.jsx)("td",{children:c.providerId}),(0,Vl.jsx)("td",{children:c.model}),(0,Vl.jsx)("td",{children:(0,Vl.jsx)(Ic,{value:edl(c.enable),onChange:n=>G(c.id,n)})}),(0,Vl.jsx)("td",{children:(0,Vl.jsxs)("div",{className:"smtcmp-settings-actions",children:[TgI(c)&&(0,Vl.jsx)("button",{onClick:()=>{new dA(c,l,I).open()},className:"clickable-icon",children:(0,Vl.jsx)(_o,{})}),!gZ.some(n=>n.id===c.id)&&(0,Vl.jsx)("button",{onClick:()=>a(c.id),className:"clickable-icon",children:(0,Vl.jsx)(da,{})})]})})]},c.id))}),(0,Vl.jsx)("tfoot",{children:(0,Vl.jsx)("tr",{children:(0,Vl.jsx)("td",{colSpan:5,children:(0,Vl.jsx)("button",{onClick:()=>{new nA(l,I).open()},children:"Add custom model"})})})})]})})]})}s();var DgI=require("obsidian");s();var R_=require("obsidian"),KgI=y(dI());var sc=y(K()),bA=class extends fl{constructor(I,e){super({app:I,Component:tdl,props:{plugin:e},options:{title:"Add Custom Embedding Model"}})}};function tdl({plugin:l,onClose:I}){let[e,t]=(0,KgI.useState)({providerId:eb[0].id,providerType:eb[0].type,id:"",model:""}),a=async()=>{try{if(l.settings.embeddingModel
This may result in slower search performance.
Do you want to continue anyway?`,onConfirm:()=>Z(!0),onCancel:()=>Z(!1)}).open()}))return;let d={...e,dimension:n},b=aA.safeParse(d);if(!b.success)throw new Error(b.error.issues.map(m=>m.message).join(`
`));await l.setSettings({...l.settings,embeddingModels:[...l.settings.embeddingModels,d]}),I()}catch(G){new R_.Notice(G instanceof Error?G.message:"An unknown error occurred")}};return(0,sc.jsxs)(sc.Fragment,{children:[(0,sc.jsx)(MI,{name:"ID",desc:"Choose an ID to identify this model in your settings. This is just for your reference.",required:!0,children:(0,sc.jsx)(Ae,{value:e.id,placeholder:"my-custom-embedding-model",onChange:G=>t(c=>({...c,id:G}))})}),(0,sc.jsx)(MI,{name:"Provider ID",required:!0,children:(0,sc.jsx)(JG,{value:e.providerId,options:Object.fromEntries(l.settings.providers.filter(G=>xI[G.type].supportEmbedding).map(G=>[G.id,G.id])),onChange:G=>{let c=l.settings.providers.find(n=>n.id===G);if(!c){new R_.Notice(`Provider with ID ${G} not found`);return}t(n=>({...n,providerId:G,providerType:c.type}))}})}),(0,sc.jsx)(MI,{name:"Model Name",required:!0,children:(0,sc.jsx)(Ae,{value:e.model,placeholder:"Enter the model name",onChange:G=>t(c=>({...c,model:G}))})}),(0,sc.jsxs)(MI,{children:[(0,sc.jsx)(Al,{text:"Add",onClick:a,cta:!0}),(0,sc.jsx)(Al,{text:"Cancel",onClick:I})]})]})}var be=y(K());function _gI({app:l,plugin:I}){let{settings:e,setSettings:t}=ql(),a=async G=>{if(G===e.embeddingModelId){new DgI.Notice("Cannot remove model that is currently selected as Embedding Model");return}let c=`Are you sure you want to delete embedding model "${G}"?
This will also delete all embeddings generated using this model from the database.`;new Oa(l,{title:"Delete Embedding Model",message:c,ctaText:"Delete",onConfirm:async()=>{let n=(await I.getDbManager()).getVectorManager(),b=(await n.getEmbeddingStats()).find(m=>m.model===G);if(b?.rowCount&&b.rowCount>0){let m=Gs({settings:e,embeddingModelId:G});await n.clearAllVectors(m)}await t({...e,embeddingModels:[...e.embeddingModels].filter(m=>m.id!==G)})}}).open()};return(0,be.jsxs)("div",{children:[(0,be.jsx)("div",{className:"smtcmp-settings-sub-header",children:"Embedding Models"}),(0,be.jsx)("div",{className:"smtcmp-settings-desc",children:"Models used for generating embeddings for RAG"}),(0,be.jsx)("div",{className:"smtcmp-settings-table-container",children:(0,be.jsxs)("table",{className:"smtcmp-settings-table",children:[(0,be.jsx)("thead",{children:(0,be.jsxs)("tr",{children:[(0,be.jsx)("th",{children:"ID"}),(0,be.jsx)("th",{children:"Provider ID"}),(0,be.jsx)("th",{children:"Model"}),(0,be.jsx)("th",{children:"Dimension"}),(0,be.jsx)("th",{children:"Actions"})]})}),(0,be.jsx)("tbody",{children:e.embeddingModels.map(G=>(0,be.jsxs)("tr",{children:[(0,be.jsx)("td",{children:G.id}),(0,be.jsx)("td",{children:G.providerId}),(0,be.jsx)("td",{children:G.model}),(0,be.jsx)("td",{children:G.dimension}),(0,be.jsx)("td",{children:(0,be.jsx)("div",{className:"smtcmp-settings-actions",children:!iR.some(c=>c.id===G.id)&&(0,be.jsx)("button",{onClick:()=>a(G.id),className:"clickable-icon",children:(0,be.jsx)(da,{})})})})]},G.id))}),(0,be.jsx)("tfoot",{children:(0,be.jsx)("tr",{children:(0,be.jsx)("td",{colSpan:5,children:(0,be.jsx)("button",{onClick:()=>{new bA(l,I).open()},children:"Add custom model"})})})})]})})]})}var UY=y(K());function qgI({app:l,plugin:I}){return(0,UY.jsxs)("div",{className:"smtcmp-settings-section",children:[(0,UY.jsx)("div",{className:"smtcmp-settings-header",children:"Models"}),(0,UY.jsx)(jgI,{app:l,plugin:I}),(0,UY.jsx)(_gI,{app:l,plugin:I})]})}s();s();var lH=require("obsidian"),PgI=y(dI());var at=y(K()),sA=class extends fl{constructor(I,e){super({app:I,Component:$gI,props:{plugin:e,provider:null},options:{title:"Add Custom Provider"}})}},eH=class extends fl{constructor(I,e,t){super({app:I,Component:$gI,props:{plugin:e,provider:t},options:{title:`Edit Provider: ${t.id}`}})}};function $gI({plugin:l,provider:I,onClose:e}){let[t,a]=(0,PgI.useState)(I?{...I}:{type:"openai-compatible",id:"",apiKey:"",baseUrl:""}),G=async()=>{if(I){let d=[...l.settings.providers].findIndex(m=>m.id===t.id);if(d===-1){new lH.Notice("No provider found with this ID");return}let b=qX.safeParse(t);if(!b.success){new lH.Notice(b.error.issues.map(m=>m.message).join(`
`));return}await l.setSettings({...l.settings,providers:[...l.settings.providers.slice(0,d),t,...l.settings.providers.slice(d+1)]})}else{if(l.settings.providers.some(d=>d.id===t.id)){new lH.Notice("Provider with this ID already exists. Try a different ID.");return}let n=qX.safeParse(t);if(!n.success){new lH.Notice(n.error.issues.map(d=>d.message).join(`
`));return}await l.setSettings({...l.settings,providers:[...l.settings.providers,t]})}e()},c=xI[t.type];return(0,at.jsxs)(at.Fragment,{children:[!I&&(0,at.jsxs)(at.Fragment,{children:[(0,at.jsx)(MI,{name:"ID",desc:"Choose an ID to identify this provider in your settings. This is just for your reference.",required:!0,children:(0,at.jsx)(Ae,{value:t.id,placeholder:"my-custom-provider",onChange:n=>a(d=>({...d,id:n}))})}),(0,at.jsx)(MI,{name:"Provider Type",required:!0,children:(0,at.jsx)(JG,{value:t.type,options:Object.fromEntries(Object.entries(xI).map(([n,d])=>[n,d.label])),onChange:n=>a(d=>({...d,type:n,additionalSettings:{}}))})})]}),(0,at.jsx)(MI,{name:"API Key",desc:"(leave blank if not required)",required:c.requireApiKey,children:(0,at.jsx)(Ae,{value:t.apiKey??"",placeholder:"Enter your API Key",onChange:n=>a(d=>({...d,apiKey:n}))})}),(0,at.jsx)(MI,{name:"Base URL",desc:"(leave blank if using default)",required:c.requireBaseUrl,children:(0,at.jsx)(Ae,{value:t.baseUrl??"",placeholder:"Enter base URL",onChange:n=>a(d=>({...d,baseUrl:n}))})}),c.additionalSettings.map(n=>(0,at.jsx)(MI,{name:n.label,desc:"description"in n?n.description:void 0,required:n.required,children:n.type==="toggle"?(0,at.jsx)(Ic,{value:t.additionalSettings?.[n.key]??!1,onChange:d=>a(b=>({...b,additionalSettings:{...b.additionalSettings??{},[n.key]:d}}))}):(0,at.jsx)(Ae,{value:t.additionalSettings?.[n.key]??"",placeholder:n.placeholder,onChange:d=>a(b=>({...b,additionalSettings:{...b.additionalSettings??{},[n.key]:d}}))})},n.key)),(0,at.jsxs)(MI,{children:[(0,at.jsx)(Al,{text:I?"Save":"Add",onClick:G,cta:!0}),(0,at.jsx)(Al,{text:"Cancel",onClick:e})]})]})}var Ql=y(K());function IyI({app:l,plugin:I}){let{settings:e,setSettings:t}=ql(),a=async G=>{let c=e.chatModels.filter(b=>b.providerId===G.id),n=e.embeddingModels.filter(b=>b.providerId===G.id),d=`Are you sure you want to delete provider "${G.id}"?
This will also delete:
- ${c.length} chat model(s)
- ${n.length} embedding model(s)
All embeddings generated using the associated embedding models will also be deleted.`;new Oa(l,{title:"Delete Provider",message:d,ctaText:"Delete",onConfirm:async()=>{let b=(await I.getDbManager()).getVectorManager(),m=await b.getEmbeddingStats();for(let Z of n){let r=m.find(o=>o.model===Z.id);if(r?.rowCount&&r.rowCount>0){let o=Gs({settings:e,embeddingModelId:Z.id});await b.clearAllVectors(o)}}await t({...e,providers:[...e.providers].filter(Z=>Z.id!==G.id),chatModels:[...e.chatModels].filter(Z=>Z.providerId!==G.id),embeddingModels:[...e.embeddingModels].filter(Z=>Z.providerId!==G.id)})}}).open()};return(0,Ql.jsxs)("div",{className:"smtcmp-settings-section",children:[(0,Ql.jsx)("div",{className:"smtcmp-settings-header",children:"Providers"}),(0,Ql.jsxs)("div",{className:"smtcmp-settings-desc",children:[(0,Ql.jsx)("span",{children:"Enter your API keys for the providers you want to use"}),(0,Ql.jsx)("br",{}),(0,Ql.jsx)("a",{href:"https://github.com/glowingjade/obsidian-smart-composer/wiki/1.2-Initial-Setup#getting-your-api-key",target:"_blank",rel:"noopener noreferrer",children:"How to obtain API keys"})]}),(0,Ql.jsx)("div",{className:"smtcmp-settings-table-container",children:(0,Ql.jsxs)("table",{className:"smtcmp-settings-table",children:[(0,Ql.jsxs)("colgroup",{children:[(0,Ql.jsx)("col",{}),(0,Ql.jsx)("col",{}),(0,Ql.jsx)("col",{}),(0,Ql.jsx)("col",{width:60})]}),(0,Ql.jsx)("thead",{children:(0,Ql.jsxs)("tr",{children:[(0,Ql.jsx)("th",{children:"ID"}),(0,Ql.jsx)("th",{children:"Type"}),(0,Ql.jsx)("th",{children:"API Key"}),(0,Ql.jsx)("th",{children:"Actions"})]})}),(0,Ql.jsx)("tbody",{children:e.providers.map(G=>(0,Ql.jsxs)("tr",{children:[(0,Ql.jsx)("td",{children:G.id}),(0,Ql.jsx)("td",{children:xI[G.type].label}),(0,Ql.jsx)("td",{className:"smtcmp-settings-table-api-key",onClick:()=>{new eH(l,I,G).open()},children:G.apiKey?"\u2022\u2022\u2022\u2022\u2022\u2022\u2022\u2022":"Set API key"}),(0,Ql.jsx)("td",{children:(0,Ql.jsxs)("div",{className:"smtcmp-settings-actions",children:[(0,Ql.jsx)("button",{onClick:()=>{new eH(l,I,G).open()},className:"clickable-icon",children:(0,Ql.jsx)(_o,{})}),!eb.some(c=>c.id===G.id)&&(0,Ql.jsx)("button",{onClick:()=>a(G),className:"clickable-icon",children:(0,Ql.jsx)(da,{})})]})})]},G.id))}),(0,Ql.jsx)("tfoot",{children:(0,Ql.jsx)("tr",{children:(0,Ql.jsx)("td",{colSpan:4,children:(0,Ql.jsx)("button",{onClick:()=>{new sA(l,I).open()},children:"Add custom provider"})})})})]})})]})}s();s();var F_=async(l,I)=>I.getMarkdownFiles().filter(t=>l.some(a=>Nt(t.path,a)));s();var eyI=y(lyI());var Q_=require("obsidian"),tyI=y(dI());var Ml=y(K()),mA=class extends fl{constructor(I,e){super({app:I,Component:adl,props:{app:I,plugin:e},options:{title:"Manage Embedding Database"}}),this.modalEl.style.width="720px"}};function adl({app:l,plugin:I}){let e=new RR({defaultOptions:{queries:{gcTime:0},mutations:{gcTime:0}}});return(0,Ml.jsx)(VZ,{app:l,children:(0,Ml.jsx)(jZ,{settings:I.settings,setSettings:t=>I.setSettings(t),addSettingsChangeListener:t=>I.addSettingsChangeListener(t),children:(0,Ml.jsx)(E1,{getDatabaseManager:()=>I.getDbManager(),children:(0,Ml.jsx)(LR,{client:e,children:(0,Ml.jsx)(Gdl,{})})})})})}function Gdl(){let{getVectorManager:l}=o0I(),{settings:I}=ql(),[e,t]=(0,tyI.useState)(new Map),{data:a=[],isLoading:G,isFetching:c,refetch:n,dataUpdatedAt:d}=xR({queryKey:["embedding-db-stats"],queryFn:async()=>{let Z=await(await l()).getEmbeddingStats(),r=new Map(Z.map(o=>[o.model,o]));return I.embeddingModels.map(o=>({model:o.id,rowCount:r.get(o.id)?.rowCount??0,totalDataBytes:r.get(o.id)?.totalDataBytes??0}))}}),b=async Z=>{try{let r=Gs({settings:I,embeddingModelId:Z});await(await l()).updateVaultIndex(r,{chunkSize:I.ragOptions.chunkSize,excludePatterns:I.ragOptions.excludePatterns,includePatterns:I.ragOptions.includePatterns,reindexAll:!0},o=>{t(u=>{let N=new Map(u);return N.set(Z,o),N})})}catch(r){console.error(r),new Q_.Notice("Failed to rebuild index")}finally{t(r=>{let o=new Map(r);return o.delete(Z),o}),await n()}},m=async Z=>{try{let r=Gs({settings:I,embeddingModelId:Z});await(await l()).c
`),onChange:async a=>{let G=a.split(`
`).map(c=>c.trim()).filter(c=>c.length>0);await t({...e,ragOptions:{...e.ragOptions,includePatterns:G}})}})}),(0,fe.jsx)(MI,{name:"Exclude patterns",desc:"Specify glob patterns to exclude files from indexing (one per line). Example: use 'notes/**' for all files in the notes folder. Leave empty to exclude nothing. Requires 'Rebuild entire vault index' after changes.",children:(0,fe.jsx)(Al,{text:"Test patterns",onClick:async()=>{let a=e.ragOptions.excludePatterns,G=await F_(a,I.app.vault);new rA(l,G).open()}})}),(0,fe.jsx)(MI,{className:"smtcmp-settings-textarea",children:(0,fe.jsx)($X,{value:e.ragOptions.excludePatterns.join(`
`),onChange:async a=>{let G=a.split(`
`).map(c=>c.trim()).filter(c=>c.length>0);await t({...e,ragOptions:{...e.ragOptions,excludePatterns:G}})}})}),(0,fe.jsx)(MI,{name:"Chunk size",desc:"Set the chunk size for text splitting. After changing this, please re-index the vault using the 'Rebuild entire vault index' command.",children:(0,fe.jsx)(Ae,{value:String(e.ragOptions.chunkSize),placeholder:"1000",onChange:async a=>{let G=parseInt(a,10);isNaN(G)||await t({...e,ragOptions:{...e.ragOptions,chunkSize:G}})}})}),(0,fe.jsx)(MI,{name:"Threshold tokens",desc:"Maximum number of tokens before switching to RAG. If the total tokens from mentioned files exceed this, RAG will be used instead of including all file contents.",children:(0,fe.jsx)(Ae,{value:String(e.ragOptions.thresholdTokens),placeholder:"8192",onChange:async a=>{let G=parseInt(a,10);isNaN(G)||await t({...e,ragOptions:{...e.ragOptions,thresholdTokens:G}})}})}),(0,fe.jsx)(MI,{name:"Minimum similarity",desc:"Minimum similarity score for RAG results. Higher values return more relevant but potentially fewer results.",children:(0,fe.jsx)(Ae,{value:String(e.ragOptions.minSimilarity),placeholder:"0.0",onChange:async a=>{if(!/^[0-9.]*$/.test(a)||a==="."||a.endsWith("."))return;let G=parseFloat(a);isNaN(G)||await t({...e,ragOptions:{...e.ragOptions,minSimilarity:G}})}})}),(0,fe.jsx)(MI,{name:"Limit",desc:"Maximum number of RAG results to include in the prompt. Higher values provide more context but increase token usage.",children:(0,fe.jsx)(Ae,{value:String(e.ragOptions.limit),placeholder:"10",onChange:async a=>{let G=parseInt(a,10);isNaN(G)||await t({...e,ragOptions:{...e.ragOptions,limit:G}})}})}),(0,fe.jsx)(MI,{name:"Manage Embedding Database",children:(0,fe.jsx)(Al,{text:"Manage",onClick:async()=>{new mA(l,I).open()}})})]})}var mc=y(K());function GyI({app:l,plugin:I}){return(0,mc.jsxs)(mc.Fragment,{children:[(0,mc.jsx)(MI,{name:"Support Smart Composer",desc:"If you find Smart Composer valuable, consider supporting its development!",heading:!0,className:"smtcmp-settings-support-smart-composer",children:(0,mc.jsx)(Al,{text:"Buy Me a Coffee",onClick:()=>window.open("https://www.buymeacoffee.com/kevin.on","_blank"),cta:!0})}),(0,mc.jsx)(UgI,{}),(0,mc.jsx)(IyI,{app:l,plugin:I}),(0,mc.jsx)(qgI,{app:l,plugin:I}),(0,mc.jsx)(ayI,{app:l,plugin:I}),(0,mc.jsx)(F1,{app:l,plugin:I}),(0,mc.jsx)(sg,{app:l}),(0,mc.jsx)(OgI,{app:l,plugin:I})]})}var w_=y(K()),uA=class extends cyI.PluginSettingTab{constructor(e,t){super(e,t);this.root=null;this.plugin=t}display(){let{containerEl:e}=this;e.empty(),this.root=(0,nyI.createRoot)(e),this.root.render((0,w_.jsx)(jZ,{settings:this.plugin.settings,setSettings:t=>this.plugin.setSettings(t),addSettingsChangeListener:t=>this.plugin.addSettingsChangeListener(t),children:(0,w_.jsx)(GyI,{app:this.app,plugin:this.plugin})}))}hide(){this.root&&(this.root.unmount(),this.root=null)}};var WA=class extends hs.Plugin{constructor(){super(...arguments);this.settingsChangeListeners=[];this.mcpManager=null;this.dbManager=null;this.ragEngine=null;this.dbManagerInitPromise=null;this.ragEngineInitPromise=null;this.timeoutIds=[]}async onload(){await this.loadSettings(),this.registerView(Cs,e=>new Ii(e,this)),this.registerView(VN,e=>new ew(e)),this.addRibbonIcon("wand-sparkles","Open smart composer",()=>this.openChatView()),this.addCommand({id:"open-new-chat",name:"Open chat",callback:()=>this.openChatView(!0)}),this.addCommand({id:"add-selection-to-chat",name:"Add selection to chat",editorCallback:(e,t)=>{this.addSelectionToChat(e,t)}}),this.addCommand({id:"rebuild-vault-index",name:"Rebuild entire vault index",callback:async()=>{let e=new hs.Notice("Rebuilding vault index...",0);try{await(await this.getRAGEngine()).updateVaultIndex({reindexAll:!0},a=>{if(a.type==="indexing"){let{completedChunks:G,totalChunks:c}=a.indexProgress;e.setMessage(`Indexing chunks: ${G} / ${c}${a.indexProgress.waitingForRateLimit?`
(waiting for rate limit to reset)`:""}`)}}),e.setMessage("Rebuilding vault index complete")}catch(t){console.error(t),e.setMessage("Rebuilding vault index failed")}finally{this.registerTimeout(()=>{e.hide()},1e3)}}}),this.addCommand({id:"update-vault-index",name:"Update index for modified files",callback:async()=>{let e=new hs.Notice("Updating vault index...",0);try{await(await this.getRAGEngine()).updateVaultIndex({reindexAll:!1},a=>{if(a.type==="indexing"){let{completedChunks:G,totalChunks:c}=a.indexProgress;e.setMessage(`Indexing chunks: ${G} / ${c}${a.indexProgress.waitingForRateLimit?`
(waiting for rate limit to reset)`:""}`)}}),e.setMessage("Vault index updated")}catch(t){console.error(t),e.setMessage("Vault index update failed")}finally{this.registerTimeout(()=>{e.hide()},1e3)}}}),this.addSettingTab(new uA(this.app,this)),this.migrateToJsonStorage()}onunload(){this.timeoutIds.forEach(e=>clearTimeout(e)),this.timeoutIds=[],this.ragEngine?.cleanup(),this.ragEngine=null,this.dbManagerInitPromise=null,this.ragEngineInitPromise=null,this.dbManager?.cleanup(),this.dbManager=null,this.mcpManager?.cleanup(),this.mcpManager=null}async loadSettings(){this.settings=LgI(await this.loadData()),await this.saveData(this.settings)}async setSettings(e){let t=Ai.safeParse(e);if(!t.success){new hs.Notice(`Invalid settings:
${t.error.issues.map(a=>a.message).join(`
`)}`);return}this.settings=e,await this.saveData(e),this.ragEngine?.setSettings(e),this.settingsChangeListeners.forEach(a=>a(e))}addSettingsChangeListener(e){return this.settingsChangeListeners.push(e),()=>{this.settingsChangeListeners=this.settingsChangeListeners.filter(t=>t!==e)}}async openChatView(e=!1){let t=this.app.workspace.getActiveViewOfType(hs.MarkdownView),a=t?.editor;if(!t||!a){this.activateChatView(void 0,e);return}let G=await ix(a,t);this.activateChatView({selectedBlock:G??void 0},e)}async activateChatView(e,t=!1){this.initialChatProps=e;let a=this.app.workspace.getLeavesOfType(Cs)[0];await(a??this.app.workspace.getRightLeaf(!1))?.setViewState({type:Cs,active:!0}),t&&a&&a.view instanceof Ii&&a.view.openNewChat(e?.selectedBlock),this.app.workspace.revealLeaf(this.app.workspace.getLeavesOfType(Cs)[0])}async addSelectionToChat(e,t){let a=await ix(e,t);if(!a)return;let G=this.app.workspace.getLeavesOfType(Cs);if(G.length===0||!(G[0].view instanceof Ii)){await this.activateChatView({selectedBlock:a});return}await this.app.workspace.revealLeaf(G[0]);let c=G[0].view;c.addSelectionToChat(a),c.focusMessage()}async getDbManager(){return this.dbManager?this.dbManager:(this.dbManagerInitPromise||(this.dbManagerInitPromise=(async()=>{try{return this.dbManager=await DX.create(this.app),this.dbManager}catch(e){throw this.dbManagerInitPromise=null,e instanceof Ni&&new g1(this.app).open(),e}})()),this.dbManagerInitPromise)}async getRAGEngine(){return this.ragEngine?this.ragEngine:(this.ragEngineInitPromise||(this.ragEngineInitPromise=(async()=>{try{let e=await this.getDbManager();return this.ragEngine=new y1(this.app,this.settings,e.getVectorManager()),this.ragEngine}catch(e){throw this.ragEngineInitPromise=null,e}})()),this.ragEngineInitPromise)}async getMcpManager(){if(this.mcpManager)return this.mcpManager;try{return this.mcpManager=new KW({settings:this.settings,registerSettingsListener:e=>this.addSettingsChangeListener(e)}),await this.mcpManager.initialize(),this.mcpManager}catch(e){throw this.mcpManager=null,e}}registerTimeout(e,t){let a=setTimeout(e,t);this.timeoutIds.push(a)}async migrateToJsonStorage(){try{let e=await this.getDbManager();await YgI(this.app,e,async()=>{await this.reloadChatView(),console.log("Migration to JSON storage completed successfully")})}catch(e){console.error("Failed to migrate to JSON storage:",e),new hs.Notice("Failed to migrate to JSON storage. Please check the console for details.")}}async reloadChatView(){let e=this.app.workspace.getLeavesOfType(Cs);e.length===0||!(e[0].view instanceof Ii)||(new hs.Notice('Reloading "smart-composer" due to migration',1e3),e[0].detach(),await this.activateChatView())}};
/*! Bundled license information:
react/cjs/react.production.min.js:
(**
* @license React
* react.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
scheduler/cjs/scheduler.production.min.js:
(**
* @license React
* scheduler.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react-dom/cjs/react-dom.production.min.js:
(**
* @license React
* react-dom.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
react/cjs/react-jsx-runtime.production.min.js:
(**
* @license React
* react-jsx-runtime.production.min.js
*
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*)
prismjs/components/prism-core.js:
(**
* Prism: Lightweight, robust, elegant syntax highlighting
*
* @license MIT <https://opensource.org/licenses/MIT>
* @author Lea Verou <https://lea.verou.me>
* @namespace
* @public
*)
lucide-react/dist/esm/shared/src/utils.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/defaultAttributes.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/Icon.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/createLucideIcon.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-big-up.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-down.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-right-left.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/arrow-up.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/book.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/check.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-down.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-right.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/chevron-up.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-minus.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/circle-stop.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/coins.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/command.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/copy.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/corner-down-left.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/cpu.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye-off.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/eye.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/file.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folder-closed.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/folders.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/history.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/image.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/info.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/link.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/loader-circle.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pencil.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/pickaxe.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/play.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/plus.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/refresh-cw.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/settings.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/square-pen.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/trash-2.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/wrench.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/icons/x.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
lucide-react/dist/esm/lucide-react.js:
(**
* @license lucide-react v0.447.0 - ISC
*
* This source code is licensed under the ISC license.
* See the LICENSE file in the root directory of this source tree.
*)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
@google/generative-ai/dist/index.mjs:
(**
* @license
* Copyright 2024 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*)
@langchain/core/dist/utils/fast-json-patch/src/helpers.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2017-2022 Joachim Wester
* MIT licensed
*)
@langchain/core/dist/utils/fast-json-patch/src/duplex.js:
(*!
* https://github.com/Starcounter-Jack/JSON-Patch
* (c) 2013-2021 Joachim Wester
* MIT license
*)
*/
/* nosourcemap */