Files
StudyDiary-20251025/.obsidian/plugins/tars/main.js
T

198 lines
444 KiB
JavaScript
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
/*
THIS IS A GENERATED/BUNDLED FILE BY ESBUILD
if you want to view the source, please visit the github repository of this plugin
*/
var Py=Object.create;var ii=Object.defineProperty;var Ry=Object.getOwnPropertyDescriptor;var Ty=Object.getOwnPropertyNames;var Iy=Object.getPrototypeOf,ky=Object.prototype.hasOwnProperty;var j=(t,e)=>()=>(e||t((e={exports:{}}).exports,e),e.exports),rd=(t,e)=>{for(var r in e)ii(t,r,{get:e[r],enumerable:!0})},nd=(t,e,r,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let s of Ty(e))!ky.call(t,s)&&s!==r&&ii(t,s,{get:()=>e[s],enumerable:!(n=Ry(e,s))||n.enumerable});return t};var Oy=(t,e,r)=>(r=t!=null?Py(Iy(t)):{},nd(e||!t||!t.__esModule?ii(r,"default",{value:t,enumerable:!0}):r,t)),My=t=>nd(ii({},"__esModule",{value:!0}),t);var Se=j(Ie=>{"use strict";Ie.__esModule=!0;Ie.extend=Lm;Ie.indexOf=nx;Ie.escapeExpression=sx;Ie.isEmpty=ox;Ie.createFrame=ix;Ie.blockParams=ax;Ie.appendContextPath=lx;var ZE={"&":"&amp;","<":"&lt;",">":"&gt;",'"':"&quot;","'":"&#x27;","`":"&#x60;","=":"&#x3D;"},ex=/[&<>"'`=]/g,tx=/[&<>"'`=]/;function rx(t){return ZE[t]}function Lm(t){for(var e=1;e<arguments.length;e++)for(var r in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],r)&&(t[r]=arguments[e][r]);return t}var nf=Object.prototype.toString;Ie.toString=nf;var rf=function(e){return typeof e=="function"};rf(/x/)&&(Ie.isFunction=rf=function(t){return typeof t=="function"&&nf.call(t)==="[object Function]"});Ie.isFunction=rf;var Nm=Array.isArray||function(t){return t&&typeof t=="object"?nf.call(t)==="[object Array]":!1};Ie.isArray=Nm;function nx(t,e){for(var r=0,n=t.length;r<n;r++)if(t[r]===e)return r;return-1}function sx(t){if(typeof t!="string"){if(t&&t.toHTML)return t.toHTML();if(t==null)return"";if(!t)return t+"";t=""+t}return tx.test(t)?t.replace(ex,rx):t}function ox(t){return!t&&t!==0?!0:!!(Nm(t)&&t.length===0)}function ix(t){var e=Lm({},t);return e._parent=t,e}function ax(t,e){return t.path=e,t}function lx(t,e){return(t?t+".":"")+e}});var Fe=j((Ya,Dm)=>{"use strict";Ya.__esModule=!0;var sf=["description","fileName","lineNumber","endLineNumber","message","name","number","stack"];function of(t,e){var r=e&&e.loc,n=void 0,s=void 0,o=void 0,i=void 0;r&&(n=r.start.line,s=r.end.line,o=r.start.column,i=r.end.column,t+=" - "+n+":"+o);for(var a=Error.prototype.constructor.call(this,t),c=0;c<sf.length;c++)this[sf[c]]=a[sf[c]];Error.captureStackTrace&&Error.captureStackTrace(this,of);try{r&&(this.lineNumber=n,this.endLineNumber=s,Object.defineProperty?(Object.defineProperty(this,"column",{value:o,enumerable:!0}),Object.defineProperty(this,"endColumn",{value:i,enumerable:!0})):(this.column=o,this.endColumn=i))}catch(l){}}of.prototype=new Error;Ya.default=of;Dm.exports=Ya.default});var Fm=j((Qa,Bm)=>{"use strict";Qa.__esModule=!0;var af=Se();Qa.default=function(t){t.registerHelper("blockHelperMissing",function(e,r){var n=r.inverse,s=r.fn;if(e===!0)return s(this);if(e===!1||e==null)return n(this);if(af.isArray(e))return e.length>0?(r.ids&&(r.ids=[r.name]),t.helpers.each(e,r)):n(this);if(r.data&&r.ids){var o=af.createFrame(r.data);o.contextPath=af.appendContextPath(r.data.contextPath,r.name),r={data:o}}return s(e,r)})};Bm.exports=Qa.default});var Um=j((Za,qm)=>{"use strict";Za.__esModule=!0;function cx(t){return t&&t.__esModule?t:{default:t}}var Ko=Se(),ux=Fe(),fx=cx(ux);Za.default=function(t){t.registerHelper("each",function(e,r){if(!r)throw new fx.default("Must pass iterator to #each");var n=r.fn,s=r.inverse,o=0,i="",a=void 0,c=void 0;r.data&&r.ids&&(c=Ko.appendContextPath(r.data.contextPath,r.ids[0])+"."),Ko.isFunction(e)&&(e=e.call(this)),r.data&&(a=Ko.createFrame(r.data));function l(p,y,g){a&&(a.key=p,a.index=y,a.first=y===0,a.last=!!g,c&&(a.contextPath=c+p)),i=i+n(e[p],{data:a,blockParams:Ko.blockParams([e[p],p],[c+p,null])})}if(e&&typeof e=="object")if(Ko.isArray(e))for(var f=e.length;o<f;o++)o in e&&l(o,o,o===e.length-1);else if(typeof Symbol=="function"&&e[Symbol.iterator]){for(var u=[],d=e[Symbol.iterator](),h=d.next();!h.done;h=d.next())u.push(h.value);e=u;for(var f=e.length;o<f;o++)l(o,o,o===e.length-1)}else(function(){var p=void 0;Object.keys(e).forEach(function(y){p!==void 0&&l(p,o-1),p=y,o++}),p!==void 0&&l(p,o-1,!0)})();return o===0&&(i=s(this)),i})};qm.exports=Za.default});var Hm=j((el,$m)=>{"use strict";el.__esModule=!0;function dx(t){return t&&t.__esModule?t:{default:t}}var hx=Fe(),px=dx(hx);el.default=function(t){t.registerHelper("helperMissing",function(){if(arguments.length!==1)throw new px.default('Missing helper: "'+arguments[arguments.length-1].name+'"')})};$m.exports=el.default});var Km=j((tl,Vm)=>{"use strict";tl.__esModule=!0;function mx(t){return t&&t.__esModule?t:{default:t}}var jm=Se(),gx=Fe(),Wm=mx(gx);tl.default=function(t){t.registerHelper("if",function(e,r){if(arguments.length!=2)throw new Wm.default("#if requires exactly one argument");return jm.isFunction(e)&&(e=e.call(this)),!r.hash.includeZero&&!e||jm.isEmpty(e)?r.inverse(this):r.fn(this)}),t.registerHelper("unless",function(e,r){if(arguments.length!=2)throw new Wm.default("#unless requires exactly one argument");return t.helpers.if.call(this,e,{fn:r.inverse,inverse:r.fn,hash:r.hash})})};Vm.exports=tl.default});var Jm=j((rl,Gm)=>{"use strict";rl.__esModule=!0;rl.default=function(t){t.registerHelper("log",function(){for(var e=[void 0],r=arguments[arguments.length-1],n=0;n<arguments.length-1;n++)e.push(arguments[n]);var s=1;r.hash.level!=null?s=r.hash.level:r.data&&r.data.level!=null&&(s=r.data.level),e[0]=s,t.log.apply(t,e)})};Gm.exports=rl.default});var Xm=j((nl,zm)=>{"use strict";nl.__esModule=!0;nl.default=function(t){t.registerHelper("lookup",function(e,r,n){return e&&n.lookupProperty(e,r)})};zm.exports=nl.default});var Qm=j((sl,Ym)=>{"use strict";sl.__esModule=!0;function yx(t){return t&&t.__esModule?t:{default:t}}var Go=Se(),bx=Fe(),wx=yx(bx);sl.default=function(t){t.registerHelper("with",function(e,r){if(arguments.length!=2)throw new wx.default("#with requires exactly one argument");Go.isFunction(e)&&(e=e.call(this));var n=r.fn;if(Go.isEmpty(e))return r.inverse(this);var s=r.data;return r.data&&r.ids&&(s=Go.createFrame(r.data),s.contextPath=Go.appendContextPath(r.data.contextPath,r.ids[0])),n(e,{data:s,blockParams:Go.blockParams([e],[s&&s.contextPath])})})};Ym.exports=sl.default});var lf=j(ol=>{"use strict";ol.__esModule=!0;ol.registerDefaultHelpers=Lx;ol.moveHelperToHooks=Nx;function Xr(t){return t&&t.__esModule?t:{default:t}}var _x=Fm(),Sx=Xr(_x),Ex=Um(),xx=Xr(Ex),Ax=Hm(),vx=Xr(Ax),Cx=Km(),Px=Xr(Cx),Rx=Jm(),Tx=Xr(Rx),Ix=Xm(),kx=Xr(Ix),Ox=Qm(),Mx=Xr(Ox);function Lx(t){Sx.default(t),xx.default(t),vx.default(t),Px.default(t),Tx.default(t),kx.default(t),Mx.default(t)}function Nx(t,e,r){t.helpers[e]&&(t.hooks[e]=t.helpers[e],r||delete t.helpers[e])}});var eg=j((il,Zm)=>{"use strict";il.__esModule=!0;var Dx=Se();il.default=function(t){t.registerDecorator("inline",function(e,r,n,s){var o=e;return r.partials||(r.partials={},o=function(i,a){var c=n.partials;n.partials=Dx.extend({},c,r.partials);var l=e(i,a);return n.partials=c,l}),r.partials[s.args[0]]=s.fn,o})};Zm.exports=il.default});var tg=j(cf=>{"use strict";cf.__esModule=!0;cf.registerDefaultDecorators=Ux;function Bx(t){return t&&t.__esModule?t:{default:t}}var Fx=eg(),qx=Bx(Fx);function Ux(t){qx.default(t)}});var uf=j((al,rg)=>{"use strict";al.__esModule=!0;var $x=Se(),vs={methodMap:["debug","info","warn","error"],level:"info",lookupLevel:function(e){if(typeof e=="string"){var r=$x.indexOf(vs.methodMap,e.toLowerCase());r>=0?e=r:e=parseInt(e,10)}return e},log:function(e){if(e=vs.lookupLevel(e),typeof console!="undefined"&&vs.lookupLevel(vs.level)<=e){var r=vs.methodMap[e];console[r]||(r="log");for(var n=arguments.length,s=Array(n>1?n-1:0),o=1;o<n;o++)s[o-1]=arguments[o];console[r].apply(console,s)}}};al.default=vs;rg.exports=al.default});var ng=j(ff=>{"use strict";ff.__esModule=!0;ff.createNewLookupObject=jx;var Hx=Se();function jx(){for(var t=arguments.length,e=Array(t),r=0;r<t;r++)e[r]=arguments[r];return Hx.extend.apply(void 0,[Object.create(null)].concat(e))}});var df=j(Jo=>{"use strict";Jo.__esModule=!0;Jo.createProtoAccessControl=Gx;Jo.resultIsAllowed=Jx;Jo.resetLoggedProperties=Xx;function Wx(t){return t&&t.__esModule?t:{default:t}}var sg=ng(),Vx=uf(),Kx=Wx(Vx),ll=Object.create(null);function Gx(t){var e=Object.create(null);e.constructor=!1,e.__defineGetter__=!1,e.__defineSetter__=!1,e.__lookupGetter__=!1;var r=Object.create(null);return r.__proto__=!1,{properties:{whitelist:sg.createNewLookupObject(r,t.allowedProtoProperties),defaultValue:t.allowProtoPropertiesByDefault},methods:{whitelist:sg.createNewLookupObject(e,t.allowedProtoMethods),defaultValue:t.allowProtoMethodsByDefault}}}function Jx(t,e,r){return og(typeof t=="function"?e.methods:e.properties,r)}function og(t,e){return t.whitelist[e]!==void 0?t.whitelist[e]===!0:t.defaultValue!==void 0?t.defaultValue:(zx(e),!1)}function zx(t){ll[t]!==!0&&(ll[t]=!0,Kx.default.log("error",'Handlebars: Access has been denied to resolve the property "'+t+`" because it is not an "own property" of its parent.
You can add a runtime option to disable the check or this warning:
See https://handlebarsjs.com/api-reference/runtime-options.html#options-to-control-prototype-access for details`))}function Xx(){Object.keys(ll).forEach(function(t){delete ll[t]})}});var ul=j(gt=>{"use strict";gt.__esModule=!0;gt.HandlebarsEnvironment=mf;function ig(t){return t&&t.__esModule?t:{default:t}}var Yr=Se(),Yx=Fe(),hf=ig(Yx),Qx=lf(),Zx=tg(),e2=uf(),cl=ig(e2),t2=df(),r2="4.7.8";gt.VERSION=r2;var n2=8;gt.COMPILER_REVISION=n2;var s2=7;gt.LAST_COMPATIBLE_COMPILER_REVISION=s2;var o2={1:"<= 1.0.rc.2",2:"== 1.0.0-rc.3",3:"== 1.0.0-rc.4",4:"== 1.x.x",5:"== 2.0.0-alpha.x",6:">= 2.0.0-beta.1",7:">= 4.0.0 <4.3.0",8:">= 4.3.0"};gt.REVISION_CHANGES=o2;var pf="[object Object]";function mf(t,e,r){this.helpers=t||{},this.partials=e||{},this.decorators=r||{},Qx.registerDefaultHelpers(this),Zx.registerDefaultDecorators(this)}mf.prototype={constructor:mf,logger:cl.default,log:cl.default.log,registerHelper:function(e,r){if(Yr.toString.call(e)===pf){if(r)throw new hf.default("Arg not supported with multiple helpers");Yr.extend(this.helpers,e)}else this.helpers[e]=r},unregisterHelper:function(e){delete this.helpers[e]},registerPartial:function(e,r){if(Yr.toString.call(e)===pf)Yr.extend(this.partials,e);else{if(typeof r=="undefined")throw new hf.default('Attempting to register a partial called "'+e+'" as undefined');this.partials[e]=r}},unregisterPartial:function(e){delete this.partials[e]},registerDecorator:function(e,r){if(Yr.toString.call(e)===pf){if(r)throw new hf.default("Arg not supported with multiple decorators");Yr.extend(this.decorators,e)}else this.decorators[e]=r},unregisterDecorator:function(e){delete this.decorators[e]},resetLoggedPropertyAccesses:function(){t2.resetLoggedProperties()}};var i2=cl.default.log;gt.log=i2;gt.createFrame=Yr.createFrame;gt.logger=cl.default});var lg=j((fl,ag)=>{"use strict";fl.__esModule=!0;function gf(t){this.string=t}gf.prototype.toString=gf.prototype.toHTML=function(){return""+this.string};fl.default=gf;ag.exports=fl.default});var cg=j(yf=>{"use strict";yf.__esModule=!0;yf.wrapHelper=a2;function a2(t,e){if(typeof t!="function")return t;var r=function(){var s=arguments[arguments.length-1];return arguments[arguments.length-1]=e(s),t.apply(this,arguments)};return r}});var pg=j(cr=>{"use strict";cr.__esModule=!0;cr.checkRevision=h2;cr.template=p2;cr.wrapProgram=dl;cr.resolvePartial=m2;cr.invokePartial=g2;cr.noop=dg;function l2(t){return t&&t.__esModule?t:{default:t}}function c2(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}var u2=Se(),Mt=c2(u2),f2=Fe(),Lt=l2(f2),Nt=ul(),ug=lf(),d2=cg(),fg=df();function h2(t){var e=t&&t[0]||1,r=Nt.COMPILER_REVISION;if(!(e>=Nt.LAST_COMPATIBLE_COMPILER_REVISION&&e<=Nt.COMPILER_REVISION))if(e<Nt.LAST_COMPATIBLE_COMPILER_REVISION){var n=Nt.REVISION_CHANGES[r],s=Nt.REVISION_CHANGES[e];throw new Lt.default("Template was precompiled with an older version of Handlebars than the current runtime. Please update your precompiler to a newer version ("+n+") or downgrade your runtime to an older version ("+s+").")}else throw new Lt.default("Template was precompiled with a newer version of Handlebars than the current runtime. Please update your runtime to a newer version ("+t[1]+").")}function p2(t,e){if(!e)throw new Lt.default("No environment passed to template");if(!t||!t.main)throw new Lt.default("Unknown template object: "+typeof t);t.main.decorator=t.main_d,e.VM.checkRevision(t.compiler);var r=t.compiler&&t.compiler[0]===7;function n(i,a,c){c.hash&&(a=Mt.extend({},a,c.hash),c.ids&&(c.ids[0]=!0)),i=e.VM.resolvePartial.call(this,i,a,c);var l=Mt.extend({},c,{hooks:this.hooks,protoAccessControl:this.protoAccessControl}),f=e.VM.invokePartial.call(this,i,a,l);if(f==null&&e.compile&&(c.partials[c.name]=e.compile(i,t.compilerOptions,e),f=c.partials[c.name](a,l)),f!=null){if(c.indent){for(var u=f.split(`
`),d=0,h=u.length;d<h&&!(!u[d]&&d+1===h);d++)u[d]=c.indent+u[d];f=u.join(`
`)}return f}else throw new Lt.default("The partial "+c.name+" could not be compiled when running in runtime-only mode")}var s={strict:function(a,c,l){if(!a||!(c in a))throw new Lt.default('"'+c+'" not defined in '+a,{loc:l});return s.lookupProperty(a,c)},lookupProperty:function(a,c){var l=a[c];if(l==null||Object.prototype.hasOwnProperty.call(a,c)||fg.resultIsAllowed(l,s.protoAccessControl,c))return l},lookup:function(a,c){for(var l=a.length,f=0;f<l;f++){var u=a[f]&&s.lookupProperty(a[f],c);if(u!=null)return a[f][c]}},lambda:function(a,c){return typeof a=="function"?a.call(c):a},escapeExpression:Mt.escapeExpression,invokePartial:n,fn:function(a){var c=t[a];return c.decorator=t[a+"_d"],c},programs:[],program:function(a,c,l,f,u){var d=this.programs[a],h=this.fn(a);return c||u||f||l?d=dl(this,a,h,c,l,f,u):d||(d=this.programs[a]=dl(this,a,h)),d},data:function(a,c){for(;a&&c--;)a=a._parent;return a},mergeIfNeeded:function(a,c){var l=a||c;return a&&c&&a!==c&&(l=Mt.extend({},c,a)),l},nullContext:Object.seal({}),noop:e.VM.noop,compilerInfo:t.compiler};function o(i){var a=arguments.length<=1||arguments[1]===void 0?{}:arguments[1],c=a.data;o._setup(a),!a.partial&&t.useData&&(c=y2(i,c));var l=void 0,f=t.useBlockParams?[]:void 0;t.useDepths&&(a.depths?l=i!=a.depths[0]?[i].concat(a.depths):a.depths:l=[i]);function u(d){return""+t.main(s,d,s.helpers,s.partials,c,f,l)}return u=hg(t.main,u,s,a.depths||[],c,f),u(i,a)}return o.isTop=!0,o._setup=function(i){if(i.partial)s.protoAccessControl=i.protoAccessControl,s.helpers=i.helpers,s.partials=i.partials,s.decorators=i.decorators,s.hooks=i.hooks;else{var a=Mt.extend({},e.helpers,i.helpers);b2(a,s),s.helpers=a,t.usePartial&&(s.partials=s.mergeIfNeeded(i.partials,e.partials)),(t.usePartial||t.useDecorators)&&(s.decorators=Mt.extend({},e.decorators,i.decorators)),s.hooks={},s.protoAccessControl=fg.createProtoAccessControl(i);var c=i.allowCallsToHelperMissing||r;ug.moveHelperToHooks(s,"helperMissing",c),ug.moveHelperToHooks(s,"blockHelperMissing",c)}},o._child=function(i,a,c,l){if(t.useBlockParams&&!c)throw new Lt.default("must pass block params");if(t.useDepths&&!l)throw new Lt.default("must pass parent depths");return dl(s,i,t[i],a,0,c,l)},o}function dl(t,e,r,n,s,o,i){function a(c){var l=arguments.length<=1||arguments[1]===void 0?{}:arguments[1],f=i;return i&&c!=i[0]&&!(c===t.nullContext&&i[0]===null)&&(f=[c].concat(i)),r(t,c,t.helpers,t.partials,l.data||n,o&&[l.blockParams].concat(o),f)}return a=hg(r,a,t,i,n,o),a.program=e,a.depth=i?i.length:0,a.blockParams=s||0,a}function m2(t,e,r){return t?!t.call&&!r.name&&(r.name=t,t=r.partials[t]):r.name==="@partial-block"?t=r.data["partial-block"]:t=r.partials[r.name],t}function g2(t,e,r){var n=r.data&&r.data["partial-block"];r.partial=!0,r.ids&&(r.data.contextPath=r.ids[0]||r.data.contextPath);var s=void 0;if(r.fn&&r.fn!==dg&&function(){r.data=Nt.createFrame(r.data);var o=r.fn;s=r.data["partial-block"]=function(a){var c=arguments.length<=1||arguments[1]===void 0?{}:arguments[1];return c.data=Nt.createFrame(c.data),c.data["partial-block"]=n,o(a,c)},o.partials&&(r.partials=Mt.extend({},r.partials,o.partials))}(),t===void 0&&s&&(t=s),t===void 0)throw new Lt.default("The partial "+r.name+" could not be found");if(t instanceof Function)return t(e,r)}function dg(){return""}function y2(t,e){return(!e||!("root"in e))&&(e=e?Nt.createFrame(e):{},e.root=t),e}function hg(t,e,r,n,s,o){if(t.decorator){var i={};e=t.decorator(e,i,r,n&&n[0],s,o,n),Mt.extend(e,i)}return e}function b2(t,e){Object.keys(t).forEach(function(r){var n=t[r];t[r]=w2(n,e)})}function w2(t,e){var r=e.lookupProperty;return d2.wrapHelper(t,function(n){return Mt.extend({lookupProperty:r},n)})}});var bf=j((hl,mg)=>{"use strict";hl.__esModule=!0;hl.default=function(t){(function(){typeof globalThis!="object"&&(Object.prototype.__defineGetter__("__magic__",function(){return this}),__magic__.globalThis=__magic__,delete Object.prototype.__magic__)})();var e=globalThis.Handlebars;t.noConflict=function(){return globalThis.Handlebars===t&&(globalThis.Handlebars=e),t}};mg.exports=hl.default});var _g=j((pl,wg)=>{"use strict";pl.__esModule=!0;function _f(t){return t&&t.__esModule?t:{default:t}}function Sf(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}var _2=ul(),gg=Sf(_2),S2=lg(),E2=_f(S2),x2=Fe(),A2=_f(x2),v2=Se(),wf=Sf(v2),C2=pg(),yg=Sf(C2),P2=bf(),R2=_f(P2);function bg(){var t=new gg.HandlebarsEnvironment;return wf.extend(t,gg),t.SafeString=E2.default,t.Exception=A2.default,t.Utils=wf,t.escapeExpression=wf.escapeExpression,t.VM=yg,t.template=function(e){return yg.template(e,t)},t}var zo=bg();zo.create=bg;R2.default(zo);zo.default=zo;pl.default=zo;wg.exports=pl.default});var Ef=j((ml,Eg)=>{"use strict";ml.__esModule=!0;var Sg={helpers:{helperExpression:function(e){return e.type==="SubExpression"||(e.type==="MustacheStatement"||e.type==="BlockStatement")&&!!(e.params&&e.params.length||e.hash)},scopedId:function(e){return/^\.|this\b/.test(e.original)},simpleId:function(e){return e.parts.length===1&&!Sg.helpers.scopedId(e)&&!e.depth}}};ml.default=Sg;Eg.exports=ml.default});var Ag=j((gl,xg)=>{"use strict";gl.__esModule=!0;var T2=function(){var t={trace:function(){},yy:{},symbols_:{error:2,root:3,program:4,EOF:5,program_repetition0:6,statement:7,mustache:8,block:9,rawBlock:10,partial:11,partialBlock:12,content:13,COMMENT:14,CONTENT:15,openRawBlock:16,rawBlock_repetition0:17,END_RAW_BLOCK:18,OPEN_RAW_BLOCK:19,helperName:20,openRawBlock_repetition0:21,openRawBlock_option0:22,CLOSE_RAW_BLOCK:23,openBlock:24,block_option0:25,closeBlock:26,openInverse:27,block_option1:28,OPEN_BLOCK:29,openBlock_repetition0:30,openBlock_option0:31,openBlock_option1:32,CLOSE:33,OPEN_INVERSE:34,openInverse_repetition0:35,openInverse_option0:36,openInverse_option1:37,openInverseChain:38,OPEN_INVERSE_CHAIN:39,openInverseChain_repetition0:40,openInverseChain_option0:41,openInverseChain_option1:42,inverseAndProgram:43,INVERSE:44,inverseChain:45,inverseChain_option0:46,OPEN_ENDBLOCK:47,OPEN:48,mustache_repetition0:49,mustache_option0:50,OPEN_UNESCAPED:51,mustache_repetition1:52,mustache_option1:53,CLOSE_UNESCAPED:54,OPEN_PARTIAL:55,partialName:56,partial_repetition0:57,partial_option0:58,openPartialBlock:59,OPEN_PARTIAL_BLOCK:60,openPartialBlock_repetition0:61,openPartialBlock_option0:62,param:63,sexpr:64,OPEN_SEXPR:65,sexpr_repetition0:66,sexpr_option0:67,CLOSE_SEXPR:68,hash:69,hash_repetition_plus0:70,hashSegment:71,ID:72,EQUALS:73,blockParams:74,OPEN_BLOCK_PARAMS:75,blockParams_repetition_plus0:76,CLOSE_BLOCK_PARAMS:77,path:78,dataName:79,STRING:80,NUMBER:81,BOOLEAN:82,UNDEFINED:83,NULL:84,DATA:85,pathSegments:86,SEP:87,$accept:0,$end:1},terminals_:{2:"error",5:"EOF",14:"COMMENT",15:"CONTENT",18:"END_RAW_BLOCK",19:"OPEN_RAW_BLOCK",23:"CLOSE_RAW_BLOCK",29:"OPEN_BLOCK",33:"CLOSE",34:"OPEN_INVERSE",39:"OPEN_INVERSE_CHAIN",44:"INVERSE",47:"OPEN_ENDBLOCK",48:"OPEN",51:"OPEN_UNESCAPED",54:"CLOSE_UNESCAPED",55:"OPEN_PARTIAL",60:"OPEN_PARTIAL_BLOCK",65:"OPEN_SEXPR",68:"CLOSE_SEXPR",72:"ID",73:"EQUALS",75:"OPEN_BLOCK_PARAMS",77:"CLOSE_BLOCK_PARAMS",80:"STRING",81:"NUMBER",82:"BOOLEAN",83:"UNDEFINED",84:"NULL",85:"DATA",87:"SEP"},productions_:[0,[3,2],[4,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[7,1],[13,1],[10,3],[16,5],[9,4],[9,4],[24,6],[27,6],[38,6],[43,2],[45,3],[45,1],[26,3],[8,5],[8,5],[11,5],[12,3],[59,5],[63,1],[63,1],[64,5],[69,1],[71,3],[74,3],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[20,1],[56,1],[56,1],[79,2],[78,1],[86,3],[86,1],[6,0],[6,2],[17,0],[17,2],[21,0],[21,2],[22,0],[22,1],[25,0],[25,1],[28,0],[28,1],[30,0],[30,2],[31,0],[31,1],[32,0],[32,1],[35,0],[35,2],[36,0],[36,1],[37,0],[37,1],[40,0],[40,2],[41,0],[41,1],[42,0],[42,1],[46,0],[46,1],[49,0],[49,2],[50,0],[50,1],[52,0],[52,2],[53,0],[53,1],[57,0],[57,2],[58,0],[58,1],[61,0],[61,2],[62,0],[62,1],[66,0],[66,2],[67,0],[67,1],[70,1],[70,2],[76,1],[76,2]],performAction:function(s,o,i,a,c,l,f){var u=l.length-1;switch(c){case 1:return l[u-1];case 2:this.$=a.prepareProgram(l[u]);break;case 3:this.$=l[u];break;case 4:this.$=l[u];break;case 5:this.$=l[u];break;case 6:this.$=l[u];break;case 7:this.$=l[u];break;case 8:this.$=l[u];break;case 9:this.$={type:"CommentStatement",value:a.stripComment(l[u]),strip:a.stripFlags(l[u],l[u]),loc:a.locInfo(this._$)};break;case 10:this.$={type:"ContentStatement",original:l[u],value:l[u],loc:a.locInfo(this._$)};break;case 11:this.$=a.prepareRawBlock(l[u-2],l[u-1],l[u],this._$);break;case 12:this.$={path:l[u-3],params:l[u-2],hash:l[u-1]};break;case 13:this.$=a.prepareBlock(l[u-3],l[u-2],l[u-1],l[u],!1,this._$);break;case 14:this.$=a.prepareBlock(l[u-3],l[u-2],l[u-1],l[u],!0,this._$);break;case 15:this.$={open:l[u-5],path:l[u-4],params:l[u-3],hash:l[u-2],blockParams:l[u-1],strip:a.stripFlags(l[u-5],l[u])};break;case 16:this.$={path:l[u-4],params:l[u-3],hash:l[u-2],blockParams:l[u-1],strip:a.stripFlags(l[u-5],l[u])};break;case 17:this.$={path:l[u-4],params:l[u-3],hash:l[u-2],blockParams:l[u-1],strip:a.stripFlags(l[u-5],l[u])};break;case 18:this.$={strip:a.stripFlags(l[u-1],l[u-1]),program:l[u]};break;case 19:var d=a.prepareBlock(l[u-2],l[u-1],l[u],l[u],!1,this._$),h=a.prepareProgram([d],l[u-1].loc);h.chained=!0,this.$={strip:l[u-2].strip,program:h,chain:!0};break;case 20:this.$=l[u];break;case 21:this.$={path:l[u-1],strip:a.stripFlags(l[u-2],l[u])};break;case 22:this.$=a.prepareMustache(l[u-3],l[u-2],l[u-1],l[u-4],a.stripFlags(l[u-4],l[u]),this._$);break;case 23:this.$=a.prepareMustache(l[u-3],l[u-2],l[u-1],l[u-4],a.stripFlags(l[u-4],l[u]),this._$);break;case 24:this.$={type:"PartialStatement",name:l[u-3],params:l[u-2],hash:l[u-1],indent:"",strip:a.stripFlags(l[u-4],l[u]),loc:a.locInfo(this._$)};break;case 25:this.$=a.preparePartialBlock(l[u-2],l[u-1],l[u],this._$);break;case 26:this.$={path:l[u-3],params:l[u-2],hash:l[u-1],strip:a.stripFlags(l[u-4],l[u])};break;case 27:this.$=l[u];break;case 28:this.$=l[u];break;case 29:this.$={type:"SubExpression",path:l[u-3],params:l[u-2],hash:l[u-1],loc:a.locInfo(this._$)};break;case 30:this.$={type:"Hash",pairs:l[u],loc:a.locInfo(this._$)};break;case 31:this.$={type:"HashPair",key:a.id(l[u-2]),value:l[u],loc:a.locInfo(this._$)};break;case 32:this.$=a.id(l[u-1]);break;case 33:this.$=l[u];break;case 34:this.$=l[u];break;case 35:this.$={type:"StringLiteral",value:l[u],original:l[u],loc:a.locInfo(this._$)};break;case 36:this.$={type:"NumberLiteral",value:Number(l[u]),original:Number(l[u]),loc:a.locInfo(this._$)};break;case 37:this.$={type:"BooleanLiteral",value:l[u]==="true",original:l[u]==="true",loc:a.locInfo(this._$)};break;case 38:this.$={type:"UndefinedLiteral",original:void 0,value:void 0,loc:a.locInfo(this._$)};break;case 39:this.$={type:"NullLiteral",original:null,value:null,loc:a.locInfo(this._$)};break;case 40:this.$=l[u];break;case 41:this.$=l[u];break;case 42:this.$=a.preparePath(!0,l[u],this._$);break;case 43:this.$=a.preparePath(!1,l[u],this._$);break;case 44:l[u-2].push({part:a.id(l[u]),original:l[u],separator:l[u-1]}),this.$=l[u-2];break;case 45:this.$=[{part:a.id(l[u]),original:l[u]}];break;case 46:this.$=[];break;case 47:l[u-1].push(l[u]);break;case 48:this.$=[];break;case 49:l[u-1].push(l[u]);break;case 50:this.$=[];break;case 51:l[u-1].push(l[u]);break;case 58:this.$=[];break;case 59:l[u-1].push(l[u]);break;case 64:this.$=[];break;case 65:l[u-1].push(l[u]);break;case 70:this.$=[];break;case 71:l[u-1].push(l[u]);break;case 78:this.$=[];break;case 79:l[u-1].push(l[u]);break;case 82:this.$=[];break;case 83:l[u-1].push(l[u]);break;case 86:this.$=[];break;case 87:l[u-1].push(l[u]);break;case 90:this.$=[];break;case 91:l[u-1].push(l[u]);break;case 94:this.$=[];break;case 95:l[u-1].push(l[u]);break;case 98:this.$=[l[u]];break;case 99:l[u-1].push(l[u]);break;case 100:this.$=[l[u]];break;case 101:l[u-1].push(l[u]);break}},table:[{3:1,4:2,5:[2,46],6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{1:[3]},{5:[1,4]},{5:[2,2],7:5,8:6,9:7,10:8,11:9,12:10,13:11,14:[1,12],15:[1,20],16:17,19:[1,23],24:15,27:16,29:[1,21],34:[1,22],39:[2,2],44:[2,2],47:[2,2],48:[1,13],51:[1,14],55:[1,18],59:19,60:[1,24]},{1:[2,1]},{5:[2,47],14:[2,47],15:[2,47],19:[2,47],29:[2,47],34:[2,47],39:[2,47],44:[2,47],47:[2,47],48:[2,47],51:[2,47],55:[2,47],60:[2,47]},{5:[2,3],14:[2,3],15:[2,3],19:[2,3],29:[2,3],34:[2,3],39:[2,3],44:[2,3],47:[2,3],48:[2,3],51:[2,3],55:[2,3],60:[2,3]},{5:[2,4],14:[2,4],15:[2,4],19:[2,4],29:[2,4],34:[2,4],39:[2,4],44:[2,4],47:[2,4],48:[2,4],51:[2,4],55:[2,4],60:[2,4]},{5:[2,5],14:[2,5],15:[2,5],19:[2,5],29:[2,5],34:[2,5],39:[2,5],44:[2,5],47:[2,5],48:[2,5],51:[2,5],55:[2,5],60:[2,5]},{5:[2,6],14:[2,6],15:[2,6],19:[2,6],29:[2,6],34:[2,6],39:[2,6],44:[2,6],47:[2,6],48:[2,6],51:[2,6],55:[2,6],60:[2,6]},{5:[2,7],14:[2,7],15:[2,7],19:[2,7],29:[2,7],34:[2,7],39:[2,7],44:[2,7],47:[2,7],48:[2,7],51:[2,7],55:[2,7],60:[2,7]},{5:[2,8],14:[2,8],15:[2,8],19:[2,8],29:[2,8],34:[2,8],39:[2,8],44:[2,8],47:[2,8],48:[2,8],51:[2,8],55:[2,8],60:[2,8]},{5:[2,9],14:[2,9],15:[2,9],19:[2,9],29:[2,9],34:[2,9],39:[2,9],44:[2,9],47:[2,9],48:[2,9],51:[2,9],55:[2,9],60:[2,9]},{20:25,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:36,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:37,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{4:38,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{15:[2,48],17:39,18:[2,48]},{20:41,56:40,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:44,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{5:[2,10],14:[2,10],15:[2,10],18:[2,10],19:[2,10],29:[2,10],34:[2,10],39:[2,10],44:[2,10],47:[2,10],48:[2,10],51:[2,10],55:[2,10],60:[2,10]},{20:45,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:46,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:47,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:41,56:48,64:42,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[2,78],49:49,65:[2,78],72:[2,78],80:[2,78],81:[2,78],82:[2,78],83:[2,78],84:[2,78],85:[2,78]},{23:[2,33],33:[2,33],54:[2,33],65:[2,33],68:[2,33],72:[2,33],75:[2,33],80:[2,33],81:[2,33],82:[2,33],83:[2,33],84:[2,33],85:[2,33]},{23:[2,34],33:[2,34],54:[2,34],65:[2,34],68:[2,34],72:[2,34],75:[2,34],80:[2,34],81:[2,34],82:[2,34],83:[2,34],84:[2,34],85:[2,34]},{23:[2,35],33:[2,35],54:[2,35],65:[2,35],68:[2,35],72:[2,35],75:[2,35],80:[2,35],81:[2,35],82:[2,35],83:[2,35],84:[2,35],85:[2,35]},{23:[2,36],33:[2,36],54:[2,36],65:[2,36],68:[2,36],72:[2,36],75:[2,36],80:[2,36],81:[2,36],82:[2,36],83:[2,36],84:[2,36],85:[2,36]},{23:[2,37],33:[2,37],54:[2,37],65:[2,37],68:[2,37],72:[2,37],75:[2,37],80:[2,37],81:[2,37],82:[2,37],83:[2,37],84:[2,37],85:[2,37]},{23:[2,38],33:[2,38],54:[2,38],65:[2,38],68:[2,38],72:[2,38],75:[2,38],80:[2,38],81:[2,38],82:[2,38],83:[2,38],84:[2,38],85:[2,38]},{23:[2,39],33:[2,39],54:[2,39],65:[2,39],68:[2,39],72:[2,39],75:[2,39],80:[2,39],81:[2,39],82:[2,39],83:[2,39],84:[2,39],85:[2,39]},{23:[2,43],33:[2,43],54:[2,43],65:[2,43],68:[2,43],72:[2,43],75:[2,43],80:[2,43],81:[2,43],82:[2,43],83:[2,43],84:[2,43],85:[2,43],87:[1,50]},{72:[1,35],86:51},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{52:52,54:[2,82],65:[2,82],72:[2,82],80:[2,82],81:[2,82],82:[2,82],83:[2,82],84:[2,82],85:[2,82]},{25:53,38:55,39:[1,57],43:56,44:[1,58],45:54,47:[2,54]},{28:59,43:60,44:[1,58],47:[2,56]},{13:62,15:[1,20],18:[1,61]},{33:[2,86],57:63,65:[2,86],72:[2,86],80:[2,86],81:[2,86],82:[2,86],83:[2,86],84:[2,86],85:[2,86]},{33:[2,40],65:[2,40],72:[2,40],80:[2,40],81:[2,40],82:[2,40],83:[2,40],84:[2,40],85:[2,40]},{33:[2,41],65:[2,41],72:[2,41],80:[2,41],81:[2,41],82:[2,41],83:[2,41],84:[2,41],85:[2,41]},{20:64,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:65,47:[1,66]},{30:67,33:[2,58],65:[2,58],72:[2,58],75:[2,58],80:[2,58],81:[2,58],82:[2,58],83:[2,58],84:[2,58],85:[2,58]},{33:[2,64],35:68,65:[2,64],72:[2,64],75:[2,64],80:[2,64],81:[2,64],82:[2,64],83:[2,64],84:[2,64],85:[2,64]},{21:69,23:[2,50],65:[2,50],72:[2,50],80:[2,50],81:[2,50],82:[2,50],83:[2,50],84:[2,50],85:[2,50]},{33:[2,90],61:70,65:[2,90],72:[2,90],80:[2,90],81:[2,90],82:[2,90],83:[2,90],84:[2,90],85:[2,90]},{20:74,33:[2,80],50:71,63:72,64:75,65:[1,43],69:73,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{72:[1,79]},{23:[2,42],33:[2,42],54:[2,42],65:[2,42],68:[2,42],72:[2,42],75:[2,42],80:[2,42],81:[2,42],82:[2,42],83:[2,42],84:[2,42],85:[2,42],87:[1,50]},{20:74,53:80,54:[2,84],63:81,64:75,65:[1,43],69:82,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{26:83,47:[1,66]},{47:[2,55]},{4:84,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],39:[2,46],44:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{47:[2,20]},{20:85,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{4:86,6:3,14:[2,46],15:[2,46],19:[2,46],29:[2,46],34:[2,46],47:[2,46],48:[2,46],51:[2,46],55:[2,46],60:[2,46]},{26:87,47:[1,66]},{47:[2,57]},{5:[2,11],14:[2,11],15:[2,11],19:[2,11],29:[2,11],34:[2,11],39:[2,11],44:[2,11],47:[2,11],48:[2,11],51:[2,11],55:[2,11],60:[2,11]},{15:[2,49],18:[2,49]},{20:74,33:[2,88],58:88,63:89,64:75,65:[1,43],69:90,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{65:[2,94],66:91,68:[2,94],72:[2,94],80:[2,94],81:[2,94],82:[2,94],83:[2,94],84:[2,94],85:[2,94]},{5:[2,25],14:[2,25],15:[2,25],19:[2,25],29:[2,25],34:[2,25],39:[2,25],44:[2,25],47:[2,25],48:[2,25],51:[2,25],55:[2,25],60:[2,25]},{20:92,72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,31:93,33:[2,60],63:94,64:75,65:[1,43],69:95,70:76,71:77,72:[1,78],75:[2,60],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,66],36:96,63:97,64:75,65:[1,43],69:98,70:76,71:77,72:[1,78],75:[2,66],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,22:99,23:[2,52],63:100,64:75,65:[1,43],69:101,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{20:74,33:[2,92],62:102,63:103,64:75,65:[1,43],69:104,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,105]},{33:[2,79],65:[2,79],72:[2,79],80:[2,79],81:[2,79],82:[2,79],83:[2,79],84:[2,79],85:[2,79]},{33:[2,81]},{23:[2,27],33:[2,27],54:[2,27],65:[2,27],68:[2,27],72:[2,27],75:[2,27],80:[2,27],81:[2,27],82:[2,27],83:[2,27],84:[2,27],85:[2,27]},{23:[2,28],33:[2,28],54:[2,28],65:[2,28],68:[2,28],72:[2,28],75:[2,28],80:[2,28],81:[2,28],82:[2,28],83:[2,28],84:[2,28],85:[2,28]},{23:[2,30],33:[2,30],54:[2,30],68:[2,30],71:106,72:[1,107],75:[2,30]},{23:[2,98],33:[2,98],54:[2,98],68:[2,98],72:[2,98],75:[2,98]},{23:[2,45],33:[2,45],54:[2,45],65:[2,45],68:[2,45],72:[2,45],73:[1,108],75:[2,45],80:[2,45],81:[2,45],82:[2,45],83:[2,45],84:[2,45],85:[2,45],87:[2,45]},{23:[2,44],33:[2,44],54:[2,44],65:[2,44],68:[2,44],72:[2,44],75:[2,44],80:[2,44],81:[2,44],82:[2,44],83:[2,44],84:[2,44],85:[2,44],87:[2,44]},{54:[1,109]},{54:[2,83],65:[2,83],72:[2,83],80:[2,83],81:[2,83],82:[2,83],83:[2,83],84:[2,83],85:[2,83]},{54:[2,85]},{5:[2,13],14:[2,13],15:[2,13],19:[2,13],29:[2,13],34:[2,13],39:[2,13],44:[2,13],47:[2,13],48:[2,13],51:[2,13],55:[2,13],60:[2,13]},{38:55,39:[1,57],43:56,44:[1,58],45:111,46:110,47:[2,76]},{33:[2,70],40:112,65:[2,70],72:[2,70],75:[2,70],80:[2,70],81:[2,70],82:[2,70],83:[2,70],84:[2,70],85:[2,70]},{47:[2,18]},{5:[2,14],14:[2,14],15:[2,14],19:[2,14],29:[2,14],34:[2,14],39:[2,14],44:[2,14],47:[2,14],48:[2,14],51:[2,14],55:[2,14],60:[2,14]},{33:[1,113]},{33:[2,87],65:[2,87],72:[2,87],80:[2,87],81:[2,87],82:[2,87],83:[2,87],84:[2,87],85:[2,87]},{33:[2,89]},{20:74,63:115,64:75,65:[1,43],67:114,68:[2,96],69:116,70:76,71:77,72:[1,78],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{33:[1,117]},{32:118,33:[2,62],74:119,75:[1,120]},{33:[2,59],65:[2,59],72:[2,59],75:[2,59],80:[2,59],81:[2,59],82:[2,59],83:[2,59],84:[2,59],85:[2,59]},{33:[2,61],75:[2,61]},{33:[2,68],37:121,74:122,75:[1,120]},{33:[2,65],65:[2,65],72:[2,65],75:[2,65],80:[2,65],81:[2,65],82:[2,65],83:[2,65],84:[2,65],85:[2,65]},{33:[2,67],75:[2,67]},{23:[1,123]},{23:[2,51],65:[2,51],72:[2,51],80:[2,51],81:[2,51],82:[2,51],83:[2,51],84:[2,51],85:[2,51]},{23:[2,53]},{33:[1,124]},{33:[2,91],65:[2,91],72:[2,91],80:[2,91],81:[2,91],82:[2,91],83:[2,91],84:[2,91],85:[2,91]},{33:[2,93]},{5:[2,22],14:[2,22],15:[2,22],19:[2,22],29:[2,22],34:[2,22],39:[2,22],44:[2,22],47:[2,22],48:[2,22],51:[2,22],55:[2,22],60:[2,22]},{23:[2,99],33:[2,99],54:[2,99],68:[2,99],72:[2,99],75:[2,99]},{73:[1,108]},{20:74,63:125,64:75,65:[1,43],72:[1,35],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,23],14:[2,23],15:[2,23],19:[2,23],29:[2,23],34:[2,23],39:[2,23],44:[2,23],47:[2,23],48:[2,23],51:[2,23],55:[2,23],60:[2,23]},{47:[2,19]},{47:[2,77]},{20:74,33:[2,72],41:126,63:127,64:75,65:[1,43],69:128,70:76,71:77,72:[1,78],75:[2,72],78:26,79:27,80:[1,28],81:[1,29],82:[1,30],83:[1,31],84:[1,32],85:[1,34],86:33},{5:[2,24],14:[2,24],15:[2,24],19:[2,24],29:[2,24],34:[2,24],39:[2,24],44:[2,24],47:[2,24],48:[2,24],51:[2,24],55:[2,24],60:[2,24]},{68:[1,129]},{65:[2,95],68:[2,95],72:[2,95],80:[2,95],81:[2,95],82:[2,95],83:[2,95],84:[2,95],85:[2,95]},{68:[2,97]},{5:[2,21],14:[2,21],15:[2,21],19:[2,21],29:[2,21],34:[2,21],39:[2,21],44:[2,21],47:[2,21],48:[2,21],51:[2,21],55:[2,21],60:[2,21]},{33:[1,130]},{33:[2,63]},{72:[1,132],76:131},{33:[1,133]},{33:[2,69]},{15:[2,12],18:[2,12]},{14:[2,26],15:[2,26],19:[2,26],29:[2,26],34:[2,26],47:[2,26],48:[2,26],51:[2,26],55:[2,26],60:[2,26]},{23:[2,31],33:[2,31],54:[2,31],68:[2,31],72:[2,31],75:[2,31]},{33:[2,74],42:134,74:135,75:[1,120]},{33:[2,71],65:[2,71],72:[2,71],75:[2,71],80:[2,71],81:[2,71],82:[2,71],83:[2,71],84:[2,71],85:[2,71]},{33:[2,73],75:[2,73]},{23:[2,29],33:[2,29],54:[2,29],65:[2,29],68:[2,29],72:[2,29],75:[2,29],80:[2,29],81:[2,29],82:[2,29],83:[2,29],84:[2,29],85:[2,29]},{14:[2,15],15:[2,15],19:[2,15],29:[2,15],34:[2,15],39:[2,15],44:[2,15],47:[2,15],48:[2,15],51:[2,15],55:[2,15],60:[2,15]},{72:[1,137],77:[1,136]},{72:[2,100],77:[2,100]},{14:[2,16],15:[2,16],19:[2,16],29:[2,16],34:[2,16],44:[2,16],47:[2,16],48:[2,16],51:[2,16],55:[2,16],60:[2,16]},{33:[1,138]},{33:[2,75]},{33:[2,32]},{72:[2,101],77:[2,101]},{14:[2,17],15:[2,17],19:[2,17],29:[2,17],34:[2,17],39:[2,17],44:[2,17],47:[2,17],48:[2,17],51:[2,17],55:[2,17],60:[2,17]}],defaultActions:{4:[2,1],54:[2,55],56:[2,20],60:[2,57],73:[2,81],82:[2,85],86:[2,18],90:[2,89],101:[2,53],104:[2,93],110:[2,19],111:[2,77],116:[2,97],119:[2,63],122:[2,69],135:[2,75],136:[2,32]},parseError:function(s,o){throw new Error(s)},parse:function(s){var o=this,i=[0],a=[null],c=[],l=this.table,f="",u=0,d=0,h=0,p=2,y=1;this.lexer.setInput(s),this.lexer.yy=this.yy,this.yy.lexer=this.lexer,this.yy.parser=this,typeof this.lexer.yylloc=="undefined"&&(this.lexer.yylloc={});var g=this.lexer.yylloc;c.push(g);var S=this.lexer.options&&this.lexer.options.ranges;typeof this.yy.parseError=="function"&&(this.parseError=this.yy.parseError);function _(Oe){i.length=i.length-2*Oe,a.length=a.length-Oe,c.length=c.length-Oe}function v(){var Oe;return Oe=o.lexer.lex()||1,typeof Oe!="number"&&(Oe=o.symbols_[Oe]||Oe),Oe}for(var P,E,R,k,M,U,F={},V,H,ee,Ee;;){if(R=i[i.length-1],this.defaultActions[R]?k=this.defaultActions[R]:((P===null||typeof P=="undefined")&&(P=v()),k=l[R]&&l[R][P]),typeof k=="undefined"||!k.length||!k[0]){var ue="";if(!h){Ee=[];for(V in l[R])this.terminals_[V]&&V>2&&Ee.push("'"+this.terminals_[V]+"'");this.lexer.showPosition?ue="Parse error on line "+(u+1)+`:
`+this.lexer.showPosition()+`
Expecting `+Ee.join(", ")+", got '"+(this.terminals_[P]||P)+"'":ue="Parse error on line "+(u+1)+": Unexpected "+(P==1?"end of input":"'"+(this.terminals_[P]||P)+"'"),this.parseError(ue,{text:this.lexer.match,token:this.terminals_[P]||P,line:this.lexer.yylineno,loc:g,expected:Ee})}}if(k[0]instanceof Array&&k.length>1)throw new Error("Parse Error: multiple actions possible at state: "+R+", token: "+P);switch(k[0]){case 1:i.push(P),a.push(this.lexer.yytext),c.push(this.lexer.yylloc),i.push(k[1]),P=null,E?(P=E,E=null):(d=this.lexer.yyleng,f=this.lexer.yytext,u=this.lexer.yylineno,g=this.lexer.yylloc,h>0&&h--);break;case 2:if(H=this.productions_[k[1]][1],F.$=a[a.length-H],F._$={first_line:c[c.length-(H||1)].first_line,last_line:c[c.length-1].last_line,first_column:c[c.length-(H||1)].first_column,last_column:c[c.length-1].last_column},S&&(F._$.range=[c[c.length-(H||1)].range[0],c[c.length-1].range[1]]),U=this.performAction.call(F,f,d,u,this.yy,k[1],a,c),typeof U!="undefined")return U;H&&(i=i.slice(0,-1*H*2),a=a.slice(0,-1*H),c=c.slice(0,-1*H)),i.push(this.productions_[k[1]][0]),a.push(F.$),c.push(F._$),ee=l[i[i.length-2]][i[i.length-1]],i.push(ee);break;case 3:return!0}}return!0}},e=function(){var n={EOF:1,parseError:function(o,i){if(this.yy.parser)this.yy.parser.parseError(o,i);else throw new Error(o)},setInput:function(o){return this._input=o,this._more=this._less=this.done=!1,this.yylineno=this.yyleng=0,this.yytext=this.matched=this.match="",this.conditionStack=["INITIAL"],this.yylloc={first_line:1,first_column:0,last_line:1,last_column:0},this.options.ranges&&(this.yylloc.range=[0,0]),this.offset=0,this},input:function(){var o=this._input[0];this.yytext+=o,this.yyleng++,this.offset++,this.match+=o,this.matched+=o;var i=o.match(/(?:\r\n?|\n).*/g);return i?(this.yylineno++,this.yylloc.last_line++):this.yylloc.last_column++,this.options.ranges&&this.yylloc.range[1]++,this._input=this._input.slice(1),o},unput:function(o){var i=o.length,a=o.split(/(?:\r\n?|\n)/g);this._input=o+this._input,this.yytext=this.yytext.substr(0,this.yytext.length-i-1),this.offset-=i;var c=this.match.split(/(?:\r\n?|\n)/g);this.match=this.match.substr(0,this.match.length-1),this.matched=this.matched.substr(0,this.matched.length-1),a.length-1&&(this.yylineno-=a.length-1);var l=this.yylloc.range;return this.yylloc={first_line:this.yylloc.first_line,last_line:this.yylineno+1,first_column:this.yylloc.first_column,last_column:a?(a.length===c.length?this.yylloc.first_column:0)+c[c.length-a.length].length-a[0].length:this.yylloc.first_column-i},this.options.ranges&&(this.yylloc.range=[l[0],l[0]+this.yyleng-i]),this},more:function(){return this._more=!0,this},less:function(o){this.unput(this.match.slice(o))},pastInput:function(){var o=this.matched.substr(0,this.matched.length-this.match.length);return(o.length>20?"...":"")+o.substr(-20).replace(/\n/g,"")},upcomingInput:function(){var o=this.match;return o.length<20&&(o+=this._input.substr(0,20-o.length)),(o.substr(0,20)+(o.length>20?"...":"")).replace(/\n/g,"")},showPosition:function(){var o=this.pastInput(),i=new Array(o.length+1).join("-");return o+this.upcomingInput()+`
`+i+"^"},next:function(){if(this.done)return this.EOF;this._input||(this.done=!0);var o,i,a,c,l,f;this._more||(this.yytext="",this.match="");for(var u=this._currentRules(),d=0;d<u.length&&(a=this._input.match(this.rules[u[d]]),!(a&&(!i||a[0].length>i[0].length)&&(i=a,c=d,!this.options.flex)));d++);return i?(f=i[0].match(/(?:\r\n?|\n).*/g),f&&(this.yylineno+=f.length),this.yylloc={first_line:this.yylloc.last_line,last_line:this.yylineno+1,first_column:this.yylloc.last_column,last_column:f?f[f.length-1].length-f[f.length-1].match(/\r?\n?/)[0].length:this.yylloc.last_column+i[0].length},this.yytext+=i[0],this.match+=i[0],this.matches=i,this.yyleng=this.yytext.length,this.options.ranges&&(this.yylloc.range=[this.offset,this.offset+=this.yyleng]),this._more=!1,this._input=this._input.slice(i[0].length),this.matched+=i[0],o=this.performAction.call(this,this.yy,this,u[c],this.conditionStack[this.conditionStack.length-1]),this.done&&this._input&&(this.done=!1),o||void 0):this._input===""?this.EOF:this.parseError("Lexical error on line "+(this.yylineno+1)+`. Unrecognized text.
`+this.showPosition(),{text:"",token:null,line:this.yylineno})},lex:function(){var o=this.next();return typeof o!="undefined"?o:this.lex()},begin:function(o){this.conditionStack.push(o)},popState:function(){return this.conditionStack.pop()},_currentRules:function(){return this.conditions[this.conditionStack[this.conditionStack.length-1]].rules},topState:function(){return this.conditionStack[this.conditionStack.length-2]},pushState:function(o){this.begin(o)}};return n.options={},n.performAction=function(o,i,a,c){function l(u,d){return i.yytext=i.yytext.substring(u,i.yyleng-d+u)}var f=c;switch(a){case 0:if(i.yytext.slice(-2)==="\\\\"?(l(0,1),this.begin("mu")):i.yytext.slice(-1)==="\\"?(l(0,1),this.begin("emu")):this.begin("mu"),i.yytext)return 15;break;case 1:return 15;case 2:return this.popState(),15;break;case 3:return this.begin("raw"),15;break;case 4:return this.popState(),this.conditionStack[this.conditionStack.length-1]==="raw"?15:(l(5,9),"END_RAW_BLOCK");case 5:return 15;case 6:return this.popState(),14;break;case 7:return 65;case 8:return 68;case 9:return 19;case 10:return this.popState(),this.begin("raw"),23;break;case 11:return 55;case 12:return 60;case 13:return 29;case 14:return 47;case 15:return this.popState(),44;break;case 16:return this.popState(),44;break;case 17:return 34;case 18:return 39;case 19:return 51;case 20:return 48;case 21:this.unput(i.yytext),this.popState(),this.begin("com");break;case 22:return this.popState(),14;break;case 23:return 48;case 24:return 73;case 25:return 72;case 26:return 72;case 27:return 87;case 28:break;case 29:return this.popState(),54;break;case 30:return this.popState(),33;break;case 31:return i.yytext=l(1,2).replace(/\\"/g,'"'),80;break;case 32:return i.yytext=l(1,2).replace(/\\'/g,"'"),80;break;case 33:return 85;case 34:return 82;case 35:return 82;case 36:return 83;case 37:return 84;case 38:return 81;case 39:return 75;case 40:return 77;case 41:return 72;case 42:return i.yytext=i.yytext.replace(/\\([\\\]])/g,"$1"),72;break;case 43:return"INVALID";case 44:return 5}},n.rules=[/^(?:[^\x00]*?(?=(\{\{)))/,/^(?:[^\x00]+)/,/^(?:[^\x00]{2,}?(?=(\{\{|\\\{\{|\\\\\{\{|$)))/,/^(?:\{\{\{\{(?=[^/]))/,/^(?:\{\{\{\{\/[^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=[=}\s\/.])\}\}\}\})/,/^(?:[^\x00]+?(?=(\{\{\{\{)))/,/^(?:[\s\S]*?--(~)?\}\})/,/^(?:\()/,/^(?:\))/,/^(?:\{\{\{\{)/,/^(?:\}\}\}\})/,/^(?:\{\{(~)?>)/,/^(?:\{\{(~)?#>)/,/^(?:\{\{(~)?#\*?)/,/^(?:\{\{(~)?\/)/,/^(?:\{\{(~)?\^\s*(~)?\}\})/,/^(?:\{\{(~)?\s*else\s*(~)?\}\})/,/^(?:\{\{(~)?\^)/,/^(?:\{\{(~)?\s*else\b)/,/^(?:\{\{(~)?\{)/,/^(?:\{\{(~)?&)/,/^(?:\{\{(~)?!--)/,/^(?:\{\{(~)?![\s\S]*?\}\})/,/^(?:\{\{(~)?\*?)/,/^(?:=)/,/^(?:\.\.)/,/^(?:\.(?=([=~}\s\/.)|])))/,/^(?:[\/.])/,/^(?:\s+)/,/^(?:\}(~)?\}\})/,/^(?:(~)?\}\})/,/^(?:"(\\["]|[^"])*")/,/^(?:'(\\[']|[^'])*')/,/^(?:@)/,/^(?:true(?=([~}\s)])))/,/^(?:false(?=([~}\s)])))/,/^(?:undefined(?=([~}\s)])))/,/^(?:null(?=([~}\s)])))/,/^(?:-?[0-9]+(?:\.[0-9]+)?(?=([~}\s)])))/,/^(?:as\s+\|)/,/^(?:\|)/,/^(?:([^\s!"#%-,\.\/;->@\[-\^`\{-~]+(?=([=~}\s\/.)|]))))/,/^(?:\[(\\\]|[^\]])*\])/,/^(?:.)/,/^(?:$)/],n.conditions={mu:{rules:[7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44],inclusive:!1},emu:{rules:[2],inclusive:!1},com:{rules:[6],inclusive:!1},raw:{rules:[3,4,5],inclusive:!1},INITIAL:{rules:[0,1,44],inclusive:!0}},n}();t.lexer=e;function r(){this.yy={}}return r.prototype=t,t.Parser=r,new r}();gl.default=T2;xg.exports=gl.default});var Af=j((wl,Pg)=>{"use strict";wl.__esModule=!0;function I2(t){return t&&t.__esModule?t:{default:t}}var k2=Fe(),xf=I2(k2);function yl(){this.parents=[]}yl.prototype={constructor:yl,mutating:!1,acceptKey:function(e,r){var n=this.accept(e[r]);if(this.mutating){if(n&&!yl.prototype[n.type])throw new xf.default('Unexpected node type "'+n.type+'" found when accepting '+r+" on "+e.type);e[r]=n}},acceptRequired:function(e,r){if(this.acceptKey(e,r),!e[r])throw new xf.default(e.type+" requires "+r)},acceptArray:function(e){for(var r=0,n=e.length;r<n;r++)this.acceptKey(e,r),e[r]||(e.splice(r,1),r--,n--)},accept:function(e){if(e){if(!this[e.type])throw new xf.default("Unknown type: "+e.type,e);this.current&&this.parents.unshift(this.current),this.current=e;var r=this[e.type](e);if(this.current=this.parents.shift(),!this.mutating||r)return r;if(r!==!1)return e}},Program:function(e){this.acceptArray(e.body)},MustacheStatement:bl,Decorator:bl,BlockStatement:vg,DecoratorBlock:vg,PartialStatement:Cg,PartialBlockStatement:function(e){Cg.call(this,e),this.acceptKey(e,"program")},ContentStatement:function(){},CommentStatement:function(){},SubExpression:bl,PathExpression:function(){},StringLiteral:function(){},NumberLiteral:function(){},BooleanLiteral:function(){},UndefinedLiteral:function(){},NullLiteral:function(){},Hash:function(e){this.acceptArray(e.pairs)},HashPair:function(e){this.acceptRequired(e,"value")}};function bl(t){this.acceptRequired(t,"path"),this.acceptArray(t.params),this.acceptKey(t,"hash")}function vg(t){bl.call(this,t),this.acceptKey(t,"program"),this.acceptKey(t,"inverse")}function Cg(t){this.acceptRequired(t,"name"),this.acceptArray(t.params),this.acceptKey(t,"hash")}wl.default=yl;Pg.exports=wl.default});var Tg=j((_l,Rg)=>{"use strict";_l.__esModule=!0;function O2(t){return t&&t.__esModule?t:{default:t}}var M2=Af(),L2=O2(M2);function yt(){var t=arguments.length<=0||arguments[0]===void 0?{}:arguments[0];this.options=t}yt.prototype=new L2.default;yt.prototype.Program=function(t){var e=!this.options.ignoreStandalone,r=!this.isRootSeen;this.isRootSeen=!0;for(var n=t.body,s=0,o=n.length;s<o;s++){var i=n[s],a=this.accept(i);if(a){var c=vf(n,s,r),l=Cf(n,s,r),f=a.openStandalone&&c,u=a.closeStandalone&&l,d=a.inlineStandalone&&c&&l;a.close&&Qr(n,s,!0),a.open&&ur(n,s,!0),e&&d&&(Qr(n,s),ur(n,s)&&i.type==="PartialStatement"&&(i.indent=/([ \t]+$)/.exec(n[s-1].original)[1])),e&&f&&(Qr((i.program||i.inverse).body),ur(n,s)),e&&u&&(Qr(n,s),ur((i.inverse||i.program).body))}}return t};yt.prototype.BlockStatement=yt.prototype.DecoratorBlock=yt.prototype.PartialBlockStatement=function(t){this.accept(t.program),this.accept(t.inverse);var e=t.program||t.inverse,r=t.program&&t.inverse,n=r,s=r;if(r&&r.chained)for(n=r.body[0].program;s.chained;)s=s.body[s.body.length-1].program;var o={open:t.openStrip.open,close:t.closeStrip.close,openStandalone:Cf(e.body),closeStandalone:vf((n||e).body)};if(t.openStrip.close&&Qr(e.body,null,!0),r){var i=t.inverseStrip;i.open&&ur(e.body,null,!0),i.close&&Qr(n.body,null,!0),t.closeStrip.open&&ur(s.body,null,!0),!this.options.ignoreStandalone&&vf(e.body)&&Cf(n.body)&&(ur(e.body),Qr(n.body))}else t.closeStrip.open&&ur(e.body,null,!0);return o};yt.prototype.Decorator=yt.prototype.MustacheStatement=function(t){return t.strip};yt.prototype.PartialStatement=yt.prototype.CommentStatement=function(t){var e=t.strip||{};return{inlineStandalone:!0,open:e.open,close:e.close}};function vf(t,e,r){e===void 0&&(e=t.length);var n=t[e-1],s=t[e-2];if(!n)return r;if(n.type==="ContentStatement")return(s||!r?/\r?\n\s*?$/:/(^|\r?\n)\s*?$/).test(n.original)}function Cf(t,e,r){e===void 0&&(e=-1);var n=t[e+1],s=t[e+2];if(!n)return r;if(n.type==="ContentStatement")return(s||!r?/^\s*?\r?\n/:/^\s*?(\r?\n|$)/).test(n.original)}function Qr(t,e,r){var n=t[e==null?0:e+1];if(!(!n||n.type!=="ContentStatement"||!r&&n.rightStripped)){var s=n.value;n.value=n.value.replace(r?/^\s+/:/^[ \t]*\r?\n?/,""),n.rightStripped=n.value!==s}}function ur(t,e,r){var n=t[e==null?t.length-1:e-1];if(!(!n||n.type!=="ContentStatement"||!r&&n.leftStripped)){var s=n.value;return n.value=n.value.replace(r?/\s+$/:/[ \t]+$/,""),n.leftStripped=n.value!==s,n.leftStripped}}_l.default=yt;Rg.exports=_l.default});var Ig=j(qe=>{"use strict";qe.__esModule=!0;qe.SourceLocation=B2;qe.id=F2;qe.stripFlags=q2;qe.stripComment=U2;qe.preparePath=$2;qe.prepareMustache=H2;qe.prepareRawBlock=j2;qe.prepareBlock=W2;qe.prepareProgram=V2;qe.preparePartialBlock=K2;function N2(t){return t&&t.__esModule?t:{default:t}}var D2=Fe(),Pf=N2(D2);function Rf(t,e){if(e=e.path?e.path.original:e,t.path.original!==e){var r={loc:t.path.loc};throw new Pf.default(t.path.original+" doesn't match "+e,r)}}function B2(t,e){this.source=t,this.start={line:e.first_line,column:e.first_column},this.end={line:e.last_line,column:e.last_column}}function F2(t){return/^\[.*\]$/.test(t)?t.substring(1,t.length-1):t}function q2(t,e){return{open:t.charAt(2)==="~",close:e.charAt(e.length-3)==="~"}}function U2(t){return t.replace(/^\{\{~?!-?-?/,"").replace(/-?-?~?\}\}$/,"")}function $2(t,e,r){r=this.locInfo(r);for(var n=t?"@":"",s=[],o=0,i=0,a=e.length;i<a;i++){var c=e[i].part,l=e[i].original!==c;if(n+=(e[i].separator||"")+c,!l&&(c===".."||c==="."||c==="this")){if(s.length>0)throw new Pf.default("Invalid path: "+n,{loc:r});c===".."&&o++}else s.push(c)}return{type:"PathExpression",data:t,depth:o,parts:s,original:n,loc:r}}function H2(t,e,r,n,s,o){var i=n.charAt(3)||n.charAt(2),a=i!=="{"&&i!=="&",c=/\*/.test(n);return{type:c?"Decorator":"MustacheStatement",path:t,params:e,hash:r,escaped:a,strip:s,loc:this.locInfo(o)}}function j2(t,e,r,n){Rf(t,r),n=this.locInfo(n);var s={type:"Program",body:e,strip:{},loc:n};return{type:"BlockStatement",path:t.path,params:t.params,hash:t.hash,program:s,openStrip:{},inverseStrip:{},closeStrip:{},loc:n}}function W2(t,e,r,n,s,o){n&&n.path&&Rf(t,n);var i=/\*/.test(t.open);e.blockParams=t.blockParams;var a=void 0,c=void 0;if(r){if(i)throw new Pf.default("Unexpected inverse block on decorator",r);r.chain&&(r.program.body[0].closeStrip=n.strip),c=r.strip,a=r.program}return s&&(s=a,a=e,e=s),{type:i?"DecoratorBlock":"BlockStatement",path:t.path,params:t.params,hash:t.hash,program:e,inverse:a,openStrip:t.strip,inverseStrip:c,closeStrip:n&&n.strip,loc:this.locInfo(o)}}function V2(t,e){if(!e&&t.length){var r=t[0].loc,n=t[t.length-1].loc;r&&n&&(e={source:r.source,start:{line:r.start.line,column:r.start.column},end:{line:n.end.line,column:n.end.column}})}return{type:"Program",body:t,strip:{},loc:e}}function K2(t,e,r,n){return Rf(t,r),{type:"PartialBlockStatement",name:t.path,params:t.params,hash:t.hash,program:e,openStrip:t.strip,closeStrip:r&&r.strip,loc:this.locInfo(n)}}});var Mg=j(Xo=>{"use strict";Xo.__esModule=!0;Xo.parseWithoutProcessing=Og;Xo.parse=e0;function G2(t){if(t&&t.__esModule)return t;var e={};if(t!=null)for(var r in t)Object.prototype.hasOwnProperty.call(t,r)&&(e[r]=t[r]);return e.default=t,e}function kg(t){return t&&t.__esModule?t:{default:t}}var J2=Ag(),Tf=kg(J2),z2=Tg(),X2=kg(z2),Y2=Ig(),Q2=G2(Y2),Z2=Se();Xo.parser=Tf.default;var Sl={};Z2.extend(Sl,Q2);function Og(t,e){if(t.type==="Program")return t;Tf.default.yy=Sl,Sl.locInfo=function(n){return new Sl.SourceLocation(e&&e.srcName,n)};var r=Tf.default.parse(t);return r}function e0(t,e){var r=Og(t,e),n=new X2.default(e);return n.accept(r)}});var Bg=j(ei=>{"use strict";ei.__esModule=!0;ei.Compiler=If;ei.precompile=s0;ei.compile=o0;function Ng(t){return t&&t.__esModule?t:{default:t}}var t0=Fe(),Qo=Ng(t0),Zo=Se(),r0=Ef(),Yo=Ng(r0),n0=[].slice;function If(){}If.prototype={compiler:If,equals:function(e){var r=this.opcodes.length;if(e.opcodes.length!==r)return!1;for(var n=0;n<r;n++){var s=this.opcodes[n],o=e.opcodes[n];if(s.opcode!==o.opcode||!Dg(s.args,o.args))return!1}r=this.children.length;for(var n=0;n<r;n++)if(!this.children[n].equals(e.children[n]))return!1;return!0},guid:0,compile:function(e,r){return this.sourceNode=[],this.opcodes=[],this.children=[],this.options=r,this.stringParams=r.stringParams,this.trackIds=r.trackIds,r.blockParams=r.blockParams||[],r.knownHelpers=Zo.extend(Object.create(null),{helperMissing:!0,blockHelperMissing:!0,each:!0,if:!0,unless:!0,with:!0,log:!0,lookup:!0},r.knownHelpers),this.accept(e)},compileProgram:function(e){var r=new this.compiler,n=r.compile(e,this.options),s=this.guid++;return this.usePartial=this.usePartial||n.usePartial,this.children[s]=n,this.useDepths=this.useDepths||n.useDepths,s},accept:function(e){if(!this[e.type])throw new Qo.default("Unknown type: "+e.type,e);this.sourceNode.unshift(e);var r=this[e.type](e);return this.sourceNode.shift(),r},Program:function(e){this.options.blockParams.unshift(e.blockParams);for(var r=e.body,n=r.length,s=0;s<n;s++)this.accept(r[s]);return this.options.blockParams.shift(),this.isSimple=n===1,this.blockParams=e.blockParams?e.blockParams.length:0,this},BlockStatement:function(e){Lg(e);var r=e.program,n=e.inverse;r=r&&this.compileProgram(r),n=n&&this.compileProgram(n);var s=this.classifySexpr(e);s==="helper"?this.helperSexpr(e,r,n):s==="simple"?(this.simpleSexpr(e),this.opcode("pushProgram",r),this.opcode("pushProgram",n),this.opcode("emptyHash"),this.opcode("blockValue",e.path.original)):(this.ambiguousSexpr(e,r,n),this.opcode("pushProgram",r),this.opcode("pushProgram",n),this.opcode("emptyHash"),this.opcode("ambiguousBlockValue")),this.opcode("append")},DecoratorBlock:function(e){var r=e.program&&this.compileProgram(e.program),n=this.setupFullMustacheParams(e,r,void 0),s=e.path;this.useDecorators=!0,this.opcode("registerDecorator",n.length,s.original)},PartialStatement:function(e){this.usePartial=!0;var r=e.program;r&&(r=this.compileProgram(e.program));var n=e.params;if(n.length>1)throw new Qo.default("Unsupported number of partial arguments: "+n.length,e);n.length||(this.options.explicitPartialContext?this.opcode("pushLiteral","undefined"):n.push({type:"PathExpression",parts:[],depth:0}));var s=e.name.original,o=e.name.type==="SubExpression";o&&this.accept(e.name),this.setupFullMustacheParams(e,r,void 0,!0);var i=e.indent||"";this.options.preventIndent&&i&&(this.opcode("appendContent",i),i=""),this.opcode("invokePartial",o,s,i),this.opcode("append")},PartialBlockStatement:function(e){this.PartialStatement(e)},MustacheStatement:function(e){this.SubExpression(e),e.escaped&&!this.options.noEscape?this.opcode("appendEscaped"):this.opcode("append")},Decorator:function(e){this.DecoratorBlock(e)},ContentStatement:function(e){e.value&&this.opcode("appendContent",e.value)},CommentStatement:function(){},SubExpression:function(e){Lg(e);var r=this.classifySexpr(e);r==="simple"?this.simpleSexpr(e):r==="helper"?this.helperSexpr(e):this.ambiguousSexpr(e)},ambiguousSexpr:function(e,r,n){var s=e.path,o=s.parts[0],i=r!=null||n!=null;this.opcode("getContext",s.depth),this.opcode("pushProgram",r),this.opcode("pushProgram",n),s.strict=!0,this.accept(s),this.opcode("invokeAmbiguous",o,i)},simpleSexpr:function(e){var r=e.path;r.strict=!0,this.accept(r),this.opcode("resolvePossibleLambda")},helperSexpr:function(e,r,n){var s=this.setupFullMustacheParams(e,r,n),o=e.path,i=o.parts[0];if(this.options.knownHelpers[i])this.opcode("invokeKnownHelper",s.length,i);else{if(this.options.knownHelpersOnly)throw new Qo.default("You specified knownHelpersOnly, but used the unknown helper "+i,e);o.strict=!0,o.falsy=!0,this.accept(o),this.opcode("invokeHelper",s.length,o.original,Yo.default.helpers.simpleId(o))}},PathExpression:function(e){this.addDepth(e.depth),this.opcode("getContext",e.depth);var r=e.parts[0],n=Yo.default.helpers.scopedId(e),s=!e.depth&&!n&&this.blockParamIndex(r);s?this.opcode("lookupBlockParam",s,e.parts):r?e.data?(this.options.data=!0,this.opcode("lookupData",e.depth,e.parts,e.strict)):this.opcode("lookupOnContext",e.parts,e.falsy,e.strict,n):this.opcode("pushContext")},StringLiteral:function(e){this.opcode("pushString",e.value)},NumberLiteral:function(e){this.opcode("pushLiteral",e.value)},BooleanLiteral:function(e){this.opcode("pushLiteral",e.value)},UndefinedLiteral:function(){this.opcode("pushLiteral","undefined")},NullLiteral:function(){this.opcode("pushLiteral","null")},Hash:function(e){var r=e.pairs,n=0,s=r.length;for(this.opcode("pushHash");n<s;n++)this.pushParam(r[n].value);for(;n--;)this.opcode("assignToHash",r[n].key);this.opcode("popHash")},opcode:function(e){this.opcodes.push({opcode:e,args:n0.call(arguments,1),loc:this.sourceNode[0].loc})},addDepth:function(e){e&&(this.useDepths=!0)},classifySexpr:function(e){var r=Yo.default.helpers.simpleId(e.path),n=r&&!!this.blockParamIndex(e.path.parts[0]),s=!n&&Yo.default.helpers.helperExpression(e),o=!n&&(s||r);if(o&&!s){var i=e.path.parts[0],a=this.options;a.knownHelpers[i]?s=!0:a.knownHelpersOnly&&(o=!1)}return s?"helper":o?"ambiguous":"simple"},pushParams:function(e){for(var r=0,n=e.length;r<n;r++)this.pushParam(e[r])},pushParam:function(e){var r=e.value!=null?e.value:e.original||"";if(this.stringParams)r.replace&&(r=r.replace(/^(\.?\.\/)*/g,"").replace(/\//g,".")),e.depth&&this.addDepth(e.depth),this.opcode("getContext",e.depth||0),this.opcode("pushStringParam",r,e.type),e.type==="SubExpression"&&this.accept(e);else{if(this.trackIds){var n=void 0;if(e.parts&&!Yo.default.helpers.scopedId(e)&&!e.depth&&(n=this.blockParamIndex(e.parts[0])),n){var s=e.parts.slice(1).join(".");this.opcode("pushId","BlockParam",n,s)}else r=e.original||r,r.replace&&(r=r.replace(/^this(?:\.|$)/,"").replace(/^\.\//,"").replace(/^\.$/,"")),this.opcode("pushId",e.type,r)}this.accept(e)}},setupFullMustacheParams:function(e,r,n,s){var o=e.params;return this.pushParams(o),this.opcode("pushProgram",r),this.opcode("pushProgram",n),e.hash?this.accept(e.hash):this.opcode("emptyHash",s),o},blockParamIndex:function(e){for(var r=0,n=this.options.blockParams.length;r<n;r++){var s=this.options.blockParams[r],o=s&&Zo.indexOf(s,e);if(s&&o>=0)return[r,o]}}};function s0(t,e,r){if(t==null||typeof t!="string"&&t.type!=="Program")throw new Qo.default("You must pass a string or Handlebars AST to Handlebars.precompile. You passed "+t);e=e||{},"data"in e||(e.data=!0),e.compat&&(e.useDepths=!0);var n=r.parse(t,e),s=new r.Compiler().compile(n,e);return new r.JavaScriptCompiler().compile(s,e)}function o0(t,e,r){if(e===void 0&&(e={}),t==null||typeof t!="string"&&t.type!=="Program")throw new Qo.default("You must pass a string or Handlebars AST to Handlebars.compile. You passed "+t);e=Zo.extend({},e),"data"in e||(e.data=!0),e.compat&&(e.useDepths=!0);var n=void 0;function s(){var i=r.parse(t,e),a=new r.Compiler().compile(i,e),c=new r.JavaScriptCompiler().compile(a,e,void 0,!0);return r.template(c)}function o(i,a){return n||(n=s()),n.call(this,i,a)}return o._setup=function(i){return n||(n=s()),n._setup(i)},o._child=function(i,a,c,l){return n||(n=s()),n._child(i,a,c,l)},o}function Dg(t,e){if(t===e)return!0;if(Zo.isArray(t)&&Zo.isArray(e)&&t.length===e.length){for(var r=0;r<t.length;r++)if(!Dg(t[r],e[r]))return!1;return!0}}function Lg(t){if(!t.path.parts){var e=t.path;t.path={type:"PathExpression",data:!1,depth:0,parts:[e.original+""],original:e.original+"",loc:e.loc}}}});var qg=j(kf=>{var Fg="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".split("");kf.encode=function(t){if(0<=t&&t<Fg.length)return Fg[t];throw new TypeError("Must be between 0 and 63: "+t)};kf.decode=function(t){var e=65,r=90,n=97,s=122,o=48,i=57,a=43,c=47,l=26,f=52;return e<=t&&t<=r?t-e:n<=t&&t<=s?t-n+l:o<=t&&t<=i?t-o+f:t==a?62:t==c?63:-1}});var Lf=j(Mf=>{var Ug=qg(),Of=5,$g=1<<Of,Hg=$g-1,jg=$g;function i0(t){return t<0?(-t<<1)+1:(t<<1)+0}function a0(t){var e=(t&1)===1,r=t>>1;return e?-r:r}Mf.encode=function(e){var r="",n,s=i0(e);do n=s&Hg,s>>>=Of,s>0&&(n|=jg),r+=Ug.encode(n);while(s>0);return r};Mf.decode=function(e,r,n){var s=e.length,o=0,i=0,a,c;do{if(r>=s)throw new Error("Expected more digits in base 64 VLQ value.");if(c=Ug.decode(e.charCodeAt(r++)),c===-1)throw new Error("Invalid base64 digit: "+e.charAt(r-1));a=!!(c&jg),c&=Hg,o=o+(c<<i),i+=Of}while(a);n.value=a0(o),n.rest=r}});var Rs=j(be=>{function l0(t,e,r){if(e in t)return t[e];if(arguments.length===3)return r;throw new Error('"'+e+'" is a required argument.')}be.getArg=l0;var Wg=/^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/,c0=/^data:.+\,.+$/;function ti(t){var e=t.match(Wg);return e?{scheme:e[1],auth:e[2],host:e[3],port:e[4],path:e[5]}:null}be.urlParse=ti;function Cs(t){var e="";return t.scheme&&(e+=t.scheme+":"),e+="//",t.auth&&(e+=t.auth+"@"),t.host&&(e+=t.host),t.port&&(e+=":"+t.port),t.path&&(e+=t.path),e}be.urlGenerate=Cs;function Nf(t){var e=t,r=ti(t);if(r){if(!r.path)return t;e=r.path}for(var n=be.isAbsolute(e),s=e.split(/\/+/),o,i=0,a=s.length-1;a>=0;a--)o=s[a],o==="."?s.splice(a,1):o===".."?i++:i>0&&(o===""?(s.splice(a+1,i),i=0):(s.splice(a,2),i--));return e=s.join("/"),e===""&&(e=n?"/":"."),r?(r.path=e,Cs(r)):e}be.normalize=Nf;function Vg(t,e){t===""&&(t="."),e===""&&(e=".");var r=ti(e),n=ti(t);if(n&&(t=n.path||"/"),r&&!r.scheme)return n&&(r.scheme=n.scheme),Cs(r);if(r||e.match(c0))return e;if(n&&!n.host&&!n.path)return n.host=e,Cs(n);var s=e.charAt(0)==="/"?e:Nf(t.replace(/\/+$/,"")+"/"+e);return n?(n.path=s,Cs(n)):s}be.join=Vg;be.isAbsolute=function(t){return t.charAt(0)==="/"||Wg.test(t)};function u0(t,e){t===""&&(t="."),t=t.replace(/\/$/,"");for(var r=0;e.indexOf(t+"/")!==0;){var n=t.lastIndexOf("/");if(n<0||(t=t.slice(0,n),t.match(/^([^\/]+:\/)?\/*$/)))return e;++r}return Array(r+1).join("../")+e.substr(t.length+1)}be.relative=u0;var Kg=function(){var t=Object.create(null);return!("__proto__"in t)}();function Gg(t){return t}function f0(t){return Jg(t)?"$"+t:t}be.toSetString=Kg?Gg:f0;function d0(t){return Jg(t)?t.slice(1):t}be.fromSetString=Kg?Gg:d0;function Jg(t){if(!t)return!1;var e=t.length;if(e<9||t.charCodeAt(e-1)!==95||t.charCodeAt(e-2)!==95||t.charCodeAt(e-3)!==111||t.charCodeAt(e-4)!==116||t.charCodeAt(e-5)!==111||t.charCodeAt(e-6)!==114||t.charCodeAt(e-7)!==112||t.charCodeAt(e-8)!==95||t.charCodeAt(e-9)!==95)return!1;for(var r=e-10;r>=0;r--)if(t.charCodeAt(r)!==36)return!1;return!0}function h0(t,e,r){var n=Ps(t.source,e.source);return n!==0||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0||r)||(n=t.generatedColumn-e.generatedColumn,n!==0)||(n=t.generatedLine-e.generatedLine,n!==0)?n:Ps(t.name,e.name)}be.compareByOriginalPositions=h0;function p0(t,e,r){var n=t.generatedLine-e.generatedLine;return n!==0||(n=t.generatedColumn-e.generatedColumn,n!==0||r)||(n=Ps(t.source,e.source),n!==0)||(n=t.originalLine-e.originalLine,n!==0)||(n=t.originalColumn-e.originalColumn,n!==0)?n:Ps(t.name,e.name)}be.compareByGeneratedPositionsDeflated=p0;function Ps(t,e){return t===e?0:t===null?1:e===null?-1:t>e?1:-1}function m0(t,e){var r=t.generatedLine-e.generatedLine;return r!==0||(r=t.generatedColumn-e.generatedColumn,r!==0)||(r=Ps(t.source,e.source),r!==0)||(r=t.originalLine-e.originalLine,r!==0)||(r=t.originalColumn-e.originalColumn,r!==0)?r:Ps(t.name,e.name)}be.compareByGeneratedPositionsInflated=m0;function g0(t){return JSON.parse(t.replace(/^\)]}'[^\n]*\n/,""))}be.parseSourceMapInput=g0;function y0(t,e,r){if(e=e||"",t&&(t[t.length-1]!=="/"&&e[0]!=="/"&&(t+="/"),e=t+e),r){var n=ti(r);if(!n)throw new Error("sourceMapURL could not be parsed");if(n.path){var s=n.path.lastIndexOf("/");s>=0&&(n.path=n.path.substring(0,s+1))}e=Vg(Cs(n),e)}return Nf(e)}be.computeSourceURL=y0});var Ff=j(zg=>{var Df=Rs(),Bf=Object.prototype.hasOwnProperty,Zr=typeof Map!="undefined";function Dt(){this._array=[],this._set=Zr?new Map:Object.create(null)}Dt.fromArray=function(e,r){for(var n=new Dt,s=0,o=e.length;s<o;s++)n.add(e[s],r);return n};Dt.prototype.size=function(){return Zr?this._set.size:Object.getOwnPropertyNames(this._set).length};Dt.prototype.add=function(e,r){var n=Zr?e:Df.toSetString(e),s=Zr?this.has(e):Bf.call(this._set,n),o=this._array.length;(!s||r)&&this._array.push(e),s||(Zr?this._set.set(e,o):this._set[n]=o)};Dt.prototype.has=function(e){if(Zr)return this._set.has(e);var r=Df.toSetString(e);return Bf.call(this._set,r)};Dt.prototype.indexOf=function(e){if(Zr){var r=this._set.get(e);if(r>=0)return r}else{var n=Df.toSetString(e);if(Bf.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')};Dt.prototype.at=function(e){if(e>=0&&e<this._array.length)return this._array[e];throw new Error("No element indexed by "+e)};Dt.prototype.toArray=function(){return this._array.slice()};zg.ArraySet=Dt});var Qg=j(Yg=>{var Xg=Rs();function b0(t,e){var r=t.generatedLine,n=e.generatedLine,s=t.generatedColumn,o=e.generatedColumn;return n>r||n==r&&o>=s||Xg.compareByGeneratedPositionsInflated(t,e)<=0}function El(){this._array=[],this._sorted=!0,this._last={generatedLine:-1,generatedColumn:0}}El.prototype.unsortedForEach=function(e,r){this._array.forEach(e,r)};El.prototype.add=function(e){b0(this._last,e)?(this._last=e,this._array.push(e)):(this._sorted=!1,this._array.push(e))};El.prototype.toArray=function(){return this._sorted||(this._array.sort(Xg.compareByGeneratedPositionsInflated),this._sorted=!0),this._array};Yg.MappingList=El});var qf=j(Zg=>{var ri=Lf(),Z=Rs(),xl=Ff().ArraySet,w0=Qg().MappingList;function Ue(t){t||(t={}),this._file=Z.getArg(t,"file",null),this._sourceRoot=Z.getArg(t,"sourceRoot",null),this._skipValidation=Z.getArg(t,"skipValidation",!1),this._sources=new xl,this._names=new xl,this._mappings=new w0,this._sourcesContents=null}Ue.prototype._version=3;Ue.fromSourceMap=function(e){var r=e.sourceRoot,n=new Ue({file:e.file,sourceRoot:r});return e.eachMapping(function(s){var o={generated:{line:s.generatedLine,column:s.generatedColumn}};s.source!=null&&(o.source=s.source,r!=null&&(o.source=Z.relative(r,o.source)),o.original={line:s.originalLine,column:s.originalColumn},s.name!=null&&(o.name=s.name)),n.addMapping(o)}),e.sources.forEach(function(s){var o=s;r!==null&&(o=Z.relative(r,s)),n._sources.has(o)||n._sources.add(o);var i=e.sourceContentFor(s);i!=null&&n.setSourceContent(s,i)}),n};Ue.prototype.addMapping=function(e){var r=Z.getArg(e,"generated"),n=Z.getArg(e,"original",null),s=Z.getArg(e,"source",null),o=Z.getArg(e,"name",null);this._skipValidation||this._validateMapping(r,n,s,o),s!=null&&(s=String(s),this._sources.has(s)||this._sources.add(s)),o!=null&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:r.line,generatedColumn:r.column,originalLine:n!=null&&n.line,originalColumn:n!=null&&n.column,source:s,name:o})};Ue.prototype.setSourceContent=function(e,r){var n=e;this._sourceRoot!=null&&(n=Z.relative(this._sourceRoot,n)),r!=null?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[Z.toSetString(n)]=r):this._sourcesContents&&(delete this._sourcesContents[Z.toSetString(n)],Object.keys(this._sourcesContents).length===0&&(this._sourcesContents=null))};Ue.prototype.applySourceMap=function(e,r,n){var s=r;if(r==null){if(e.file==null)throw new Error(`SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map's "file" property. Both were omitted.`);s=e.file}var o=this._sourceRoot;o!=null&&(s=Z.relative(o,s));var i=new xl,a=new xl;this._mappings.unsortedForEach(function(c){if(c.source===s&&c.originalLine!=null){var l=e.originalPositionFor({line:c.originalLine,column:c.originalColumn});l.source!=null&&(c.source=l.source,n!=null&&(c.source=Z.join(n,c.source)),o!=null&&(c.source=Z.relative(o,c.source)),c.originalLine=l.line,c.originalColumn=l.column,l.name!=null&&(c.name=l.name))}var f=c.source;f!=null&&!i.has(f)&&i.add(f);var u=c.name;u!=null&&!a.has(u)&&a.add(u)},this),this._sources=i,this._names=a,e.sources.forEach(function(c){var l=e.sourceContentFor(c);l!=null&&(n!=null&&(c=Z.join(n,c)),o!=null&&(c=Z.relative(o,c)),this.setSourceContent(c,l))},this)};Ue.prototype._validateMapping=function(e,r,n,s){if(r&&typeof r.line!="number"&&typeof r.column!="number")throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if(!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0&&!r&&!n&&!s)){if(e&&"line"in e&&"column"in e&&r&&"line"in r&&"column"in r&&e.line>0&&e.column>=0&&r.line>0&&r.column>=0&&n)return;throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:r,name:s}))}};Ue.prototype._serializeMappings=function(){for(var e=0,r=1,n=0,s=0,o=0,i=0,a="",c,l,f,u,d=this._mappings.toArray(),h=0,p=d.length;h<p;h++){if(l=d[h],c="",l.generatedLine!==r)for(e=0;l.generatedLine!==r;)c+=";",r++;else if(h>0){if(!Z.compareByGeneratedPositionsInflated(l,d[h-1]))continue;c+=","}c+=ri.encode(l.generatedColumn-e),e=l.generatedColumn,l.source!=null&&(u=this._sources.indexOf(l.source),c+=ri.encode(u-i),i=u,c+=ri.encode(l.originalLine-1-s),s=l.originalLine-1,c+=ri.encode(l.originalColumn-n),n=l.originalColumn,l.name!=null&&(f=this._names.indexOf(l.name),c+=ri.encode(f-o),o=f)),a+=c}return a};Ue.prototype._generateSourcesContent=function(e,r){return e.map(function(n){if(!this._sourcesContents)return null;r!=null&&(n=Z.relative(r,n));var s=Z.toSetString(n);return Object.prototype.hasOwnProperty.call(this._sourcesContents,s)?this._sourcesContents[s]:null},this)};Ue.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return this._file!=null&&(e.file=this._file),this._sourceRoot!=null&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e};Ue.prototype.toString=function(){return JSON.stringify(this.toJSON())};Zg.SourceMapGenerator=Ue});var ey=j(en=>{en.GREATEST_LOWER_BOUND=1;en.LEAST_UPPER_BOUND=2;function Uf(t,e,r,n,s,o){var i=Math.floor((e-t)/2)+t,a=s(r,n[i],!0);return a===0?i:a>0?e-i>1?Uf(i,e,r,n,s,o):o==en.LEAST_UPPER_BOUND?e<n.length?e:-1:i:i-t>1?Uf(t,i,r,n,s,o):o==en.LEAST_UPPER_BOUND?i:t<0?-1:t}en.search=function(e,r,n,s){if(r.length===0)return-1;var o=Uf(-1,r.length,e,r,n,s||en.GREATEST_LOWER_BOUND);if(o<0)return-1;for(;o-1>=0&&n(r[o],r[o-1],!0)===0;)--o;return o}});var ry=j(ty=>{function $f(t,e,r){var n=t[e];t[e]=t[r],t[r]=n}function _0(t,e){return Math.round(t+Math.random()*(e-t))}function Hf(t,e,r,n){if(r<n){var s=_0(r,n),o=r-1;$f(t,s,n);for(var i=t[n],a=r;a<n;a++)e(t[a],i)<=0&&(o+=1,$f(t,o,a));$f(t,o+1,a);var c=o+1;Hf(t,e,r,c-1),Hf(t,e,c+1,n)}}ty.quickSort=function(t,e){Hf(t,e,0,t.length-1)}});var sy=j(Al=>{var O=Rs(),jf=ey(),Ts=Ff().ArraySet,S0=Lf(),ni=ry().quickSort;function G(t,e){var r=t;return typeof t=="string"&&(r=O.parseSourceMapInput(t)),r.sections!=null?new ze(r,e):new me(r,e)}G.fromSourceMap=function(t,e){return me.fromSourceMap(t,e)};G.prototype._version=3;G.prototype.__generatedMappings=null;Object.defineProperty(G.prototype,"_generatedMappings",{configurable:!0,enumerable:!0,get:function(){return this.__generatedMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__generatedMappings}});G.prototype.__originalMappings=null;Object.defineProperty(G.prototype,"_originalMappings",{configurable:!0,enumerable:!0,get:function(){return this.__originalMappings||this._parseMappings(this._mappings,this.sourceRoot),this.__originalMappings}});G.prototype._charIsMappingSeparator=function(e,r){var n=e.charAt(r);return n===";"||n===","};G.prototype._parseMappings=function(e,r){throw new Error("Subclasses must implement _parseMappings")};G.GENERATED_ORDER=1;G.ORIGINAL_ORDER=2;G.GREATEST_LOWER_BOUND=1;G.LEAST_UPPER_BOUND=2;G.prototype.eachMapping=function(e,r,n){var s=r||null,o=n||G.GENERATED_ORDER,i;switch(o){case G.GENERATED_ORDER:i=this._generatedMappings;break;case G.ORIGINAL_ORDER:i=this._originalMappings;break;default:throw new Error("Unknown order of iteration.")}var a=this.sourceRoot;i.map(function(c){var l=c.source===null?null:this._sources.at(c.source);return l=O.computeSourceURL(a,l,this._sourceMapURL),{source:l,generatedLine:c.generatedLine,generatedColumn:c.generatedColumn,originalLine:c.originalLine,originalColumn:c.originalColumn,name:c.name===null?null:this._names.at(c.name)}},this).forEach(e,s)};G.prototype.allGeneratedPositionsFor=function(e){var r=O.getArg(e,"line"),n={source:O.getArg(e,"source"),originalLine:r,originalColumn:O.getArg(e,"column",0)};if(n.source=this._findSourceIndex(n.source),n.source<0)return[];var s=[],o=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",O.compareByOriginalPositions,jf.LEAST_UPPER_BOUND);if(o>=0){var i=this._originalMappings[o];if(e.column===void 0)for(var a=i.originalLine;i&&i.originalLine===a;)s.push({line:O.getArg(i,"generatedLine",null),column:O.getArg(i,"generatedColumn",null),lastColumn:O.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o];else for(var c=i.originalColumn;i&&i.originalLine===r&&i.originalColumn==c;)s.push({line:O.getArg(i,"generatedLine",null),column:O.getArg(i,"generatedColumn",null),lastColumn:O.getArg(i,"lastGeneratedColumn",null)}),i=this._originalMappings[++o]}return s};Al.SourceMapConsumer=G;function me(t,e){var r=t;typeof t=="string"&&(r=O.parseSourceMapInput(t));var n=O.getArg(r,"version"),s=O.getArg(r,"sources"),o=O.getArg(r,"names",[]),i=O.getArg(r,"sourceRoot",null),a=O.getArg(r,"sourcesContent",null),c=O.getArg(r,"mappings"),l=O.getArg(r,"file",null);if(n!=this._version)throw new Error("Unsupported version: "+n);i&&(i=O.normalize(i)),s=s.map(String).map(O.normalize).map(function(f){return i&&O.isAbsolute(i)&&O.isAbsolute(f)?O.relative(i,f):f}),this._names=Ts.fromArray(o.map(String),!0),this._sources=Ts.fromArray(s,!0),this._absoluteSources=this._sources.toArray().map(function(f){return O.computeSourceURL(i,f,e)}),this.sourceRoot=i,this.sourcesContent=a,this._mappings=c,this._sourceMapURL=e,this.file=l}me.prototype=Object.create(G.prototype);me.prototype.consumer=G;me.prototype._findSourceIndex=function(t){var e=t;if(this.sourceRoot!=null&&(e=O.relative(this.sourceRoot,e)),this._sources.has(e))return this._sources.indexOf(e);var r;for(r=0;r<this._absoluteSources.length;++r)if(this._absoluteSources[r]==t)return r;return-1};me.fromSourceMap=function(e,r){var n=Object.create(me.prototype),s=n._names=Ts.fromArray(e._names.toArray(),!0),o=n._sources=Ts.fromArray(e._sources.toArray(),!0);n.sourceRoot=e._sourceRoot,n.sourcesContent=e._generateSourcesContent(n._sources.toArray(),n.sourceRoot),n.file=e._file,n._sourceMapURL=r,n._absoluteSources=n._sources.toArray().map(function(h){return O.computeSourceURL(n.sourceRoot,h,r)});for(var i=e._mappings.toArray().slice(),a=n.__generatedMappings=[],c=n.__originalMappings=[],l=0,f=i.length;l<f;l++){var u=i[l],d=new ny;d.generatedLine=u.generatedLine,d.generatedColumn=u.generatedColumn,u.source&&(d.source=o.indexOf(u.source),d.originalLine=u.originalLine,d.originalColumn=u.originalColumn,u.name&&(d.name=s.indexOf(u.name)),c.push(d)),a.push(d)}return ni(n.__originalMappings,O.compareByOriginalPositions),n};me.prototype._version=3;Object.defineProperty(me.prototype,"sources",{get:function(){return this._absoluteSources.slice()}});function ny(){this.generatedLine=0,this.generatedColumn=0,this.source=null,this.originalLine=null,this.originalColumn=null,this.name=null}me.prototype._parseMappings=function(e,r){for(var n=1,s=0,o=0,i=0,a=0,c=0,l=e.length,f=0,u={},d={},h=[],p=[],y,g,S,_,v;f<l;)if(e.charAt(f)===";")n++,f++,s=0;else if(e.charAt(f)===",")f++;else{for(y=new ny,y.generatedLine=n,_=f;_<l&&!this._charIsMappingSeparator(e,_);_++);if(g=e.slice(f,_),S=u[g],S)f+=g.length;else{for(S=[];f<_;)S0.decode(e,f,d),v=d.value,f=d.rest,S.push(v);if(S.length===2)throw new Error("Found a source, but no line and column");if(S.length===3)throw new Error("Found a source and line, but no column");u[g]=S}y.generatedColumn=s+S[0],s=y.generatedColumn,S.length>1&&(y.source=a+S[1],a+=S[1],y.originalLine=o+S[2],o=y.originalLine,y.originalLine+=1,y.originalColumn=i+S[3],i=y.originalColumn,S.length>4&&(y.name=c+S[4],c+=S[4])),p.push(y),typeof y.originalLine=="number"&&h.push(y)}ni(p,O.compareByGeneratedPositionsDeflated),this.__generatedMappings=p,ni(h,O.compareByOriginalPositions),this.__originalMappings=h};me.prototype._findMapping=function(e,r,n,s,o,i){if(e[n]<=0)throw new TypeError("Line must be greater than or equal to 1, got "+e[n]);if(e[s]<0)throw new TypeError("Column must be greater than or equal to 0, got "+e[s]);return jf.search(e,r,o,i)};me.prototype.computeColumnSpans=function(){for(var e=0;e<this._generatedMappings.length;++e){var r=this._generatedMappings[e];if(e+1<this._generatedMappings.length){var n=this._generatedMappings[e+1];if(r.generatedLine===n.generatedLine){r.lastGeneratedColumn=n.generatedColumn-1;continue}}r.lastGeneratedColumn=1/0}};me.prototype.originalPositionFor=function(e){var r={generatedLine:O.getArg(e,"line"),generatedColumn:O.getArg(e,"column")},n=this._findMapping(r,this._generatedMappings,"generatedLine","generatedColumn",O.compareByGeneratedPositionsDeflated,O.getArg(e,"bias",G.GREATEST_LOWER_BOUND));if(n>=0){var s=this._generatedMappings[n];if(s.generatedLine===r.generatedLine){var o=O.getArg(s,"source",null);o!==null&&(o=this._sources.at(o),o=O.computeSourceURL(this.sourceRoot,o,this._sourceMapURL));var i=O.getArg(s,"name",null);return i!==null&&(i=this._names.at(i)),{source:o,line:O.getArg(s,"originalLine",null),column:O.getArg(s,"originalColumn",null),name:i}}}return{source:null,line:null,column:null,name:null}};me.prototype.hasContentsOfAllSources=function(){return this.sourcesContent?this.sourcesContent.length>=this._sources.size()&&!this.sourcesContent.some(function(e){return e==null}):!1};me.prototype.sourceContentFor=function(e,r){if(!this.sourcesContent)return null;var n=this._findSourceIndex(e);if(n>=0)return this.sourcesContent[n];var s=e;this.sourceRoot!=null&&(s=O.relative(this.sourceRoot,s));var o;if(this.sourceRoot!=null&&(o=O.urlParse(this.sourceRoot))){var i=s.replace(/^file:\/\//,"");if(o.scheme=="file"&&this._sources.has(i))return this.sourcesContent[this._sources.indexOf(i)];if((!o.path||o.path=="/")&&this._sources.has("/"+s))return this.sourcesContent[this._sources.indexOf("/"+s)]}if(r)return null;throw new Error('"'+s+'" is not in the SourceMap.')};me.prototype.generatedPositionFor=function(e){var r=O.getArg(e,"source");if(r=this._findSourceIndex(r),r<0)return{line:null,column:null,lastColumn:null};var n={source:r,originalLine:O.getArg(e,"line"),originalColumn:O.getArg(e,"column")},s=this._findMapping(n,this._originalMappings,"originalLine","originalColumn",O.compareByOriginalPositions,O.getArg(e,"bias",G.GREATEST_LOWER_BOUND));if(s>=0){var o=this._originalMappings[s];if(o.source===n.source)return{line:O.getArg(o,"generatedLine",null),column:O.getArg(o,"generatedColumn",null),lastColumn:O.getArg(o,"lastGeneratedColumn",null)}}return{line:null,column:null,lastColumn:null}};Al.BasicSourceMapConsumer=me;function ze(t,e){var r=t;typeof t=="string"&&(r=O.parseSourceMapInput(t));var n=O.getArg(r,"version"),s=O.getArg(r,"sections");if(n!=this._version)throw new Error("Unsupported version: "+n);this._sources=new Ts,this._names=new Ts;var o={line:-1,column:0};this._sections=s.map(function(i){if(i.url)throw new Error("Support for url field in sections not implemented.");var a=O.getArg(i,"offset"),c=O.getArg(a,"line"),l=O.getArg(a,"column");if(c<o.line||c===o.line&&l<o.column)throw new Error("Section offsets must be ordered and non-overlapping.");return o=a,{generatedOffset:{generatedLine:c+1,generatedColumn:l+1},consumer:new G(O.getArg(i,"map"),e)}})}ze.prototype=Object.create(G.prototype);ze.prototype.constructor=G;ze.prototype._version=3;Object.defineProperty(ze.prototype,"sources",{get:function(){for(var t=[],e=0;e<this._sections.length;e++)for(var r=0;r<this._sections[e].consumer.sources.length;r++)t.push(this._sections[e].consumer.sources[r]);return t}});ze.prototype.originalPositionFor=function(e){var r={generatedLine:O.getArg(e,"line"),generatedColumn:O.getArg(e,"column")},n=jf.search(r,this._sections,function(o,i){var a=o.generatedLine-i.generatedOffset.generatedLine;return a||o.generatedColumn-i.generatedOffset.generatedColumn}),s=this._sections[n];return s?s.consumer.originalPositionFor({line:r.generatedLine-(s.generatedOffset.generatedLine-1),column:r.generatedColumn-(s.generatedOffset.generatedLine===r.generatedLine?s.generatedOffset.generatedColumn-1:0),bias:e.bias}):{source:null,line:null,column:null,name:null}};ze.prototype.hasContentsOfAllSources=function(){return this._sections.every(function(e){return e.consumer.hasContentsOfAllSources()})};ze.prototype.sourceContentFor=function(e,r){for(var n=0;n<this._sections.length;n++){var s=this._sections[n],o=s.consumer.sourceContentFor(e,!0);if(o)return o}if(r)return null;throw new Error('"'+e+'" is not in the SourceMap.')};ze.prototype.generatedPositionFor=function(e){for(var r=0;r<this._sections.length;r++){var n=this._sections[r];if(n.consumer._findSourceIndex(O.getArg(e,"source"))!==-1){var s=n.consumer.generatedPositionFor(e);if(s){var o={line:s.line+(n.generatedOffset.generatedLine-1),column:s.column+(n.generatedOffset.generatedLine===s.line?n.generatedOffset.generatedColumn-1:0)};return o}}}return{line:null,column:null}};ze.prototype._parseMappings=function(e,r){this.__generatedMappings=[],this.__originalMappings=[];for(var n=0;n<this._sections.length;n++)for(var s=this._sections[n],o=s.consumer._generatedMappings,i=0;i<o.length;i++){var a=o[i],c=s.consumer._sources.at(a.source);c=O.computeSourceURL(s.consumer.sourceRoot,c,this._sourceMapURL),this._sources.add(c),c=this._sources.indexOf(c);var l=null;a.name&&(l=s.consumer._names.at(a.name),this._names.add(l),l=this._names.indexOf(l));var f={source:c,generatedLine:a.generatedLine+(s.generatedOffset.generatedLine-1),generatedColumn:a.generatedColumn+(s.generatedOffset.generatedLine===a.generatedLine?s.generatedOffset.generatedColumn-1:0),originalLine:a.originalLine,originalColumn:a.originalColumn,name:l};this.__generatedMappings.push(f),typeof f.originalLine=="number"&&this.__originalMappings.push(f)}ni(this.__generatedMappings,O.compareByGeneratedPositionsDeflated),ni(this.__originalMappings,O.compareByOriginalPositions)};Al.IndexedSourceMapConsumer=ze});var iy=j(oy=>{var E0=qf().SourceMapGenerator,vl=Rs(),x0=/(\r?\n)/,A0=10,Is="$$$isSourceNode$$$";function ke(t,e,r,n,s){this.children=[],this.sourceContents={},this.line=t==null?null:t,this.column=e==null?null:e,this.source=r==null?null:r,this.name=s==null?null:s,this[Is]=!0,n!=null&&this.add(n)}ke.fromStringWithSourceMap=function(e,r,n){var s=new ke,o=e.split(x0),i=0,a=function(){var d=p(),h=p()||"";return d+h;function p(){return i<o.length?o[i++]:void 0}},c=1,l=0,f=null;return r.eachMapping(function(d){if(f!==null)if(c<d.generatedLine)u(f,a()),c++,l=0;else{var h=o[i]||"",p=h.substr(0,d.generatedColumn-l);o[i]=h.substr(d.generatedColumn-l),l=d.generatedColumn,u(f,p),f=d;return}for(;c<d.generatedLine;)s.add(a()),c++;if(l<d.generatedColumn){var h=o[i]||"";s.add(h.substr(0,d.generatedColumn)),o[i]=h.substr(d.generatedColumn),l=d.generatedColumn}f=d},this),i<o.length&&(f&&u(f,a()),s.add(o.splice(i).join(""))),r.sources.forEach(function(d){var h=r.sourceContentFor(d);h!=null&&(n!=null&&(d=vl.join(n,d)),s.setSourceContent(d,h))}),s;function u(d,h){if(d===null||d.source===void 0)s.add(h);else{var p=n?vl.join(n,d.source):d.source;s.add(new ke(d.originalLine,d.originalColumn,p,h,d.name))}}};ke.prototype.add=function(e){if(Array.isArray(e))e.forEach(function(r){this.add(r)},this);else if(e[Is]||typeof e=="string")e&&this.children.push(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};ke.prototype.prepend=function(e){if(Array.isArray(e))for(var r=e.length-1;r>=0;r--)this.prepend(e[r]);else if(e[Is]||typeof e=="string")this.children.unshift(e);else throw new TypeError("Expected a SourceNode, string, or an array of SourceNodes and strings. Got "+e);return this};ke.prototype.walk=function(e){for(var r,n=0,s=this.children.length;n<s;n++)r=this.children[n],r[Is]?r.walk(e):r!==""&&e(r,{source:this.source,line:this.line,column:this.column,name:this.name})};ke.prototype.join=function(e){var r,n,s=this.children.length;if(s>0){for(r=[],n=0;n<s-1;n++)r.push(this.children[n]),r.push(e);r.push(this.children[n]),this.children=r}return this};ke.prototype.replaceRight=function(e,r){var n=this.children[this.children.length-1];return n[Is]?n.replaceRight(e,r):typeof n=="string"?this.children[this.children.length-1]=n.replace(e,r):this.children.push("".replace(e,r)),this};ke.prototype.setSourceContent=function(e,r){this.sourceContents[vl.toSetString(e)]=r};ke.prototype.walkSourceContents=function(e){for(var r=0,n=this.children.length;r<n;r++)this.children[r][Is]&&this.children[r].walkSourceContents(e);for(var s=Object.keys(this.sourceContents),r=0,n=s.length;r<n;r++)e(vl.fromSetString(s[r]),this.sourceContents[s[r]])};ke.prototype.toString=function(){var e="";return this.walk(function(r){e+=r}),e};ke.prototype.toStringWithSourceMap=function(e){var r={code:"",line:1,column:0},n=new E0(e),s=!1,o=null,i=null,a=null,c=null;return this.walk(function(l,f){r.code+=l,f.source!==null&&f.line!==null&&f.column!==null?((o!==f.source||i!==f.line||a!==f.column||c!==f.name)&&n.addMapping({source:f.source,original:{line:f.line,column:f.column},generated:{line:r.line,column:r.column},name:f.name}),o=f.source,i=f.line,a=f.column,c=f.name,s=!0):s&&(n.addMapping({generated:{line:r.line,column:r.column}}),o=null,s=!1);for(var u=0,d=l.length;u<d;u++)l.charCodeAt(u)===A0?(r.line++,r.column=0,u+1===d?(o=null,s=!1):s&&n.addMapping({source:f.source,original:{line:f.line,column:f.column},generated:{line:r.line,column:r.column},name:f.name})):r.column++}),this.walkSourceContents(function(l,f){n.setSourceContent(l,f)}),{code:r.code,map:n}};oy.SourceNode=ke});var ay=j(Cl=>{Cl.SourceMapGenerator=qf().SourceMapGenerator;Cl.SourceMapConsumer=sy().SourceMapConsumer;Cl.SourceNode=iy().SourceNode});var fy=j((Pl,uy)=>{"use strict";Pl.__esModule=!0;var Vf=Se(),tn=void 0;try{(typeof define!="function"||!define.amd)&&(ly=ay(),tn=ly.SourceNode)}catch(t){}var ly;tn||(tn=function(t,e,r,n){this.src="",n&&this.add(n)},tn.prototype={add:function(e){Vf.isArray(e)&&(e=e.join("")),this.src+=e},prepend:function(e){Vf.isArray(e)&&(e=e.join("")),this.src=e+this.src},toStringWithSourceMap:function(){return{code:this.toString()}},toString:function(){return this.src}});function Wf(t,e,r){if(Vf.isArray(t)){for(var n=[],s=0,o=t.length;s<o;s++)n.push(e.wrap(t[s],r));return n}else if(typeof t=="boolean"||typeof t=="number")return t+"";return t}function cy(t){this.srcFile=t,this.source=[]}cy.prototype={isEmpty:function(){return!this.source.length},prepend:function(e,r){this.source.unshift(this.wrap(e,r))},push:function(e,r){this.source.push(this.wrap(e,r))},merge:function(){var e=this.empty();return this.each(function(r){e.add([" ",r,`
`])}),e},each:function(e){for(var r=0,n=this.source.length;r<n;r++)e(this.source[r])},empty:function(){var e=this.currentLocation||{start:{}};return new tn(e.start.line,e.start.column,this.srcFile)},wrap:function(e){var r=arguments.length<=1||arguments[1]===void 0?this.currentLocation||{start:{}}:arguments[1];return e instanceof tn?e:(e=Wf(e,this,r),new tn(r.start.line,r.start.column,this.srcFile,e))},functionCall:function(e,r,n){return n=this.generateList(n),this.wrap([e,r?"."+r+"(":"(",n,")"])},quotedString:function(e){return'"'+(e+"").replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/\n/g,"\\n").replace(/\r/g,"\\r").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")+'"'},objectLiteral:function(e){var r=this,n=[];Object.keys(e).forEach(function(o){var i=Wf(e[o],r);i!=="undefined"&&n.push([r.quotedString(o),":",i])});var s=this.generateList(n);return s.prepend("{"),s.add("}"),s},generateList:function(e){for(var r=this.empty(),n=0,s=e.length;n<s;n++)n&&r.add(","),r.add(Wf(e[n],this));return r},generateArray:function(e){var r=this.generateList(e);return r.prepend("["),r.add("]"),r}};Pl.default=cy;uy.exports=Pl.default});var gy=j((Rl,my)=>{"use strict";Rl.__esModule=!0;function py(t){return t&&t.__esModule?t:{default:t}}var dy=ul(),v0=Fe(),Kf=py(v0),C0=Se(),P0=fy(),hy=py(P0);function ks(t){this.value=t}function Os(){}Os.prototype={nameLookup:function(e,r){return this.internalNameLookup(e,r)},depthedLookup:function(e){return[this.aliasable("container.lookup"),"(depths, ",JSON.stringify(e),")"]},compilerInfo:function(){var e=dy.COMPILER_REVISION,r=dy.REVISION_CHANGES[e];return[e,r]},appendToBuffer:function(e,r,n){return C0.isArray(e)||(e=[e]),e=this.source.wrap(e,r),this.environment.isSimple?["return ",e,";"]:n?["buffer += ",e,";"]:(e.appendToBuffer=!0,e)},initializeBuffer:function(){return this.quotedString("")},internalNameLookup:function(e,r){return this.lookupPropertyFunctionIsUsed=!0,["lookupProperty(",e,",",JSON.stringify(r),")"]},lookupPropertyFunctionIsUsed:!1,compile:function(e,r,n,s){this.environment=e,this.options=r,this.stringParams=this.options.stringParams,this.trackIds=this.options.trackIds,this.precompile=!s,this.name=this.environment.name,this.isChild=!!n,this.context=n||{decorators:[],programs:[],environments:[]},this.preamble(),this.stackSlot=0,this.stackVars=[],this.aliases={},this.registers={list:[]},this.hashes=[],this.compileStack=[],this.inlineStack=[],this.blockParams=[],this.compileChildren(e,r),this.useDepths=this.useDepths||e.useDepths||e.useDecorators||this.options.compat,this.useBlockParams=this.useBlockParams||e.useBlockParams;var o=e.opcodes,i=void 0,a=void 0,c=void 0,l=void 0;for(c=0,l=o.length;c<l;c++)i=o[c],this.source.currentLocation=i.loc,a=a||i.loc,this[i.opcode].apply(this,i.args);if(this.source.currentLocation=a,this.pushSource(""),this.stackSlot||this.inlineStack.length||this.compileStack.length)throw new Kf.default("Compile completed with content left on stack");this.decorators.isEmpty()?this.decorators=void 0:(this.useDecorators=!0,this.decorators.prepend(["var decorators = container.decorators, ",this.lookupPropertyFunctionVarDeclaration(),`;
`]),this.decorators.push("return fn;"),s?this.decorators=Function.apply(this,["fn","props","container","depth0","data","blockParams","depths",this.decorators.merge()]):(this.decorators.prepend(`function(fn, props, container, depth0, data, blockParams, depths) {
`),this.decorators.push(`}
`),this.decorators=this.decorators.merge()));var f=this.createFunctionContext(s);if(this.isChild)return f;var u={compiler:this.compilerInfo(),main:f};this.decorators&&(u.main_d=this.decorators,u.useDecorators=!0);var d=this.context,h=d.programs,p=d.decorators;for(c=0,l=h.length;c<l;c++)h[c]&&(u[c]=h[c],p[c]&&(u[c+"_d"]=p[c],u.useDecorators=!0));return this.environment.usePartial&&(u.usePartial=!0),this.options.data&&(u.useData=!0),this.useDepths&&(u.useDepths=!0),this.useBlockParams&&(u.useBlockParams=!0),this.options.compat&&(u.compat=!0),s?u.compilerOptions=this.options:(u.compiler=JSON.stringify(u.compiler),this.source.currentLocation={start:{line:1,column:0}},u=this.objectLiteral(u),r.srcName?(u=u.toStringWithSourceMap({file:r.destName}),u.map=u.map&&u.map.toString()):u=u.toString()),u},preamble:function(){this.lastContext=0,this.source=new hy.default(this.options.srcName),this.decorators=new hy.default(this.options.srcName)},createFunctionContext:function(e){var r=this,n="",s=this.stackVars.concat(this.registers.list);s.length>0&&(n+=", "+s.join(", "));var o=0;Object.keys(this.aliases).forEach(function(c){var l=r.aliases[c];l.children&&l.referenceCount>1&&(n+=", alias"+ ++o+"="+c,l.children[0]="alias"+o)}),this.lookupPropertyFunctionIsUsed&&(n+=", "+this.lookupPropertyFunctionVarDeclaration());var i=["container","depth0","helpers","partials","data"];(this.useBlockParams||this.useDepths)&&i.push("blockParams"),this.useDepths&&i.push("depths");var a=this.mergeSource(n);return e?(i.push(a),Function.apply(this,i)):this.source.wrap(["function(",i.join(","),`) {
`,a,"}"])},mergeSource:function(e){var r=this.environment.isSimple,n=!this.forceBuffer,s=void 0,o=void 0,i=void 0,a=void 0;return this.source.each(function(c){c.appendToBuffer?(i?c.prepend(" + "):i=c,a=c):(i&&(o?i.prepend("buffer += "):s=!0,a.add(";"),i=a=void 0),o=!0,r||(n=!1))}),n?i?(i.prepend("return "),a.add(";")):o||this.source.push('return "";'):(e+=", buffer = "+(s?"":this.initializeBuffer()),i?(i.prepend("return buffer + "),a.add(";")):this.source.push("return buffer;")),e&&this.source.prepend("var "+e.substring(2)+(s?"":`;
`)),this.source.merge()},lookupPropertyFunctionVarDeclaration:function(){return`
lookupProperty = container.lookupProperty || function(parent, propertyName) {
if (Object.prototype.hasOwnProperty.call(parent, propertyName)) {
return parent[propertyName];
}
return undefined
}
`.trim()},blockValue:function(e){var r=this.aliasable("container.hooks.blockHelperMissing"),n=[this.contextName(0)];this.setupHelperArgs(e,0,n);var s=this.popStack();n.splice(1,0,s),this.push(this.source.functionCall(r,"call",n))},ambiguousBlockValue:function(){var e=this.aliasable("container.hooks.blockHelperMissing"),r=[this.contextName(0)];this.setupHelperArgs("",0,r,!0),this.flushInline();var n=this.topStack();r.splice(1,0,n),this.pushSource(["if (!",this.lastHelper,") { ",n," = ",this.source.functionCall(e,"call",r),"}"])},appendContent:function(e){this.pendingContent?e=this.pendingContent+e:this.pendingLocation=this.source.currentLocation,this.pendingContent=e},append:function(){if(this.isInline())this.replaceStack(function(r){return[" != null ? ",r,' : ""']}),this.pushSource(this.appendToBuffer(this.popStack()));else{var e=this.popStack();this.pushSource(["if (",e," != null) { ",this.appendToBuffer(e,void 0,!0)," }"]),this.environment.isSimple&&this.pushSource(["else { ",this.appendToBuffer("''",void 0,!0)," }"])}},appendEscaped:function(){this.pushSource(this.appendToBuffer([this.aliasable("container.escapeExpression"),"(",this.popStack(),")"]))},getContext:function(e){this.lastContext=e},pushContext:function(){this.pushStackLiteral(this.contextName(this.lastContext))},lookupOnContext:function(e,r,n,s){var o=0;!s&&this.options.compat&&!this.lastContext?this.push(this.depthedLookup(e[o++])):this.pushContext(),this.resolvePath("context",e,o,r,n)},lookupBlockParam:function(e,r){this.useBlockParams=!0,this.push(["blockParams[",e[0],"][",e[1],"]"]),this.resolvePath("context",r,1)},lookupData:function(e,r,n){e?this.pushStackLiteral("container.data(data, "+e+")"):this.pushStackLiteral("data"),this.resolvePath("data",r,0,!0,n)},resolvePath:function(e,r,n,s,o){var i=this;if(this.options.strict||this.options.assumeObjects){this.push(R0(this.options.strict&&o,this,r,n,e));return}for(var a=r.length;n<a;n++)this.replaceStack(function(c){var l=i.nameLookup(c,r[n],e);return s?[" && ",l]:[" != null ? ",l," : ",c]})},resolvePossibleLambda:function(){this.push([this.aliasable("container.lambda"),"(",this.popStack(),", ",this.contextName(0),")"])},pushStringParam:function(e,r){this.pushContext(),this.pushString(r),r!=="SubExpression"&&(typeof e=="string"?this.pushString(e):this.pushStackLiteral(e))},emptyHash:function(e){this.trackIds&&this.push("{}"),this.stringParams&&(this.push("{}"),this.push("{}")),this.pushStackLiteral(e?"undefined":"{}")},pushHash:function(){this.hash&&this.hashes.push(this.hash),this.hash={values:{},types:[],contexts:[],ids:[]}},popHash:function(){var e=this.hash;this.hash=this.hashes.pop(),this.trackIds&&this.push(this.objectLiteral(e.ids)),this.stringParams&&(this.push(this.objectLiteral(e.contexts)),this.push(this.objectLiteral(e.types))),this.push(this.objectLiteral(e.values))},pushString:function(e){this.pushStackLiteral(this.quotedString(e))},pushLiteral:function(e){this.pushStackLiteral(e)},pushProgram:function(e){e!=null?this.pushStackLiteral(this.programExpression(e)):this.pushStackLiteral(null)},registerDecorator:function(e,r){var n=this.nameLookup("decorators",r,"decorator"),s=this.setupHelperArgs(r,e);this.decorators.push(["fn = ",this.decorators.functionCall(n,"",["fn","props","container",s])," || fn;"])},invokeHelper:function(e,r,n){var s=this.popStack(),o=this.setupHelper(e,r),i=[];n&&i.push(o.name),i.push(s),this.options.strict||i.push(this.aliasable("container.hooks.helperMissing"));var a=["(",this.itemsSeparatedBy(i,"||"),")"],c=this.source.functionCall(a,"call",o.callParams);this.push(c)},itemsSeparatedBy:function(e,r){var n=[];n.push(e[0]);for(var s=1;s<e.length;s++)n.push(r,e[s]);return n},invokeKnownHelper:function(e,r){var n=this.setupHelper(e,r);this.push(this.source.functionCall(n.name,"call",n.callParams))},invokeAmbiguous:function(e,r){this.useRegister("helper");var n=this.popStack();this.emptyHash();var s=this.setupHelper(0,e,r),o=this.lastHelper=this.nameLookup("helpers",e,"helper"),i=["(","(helper = ",o," || ",n,")"];this.options.strict||(i[0]="(helper = ",i.push(" != null ? helper : ",this.aliasable("container.hooks.helperMissing"))),this.push(["(",i,s.paramsInit?["),(",s.paramsInit]:[],"),","(typeof helper === ",this.aliasable('"function"')," ? ",this.source.functionCall("helper","call",s.callParams)," : helper))"])},invokePartial:function(e,r,n){var s=[],o=this.setupParams(r,1,s);e&&(r=this.popStack(),delete o.name),n&&(o.indent=JSON.stringify(n)),o.helpers="helpers",o.partials="partials",o.decorators="container.decorators",e?s.unshift(r):s.unshift(this.nameLookup("partials",r,"partial")),this.options.compat&&(o.depths="depths"),o=this.objectLiteral(o),s.push(o),this.push(this.source.functionCall("container.invokePartial","",s))},assignToHash:function(e){var r=this.popStack(),n=void 0,s=void 0,o=void 0;this.trackIds&&(o=this.popStack()),this.stringParams&&(s=this.popStack(),n=this.popStack());var i=this.hash;n&&(i.contexts[e]=n),s&&(i.types[e]=s),o&&(i.ids[e]=o),i.values[e]=r},pushId:function(e,r,n){e==="BlockParam"?this.pushStackLiteral("blockParams["+r[0]+"].path["+r[1]+"]"+(n?" + "+JSON.stringify("."+n):"")):e==="PathExpression"?this.pushString(r):e==="SubExpression"?this.pushStackLiteral("true"):this.pushStackLiteral("null")},compiler:Os,compileChildren:function(e,r){for(var n=e.children,s=void 0,o=void 0,i=0,a=n.length;i<a;i++){s=n[i],o=new this.compiler;var c=this.matchExistingProgram(s);if(c==null){this.context.programs.push("");var l=this.context.programs.length;s.index=l,s.name="program"+l,this.context.programs[l]=o.compile(s,r,this.context,!this.precompile),this.context.decorators[l]=o.decorators,this.context.environments[l]=s,this.useDepths=this.useDepths||o.useDepths,this.useBlockParams=this.useBlockParams||o.useBlockParams,s.useDepths=this.useDepths,s.useBlockParams=this.useBlockParams}else s.index=c.index,s.name="program"+c.index,this.useDepths=this.useDepths||c.useDepths,this.useBlockParams=this.useBlockParams||c.useBlockParams}},matchExistingProgram:function(e){for(var r=0,n=this.context.environments.length;r<n;r++){var s=this.context.environments[r];if(s&&s.equals(e))return s}},programExpression:function(e){var r=this.environment.children[e],n=[r.index,"data",r.blockParams];return(this.useBlockParams||this.useDepths)&&n.push("blockParams"),this.useDepths&&n.push("depths"),"container.program("+n.join(", ")+")"},useRegister:function(e){this.registers[e]||(this.registers[e]=!0,this.registers.list.push(e))},push:function(e){return e instanceof ks||(e=this.source.wrap(e)),this.inlineStack.push(e),e},pushStackLiteral:function(e){this.push(new ks(e))},pushSource:function(e){this.pendingContent&&(this.source.push(this.appendToBuffer(this.source.quotedString(this.pendingContent),this.pendingLocation)),this.pendingContent=void 0),e&&this.source.push(e)},replaceStack:function(e){var r=["("],n=void 0,s=void 0,o=void 0;if(!this.isInline())throw new Kf.default("replaceStack on non-inline");var i=this.popStack(!0);if(i instanceof ks)n=[i.value],r=["(",n],o=!0;else{s=!0;var a=this.incrStack();r=["((",this.push(a)," = ",i,")"],n=this.topStack()}var c=e.call(this,n);o||this.popStack(),s&&this.stackSlot--,this.push(r.concat(c,")"))},incrStack:function(){return this.stackSlot++,this.stackSlot>this.stackVars.length&&this.stackVars.push("stack"+this.stackSlot),this.topStackName()},topStackName:function(){return"stack"+this.stackSlot},flushInline:function(){var e=this.inlineStack;this.inlineStack=[];for(var r=0,n=e.length;r<n;r++){var s=e[r];if(s instanceof ks)this.compileStack.push(s);else{var o=this.incrStack();this.pushSource([o," = ",s,";"]),this.compileStack.push(o)}}},isInline:function(){return this.inlineStack.length},popStack:function(e){var r=this.isInline(),n=(r?this.inlineStack:this.compileStack).pop();if(!e&&n instanceof ks)return n.value;if(!r){if(!this.stackSlot)throw new Kf.default("Invalid stack pop");this.stackSlot--}return n},topStack:function(){var e=this.isInline()?this.inlineStack:this.compileStack,r=e[e.length-1];return r instanceof ks?r.value:r},contextName:function(e){return this.useDepths&&e?"depths["+e+"]":"depth"+e},quotedString:function(e){return this.source.quotedString(e)},objectLiteral:function(e){return this.source.objectLiteral(e)},aliasable:function(e){var r=this.aliases[e];return r?(r.referenceCount++,r):(r=this.aliases[e]=this.source.wrap(e),r.aliasable=!0,r.referenceCount=1,r)},setupHelper:function(e,r,n){var s=[],o=this.setupHelperArgs(r,e,s,n),i=this.nameLookup("helpers",r,"helper"),a=this.aliasable(this.contextName(0)+" != null ? "+this.contextName(0)+" : (container.nullContext || {})");return{params:s,paramsInit:o,name:i,callParams:[a].concat(s)}},setupParams:function(e,r,n){var s={},o=[],i=[],a=[],c=!n,l=void 0;c&&(n=[]),s.name=this.quotedString(e),s.hash=this.popStack(),this.trackIds&&(s.hashIds=this.popStack()),this.stringParams&&(s.hashTypes=this.popStack(),s.hashContexts=this.popStack());var f=this.popStack(),u=this.popStack();(u||f)&&(s.fn=u||"container.noop",s.inverse=f||"container.noop");for(var d=r;d--;)l=this.popStack(),n[d]=l,this.trackIds&&(a[d]=this.popStack()),this.stringParams&&(i[d]=this.popStack(),o[d]=this.popStack());return c&&(s.args=this.source.generateArray(n)),this.trackIds&&(s.ids=this.source.generateArray(a)),this.stringParams&&(s.types=this.source.generateArray(i),s.contexts=this.source.generateArray(o)),this.options.data&&(s.data="data"),this.useBlockParams&&(s.blockParams="blockParams"),s},setupHelperArgs:function(e,r,n,s){var o=this.setupParams(e,r,n);return o.loc=JSON.stringify(this.source.currentLocation),o=this.objectLiteral(o),s?(this.useRegister("options"),n.push("options"),["options=",o]):n?(n.push(o),""):o}};(function(){for(var t="break else new var case finally return void catch for switch while continue function this with default if throw delete in try do instanceof typeof abstract enum int short boolean export interface static byte extends long super char final native synchronized class float package throws const goto private transient debugger implements protected volatile double import public let yield await null true false".split(" "),e=Os.RESERVED_WORDS={},r=0,n=t.length;r<n;r++)e[t[r]]=!0})();Os.isValidJavaScriptVariableName=function(t){return!Os.RESERVED_WORDS[t]&&/^[a-zA-Z_$][0-9a-zA-Z_$]*$/.test(t)};function R0(t,e,r,n,s){var o=e.popStack(),i=r.length;for(t&&i--;n<i;n++)o=e.nameLookup(o,r[n],s);return t?[e.aliasable("container.strict"),"(",o,", ",e.quotedString(r[n]),", ",JSON.stringify(e.source.currentLocation)," )"]:o}Rl.default=Os;my.exports=Rl.default});var wy=j((Tl,by)=>{"use strict";Tl.__esModule=!0;function si(t){return t&&t.__esModule?t:{default:t}}var T0=_g(),I0=si(T0),k0=Ef(),O0=si(k0),Gf=Mg(),Jf=Bg(),M0=gy(),L0=si(M0),N0=Af(),D0=si(N0),B0=bf(),F0=si(B0),q0=I0.default.create;function yy(){var t=q0();return t.compile=function(e,r){return Jf.compile(e,r,t)},t.precompile=function(e,r){return Jf.precompile(e,r,t)},t.AST=O0.default,t.Compiler=Jf.Compiler,t.JavaScriptCompiler=L0.default,t.Parser=Gf.parser,t.parse=Gf.parse,t.parseWithoutProcessing=Gf.parseWithoutProcessing,t}var Ms=yy();Ms.create=yy;F0.default(Ms);Ms.Visitor=D0.default;Ms.default=Ms;Tl.default=Ms;by.exports=Tl.default});var G0={};rd(G0,{default:()=>Nl});module.exports=My(G0);var Bt=require("obsidian");var Je=require("obsidian");var Ot=require("obsidian");var Dl={Error:"Error",user:"user",system:"system",assistant:"assistant",newChat:"newChat","Conversion failed. Selected sections is a":"Conversion failed. Selected sections is a",message:"message","Check the developer console for error details. ":"Check the developer console for error details. ","Cancel generation":"Cancel generation","Regenerate?":"Regenerate?","This will delete the current response content. You can configure this in settings to not require confirmation.":"This will delete the current response content. You can configure this in settings to not require confirmation.",Yes:"Yes","Export conversations to JSONL":"Export conversations to JSONL","No conversation found":"No conversation found","Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software.":"Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software.","Replace speaker with tag":"Replace speaker with tag","No speaker found":"No speaker found","Replace the names of the two most frequently occurring speakers with tag format.":"Replace the names of the two most frequently occurring speakers with tag format.",Replace:"Replace","Select message at cursor":"Select message at cursor","No message found at cursor":"No message found at cursor","API key is required":"API key is required","API secret is required":"API secret is required","Model is required":"Model is required","API URL is required":"API URL is required","API key may be incorrect. Please check your API key.":"API key may be incorrect. Please check your API key.","Access denied. Please check your API permissions.":"Access denied. Please check your API permissions.","Text Generation":"Text Generation","Image Vision":"Image Vision","PDF Vision":"PDF Vision","Image Generation":"Image Generation","Image Editing":"Image Editing","Web Search":"Web Search",Reasoning:"Reasoning","Only PNG, JPEG, GIF, and WebP images are supported.":"Only PNG, JPEG, GIF, and WebP images are supported.","Only PNG, JPEG, GIF, WebP, and PDF files are supported.":"Only PNG, JPEG, GIF, WebP, and PDF files are supported.","Only the last user message is used for image generation. Other messages are ignored.":"Only the last user message is used for image generation. Other messages are ignored.","Multiple embeds found, only the first one will be used":"Multiple embeds found, only the first one will be used","Only PNG, JPEG, and WebP images are supported for editing.":"Only PNG, JPEG, and WebP images are supported for editing.","Embed data is empty or invalid":"Embed data is empty or invalid","Failed to generate image. no data received from API":"Failed to generate image. no data received from API","Load template file: ":"Load template file: ","Templates have been updated: ":"Templates have been updated: ","Syntax Error Report":"Syntax Error Report","Create prompt template file":"Create prompt template file","Expected at least 2 sections, heading and content":"Expected at least 2 sections, heading and content","Expected heading":"Expected heading","Duplicate title:":"Duplicate title:","Please add a user message first, or wait for the user message to be parsed.":"Please add a user message first, or wait for the user message to be parsed.","Waiting for metadata to be ready. Please try again.":"Waiting for metadata to be ready. Please try again.","No text generated":"No text generated",characters:"characters","Removed commands":"Removed commands","Added commands":"Added commands","No active generation to cancel":"No active generation to cancel","Generation already cancelled":"Generation already cancelled","Generation cancelled":"Generation cancelled","Restore default":"Restore default","AI assistants":"AI assistants","New AI assistant":"New AI assistant","For those compatible with the OpenAI protocol, you can select OpenAI.":"For those compatible with the OpenAI protocol, you can select OpenAI.","Add AI Provider":"Add AI Provider","Please add at least one AI assistant to start using the plugin.":"Please add at least one AI assistant to start using the plugin.","Message tags":"Message tags","Keywords for tags in the text box are separated by spaces":"Keywords for tags in the text box are separated by spaces","New chat tags":"New chat tags","User message tags":"User message tags","System message tags":"System message tags","At least one tag is required":"At least one tag is required","Assistant message tag":"Assistant message tag","Tag used to trigger AI text generation":"Tag used to trigger AI text generation","Obtain key from ":"Obtain key from ","Web search":"Web search","Enable web search for AI":"Enable web search for AI","Enter your key":"Enter your key","Default:":"Default:","Refer to the technical documentation":"Refer to the technical documentation","Keyword for tag must not contain #":"Keyword for tag must not contain #","Keyword for tag must not contain space":"Keyword for tag must not contain space","Keyword for tag must be unique":"Keyword for tag must be unique",Model:"Model","Supported features":"Supported features","Select the model to use":"Select the model to use","Please input API key first":"Please input API key first","Please enter a number":"Please enter a number","Minimum value is 256":"Minimum value is 256","Invalid URL":"Invalid URL","Override input parameters":"Override input parameters",'Developer feature, in JSON format. For example, if the model list doesn\'t have the model you want, enter {"model": "your desired model"}':`Developer feature, in JSON format. For example, if the model list doesn't have the model you want, enter {"model": "your desired model"}`,"Remove AI assistant":"Remove AI assistant",Remove:"Remove",Endpoint:"Endpoint","API version":"API version","Select assistant":"Select assistant","Confirm before regeneration":"Confirm before regeneration","Confirm before replacing existing assistant responses when using assistant commands":"Confirm before replacing existing assistant responses when using assistant commands","Internal links":"Internal links","Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.":"Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.","Internal links for assistant messages":"Internal links for assistant messages","Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.":"Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.","System message":"System message","Enable default system message":"Enable default system message","Automatically add a system message when none exists in the conversation":"Automatically add a system message when none exists in the conversation","Default system message":"Default system message",Advanced:"Advanced","Delay before answer (Seconds)":"Delay before answer (Seconds)","If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.":"If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.","Replace tag Command":"Replace tag Command","Export to JSONL Command":"Export to JSONL Command","Tag suggest":"Tag suggest","If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.":"If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.","Image Display Width":"Image Display Width","Example: 400px width would output as ![[image.jpg|400]]":"Example: 400px width would output as ![[image.jpg|400]]","Number of images":"Number of images","Number of images to generate (1-5)":"Number of images to generate (1-5)","Image size":"Image size",landscape:"landscape",portrait:"portrait","Output format":"Output format",Quality:"Quality","Quality level for generated images. default: Auto":"Quality level for generated images. default: Auto",Auto:"Auto",High:"High",Medium:"Medium",Low:"Low",Background:"Background","Background of the generated image. default: Auto":"Background of the generated image. default: Auto",Transparent:"Transparent",Opaque:"Opaque","Output compression":"Output compression","Compression level of the output image, 10% - 100%. Only for webp or jpeg output format":"Compression level of the output image, 10% - 100%. Only for webp or jpeg output format","AI generate":"AI generate","Text generated successfully":"Text generated successfully","This is a non-streaming request, please wait...":"This is a non-streaming request, please wait...",promptFileName:"prompt.en",PRESET_PROMPT_TEMPLATES:`# Instructions
- Collect your commonly used prompts here for use with the Tars plugin commands.
- This file follows Obsidian's slide format, using \`---\` to separate each page.
- The first page contains instructions, and each subsequent page is a prompt template.
- Each template starts with a title in Markdown heading format, titles cannot be repeated. This is followed by the template content. Both title and content are required.
- If the content contains \`{{s}}\`, it will be replaced with your selected text.
- If there's no \`{{s}}\`, the selected text will be appended.
- If no text is selected, the template content will be used as is.
- If a page contains syntax errors, it won't appear in the command list.
- If you've edited this file, to load the updated templates into commands, please ==run the 'Load template file' command==, which will also check for syntax errors and display them in a popup.
---
# Prompt example
Tell me a joke
---
# Translation
Translate the following content into English\uFF1A{{s}}
---
# One-sentence summary
{{s}} Summarize the above content in one sentence
`,Thinking:"Thinking","When enabled, Claude will show its reasoning process before giving the final answer.":"When enabled, Claude will show its reasoning process before giving the final answer.","Budget tokens for thinking":"Budget tokens for thinking","Must be \u22651024 and less than max_tokens":"Must be \u22651024 and less than max_tokens","Minimum value is 1024":"Minimum value is 1024","AI Generation Details":"AI Generation Details",Round:"Round",Duration:"Duration","Start Time":"Start Time","End Time":"End Time","Error Details":"Error Details","Error Type":"Error Type","Error Message":"Error Message","Occurrence Time":"Occurrence Time","Stack Trace":"Stack Trace","Copy Error Info":"Copy Error Info","Error info copied to clipboard":"Error info copied to clipboard","Unknown Error":"Unknown Error","Tars AI assistant is ready":"Tars AI assistant is ready","Generating round":"Generating round","answer...":"answer...","Generating...":"Generating...","Click status bar for error details. ":"Click status bar for error details. ",Vendor:"Vendor",Characters:"Characters"};var sd={Error:"\u5F02\u5E38",user:"\u7528\u6237",system:"\u7CFB\u7EDF",assistant:"\u52A9\u624B",newChat:"\u65B0\u5BF9\u8BDD","Conversion failed. Selected sections is a":"\u8F6C\u6362\u5931\u8D25\u3002\u9009\u4E2D\u7684\u6BB5\u843D\u662F",message:"\u6D88\u606F","Check the developer console for error details. ":"\u67E5\u770B\u5F00\u53D1\u8005\u63A7\u5236\u53F0\u4E86\u89E3\u9519\u8BEF\u8BE6\u60C5\u3002","Cancel generation":"\u53D6\u6D88\u751F\u6210","Regenerate?":"\u91CD\u65B0\u751F\u6210?","This will delete the current response content. You can configure this in settings to not require confirmation.":"\u8FD9\u4F1A\u5220\u6389\u5F53\u524D\u7684\u56DE\u7B54\u5185\u5BB9\u3002\u4F60\u53EF\u4EE5\u5728\u8BBE\u7F6E\u91CC\u914D\u7F6E\u4E0D\u9700\u8981\u5F39\u7A97\u786E\u8BA4\u3002",Yes:"\u662F","Export conversations to JSONL":"\u5BFC\u51FA\u5BF9\u8BDD\u5230 JSONL","No conversation found":"\u6CA1\u6709\u627E\u5230\u5BF9\u8BDD","Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software.":"\u5DF2\u7ECF\u5BFC\u51FA\u5230\u540C\u4E00\u76EE\u5F55\uFF0Cobsidian \u4E0D\u663E\u793A jsonl \u683C\u5F0F\uFF0C\u8BF7\u7528\u5176\u4ED6\u8F6F\u4EF6\u6253\u5F00","Replace speaker with tag":"\u628A\u8BF4\u8BDD\u8005\u66FF\u6362\u4E3A\u6807\u7B7E","No speaker found":"\u6CA1\u6709\u627E\u5230\u8BF4\u8BDD\u8005","Replace the names of the two most frequently occurring speakers with tag format.":"\u7528\u6807\u7B7E\u683C\u5F0F\u66FF\u6362\u4E24\u4E2A\u6700\u5E38\u51FA\u73B0\u7684\u8BF4\u8BDD\u8005\u7684\u540D\u5B57",Replace:"\u66FF\u6362","Select message at cursor":"\u9009\u62E9\u5149\u6807\u5904\u7684\u6D88\u606F","No message found at cursor":"\u5149\u6807\u5904\u6CA1\u6709\u627E\u5230\u6D88\u606F","API key is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684 API key","API secret is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684 API secret","Model is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684\u6A21\u578B","API URL is required":"\u8BF7\u914D\u7F6E\u5BF9\u5E94\u7684 API URL","API key may be incorrect. Please check your API key.":"API key \u53EF\u80FD\u4E0D\u6B63\u786E\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684 API key\u3002","Access denied. Please check your API permissions.":"\u8BBF\u95EE\u88AB\u62D2\u7EDD\uFF0C\u8BF7\u68C0\u67E5\u60A8\u7684 API \u6743\u9650\u3002","Text Generation":"\u6587\u672C\u751F\u6210","Image Vision":"\u56FE\u50CF\u89C6\u89C9","PDF Vision":"PDF\u89C6\u89C9","Image Generation":"\u56FE\u50CF\u751F\u6210","Image Editing":"\u56FE\u50CF\u7F16\u8F91","Web Search":"\u7F51\u7EDC\u641C\u7D22",Reasoning:"\u63A8\u7406","Only PNG, JPEG, GIF, and WebP images are supported.":"\u4EC5\u652F\u6301 PNG\u3001JPEG\u3001GIF \u548C WebP \u683C\u5F0F\u7684\u56FE\u7247\u3002","Only PNG, JPEG, GIF, WebP, and PDF files are supported.":"\u4EC5\u652F\u6301 PNG\u3001JPEG\u3001GIF\u3001WebP \u548C PDF \u6587\u4EF6\u3002","Only the last user message is used for image generation. Other messages are ignored.":"\u4EC5\u4F7F\u7528\u6700\u540E\u4E00\u6761\u7528\u6237\u6D88\u606F\u8FDB\u884C\u56FE\u7247\u751F\u6210\uFF0C\u5176\u4ED6\u6D88\u606F\u5C06\u88AB\u5FFD\u7565\u3002","Multiple embeds found, only the first one will be used":"\u53D1\u73B0\u591A\u4E2A\u5D4C\u5165\u5185\u5BB9\uFF0C\u4EC5\u4F7F\u7528\u7B2C\u4E00\u4E2A","Only PNG, JPEG, and WebP images are supported for editing.":"\u4EC5\u652F\u6301 PNG\u3001JPEG \u548C WebP \u683C\u5F0F\u7684\u56FE\u7247\u8FDB\u884C\u7F16\u8F91","Embed data is empty or invalid":"\u5D4C\u5165\u6570\u636E\u4E3A\u7A7A\u6216\u65E0\u6548","Failed to generate image. no data received from API":"\u751F\u6210\u56FE\u7247\u5931\u8D25\u3002\u6CA1\u6709\u4ECE API \u63A5\u6536\u5230\u6570\u636E","Load template file: ":"\u52A0\u8F7D\u6A21\u677F\u6587\u4EF6: ","Templates have been updated: ":"\u6A21\u677F\u5DF2\u66F4\u65B0: ","Syntax Error Report":"\u8BED\u6CD5\u9519\u8BEF\u62A5\u544A","Create prompt template file":"\u521B\u5EFA\u63D0\u793A\u8BCD\u6A21\u677F\u6587\u4EF6","Expected at least 2 sections, heading and content":"\u81F3\u5C11\u9700\u8981 2 \u4E2A\u90E8\u5206\uFF0C\u6807\u9898\u548C\u5185\u5BB9","Expected heading":"\u9700\u8981\u6807\u9898","Duplicate title:":"\u91CD\u590D\u7684\u6807\u9898:","Please add a user message first, or wait for the user message to be parsed.":"\u8BF7\u5148\u6DFB\u52A0\u7528\u6237\u6D88\u606F\uFF0C\u6216\u8005\u7A0D\u7B49\u7528\u6237\u6D88\u606F\u89E3\u6790\u5B8C\u6210","Waiting for metadata to be ready. Please try again.":"\u6B63\u5728\u7B49\u5F85\u5143\u6570\u636E\u51C6\u5907\u5C31\u7EEA\u3002\u8BF7\u91CD\u8BD5\u3002","No text generated":"\u6CA1\u6709\u751F\u6210\u6587\u672C",characters:"\u4E2A\u5B57\u7B26","Removed commands":"\u5DF2\u79FB\u9664\u547D\u4EE4","Added commands":"\u5DF2\u6DFB\u52A0\u547D\u4EE4","No active generation to cancel":"\u6CA1\u6709\u6B63\u5728\u8FDB\u884C\u7684\u751F\u6210\u53EF\u53D6\u6D88","Generation already cancelled":"\u751F\u6210\u5DF2\u7ECF\u53D6\u6D88","Generation cancelled":"\u5DF2\u53D6\u6D88\u751F\u6210","Restore default":"\u6062\u590D\u9ED8\u8BA4","AI assistants":"AI \u52A9\u624B","New AI assistant":"\u65B0\u7684 AI \u52A9\u624B","For those compatible with the OpenAI protocol, you can select OpenAI.":"\u5BF9\u4E8E\u517C\u5BB9 OpenAI \u534F\u8BAE\u7684\uFF0C\u53EF\u4EE5\u9009\u62E9 OpenAI.","Add AI Provider":"\u6DFB\u52A0 AI \u670D\u52A1\u5546","Please add at least one AI assistant to start using the plugin.":"\u8BF7\u81F3\u5C11\u6DFB\u52A0\u4E00\u4E2A AI \u52A9\u624B\uFF0C\u4EE5\u4FBF\u5F00\u59CB\u4F7F\u7528\u63D2\u4EF6","Message tags":"\u6D88\u606F\u6807\u7B7E","Keywords for tags in the text box are separated by spaces":"\u5728\u6587\u672C\u6846\u4E2D\u7684\u6807\u7B7E\u5173\u952E\u5B57\u7528\u7A7A\u683C\u5206\u9694","New chat tags":"\u65B0\u5BF9\u8BDD\u7684\u6807\u7B7E","User message tags":"\u7528\u6237\u6D88\u606F\u7684\u6807\u7B7E","System message tags":"\u7CFB\u7EDF\u6D88\u606F\u7684\u6807\u7B7E","At least one tag is required":"\u81F3\u5C11\u9700\u8981\u4E00\u4E2A\u6807\u7B7E","Assistant message tag":"\u52A9\u624B\u6D88\u606F\u7684\u6807\u7B7E","Tag used to trigger AI text generation":"\u7528\u4E8E\u89E6\u53D1 AI \u6587\u672C\u751F\u6210\u7684\u6807\u7B7E","Obtain key from ":"\u83B7\u53D6 key \u7F51\u7AD9 ","Web search":"\u7F51\u7EDC\u641C\u7D22","Enable web search for AI":"\u4E3A\u5F53\u524D AI \u542F\u7528\u7F51\u7EDC\u641C\u7D22","Enter your key":"\u8F93\u5165\u4F60\u7684 key","Default:":"\u9ED8\u8BA4:","Refer to the technical documentation":"\u53C2\u8003\u6280\u672F\u6587\u6863","Keyword for tag must not contain #":"\u6807\u7B7E\u5173\u952E\u5B57\u4E0D\u80FD\u5305\u542B #","Keyword for tag must not contain space":"\u6807\u7B7E\u5173\u952E\u5B57\u4E0D\u80FD\u5305\u542B\u7A7A\u683C","Keyword for tag must be unique":"\u6807\u7B7E\u5173\u952E\u5B57\u5FC5\u987B\u552F\u4E00",Model:"\u6A21\u578B","Supported features":"\u652F\u6301\u529F\u80FD","Select the model to use":"\u9009\u62E9\u8981\u4F7F\u7528\u7684\u6A21\u578B","Please input API key first":"\u8BF7\u5148\u8F93\u5165 API key","Please enter a number":"\u8BF7\u8F93\u5165\u4E00\u4E2A\u6570\u5B57","Minimum value is 256":"\u6700\u5C0F\u503C\u662F256","Invalid URL":"\u65E0\u6548\u7684 URL","Override input parameters":"\u8986\u76D6\u8F93\u5165\u53C2\u6570",'Developer feature, in JSON format. For example, if the model list doesn\'t have the model you want, enter {"model": "your desired model"}':'\u5F00\u53D1\u8005\u529F\u80FD\uFF0C\u4EE5 JSON \u683C\u5F0F\u3002\u4F8B\u5982: \u6A21\u578B\u5217\u8868\u4E2D\u6CA1\u6709\u4F60\u9700\u8981\u7684\u6A21\u578B\u65F6\uFF0C\u53EF\u4EE5\u586B\u5165 {"model": "\u4F60\u60F3\u8981\u7684model"}',"Remove AI assistant":"\u79FB\u9664 AI \u52A9\u624B",Remove:"\u79FB\u9664",Endpoint:"\u7EC8\u7ED3\u70B9","API version":"API \u7248\u672C","Select assistant":"\u9009\u62E9\u52A9\u624B","Confirm before regeneration":"\u91CD\u65B0\u751F\u6210\u524D\u662F\u5426\u9700\u8981\u786E\u8BA4","Confirm before replacing existing assistant responses when using assistant commands":"\u5728\u4F7F\u7528\u52A9\u624B\u6807\u7B7E\u547D\u4EE4\u65F6\uFF0C\u66FF\u6362\u65E7\u7684\u52A9\u624B\u6D88\u606F\uFF0C\u662F\u5426\u9700\u8981\u5F39\u7A97\u786E\u8BA4","Internal links":"\u5185\u90E8\u94FE\u63A5","Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.":"\u7528\u6237\u548C\u7CFB\u7EDF\u6D88\u606F\u4E2D\u7684\u5185\u90E8\u94FE\u63A5\u5C06\u88AB\u66FF\u6362\u4E3A\u5176\u5F15\u7528\u7684\u5185\u5BB9\u3002\u7981\u7528\u65F6\uFF0C\u4EC5\u4F7F\u7528\u94FE\u63A5\u7684\u539F\u59CB\u6587\u672C\u3002","Internal links for assistant messages":"\u52A9\u624B\u6D88\u606F\u7684\u5185\u90E8\u94FE\u63A5","Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.":"\u52A9\u624B\u6D88\u606F\u4E2D\u7684\u5185\u90E8\u94FE\u63A5\u66FF\u6362\u4E3A\u5176\u5F15\u7528\u7684\u5185\u5BB9\u3002\u6CE8\u610F\uFF1A\u901A\u5E38\u60C5\u51B5\u4E0B\u4E0D\u5EFA\u8BAE\u542F\u7528\u6B64\u529F\u80FD\uFF0C\u56E0\u4E3A\u52A9\u624B\u751F\u6210\u7684\u5185\u5BB9\u53EF\u80FD\u5305\u542B\u4E0D\u5B58\u5728\u7684\u94FE\u63A5\u3002","System message":"\u7CFB\u7EDF\u6D88\u606F","Enable default system message":"\u542F\u7528\u9ED8\u8BA4\u7CFB\u7EDF\u6D88\u606F","Automatically add a system message when none exists in the conversation":"\u5F53\u5BF9\u8BDD\u4E2D\u6CA1\u6709\u7CFB\u7EDF\u6D88\u606F\u65F6\uFF0C\u81EA\u52A8\u6DFB\u52A0\u81EA\u5B9A\u4E49\u7684\u9ED8\u8BA4\u7684\u7CFB\u7EDF\u6D88\u606F","Default system message":"\u9ED8\u8BA4\u7CFB\u7EDF\u6D88\u606F",Advanced:"\u9AD8\u7EA7","Delay before answer (Seconds)":"\u56DE\u7B54\u524D\u7684\u5EF6\u8FDF\uFF08\u79D2\uFF09","If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.":"\u5728\u9009\u4E2D\u6587\u672C\u6267\u884C\u52A9\u624B\u547D\u4EE4\u7684\u65F6\u5019\uFF0C\u5982\u679C\u9047\u5230\u7F3A\u5C11\u7528\u6237\u6D88\u606F\u7684\u9519\u8BEF\uFF0C\u53EF\u80FD\u662F\u9700\u8981\u66F4\u591A\u65F6\u95F4\u6765\u89E3\u6790\u6D88\u606F\uFF0C\u8BF7\u7A0D\u5FAE\u589E\u52A0\u5EF6\u8FDF","Replace tag Command":"\u66FF\u6362\u6807\u7B7E\u547D\u4EE4","Export to JSONL Command":"\u5BFC\u51FA\u5230 JSONL \u547D\u4EE4","Tag suggest":"\u6807\u7B7E\u5EFA\u8BAE","If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.":"\u5982\u679C\u4F60\u53EA\u4F7F\u7528\u547D\u4EE4\u800C\u4E0D\u9700\u8981\u6807\u7B7E\u5EFA\u8BAE\uFF0C\u53EF\u4EE5\u7981\u7528\u6B64\u529F\u80FD\u3002\u66F4\u6539\u5C06\u5728\u91CD\u65B0\u542F\u52A8\u63D2\u4EF6\u540E\u751F\u6548\u3002","Image Display Width":"\u56FE\u7247\u663E\u793A\u5BBD\u5EA6","Example: 400px width would output as ![[image.jpg|400]]":"\u4F8B\u5982: 400px \u5BBD\u5EA6\u4F1A\u8F93\u51FA\u4E3A ![[image.jpg|400]]","Number of images":"\u56FE\u7247\u6570\u91CF","Number of images to generate (1-5)":"\u751F\u6210\u7684\u56FE\u7247\u6570\u91CF (1-5)","Image size":"\u56FE\u7247\u5C3A\u5BF8",landscape:"\u6A2A\u5411",portrait:"\u7EB5\u5411","Output format":"\u8F93\u51FA\u683C\u5F0F",Quality:"\u8D28\u91CF","Quality level for generated images. default: Auto":"\u751F\u6210\u56FE\u7247\u7684\u8D28\u91CF\u7B49\u7EA7\u3002\u9ED8\u8BA4: \u81EA\u52A8",Auto:"\u81EA\u52A8",High:"\u9AD8",Medium:"\u4E2D",Low:"\u4F4E",Background:"\u80CC\u666F","Background of the generated image. default: Auto":"\u751F\u6210\u56FE\u7247\u7684\u80CC\u666F\u3002\u9ED8\u8BA4: \u81EA\u52A8",Transparent:"\u900F\u660E",Opaque:"\u4E0D\u900F\u660E","Output compression":"\u8F93\u51FA\u538B\u7F29","Compression level of the output image, 10% - 100%. Only for webp or jpeg output format":"\u8F93\u51FA\u56FE\u7247\u7684\u538B\u7F29\u7EA7\u522B\uFF0C10% - 100%\u3002\u4EC5\u9002\u7528\u4E8E webp \u6216 jpeg \u8F93\u51FA\u683C\u5F0F","AI generate":"AI \u751F\u6210","Text generated successfully":"\u6587\u672C\u751F\u6210\u6210\u529F","This is a non-streaming request, please wait...":"\u8FD9\u662F\u4E00\u4E2A\u975E\u6D41\u5F0F\u8BF7\u6C42\uFF0C\u8BF7\u7A0D\u5019...",promptFileName:"prompt.zh",PRESET_PROMPT_TEMPLATES:`# \u4F7F\u7528\u8BF4\u660E
- \u628A\u4F60\u7684\u5E38\u7528\u63D0\u793A\u8BCD\u6536\u96C6\u5230\u8FD9\u91CC\uFF0C\u4EE5\u4FBF\u5728Tars\u63D2\u4EF6\u7684\u547D\u4EE4\u4E2D\u4F7F\u7528\u3002
- \u672C\u6587\u4EF6\u6309\u7167 obsidian \u7684\u5E7B\u706F\u7247\u683C\u5F0F\uFF0C\u7528\`---\`\u6765\u5206\u9694\u6BCF\u4E00\u9875
- \u7B2C\u4E00\u9875\u662F\u8BF4\u660E\uFF0C\u540E\u9762\u7684\u6BCF\u4E00\u9875\u90FD\u662F\u4E00\u4E2A\u63D0\u793A\u8BCD\u6A21\u677F
- \u9996\u5148\u662F\u6A21\u677F\u7684\u6807\u9898, \u4EE5markdown\u7684\u6807\u9898\u683C\u5F0F, \u6807\u9898\u4E0D\u80FD\u91CD\u590D\u3002\u63A5\u4E0B\u6765\u90FD\u662F\u6A21\u677F\u7684\u5185\u5BB9\u3002\u6807\u9898\u548C\u5185\u5BB9\u90FD\u4E0D\u53EF\u7F3A\u5C11\u3002
- \u5982\u679C\u5185\u5BB9\u6709 \`{{s}}\`\uFF0C\u4F1A\u628A \`{{s}}\`\u66FF\u6362\u4E3A\u9009\u4E2D\u7684\u6587\u672C
- \u5982\u679C\u6CA1\u6709 \`{{s}}\`\uFF0C\u5219\u8FFD\u52A0
- \u5982\u679C\u6CA1\u6709\u9009\u4E2D\u7684\u6587\u672C\uFF0C\u5219\u76F4\u63A5\u4F7F\u7528\u6A21\u677F\u7684\u5185\u5BB9
- \u5982\u679C\u67D0\u4E00\u9875\u6709\u8BED\u6CD5\u9519\u8BEF\uFF0C\u5219\u4E0D\u4F1A\u51FA\u73B0\u5728\u547D\u4EE4\u4E2D
- \u5982\u679C\u4F60\u7F16\u8F91\u4E86\u8BE5\u6587\u4EF6\uFF0C\u8981\u628A\u66F4\u65B0\u540E\u7684\u6A21\u677F\u52A0\u8F7D\u5230\u547D\u4EE4\u4E2D\uFF0C==\u6267\u884C\u547D\u4EE4\u201C\u52A0\u8F7D\u6A21\u677F\u6587\u4EF6\u201D==\uFF0C\u8BE5\u547D\u4EE4\u540C\u65F6\u4F1A\u68C0\u67E5\u8BED\u6CD5\u9519\u8BEF\u5E76\u5F39\u7A97\u663E\u793A\u3002
---
# \u63D0\u793A\u8BCD\u4F8B\u5B50
\u7ED9\u6211\u8BB2\u4E2A\u7B11\u8BDD
---
# \u7FFB\u8BD1
\u628A\u4EE5\u4E0B\u5185\u5BB9\u7FFB\u8BD1\u4E3A\u4E2D\u6587\uFF1A{{s}}
---
# \u4E00\u53E5\u8BDD\u603B\u7ED3
{{s}} \u7528\u4E00\u53E5\u8BDD\u603B\u7ED3\u4EE5\u4E0A\u5185\u5BB9
`,Thinking:"\u601D\u8003","When enabled, Claude will show its reasoning process before giving the final answer.":"\u542F\u7528\u540E\uFF0CClaude \u5C06\u5728\u7ED9\u51FA\u6700\u7EC8\u7B54\u6848\u524D\u5C55\u793A\u5176\u63A8\u7406\u8FC7\u7A0B","Budget tokens for thinking":"\u601D\u8003\u4EE4\u724C\u9884\u7B97","Must be \u22651024 and less than max_tokens":"\u5FC5\u987B \u22651024 \u4E14\u5C0F\u4E8E max_tokens","Minimum value is 1024":"\u6700\u5C0F\u503C\u4E3A 1024","AI Generation Details":"AI \u751F\u6210\u8BE6\u60C5",Round:"\u56DE\u5408",Duration:"\u7528\u65F6","Start Time":"\u5F00\u59CB\u65F6\u95F4","End Time":"\u7ED3\u675F\u65F6\u95F4","Error Details":"\u9519\u8BEF\u8BE6\u60C5","Error Type":"\u9519\u8BEF\u7C7B\u578B","Error Message":"\u9519\u8BEF\u4FE1\u606F","Occurrence Time":"\u53D1\u751F\u65F6\u95F4","Stack Trace":"\u5806\u6808\u8DDF\u8E2A","Copy Error Info":"\u590D\u5236\u9519\u8BEF\u4FE1\u606F","Error info copied to clipboard":"\u9519\u8BEF\u4FE1\u606F\u5DF2\u590D\u5236\u5230\u526A\u8D34\u677F","Unknown Error":"\u672A\u77E5\u9519\u8BEF","Tars AI assistant is ready":"Tars AI \u52A9\u624B\u5DF2\u5C31\u7EEA","Generating round":"\u6B63\u5728\u751F\u6210\u7B2C","answer...":"\u8F6E\u56DE\u7B54...","Generating...":"\u6B63\u5728\u751F\u6210...","Click status bar for error details. ":"\u70B9\u51FB\u72B6\u6001\u680F\u67E5\u770B\u9519\u8BEF\u8BE6\u60C5\u3002",Vendor:"\u670D\u52A1\u5546",Characters:"\u5B57\u7B26\u6570"};var od={};var Ly={en:Dl,"zh-TW":od,zh:sd},id=window.localStorage.getItem("language"),Bl=Ly[id||"en"];function m(t){return Bl||console.error("Error: locale not found",id),Bl&&Bl[t]||Dl[t]}var Em=require("obsidian");function N(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function b(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var Fl=function(){let{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return Fl=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function Ls(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var Ns=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch(e){}try{return new Error(JSON.stringify(t))}catch(e){}}return new Error(t)};var T=class extends Error{},te=class t extends T{constructor(e,r,n,s){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("x-request-id"),this.error=r;let o=r;this.code=o==null?void 0:o.code,this.param=o==null?void 0:o.param,this.type=o==null?void 0:o.type}static makeMessage(e,r,n){let s=r!=null&&r.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,r,n,s){if(!e||!s)return new Ft({message:n,cause:Ns(r)});let o=r==null?void 0:r.error;return e===400?new nn(e,o,n,s):e===401?new sn(e,o,n,s):e===403?new on(e,o,n,s):e===404?new an(e,o,n,s):e===409?new ln(e,o,n,s):e===422?new cn(e,o,n,s):e===429?new un(e,o,n,s):e>=500?new fn(e,o,n,s):new t(e,o,n,s)}},X=class extends te{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Ft=class extends te{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},qt=class extends Ft{constructor({message:e}={}){super({message:e!=null?e:"Request timed out."})}},nn=class extends te{},sn=class extends te{},on=class extends te{},an=class extends te{},ln=class extends te{},cn=class extends te{},un=class extends te{},fn=class extends te{},dn=class extends T{constructor(){super("Could not parse response content as the length limit was reached")}},hn=class extends T{constructor(){super("Could not parse response content as the request was rejected by the content filter")}};var Dy=/^[a-z][a-z0-9+.-]*:/i,ad=t=>Dy.test(t);function ld(t){return typeof t!="object"?{}:t!=null?t:{}}function cd(t){if(!t)return!0;for(let e in t)return!1;return!0}function ud(t,e){return Object.prototype.hasOwnProperty.call(t,e)}function pn(t){return t!=null&&typeof t=="object"&&!Array.isArray(t)}var fd=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new T(`${t} must be an integer`);if(e<0)throw new T(`${t} must be a positive integer`);return e};var dd=t=>{try{return JSON.parse(t)}catch(e){return}};var Ye=t=>new Promise(e=>setTimeout(e,t));var li={off:0,error:200,warn:300,info:400,debug:500},ql=(t,e,r)=>{if(t){if(ud(li,t))return t;re(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(li))}`)}};function Ds(){}function ai(t,e,r){return!e||li[t]>li[r]?Ds:e[t].bind(e)}var By={error:Ds,warn:Ds,info:Ds,debug:Ds},hd=new WeakMap;function re(t){var o;let e=t.logger,r=(o=t.logLevel)!=null?o:"off";if(!e)return By;let n=hd.get(e);if(n&&n[0]===r)return n[1];let s={error:ai("error",e,r),warn:ai("warn",e,r),info:ai("info",e,r),debug:ai("debug",e,r)};return hd.set(e,[r,s]),s}var bt=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var Ut="5.1.1";var gd=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";function Fy(){return typeof Deno!="undefined"&&Deno.build!=null?"deno":typeof EdgeRuntime!="undefined"?"edge":Object.prototype.toString.call(typeof globalThis.process!="undefined"?globalThis.process:0)==="[object process]"?"node":"unknown"}var qy=()=>{var r,n,s,o,i;let t=Fy();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":md(Deno.build.os),"X-Stainless-Arch":pd(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(n=(r=Deno.version)==null?void 0:r.deno)!=null?n:"unknown"};if(typeof EdgeRuntime!="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":md((s=globalThis.process.platform)!=null?s:"unknown"),"X-Stainless-Arch":pd((o=globalThis.process.arch)!=null?o:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(i=globalThis.process.version)!=null?i:"unknown"};let e=Uy();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":Ut,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function Uy(){if(typeof navigator=="undefined"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var pd=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",md=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),ci,yd=()=>ci!=null?ci:ci=qy();function bd(){if(typeof fetch!="undefined")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new OpenAI({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function Ul(...t){let e=globalThis.ReadableStream;if(typeof e=="undefined")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function ui(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return Ul({start(){},async pull(r){let{done:n,value:s}=await e.next();n?r.close():r.enqueue(s)},async cancel(){var r;await((r=e.return)==null?void 0:r.call(e))}})}function $l(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r!=null&&r.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function wd(t){var n,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(n=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(n));return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var _d=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});var Bs="RFC3986",Fs={RFC1738:t=>String(t).replace(/%20/g,"+"),RFC3986:t=>String(t)},Hl="RFC1738";var jy=Array.isArray,Qe=(()=>{let t=[];for(let e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t})();var jl=1024,Sd=(t,e,r,n,s)=>{if(t.length===0)return t;let o=t;if(typeof t=="symbol"?o=Symbol.prototype.toString.call(t):typeof t!="string"&&(o=String(t)),r==="iso-8859-1")return escape(o).replace(/%u[0-9a-f]{4}/gi,function(a){return"%26%23"+parseInt(a.slice(2),16)+"%3B"});let i="";for(let a=0;a<o.length;a+=jl){let c=o.length>=jl?o.slice(a,a+jl):o,l=[];for(let f=0;f<c.length;++f){let u=c.charCodeAt(f);if(u===45||u===46||u===95||u===126||u>=48&&u<=57||u>=65&&u<=90||u>=97&&u<=122||s===Hl&&(u===40||u===41)){l[l.length]=c.charAt(f);continue}if(u<128){l[l.length]=Qe[u];continue}if(u<2048){l[l.length]=Qe[192|u>>6]+Qe[128|u&63];continue}if(u<55296||u>=57344){l[l.length]=Qe[224|u>>12]+Qe[128|u>>6&63]+Qe[128|u&63];continue}f+=1,u=65536+((u&1023)<<10|c.charCodeAt(f)&1023),l[l.length]=Qe[240|u>>18]+Qe[128|u>>12&63]+Qe[128|u>>6&63]+Qe[128|u&63]}i+=l.join("")}return i};function Ed(t){return!t||typeof t!="object"?!1:!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))}function Wl(t,e){if(jy(t)){let r=[];for(let n=0;n<t.length;n+=1)r.push(e(t[n]));return r}return e(t)}var Wy=Object.prototype.hasOwnProperty,xd={brackets(t){return String(t)+"[]"},comma:"comma",indices(t,e){return String(t)+"["+e+"]"},repeat(t){return String(t)}},Ze=Array.isArray,Vy=Array.prototype.push,Ad=function(t,e){Vy.apply(t,Ze(e)?e:[e])},Ky=Date.prototype.toISOString,ne={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:Sd,encodeValuesOnly:!1,format:Bs,formatter:Fs[Bs],indices:!1,serializeDate(t){return Ky.call(t)},skipNulls:!1,strictNullHandling:!1};function Gy(t){return typeof t=="string"||typeof t=="number"||typeof t=="boolean"||typeof t=="symbol"||typeof t=="bigint"}var Vl={};function vd(t,e,r,n,s,o,i,a,c,l,f,u,d,h,p,y,g,S){let _=t,v=S,P=0,E=!1;for(;(v=v.get(Vl))!==void 0&&!E;){let F=v.get(t);if(P+=1,typeof F!="undefined"){if(F===P)throw new RangeError("Cyclic object value");E=!0}typeof v.get(Vl)=="undefined"&&(P=0)}if(typeof l=="function"?_=l(e,_):_ instanceof Date?_=d==null?void 0:d(_):r==="comma"&&Ze(_)&&(_=Wl(_,function(F){return F instanceof Date?d==null?void 0:d(F):F})),_===null){if(o)return c&&!y?c(e,ne.encoder,g,"key",h):e;_=""}if(Gy(_)||Ed(_)){if(c){let F=y?e:c(e,ne.encoder,g,"key",h);return[(p==null?void 0:p(F))+"="+(p==null?void 0:p(c(_,ne.encoder,g,"value",h)))]}return[(p==null?void 0:p(e))+"="+(p==null?void 0:p(String(_)))]}let R=[];if(typeof _=="undefined")return R;let k;if(r==="comma"&&Ze(_))y&&c&&(_=Wl(_,c)),k=[{value:_.length>0?_.join(",")||null:void 0}];else if(Ze(l))k=l;else{let F=Object.keys(_);k=f?F.sort(f):F}let M=a?String(e).replace(/\./g,"%2E"):String(e),U=n&&Ze(_)&&_.length===1?M+"[]":M;if(s&&Ze(_)&&_.length===0)return U+"[]";for(let F=0;F<k.length;++F){let V=k[F],H=typeof V=="object"&&typeof V.value!="undefined"?V.value:_[V];if(i&&H===null)continue;let ee=u&&a?V.replace(/\./g,"%2E"):V,Ee=Ze(_)?typeof r=="function"?r(U,ee):U:U+(u?"."+ee:"["+ee+"]");S.set(t,P);let ue=new WeakMap;ue.set(Vl,S),Ad(R,vd(H,Ee,r,n,s,o,i,a,r==="comma"&&y&&Ze(_)?null:c,l,f,u,d,h,p,y,g,ue))}return R}function Jy(t=ne){if(typeof t.allowEmptyArrays!="undefined"&&typeof t.allowEmptyArrays!="boolean")throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(typeof t.encodeDotInKeys!="undefined"&&typeof t.encodeDotInKeys!="boolean")throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(t.encoder!==null&&typeof t.encoder!="undefined"&&typeof t.encoder!="function")throw new TypeError("Encoder has to be a function.");let e=t.charset||ne.charset;if(typeof t.charset!="undefined"&&t.charset!=="utf-8"&&t.charset!=="iso-8859-1")throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");let r=Bs;if(typeof t.format!="undefined"){if(!Wy.call(Fs,t.format))throw new TypeError("Unknown format option provided.");r=t.format}let n=Fs[r],s=ne.filter;(typeof t.filter=="function"||Ze(t.filter))&&(s=t.filter);let o;if(t.arrayFormat&&t.arrayFormat in xd?o=t.arrayFormat:"indices"in t?o=t.indices?"indices":"repeat":o=ne.arrayFormat,"commaRoundTrip"in t&&typeof t.commaRoundTrip!="boolean")throw new TypeError("`commaRoundTrip` must be a boolean, or absent");let i=typeof t.allowDots=="undefined"?t.encodeDotInKeys?!0:ne.allowDots:!!t.allowDots;return{addQueryPrefix:typeof t.addQueryPrefix=="boolean"?t.addQueryPrefix:ne.addQueryPrefix,allowDots:i,allowEmptyArrays:typeof t.allowEmptyArrays=="boolean"?!!t.allowEmptyArrays:ne.allowEmptyArrays,arrayFormat:o,charset:e,charsetSentinel:typeof t.charsetSentinel=="boolean"?t.charsetSentinel:ne.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:typeof t.delimiter=="undefined"?ne.delimiter:t.delimiter,encode:typeof t.encode=="boolean"?t.encode:ne.encode,encodeDotInKeys:typeof t.encodeDotInKeys=="boolean"?t.encodeDotInKeys:ne.encodeDotInKeys,encoder:typeof t.encoder=="function"?t.encoder:ne.encoder,encodeValuesOnly:typeof t.encodeValuesOnly=="boolean"?t.encodeValuesOnly:ne.encodeValuesOnly,filter:s,format:r,formatter:n,serializeDate:typeof t.serializeDate=="function"?t.serializeDate:ne.serializeDate,skipNulls:typeof t.skipNulls=="boolean"?t.skipNulls:ne.skipNulls,sort:typeof t.sort=="function"?t.sort:null,strictNullHandling:typeof t.strictNullHandling=="boolean"?t.strictNullHandling:ne.strictNullHandling}}function Kl(t,e={}){let r=t,n=Jy(e),s,o;typeof n.filter=="function"?(o=n.filter,r=o("",r)):Ze(n.filter)&&(o=n.filter,s=o);let i=[];if(typeof r!="object"||r===null)return"";let a=xd[n.arrayFormat],c=a==="comma"&&n.commaRoundTrip;s||(s=Object.keys(r)),n.sort&&s.sort(n.sort);let l=new WeakMap;for(let d=0;d<s.length;++d){let h=s[d];n.skipNulls&&r[h]===null||Ad(i,vd(r[h],h,a,c,n.allowEmptyArrays,n.strictNullHandling,n.skipNulls,n.encodeDotInKeys,n.encode?n.encoder:null,n.filter,n.sort,n.allowDots,n.serializeDate,n.format,n.formatter,n.encodeValuesOnly,n.charset,l))}let f=i.join(n.delimiter),u=n.addQueryPrefix===!0?"?":"";return n.charsetSentinel&&(n.charset==="iso-8859-1"?u+="utf8=%26%2310003%3B&":u+="utf8=%E2%9C%93&"),f.length>0?u+f:""}function Cd(t){let e=0;for(let s of t)e+=s.length;let r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}var fi;function mn(t){let e;return(fi!=null?fi:(e=new globalThis.TextEncoder,fi=e.encode.bind(e)))(t)}var di;function Gl(t){let e;return(di!=null?di:(e=new globalThis.TextDecoder,di=e.decode.bind(e)))(t)}var xe,Ae,fr=class{constructor(){xe.set(this,void 0),Ae.set(this,void 0),N(this,xe,new Uint8Array,"f"),N(this,Ae,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?mn(e):e;N(this,xe,Cd([b(this,xe,"f"),r]),"f");let n=[],s;for(;(s=Xy(b(this,xe,"f"),b(this,Ae,"f")))!=null;){if(s.carriage&&b(this,Ae,"f")==null){N(this,Ae,s.index,"f");continue}if(b(this,Ae,"f")!=null&&(s.index!==b(this,Ae,"f")+1||s.carriage)){n.push(Gl(b(this,xe,"f").subarray(0,b(this,Ae,"f")-1))),N(this,xe,b(this,xe,"f").subarray(b(this,Ae,"f")),"f"),N(this,Ae,null,"f");continue}let o=b(this,Ae,"f")!==null?s.preceding-1:s.preceding,i=Gl(b(this,xe,"f").subarray(0,o));n.push(i),N(this,xe,b(this,xe,"f").subarray(s.index),"f"),N(this,Ae,null,"f")}return n}flush(){return b(this,xe,"f").length?this.decode(`
`):[]}};xe=new WeakMap,Ae=new WeakMap;fr.NEWLINE_CHARS=new Set([`
`,"\r"]);fr.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function Xy(t,e){for(let s=e!=null?e:0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function Pd(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var et=class t{constructor(e,r){this.iterator=e,this.controller=r}static fromSSEResponse(e,r){let n=!1;async function*s(){if(n)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let o=!1;try{for await(let i of Yy(e,r))if(!o){if(i.data.startsWith("[DONE]")){o=!0;continue}if(i.event===null||i.event.startsWith("response.")||i.event.startsWith("transcript.")){let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(a&&a.error)throw new te(void 0,a.error,void 0,e.headers);yield a}else{let a;try{a=JSON.parse(i.data)}catch(c){throw console.error("Could not parse message into JSON:",i.data),console.error("From chunk:",i.raw),c}if(i.event=="error")throw new te(void 0,a.error,a.message,void 0);yield{event:i.event,data:a}}}o=!0}catch(i){if(Ls(i))return;throw i}finally{o||r.abort()}}return new t(s,r)}static fromReadableStream(e,r){let n=!1;async function*s(){let i=new fr,a=$l(e);for await(let c of a)for(let l of i.decode(c))yield l;for(let c of i.flush())yield c}async function*o(){if(n)throw new T("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");n=!0;let i=!1;try{for await(let a of s())i||a&&(yield JSON.parse(a));i=!0}catch(a){if(Ls(a))return;throw a}finally{i||r.abort()}}return new t(o,r)}[Symbol.asyncIterator](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=n.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>s(e),this.controller),new t(()=>s(r),this.controller)]}toReadableStream(){let e=this,r;return Ul({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await r.next();if(o)return n.close();let i=mn(JSON.stringify(s)+`
`);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){var n;await((n=r.return)==null?void 0:n.call(r))}})}};async function*Yy(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new T("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new T("Attempted to iterate over a response with no body");let r=new Jl,n=new fr,s=$l(t.body);for await(let o of Qy(s))for(let i of n.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of n.flush()){let i=r.decode(o);i&&(yield i)}}async function*Qy(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?mn(r):r,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=Pd(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Jl=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,s]=Zy(e,":");return s.startsWith(" ")&&(s=s.substring(1)),r==="event"?this.event=s:r==="data"&&this.data.push(s),null}};function Zy(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function hi(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{var u;if(e.options.stream)return re(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller):et.fromSSEResponse(r,e.controller);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let a=r.headers.get("content-type"),c=(u=a==null?void 0:a.split(";")[0])==null?void 0:u.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){let d=await r.json();return zl(d,r)}return await r.text()})();return re(t).debug(`[${n}] response parsed`,bt({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function zl(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("x-request-id"),enumerable:!1})}var qs,dr=class t extends Promise{constructor(e,r,n=hi){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,qs.set(this,void 0),N(this,qs,e,"f")}_thenUnwrap(e){return new t(b(this,qs,"f"),this.responsePromise,async(r,n)=>zl(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("x-request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(b(this,qs,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};qs=new WeakMap;var pi,mi=class{constructor(e,r,n,s){pi.set(this,void 0),N(this,pi,e,"f"),this.options=s,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new T("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await b(this,pi,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(pi=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},Us=class extends dr{constructor(e,r,n){super(e,r,async(s,o)=>new n(s,o.response,await hi(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},tt=class extends mi{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.object=n.object}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}nextPageRequestOptions(){return null}},W=class extends mi{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.has_more=n.has_more||!1}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var n;let e=this.getPaginatedItems(),r=(n=e[e.length-1])==null?void 0:n.id;return r?{...this.options,query:{...ld(this.options.query),after:r}}:null}};var Yl=()=>{var t;if(typeof File=="undefined"){let{process:e}=globalThis,r=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(r?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function gn(t,e,r){return Yl(),new File(t,e!=null?e:"unknown_file",r)}function $s(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var Ql=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var ve=async(t,e)=>({...t,body:await rb(t.body,e)}),Rd=new WeakMap;function tb(t){let e=typeof t=="function"?t:t.fetch,r=Rd.get(e);if(r)return r;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch(s){return!0}})();return Rd.set(e,n),n}var rb=async(t,e)=>{if(!await tb(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,s])=>Xl(r,n,s))),r},nb=t=>t instanceof Blob&&"name"in t;var Xl=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response)t.append(e,gn([await r.blob()],$s(r)));else if(Ql(r))t.append(e,gn([await new Response(ui(r)).blob()],$s(r)));else if(nb(r))t.append(e,r,$s(r));else if(Array.isArray(r))await Promise.all(r.map(n=>Xl(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Xl(t,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Td=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",sb=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Td(t),ob=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function gi(t,e,r){if(Yl(),t=await t,sb(t))return t instanceof File?t:gn([await t.arrayBuffer()],t.name);if(ob(t)){let s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),gn(await Zl(s),e,r)}let n=await Zl(t);if(e||(e=$s(t)),!(r!=null&&r.type)){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return gn(n,e,r)}async function Zl(t){var r;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Td(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(Ql(t))for await(let n of t)e.push(...await Zl(n));else{let n=(r=t==null?void 0:t.constructor)==null?void 0:r.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${ib(t)}`)}return e}function ib(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var C=class{constructor(e){this._client=e}};function Id(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var lb=(t=Id)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=r.reduce((f,u,d)=>(/[?#]/.test(u)&&(s=!0),f+u+(d===n.length?"":(s?encodeURIComponent:t)(String(n[d])))),""),i=o.split(/[?#]/,1)[0],a=[],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(i))!==null;)a.push({start:l.index,length:l[0].length});if(a.length>0){let f=0,u=a.reduce((d,h)=>{let p=" ".repeat(h.start-f),y="^".repeat(h.length);return f=h.start+h.length,d+p+y},"");throw new T(`Path parameters result in path with invalid segments:
${o}
${u}`)}return o},A=lb(Id);var hr=class extends C{list(e,r={},n){return this._client.getAPIList(A`/chat/completions/${e}/messages`,W,{query:r,...n})}};function kd(t){return typeof t.parse=="function"}var yn=t=>(t==null?void 0:t.role)==="assistant",ec=t=>(t==null?void 0:t.role)==="tool";var tc,yi,bi,Hs,js,wi,Ws,wt,Vs,_i,Si,bn,Od,$t=class{constructor(){tc.add(this),this.controller=new AbortController,yi.set(this,void 0),bi.set(this,()=>{}),Hs.set(this,()=>{}),js.set(this,void 0),wi.set(this,()=>{}),Ws.set(this,()=>{}),wt.set(this,{}),Vs.set(this,!1),_i.set(this,!1),Si.set(this,!1),bn.set(this,!1),N(this,yi,new Promise((e,r)=>{N(this,bi,e,"f"),N(this,Hs,r,"f")}),"f"),N(this,js,new Promise((e,r)=>{N(this,wi,e,"f"),N(this,Ws,r,"f")}),"f"),b(this,yi,"f").catch(()=>{}),b(this,js,"f").catch(()=>{})}_run(e){setTimeout(()=>{e().then(()=>{this._emitFinal(),this._emit("end")},b(this,tc,"m",Od).bind(this))},0)}_connected(){this.ended||(b(this,bi,"f").call(this),this._emit("connect"))}get ended(){return b(this,Vs,"f")}get errored(){return b(this,_i,"f")}get aborted(){return b(this,Si,"f")}abort(){this.controller.abort()}on(e,r){return(b(this,wt,"f")[e]||(b(this,wt,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=b(this,wt,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===r);return s>=0&&n.splice(s,1),this}once(e,r){return(b(this,wt,"f")[e]||(b(this,wt,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{N(this,bn,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){N(this,bn,!0,"f"),await b(this,js,"f")}_emit(e,...r){if(b(this,Vs,"f"))return;e==="end"&&(N(this,Vs,!0,"f"),b(this,wi,"f").call(this));let n=b(this,wt,"f")[e];if(n&&(b(this,wt,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...r))),e==="abort"){let s=r[0];!b(this,bn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),b(this,Hs,"f").call(this,s),b(this,Ws,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=r[0];!b(this,bn,"f")&&!(n!=null&&n.length)&&Promise.reject(s),b(this,Hs,"f").call(this,s),b(this,Ws,"f").call(this,s),this._emit("end")}}_emitFinal(){}};yi=new WeakMap,bi=new WeakMap,Hs=new WeakMap,js=new WeakMap,wi=new WeakMap,Ws=new WeakMap,wt=new WeakMap,Vs=new WeakMap,_i=new WeakMap,Si=new WeakMap,bn=new WeakMap,tc=new WeakSet,Od=function(e){if(N(this,_i,!0,"f"),e instanceof Error&&e.name==="AbortError"&&(e=new X),e instanceof X)return N(this,Si,!0,"f"),this._emit("abort",e);if(e instanceof T)return this._emit("error",e);if(e instanceof Error){let r=new T(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new T(String(e)))};function Ks(t){return(t==null?void 0:t.$brand)==="auto-parseable-response-format"}function pr(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function Md(t,e){return!e||!rc(e)?{...t,choices:t.choices.map(r=>({...r,message:{...r.message,parsed:null,...r.message.tool_calls?{tool_calls:r.message.tool_calls}:void 0}}))}:Gs(t,e)}function Gs(t,e){let r=t.choices.map(n=>{var s,o;if(n.finish_reason==="length")throw new dn;if(n.finish_reason==="content_filter")throw new hn;return{...n,message:{...n.message,...n.message.tool_calls?{tool_calls:(o=(s=n.message.tool_calls)==null?void 0:s.map(i=>db(e,i)))!=null?o:void 0}:void 0,parsed:n.message.content&&!n.message.refusal?fb(e,n.message.content):null}}});return{...t,choices:r}}function fb(t,e){var r,n;return((r=t.response_format)==null?void 0:r.type)!=="json_schema"?null:((n=t.response_format)==null?void 0:n.type)==="json_schema"?"$parseRaw"in t.response_format?t.response_format.$parseRaw(e):JSON.parse(e):null}function db(t,e){var n;let r=(n=t.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return{...e,function:{...e.function,parsed_arguments:pr(r)?r.$parseRaw(e.function.arguments):r!=null&&r.function.strict?JSON.parse(e.function.arguments):null}}}function Ld(t,e){var n;if(!t)return!1;let r=(n=t.tools)==null?void 0:n.find(s=>{var o;return((o=s.function)==null?void 0:o.name)===e.function.name});return pr(r)||(r==null?void 0:r.function.strict)||!1}function rc(t){var e,r;return Ks(t.response_format)?!0:(r=(e=t.tools)==null?void 0:e.some(n=>pr(n)||n.type==="function"&&n.function.strict===!0))!=null?r:!1}function Nd(t){for(let e of t!=null?t:[]){if(e.type!=="function")throw new T(`Currently only \`function\` tool types support auto-parsing; Received \`${e.type}\``);if(e.function.strict!==!0)throw new T(`The \`${e.function.name}\` tool is not marked with \`strict: true\`. Only strict function tools can be auto-parsed`)}}var we,nc,Ei,sc,oc,ic,Dd,Bd,hb=10,wn=class extends $t{constructor(){super(...arguments),we.add(this),this._chatCompletions=[],this.messages=[]}_addChatCompletion(e){var n;this._chatCompletions.push(e),this._emit("chatCompletion",e);let r=(n=e.choices[0])==null?void 0:n.message;return r&&this._addMessage(r),e}_addMessage(e,r=!0){if("content"in e||(e.content=null),this.messages.push(e),r){if(this._emit("message",e),ec(e)&&e.content)this._emit("functionToolCallResult",e.content);else if(yn(e)&&e.tool_calls)for(let n of e.tool_calls)n.type==="function"&&this._emit("functionToolCall",n.function)}}async finalChatCompletion(){await this.done();let e=this._chatCompletions[this._chatCompletions.length-1];if(!e)throw new T("stream ended without producing a ChatCompletion");return e}async finalContent(){return await this.done(),b(this,we,"m",nc).call(this)}async finalMessage(){return await this.done(),b(this,we,"m",Ei).call(this)}async finalFunctionToolCall(){return await this.done(),b(this,we,"m",sc).call(this)}async finalFunctionToolCallResult(){return await this.done(),b(this,we,"m",oc).call(this)}async totalUsage(){return await this.done(),b(this,we,"m",ic).call(this)}allChatCompletions(){return[...this._chatCompletions]}_emitFinal(){let e=this._chatCompletions[this._chatCompletions.length-1];e&&this._emit("finalChatCompletion",e);let r=b(this,we,"m",Ei).call(this);r&&this._emit("finalMessage",r);let n=b(this,we,"m",nc).call(this);n&&this._emit("finalContent",n);let s=b(this,we,"m",sc).call(this);s&&this._emit("finalFunctionToolCall",s);let o=b(this,we,"m",oc).call(this);o!=null&&this._emit("finalFunctionToolCallResult",o),this._chatCompletions.some(i=>i.usage)&&this._emit("totalUsage",b(this,we,"m",ic).call(this))}async _createChatCompletion(e,r,n){let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),b(this,we,"m",Dd).call(this,r);let o=await e.chat.completions.create({...r,stream:!1},{...n,signal:this.controller.signal});return this._connected(),this._addChatCompletion(Gs(o,r))}async _runChatCompletion(e,r,n){for(let s of r.messages)this._addMessage(s,!1);return await this._createChatCompletion(e,r,n)}async _runTools(e,r,n){var h,p,y;let s="tool",{tool_choice:o="auto",stream:i,...a}=r,c=typeof o!="string"&&((h=o==null?void 0:o.function)==null?void 0:h.name),{maxChatCompletions:l=hb}=n||{},f=r.tools.map(g=>{if(pr(g)){if(!g.$callback)throw new T("Tool given to `.runTools()` that does not have an associated function");return{type:"function",function:{function:g.$callback,name:g.function.name,description:g.function.description||"",parameters:g.function.parameters,parse:g.$parseRaw,strict:!0}}}return g}),u={};for(let g of f)g.type==="function"&&(u[g.function.name||g.function.function.name]=g.function);let d="tools"in r?f.map(g=>g.type==="function"?{type:"function",function:{name:g.function.name||g.function.function.name,parameters:g.function.parameters,description:g.function.description,strict:g.function.strict}}:g):void 0;for(let g of r.messages)this._addMessage(g,!1);for(let g=0;g<l;++g){let _=(p=(await this._createChatCompletion(e,{...a,tool_choice:o,tools:d,messages:[...this.messages]},n)).choices[0])==null?void 0:p.message;if(!_)throw new T("missing message in ChatCompletion response");if(!((y=_.tool_calls)!=null&&y.length))return;for(let v of _.tool_calls){if(v.type!=="function")continue;let P=v.id,{name:E,arguments:R}=v.function,k=u[E];if(k){if(c&&c!==E){let V=`Invalid tool_call: ${JSON.stringify(E)}. ${JSON.stringify(c)} requested. Please try again`;this._addMessage({role:s,tool_call_id:P,content:V});continue}}else{let V=`Invalid tool_call: ${JSON.stringify(E)}. Available options are: ${Object.keys(u).map(H=>JSON.stringify(H)).join(", ")}. Please try again`;this._addMessage({role:s,tool_call_id:P,content:V});continue}let M;try{M=kd(k)?await k.parse(R):R}catch(V){let H=V instanceof Error?V.message:String(V);this._addMessage({role:s,tool_call_id:P,content:H});continue}let U=await k.function(M,this),F=b(this,we,"m",Bd).call(this,U);if(this._addMessage({role:s,tool_call_id:P,content:F}),c)return}}}};we=new WeakSet,nc=function(){var e;return(e=b(this,we,"m",Ei).call(this).content)!=null?e:null},Ei=function(){var r,n;let e=this.messages.length;for(;e-- >0;){let s=this.messages[e];if(yn(s))return{...s,content:(r=s.content)!=null?r:null,refusal:(n=s.refusal)!=null?n:null}}throw new T("stream ended without producing a ChatCompletionMessage with role=assistant")},sc=function(){var e,r;for(let n=this.messages.length-1;n>=0;n--){let s=this.messages[n];if(yn(s)&&((e=s==null?void 0:s.tool_calls)!=null&&e.length))return(r=s.tool_calls.at(-1))==null?void 0:r.function}},oc=function(){for(let e=this.messages.length-1;e>=0;e--){let r=this.messages[e];if(ec(r)&&r.content!=null&&typeof r.content=="string"&&this.messages.some(n=>{var s;return n.role==="assistant"&&((s=n.tool_calls)==null?void 0:s.some(o=>o.type==="function"&&o.id===r.tool_call_id))}))return r.content}},ic=function(){let e={completion_tokens:0,prompt_tokens:0,total_tokens:0};for(let{usage:r}of this._chatCompletions)r&&(e.completion_tokens+=r.completion_tokens,e.prompt_tokens+=r.prompt_tokens,e.total_tokens+=r.total_tokens);return e},Dd=function(e){if(e.n!=null&&e.n>1)throw new T("ChatCompletion convenience helpers only support n=1 at this time. To use n>1, please use chat.completions.create() directly.")},Bd=function(e){return typeof e=="string"?e:e===void 0?"undefined":JSON.stringify(e)};var Js=class t extends wn{static runTools(e,r,n){let s=new t,o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,r,o)),s}_addMessage(e,r=!0){super._addMessage(e,r),yn(e)&&e.content&&this._emit("content",e.content)}};var ae={STR:1,NUM:2,ARR:4,OBJ:8,NULL:16,BOOL:32,NAN:64,INFINITY:128,MINUS_INFINITY:256,INF:384,SPECIAL:496,ATOM:499,COLLECTION:12,ALL:511},ac=class extends Error{},lc=class extends Error{};function pb(t,e=ae.ALL){if(typeof t!="string")throw new TypeError(`expecting str, got ${typeof t}`);if(!t.trim())throw new Error(`${t} is empty`);return mb(t.trim(),e)}var mb=(t,e)=>{let r=t.length,n=0,s=d=>{throw new ac(`${d} at position ${n}`)},o=d=>{throw new lc(`${d} at position ${n}`)},i=()=>(u(),n>=r&&s("Unexpected end of input"),t[n]==='"'?a():t[n]==="{"?c():t[n]==="["?l():t.substring(n,n+4)==="null"||ae.NULL&e&&r-n<4&&"null".startsWith(t.substring(n))?(n+=4,null):t.substring(n,n+4)==="true"||ae.BOOL&e&&r-n<4&&"true".startsWith(t.substring(n))?(n+=4,!0):t.substring(n,n+5)==="false"||ae.BOOL&e&&r-n<5&&"false".startsWith(t.substring(n))?(n+=5,!1):t.substring(n,n+8)==="Infinity"||ae.INFINITY&e&&r-n<8&&"Infinity".startsWith(t.substring(n))?(n+=8,1/0):t.substring(n,n+9)==="-Infinity"||ae.MINUS_INFINITY&e&&1<r-n&&r-n<9&&"-Infinity".startsWith(t.substring(n))?(n+=9,-1/0):t.substring(n,n+3)==="NaN"||ae.NAN&e&&r-n<3&&"NaN".startsWith(t.substring(n))?(n+=3,NaN):f()),a=()=>{let d=n,h=!1;for(n++;n<r&&(t[n]!=='"'||h&&t[n-1]==="\\");)h=t[n]==="\\"?!h:!1,n++;if(t.charAt(n)=='"')try{return JSON.parse(t.substring(d,++n-Number(h)))}catch(p){o(String(p))}else if(ae.STR&e)try{return JSON.parse(t.substring(d,n-Number(h))+'"')}catch(p){return JSON.parse(t.substring(d,t.lastIndexOf("\\"))+'"')}s("Unterminated string literal")},c=()=>{n++,u();let d={};try{for(;t[n]!=="}";){if(u(),n>=r&&ae.OBJ&e)return d;let h=a();u(),n++;try{let p=i();Object.defineProperty(d,h,{value:p,writable:!0,enumerable:!0,configurable:!0})}catch(p){if(ae.OBJ&e)return d;throw p}u(),t[n]===","&&n++}}catch(h){if(ae.OBJ&e)return d;s("Expected '}' at end of object")}return n++,d},l=()=>{n++;let d=[];try{for(;t[n]!=="]";)d.push(i()),u(),t[n]===","&&n++}catch(h){if(ae.ARR&e)return d;s("Expected ']' at end of array")}return n++,d},f=()=>{if(n===0){t==="-"&&ae.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t)}catch(h){if(ae.NUM&e)try{return t[t.length-1]==="."?JSON.parse(t.substring(0,t.lastIndexOf("."))):JSON.parse(t.substring(0,t.lastIndexOf("e")))}catch(p){}o(String(h))}}let d=n;for(t[n]==="-"&&n++;t[n]&&!",]}".includes(t[n]);)n++;n==r&&!(ae.NUM&e)&&s("Unterminated number literal");try{return JSON.parse(t.substring(d,n))}catch(h){t.substring(d,n)==="-"&&ae.NUM&e&&s("Not sure what '-' is");try{return JSON.parse(t.substring(d,t.lastIndexOf("e")))}catch(p){o(String(p))}}},u=()=>{for(;n<r&&`
\r `.includes(t[n]);)n++};return i()},cc=t=>pb(t,ae.ALL^ae.NUM);var se,_t,_n,Ht,uc,xi,fc,dc,hc,Ai,pc,Fd,mr=class t extends wn{constructor(e){super(),se.add(this),_t.set(this,void 0),_n.set(this,void 0),Ht.set(this,void 0),N(this,_t,e,"f"),N(this,_n,[],"f")}get currentChatCompletionSnapshot(){return b(this,Ht,"f")}static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static createChatCompletion(e,r,n){let s=new t(r);return s._run(()=>s._runChatCompletion(e,{...r,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createChatCompletion(e,r,n){var i;super._createChatCompletion;let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),b(this,se,"m",uc).call(this);let o=await e.chat.completions.create({...r,stream:!0},{...n,signal:this.controller.signal});this._connected();for await(let a of o)b(this,se,"m",fc).call(this,a);if((i=o.controller.signal)!=null&&i.aborted)throw new X;return this._addChatCompletion(b(this,se,"m",Ai).call(this))}async _fromReadableStream(e,r){var i;let n=r==null?void 0:r.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),b(this,se,"m",uc).call(this),this._connected();let s=et.fromReadableStream(e,this.controller),o;for await(let a of s)o&&o!==a.id&&this._addChatCompletion(b(this,se,"m",Ai).call(this)),b(this,se,"m",fc).call(this,a),o=a.id;if((i=s.controller.signal)!=null&&i.aborted)throw new X;return this._addChatCompletion(b(this,se,"m",Ai).call(this))}[(_t=new WeakMap,_n=new WeakMap,Ht=new WeakMap,se=new WeakSet,uc=function(){this.ended||N(this,Ht,void 0,"f")},xi=function(r){let n=b(this,_n,"f")[r.index];return n||(n={content_done:!1,refusal_done:!1,logprobs_content_done:!1,logprobs_refusal_done:!1,done_tool_calls:new Set,current_tool_call_index:null},b(this,_n,"f")[r.index]=n,n)},fc=function(r){var s,o,i,a,c,l,f,u,d,h,p,y,g,S,_,v,P,E,R,k;if(this.ended)return;let n=b(this,se,"m",Fd).call(this,r);this._emit("chunk",r,n);for(let M of r.choices){let U=n.choices[M.index];M.delta.content!=null&&((s=U.message)==null?void 0:s.role)==="assistant"&&((o=U.message)!=null&&o.content)&&(this._emit("content",M.delta.content,U.message.content),this._emit("content.delta",{delta:M.delta.content,snapshot:U.message.content,parsed:U.message.parsed})),M.delta.refusal!=null&&((i=U.message)==null?void 0:i.role)==="assistant"&&((a=U.message)!=null&&a.refusal)&&this._emit("refusal.delta",{delta:M.delta.refusal,snapshot:U.message.refusal}),((c=M.logprobs)==null?void 0:c.content)!=null&&((l=U.message)==null?void 0:l.role)==="assistant"&&this._emit("logprobs.content.delta",{content:(f=M.logprobs)==null?void 0:f.content,snapshot:(d=(u=U.logprobs)==null?void 0:u.content)!=null?d:[]}),((h=M.logprobs)==null?void 0:h.refusal)!=null&&((p=U.message)==null?void 0:p.role)==="assistant"&&this._emit("logprobs.refusal.delta",{refusal:(y=M.logprobs)==null?void 0:y.refusal,snapshot:(S=(g=U.logprobs)==null?void 0:g.refusal)!=null?S:[]});let F=b(this,se,"m",xi).call(this,U);U.finish_reason&&(b(this,se,"m",hc).call(this,U),F.current_tool_call_index!=null&&b(this,se,"m",dc).call(this,U,F.current_tool_call_index));for(let V of(_=M.delta.tool_calls)!=null?_:[])F.current_tool_call_index!==V.index&&(b(this,se,"m",hc).call(this,U),F.current_tool_call_index!=null&&b(this,se,"m",dc).call(this,U,F.current_tool_call_index)),F.current_tool_call_index=V.index;for(let V of(v=M.delta.tool_calls)!=null?v:[]){let H=(P=U.message.tool_calls)==null?void 0:P[V.index];H!=null&&H.type&&((H==null?void 0:H.type)==="function"?this._emit("tool_calls.function.arguments.delta",{name:(E=H.function)==null?void 0:E.name,index:V.index,arguments:H.function.arguments,parsed_arguments:H.function.parsed_arguments,arguments_delta:(k=(R=V.function)==null?void 0:R.arguments)!=null?k:""}):(H==null||H.type,void 0))}}},dc=function(r,n){var i,a,c;if(b(this,se,"m",xi).call(this,r).done_tool_calls.has(n))return;let o=(i=r.message.tool_calls)==null?void 0:i[n];if(!o)throw new Error("no tool call snapshot");if(!o.type)throw new Error("tool call snapshot missing `type`");if(o.type==="function"){let l=(c=(a=b(this,_t,"f"))==null?void 0:a.tools)==null?void 0:c.find(f=>f.type==="function"&&f.function.name===o.function.name);this._emit("tool_calls.function.arguments.done",{name:o.function.name,index:n,arguments:o.function.arguments,parsed_arguments:pr(l)?l.$parseRaw(o.function.arguments):l!=null&&l.function.strict?JSON.parse(o.function.arguments):null})}else o.type},hc=function(r){var s,o;let n=b(this,se,"m",xi).call(this,r);if(r.message.content&&!n.content_done){n.content_done=!0;let i=b(this,se,"m",pc).call(this);this._emit("content.done",{content:r.message.content,parsed:i?i.$parseRaw(r.message.content):null})}r.message.refusal&&!n.refusal_done&&(n.refusal_done=!0,this._emit("refusal.done",{refusal:r.message.refusal})),(s=r.logprobs)!=null&&s.content&&!n.logprobs_content_done&&(n.logprobs_content_done=!0,this._emit("logprobs.content.done",{content:r.logprobs.content})),(o=r.logprobs)!=null&&o.refusal&&!n.logprobs_refusal_done&&(n.logprobs_refusal_done=!0,this._emit("logprobs.refusal.done",{refusal:r.logprobs.refusal}))},Ai=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let r=b(this,Ht,"f");if(!r)throw new T("request ended without sending any chunks");return N(this,Ht,void 0,"f"),N(this,_n,[],"f"),gb(r,b(this,_t,"f"))},pc=function(){var n;let r=(n=b(this,_t,"f"))==null?void 0:n.response_format;return Ks(r)?r:null},Fd=function(r){var f,u,d,h,p,y;var n,s,o,i;let a=b(this,Ht,"f"),{choices:c,...l}=r;a?Object.assign(a,l):a=N(this,Ht,{...l,choices:[]},"f");for(let{delta:g,finish_reason:S,index:_,logprobs:v=null,...P}of r.choices){let E=a.choices[_];if(E||(E=a.choices[_]={finish_reason:S,index:_,message:{},logprobs:v,...P}),v)if(!E.logprobs)E.logprobs=Object.assign({},v);else{let{content:H,refusal:ee,...Ee}=v;Object.assign(E.logprobs,Ee),H&&((f=(n=E.logprobs).content)!=null||(n.content=[]),E.logprobs.content.push(...H)),ee&&((u=(s=E.logprobs).refusal)!=null||(s.refusal=[]),E.logprobs.refusal.push(...ee))}if(S&&(E.finish_reason=S,b(this,_t,"f")&&rc(b(this,_t,"f")))){if(S==="length")throw new dn;if(S==="content_filter")throw new hn}if(Object.assign(E,P),!g)continue;let{content:R,refusal:k,function_call:M,role:U,tool_calls:F,...V}=g;if(Object.assign(E.message,V),k&&(E.message.refusal=(E.message.refusal||"")+k),U&&(E.message.role=U),M&&(E.message.function_call?(M.name&&(E.message.function_call.name=M.name),M.arguments&&((d=(o=E.message.function_call).arguments)!=null||(o.arguments=""),E.message.function_call.arguments+=M.arguments)):E.message.function_call=M),R&&(E.message.content=(E.message.content||"")+R,!E.message.refusal&&b(this,se,"m",pc).call(this)&&(E.message.parsed=cc(E.message.content))),F){E.message.tool_calls||(E.message.tool_calls=[]);for(let{index:H,id:ee,type:Ee,function:ue,...Oe}of F){let Xe=(h=(i=E.message.tool_calls)[H])!=null?h:i[H]={};Object.assign(Xe,Oe),ee&&(Xe.id=ee),Ee&&(Xe.type=Ee),ue&&((y=Xe.function)!=null||(Xe.function={name:(p=ue.name)!=null?p:"",arguments:""})),ue!=null&&ue.name&&(Xe.function.name=ue.name),ue!=null&&ue.arguments&&(Xe.function.arguments+=ue.arguments,Ld(b(this,_t,"f"),Xe)&&(Xe.function.parsed_arguments=cc(Xe.function.arguments)))}}}return a},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("chunk",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};function gb(t,e){let{id:r,choices:n,created:s,model:o,system_fingerprint:i,...a}=t,c={...a,id:r,choices:n.map(({message:l,finish_reason:f,index:u,logprobs:d,...h})=>{var v,P,E;if(!f)throw new T(`missing finish_reason for choice ${u}`);let{content:p=null,function_call:y,tool_calls:g,...S}=l,_=l.role;if(!_)throw new T(`missing role for choice ${u}`);if(y){let{arguments:R,name:k}=y;if(R==null)throw new T(`missing function_call.arguments for choice ${u}`);if(!k)throw new T(`missing function_call.name for choice ${u}`);return{...h,message:{content:p,function_call:{arguments:R,name:k},role:_,refusal:(v=l.refusal)!=null?v:null},finish_reason:f,index:u,logprobs:d}}return g?{...h,index:u,finish_reason:f,logprobs:d,message:{...S,role:_,content:p,refusal:(P=l.refusal)!=null?P:null,tool_calls:g.map((R,k)=>{let{function:M,type:U,id:F,...V}=R,{arguments:H,name:ee,...Ee}=M||{};if(F==null)throw new T(`missing choices[${u}].tool_calls[${k}].id
${vi(t)}`);if(U==null)throw new T(`missing choices[${u}].tool_calls[${k}].type
${vi(t)}`);if(ee==null)throw new T(`missing choices[${u}].tool_calls[${k}].function.name
${vi(t)}`);if(H==null)throw new T(`missing choices[${u}].tool_calls[${k}].function.arguments
${vi(t)}`);return{...V,id:F,type:U,function:{...Ee,name:ee,arguments:H}}})}}:{...h,message:{...S,content:p,role:_,refusal:(E=l.refusal)!=null?E:null},finish_reason:f,index:u,logprobs:d}}),created:s,model:o,object:"chat.completion",...i?{system_fingerprint:i}:{}};return Md(c,e)}function vi(t){return JSON.stringify(t)}var zs=class t extends mr{static fromReadableStream(e){let r=new t(null);return r._run(()=>r._fromReadableStream(e)),r}static runTools(e,r,n){let s=new t(r),o={...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"runTools"}};return s._run(()=>s._runTools(e,r,o)),s}};var St=class extends C{constructor(){super(...arguments),this.messages=new hr(this._client)}create(e,r){var n;return this._client.post("/chat/completions",{body:e,...r,stream:(n=e.stream)!=null?n:!1})}retrieve(e,r){return this._client.get(A`/chat/completions/${e}`,r)}update(e,r,n){return this._client.post(A`/chat/completions/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/chat/completions",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/chat/completions/${e}`,r)}parse(e,r){return Nd(e.tools),this._client.chat.completions.create(e,{...r,headers:{...r==null?void 0:r.headers,"X-Stainless-Helper-Method":"chat.completions.parse"}})._thenUnwrap(n=>Gs(n,e))}runTools(e,r){return e.stream?zs.runTools(this._client,e,r):Js.runTools(this._client,e,r)}stream(e,r){return mr.createChatCompletion(this._client,e,r)}};St.Messages=hr;var jt=class extends C{constructor(){super(...arguments),this.completions=new St(this._client)}};jt.Completions=St;var Ud=Symbol("brand.privateNullableHeaders"),qd=Array.isArray;function*bb(t){if(!t)return;if(Ud in t){let{values:n,nulls:s}=t;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():qd(t)?r=t:(e=!0,r=Object.entries(t!=null?t:{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=qd(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var I=t=>{let e=new Headers,r=new Set;for(let n of t){let s=new Set;for(let[o,i]of bb(n)){let a=o.toLowerCase();s.has(a)||(e.delete(o),s.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[Ud]:!0,values:e,nulls:r}};var Sn=class extends C{create(e,r){return this._client.post("/audio/speech",{body:e,...r,headers:I([{Accept:"application/octet-stream"},r==null?void 0:r.headers]),__binaryResponse:!0})}};var En=class extends C{create(e,r){var n;return this._client.post("/audio/transcriptions",ve({body:e,...r,stream:(n=e.stream)!=null?n:!1,__metadata:{model:e.model}},this._client))}};var xn=class extends C{create(e,r){return this._client.post("/audio/translations",ve({body:e,...r,__metadata:{model:e.model}},this._client))}};var rt=class extends C{constructor(){super(...arguments),this.transcriptions=new En(this._client),this.translations=new xn(this._client),this.speech=new Sn(this._client)}};rt.Transcriptions=En;rt.Translations=xn;rt.Speech=Sn;var gr=class extends C{create(e,r){return this._client.post("/batches",{body:e,...r})}retrieve(e,r){return this._client.get(A`/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/batches",W,{query:e,...r})}cancel(e,r){return this._client.post(A`/batches/${e}/cancel`,r)}};var An=class extends C{create(e,r){return this._client.post("/assistants",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,r){return this._client.get(A`/assistants/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,r,n){return this._client.post(A`/assistants/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},r){return this._client.getAPIList("/assistants",W,{query:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,r){return this._client.delete(A`/assistants/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};var vn=class extends C{create(e,r){return this._client.post("/realtime/sessions",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};var Cn=class extends C{create(e,r){return this._client.post("/realtime/transcription_sessions",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}};var Wt=class extends C{constructor(){super(...arguments),this.sessions=new vn(this._client),this.transcriptionSessions=new Cn(this._client)}};Wt.Sessions=vn;Wt.TranscriptionSessions=Cn;var Pn=class extends C{create(e,r,n){return this._client.post(A`/threads/${e}/messages`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,r,n){let{thread_id:s}=r;return this._client.get(A`/threads/${s}/messages/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,r,n){let{thread_id:s,...o}=r;return this._client.post(A`/threads/${s}/messages/${e}`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r={},n){return this._client.getAPIList(A`/threads/${e}/messages`,W,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,r,n){let{thread_id:s}=r;return this._client.delete(A`/threads/${s}/messages/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};var Rn=class extends C{retrieve(e,r,n){let{thread_id:s,run_id:o,...i}=r;return this._client.get(A`/threads/${s}/runs/${o}/steps/${e}`,{query:i,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r,n){let{thread_id:s,...o}=r;return this._client.getAPIList(A`/threads/${s}/runs/${e}/steps`,W,{query:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};var $d=t=>{if(typeof Buffer!="undefined"){let e=Buffer.from(t,"base64");return Array.from(new Float32Array(e.buffer,e.byteOffset,e.length/Float32Array.BYTES_PER_ELEMENT))}else{let e=atob(t),r=e.length,n=new Uint8Array(r);for(let s=0;s<r;s++)n[s]=e.charCodeAt(s);return Array.from(new Float32Array(n.buffer))}};var nt=t=>{var e,r,n,s,o,i;if(typeof globalThis.process!="undefined")return(n=(r=(e=globalThis.process.env)==null?void 0:e[t])==null?void 0:r.trim())!=null?n:void 0;if(typeof globalThis.Deno!="undefined")return(i=(o=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:o.call(s,t))==null?void 0:i.trim()};var fe,br,mc,st,Ci,He,wr,Tn,yr,Ti,Ce,Pi,Ri,Qs,Xs,Ys,Hd,jd,Wd,Vd,Kd,Gd,Jd,Et=class extends $t{constructor(){super(...arguments),fe.add(this),mc.set(this,[]),st.set(this,{}),Ci.set(this,{}),He.set(this,void 0),wr.set(this,void 0),Tn.set(this,void 0),yr.set(this,void 0),Ti.set(this,void 0),Ce.set(this,void 0),Pi.set(this,void 0),Ri.set(this,void 0),Qs.set(this,void 0)}[(mc=new WeakMap,st=new WeakMap,Ci=new WeakMap,He=new WeakMap,wr=new WeakMap,Tn=new WeakMap,yr=new WeakMap,Ti=new WeakMap,Ce=new WeakMap,Pi=new WeakMap,Ri=new WeakMap,Qs=new WeakMap,fe=new WeakSet,Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}static fromReadableStream(e){let r=new br;return r._run(()=>r._fromReadableStream(e)),r}async _fromReadableStream(e,r){var o;let n=r==null?void 0:r.signal;n&&(n.aborted&&this.controller.abort(),n.addEventListener("abort",()=>this.controller.abort())),this._connected();let s=et.fromReadableStream(e,this.controller);for await(let i of s)b(this,fe,"m",Xs).call(this,i);if((o=s.controller.signal)!=null&&o.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}toReadableStream(){return new et(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}static createToolAssistantStream(e,r,n,s){let o=new br;return o._run(()=>o._runToolAssistantStream(e,r,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}async _createToolAssistantStream(e,r,n,s){var c;let o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.submitToolOutputs(r,i,{...s,signal:this.controller.signal});this._connected();for await(let l of a)b(this,fe,"m",Xs).call(this,l);if((c=a.controller.signal)!=null&&c.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}static createThreadAssistantStream(e,r,n){let s=new br;return s._run(()=>s._threadAssistantStream(e,r,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}static createAssistantStream(e,r,n,s){let o=new br;return o._run(()=>o._runAssistantStream(e,r,n,{...s,headers:{...s==null?void 0:s.headers,"X-Stainless-Helper-Method":"stream"}})),o}currentEvent(){return b(this,Pi,"f")}currentRun(){return b(this,Ri,"f")}currentMessageSnapshot(){return b(this,He,"f")}currentRunStepSnapshot(){return b(this,Qs,"f")}async finalRunSteps(){return await this.done(),Object.values(b(this,st,"f"))}async finalMessages(){return await this.done(),Object.values(b(this,Ci,"f"))}async finalRun(){if(await this.done(),!b(this,wr,"f"))throw Error("Final run was not received.");return b(this,wr,"f")}async _createThreadAssistantStream(e,r,n){var a;let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort()));let o={...r,stream:!0},i=await e.createAndRun(o,{...n,signal:this.controller.signal});this._connected();for await(let c of i)b(this,fe,"m",Xs).call(this,c);if((a=i.controller.signal)!=null&&a.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}async _createAssistantStream(e,r,n,s){var c;let o=s==null?void 0:s.signal;o&&(o.aborted&&this.controller.abort(),o.addEventListener("abort",()=>this.controller.abort()));let i={...n,stream:!0},a=await e.create(r,i,{...s,signal:this.controller.signal});this._connected();for await(let l of a)b(this,fe,"m",Xs).call(this,l);if((c=a.controller.signal)!=null&&c.aborted)throw new X;return this._addRun(b(this,fe,"m",Ys).call(this))}static accumulateDelta(e,r){for(let[n,s]of Object.entries(r)){if(!e.hasOwnProperty(n)){e[n]=s;continue}let o=e[n];if(o==null){e[n]=s;continue}if(n==="index"||n==="type"){e[n]=s;continue}if(typeof o=="string"&&typeof s=="string")o+=s;else if(typeof o=="number"&&typeof s=="number")o+=s;else if(pn(o)&&pn(s))o=this.accumulateDelta(o,s);else if(Array.isArray(o)&&Array.isArray(s)){if(o.every(i=>typeof i=="string"||typeof i=="number")){o.push(...s);continue}for(let i of s){if(!pn(i))throw new Error(`Expected array delta entry to be an object but got: ${i}`);let a=i.index;if(a==null)throw console.error(i),new Error("Expected array delta entry to have an `index` property");if(typeof a!="number")throw new Error(`Expected array delta entry \`index\` property to be a number but got ${a}`);let c=o[a];c==null?o.push(i):o[a]=this.accumulateDelta(c,i)}continue}else throw Error(`Unhandled record type: ${n}, deltaValue: ${s}, accValue: ${o}`);e[n]=o}return e}_addRun(e){return e}async _threadAssistantStream(e,r,n){return await this._createThreadAssistantStream(r,e,n)}async _runAssistantStream(e,r,n,s){return await this._createAssistantStream(r,e,n,s)}async _runToolAssistantStream(e,r,n,s){return await this._createToolAssistantStream(r,e,n,s)}};br=Et,Xs=function(e){if(!this.ended)switch(N(this,Pi,e,"f"),b(this,fe,"m",Wd).call(this,e),e.event){case"thread.created":break;case"thread.run.created":case"thread.run.queued":case"thread.run.in_progress":case"thread.run.requires_action":case"thread.run.completed":case"thread.run.incomplete":case"thread.run.failed":case"thread.run.cancelling":case"thread.run.cancelled":case"thread.run.expired":b(this,fe,"m",Jd).call(this,e);break;case"thread.run.step.created":case"thread.run.step.in_progress":case"thread.run.step.delta":case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":b(this,fe,"m",jd).call(this,e);break;case"thread.message.created":case"thread.message.in_progress":case"thread.message.delta":case"thread.message.completed":case"thread.message.incomplete":b(this,fe,"m",Hd).call(this,e);break;case"error":throw new Error("Encountered an error event in event processing - errors should be processed earlier");default:}},Ys=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");if(!b(this,wr,"f"))throw Error("Final run has not been received");return b(this,wr,"f")},Hd=function(e){let[r,n]=b(this,fe,"m",Kd).call(this,e,b(this,He,"f"));N(this,He,r,"f"),b(this,Ci,"f")[r.id]=r;for(let s of n){let o=r.content[s.index];(o==null?void 0:o.type)=="text"&&this._emit("textCreated",o.text)}switch(e.event){case"thread.message.created":this._emit("messageCreated",e.data);break;case"thread.message.in_progress":break;case"thread.message.delta":if(this._emit("messageDelta",e.data.delta,r),e.data.delta.content)for(let s of e.data.delta.content){if(s.type=="text"&&s.text){let o=s.text,i=r.content[s.index];if(i&&i.type=="text")this._emit("textDelta",o,i.text);else throw Error("The snapshot associated with this text delta is not text or missing")}if(s.index!=b(this,Tn,"f")){if(b(this,yr,"f"))switch(b(this,yr,"f").type){case"text":this._emit("textDone",b(this,yr,"f").text,b(this,He,"f"));break;case"image_file":this._emit("imageFileDone",b(this,yr,"f").image_file,b(this,He,"f"));break}N(this,Tn,s.index,"f")}N(this,yr,r.content[s.index],"f")}break;case"thread.message.completed":case"thread.message.incomplete":if(b(this,Tn,"f")!==void 0){let s=e.data.content[b(this,Tn,"f")];if(s)switch(s.type){case"image_file":this._emit("imageFileDone",s.image_file,b(this,He,"f"));break;case"text":this._emit("textDone",s.text,b(this,He,"f"));break}}b(this,He,"f")&&this._emit("messageDone",e.data),N(this,He,void 0,"f")}},jd=function(e){let r=b(this,fe,"m",Vd).call(this,e);switch(N(this,Qs,r,"f"),e.event){case"thread.run.step.created":this._emit("runStepCreated",e.data);break;case"thread.run.step.delta":let n=e.data.delta;if(n.step_details&&n.step_details.type=="tool_calls"&&n.step_details.tool_calls&&r.step_details.type=="tool_calls")for(let o of n.step_details.tool_calls)o.index==b(this,Ti,"f")?this._emit("toolCallDelta",o,r.step_details.tool_calls[o.index]):(b(this,Ce,"f")&&this._emit("toolCallDone",b(this,Ce,"f")),N(this,Ti,o.index,"f"),N(this,Ce,r.step_details.tool_calls[o.index],"f"),b(this,Ce,"f")&&this._emit("toolCallCreated",b(this,Ce,"f")));this._emit("runStepDelta",e.data.delta,r);break;case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":N(this,Qs,void 0,"f"),e.data.step_details.type=="tool_calls"&&b(this,Ce,"f")&&(this._emit("toolCallDone",b(this,Ce,"f")),N(this,Ce,void 0,"f")),this._emit("runStepDone",e.data,r);break;case"thread.run.step.in_progress":break}},Wd=function(e){b(this,mc,"f").push(e),this._emit("event",e)},Vd=function(e){switch(e.event){case"thread.run.step.created":return b(this,st,"f")[e.data.id]=e.data,e.data;case"thread.run.step.delta":let r=b(this,st,"f")[e.data.id];if(!r)throw Error("Received a RunStepDelta before creation of a snapshot");let n=e.data;if(n.delta){let s=br.accumulateDelta(r,n.delta);b(this,st,"f")[e.data.id]=s}return b(this,st,"f")[e.data.id];case"thread.run.step.completed":case"thread.run.step.failed":case"thread.run.step.cancelled":case"thread.run.step.expired":case"thread.run.step.in_progress":b(this,st,"f")[e.data.id]=e.data;break}if(b(this,st,"f")[e.data.id])return b(this,st,"f")[e.data.id];throw new Error("No snapshot available")},Kd=function(e,r){let n=[];switch(e.event){case"thread.message.created":return[e.data,n];case"thread.message.delta":if(!r)throw Error("Received a delta with no existing snapshot (there should be one from message creation)");let s=e.data;if(s.delta.content)for(let o of s.delta.content)if(o.index in r.content){let i=r.content[o.index];r.content[o.index]=b(this,fe,"m",Gd).call(this,o,i)}else r.content[o.index]=o,n.push(o);return[r,n];case"thread.message.in_progress":case"thread.message.completed":case"thread.message.incomplete":if(r)return[r,n];throw Error("Received thread message event with no existing snapshot")}throw Error("Tried to accumulate a non-message event")},Gd=function(e,r){return br.accumulateDelta(r,e)},Jd=function(e){switch(N(this,Ri,e.data,"f"),e.event){case"thread.run.created":break;case"thread.run.queued":break;case"thread.run.in_progress":break;case"thread.run.requires_action":case"thread.run.cancelled":case"thread.run.failed":case"thread.run.completed":case"thread.run.expired":case"thread.run.incomplete":N(this,wr,e.data,"f"),b(this,Ce,"f")&&(this._emit("toolCallDone",b(this,Ce,"f")),N(this,Ce,void 0,"f"));break;case"thread.run.cancelling":break}};var _r=class extends C{constructor(){super(...arguments),this.steps=new Rn(this._client)}create(e,r,n){var i;let{include:s,...o}=r;return this._client.post(A`/threads/${e}/runs`,{query:{include:s},body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:(i=r.stream)!=null?i:!1})}retrieve(e,r,n){let{thread_id:s}=r;return this._client.get(A`/threads/${s}/runs/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,r,n){let{thread_id:s,...o}=r;return this._client.post(A`/threads/${s}/runs/${e}`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r={},n){return this._client.getAPIList(A`/threads/${e}/runs`,W,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,r,n){let{thread_id:s}=r;return this._client.post(A`/threads/${s}/runs/${e}/cancel`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,r,n){let s=await this.create(e,r,n);return await this.poll(s.id,{thread_id:e},n)}createAndStream(e,r,n){return Et.createAssistantStream(e,this._client.beta.threads.runs,r,n)}async poll(e,r,n){var o,i;let s=I([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":(i=(o=n==null?void 0:n.pollIntervalMs)==null?void 0:o.toString())!=null?i:void 0}]);for(;;){let{data:a,response:c}=await this.retrieve(e,r,{...n,headers:{...n==null?void 0:n.headers,...s}}).withResponse();switch(a.status){case"queued":case"in_progress":case"cancelling":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{let f=c.headers.get("openai-poll-after-ms");if(f){let u=parseInt(f);isNaN(u)||(l=u)}}await Ye(l);break;case"requires_action":case"incomplete":case"cancelled":case"completed":case"failed":case"expired":return a}}}stream(e,r,n){return Et.createAssistantStream(e,this._client.beta.threads.runs,r,n)}submitToolOutputs(e,r,n){var i;let{thread_id:s,...o}=r;return this._client.post(A`/threads/${s}/runs/${e}/submit_tool_outputs`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers]),stream:(i=r.stream)!=null?i:!1})}async submitToolOutputsAndPoll(e,r,n){let s=await this.submitToolOutputs(e,r,n);return await this.poll(s.id,r,n)}submitToolOutputsStream(e,r,n){return Et.createToolAssistantStream(e,this._client.beta.threads.runs,r,n)}};_r.Steps=Rn;var Vt=class extends C{constructor(){super(...arguments),this.runs=new _r(this._client),this.messages=new Pn(this._client)}create(e={},r){return this._client.post("/threads",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,r){return this._client.get(A`/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,r,n){return this._client.post(A`/threads/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,r){return this._client.delete(A`/threads/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}createAndRun(e,r){var n;return this._client.post("/threads/runs",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers]),stream:(n=e.stream)!=null?n:!1})}async createAndRunPoll(e,r){let n=await this.createAndRun(e,r);return await this.runs.poll(n.id,{thread_id:n.thread_id},r)}createAndRunStream(e,r){return Et.createThreadAssistantStream(e,this._client.beta.threads,r)}};Vt.Runs=_r;Vt.Messages=Pn;var ot=class extends C{constructor(){super(...arguments),this.realtime=new Wt(this._client),this.assistants=new An(this._client),this.threads=new Vt(this._client)}};ot.Realtime=Wt;ot.Assistants=An;ot.Threads=Vt;var Sr=class extends C{create(e,r){var n;return this._client.post("/completions",{body:e,...r,stream:(n=e.stream)!=null?n:!1})}};var In=class extends C{retrieve(e,r,n){let{container_id:s}=r;return this._client.get(A`/containers/${s}/files/${e}/content`,{...n,headers:I([{Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}};var Er=class extends C{constructor(){super(...arguments),this.content=new In(this._client)}create(e,r,n){return this._client.post(A`/containers/${e}/files`,ve({body:r,...n},this._client))}retrieve(e,r,n){let{container_id:s}=r;return this._client.get(A`/containers/${s}/files/${e}`,n)}list(e,r={},n){return this._client.getAPIList(A`/containers/${e}/files`,W,{query:r,...n})}delete(e,r,n){let{container_id:s}=r;return this._client.delete(A`/containers/${s}/files/${e}`,{...n,headers:I([{Accept:"*/*"},n==null?void 0:n.headers])})}};Er.Content=In;var Kt=class extends C{constructor(){super(...arguments),this.files=new Er(this._client)}create(e,r){return this._client.post("/containers",{body:e,...r})}retrieve(e,r){return this._client.get(A`/containers/${e}`,r)}list(e={},r){return this._client.getAPIList("/containers",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/containers/${e}`,{...r,headers:I([{Accept:"*/*"},r==null?void 0:r.headers])})}};Kt.Files=Er;var xr=class extends C{create(e,r){let n=!!e.encoding_format,s=n?e.encoding_format:"base64";n&&re(this._client).debug("embeddings/user defined encoding_format:",e.encoding_format);let o=this._client.post("/embeddings",{body:{...e,encoding_format:s},...r});return n?o:(re(this._client).debug("embeddings/decoding base64 embeddings from base64"),o._thenUnwrap(i=>(i&&i.data&&i.data.forEach(a=>{let c=a.embedding;a.embedding=$d(c)}),i)))}};var kn=class extends C{retrieve(e,r,n){let{eval_id:s,run_id:o}=r;return this._client.get(A`/evals/${s}/runs/${o}/output_items/${e}`,n)}list(e,r,n){let{eval_id:s,...o}=r;return this._client.getAPIList(A`/evals/${s}/runs/${e}/output_items`,W,{query:o,...n})}};var Ar=class extends C{constructor(){super(...arguments),this.outputItems=new kn(this._client)}create(e,r,n){return this._client.post(A`/evals/${e}/runs`,{body:r,...n})}retrieve(e,r,n){let{eval_id:s}=r;return this._client.get(A`/evals/${s}/runs/${e}`,n)}list(e,r={},n){return this._client.getAPIList(A`/evals/${e}/runs`,W,{query:r,...n})}delete(e,r,n){let{eval_id:s}=r;return this._client.delete(A`/evals/${s}/runs/${e}`,n)}cancel(e,r,n){let{eval_id:s}=r;return this._client.post(A`/evals/${s}/runs/${e}`,n)}};Ar.OutputItems=kn;var Gt=class extends C{constructor(){super(...arguments),this.runs=new Ar(this._client)}create(e,r){return this._client.post("/evals",{body:e,...r})}retrieve(e,r){return this._client.get(A`/evals/${e}`,r)}update(e,r,n){return this._client.post(A`/evals/${e}`,{body:r,...n})}list(e={},r){return this._client.getAPIList("/evals",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/evals/${e}`,r)}};Gt.Runs=Ar;var vr=class extends C{create(e,r){return this._client.post("/files",ve({body:e,...r},this._client))}retrieve(e,r){return this._client.get(A`/files/${e}`,r)}list(e={},r){return this._client.getAPIList("/files",W,{query:e,...r})}delete(e,r){return this._client.delete(A`/files/${e}`,r)}content(e,r){return this._client.get(A`/files/${e}/content`,{...r,headers:I([{Accept:"application/binary"},r==null?void 0:r.headers]),__binaryResponse:!0})}async waitForProcessing(e,{pollInterval:r=5e3,maxWait:n=1800*1e3}={}){let s=new Set(["processed","error","deleted"]),o=Date.now(),i=await this.retrieve(e);for(;!i.status||!s.has(i.status);)if(await Ye(r),i=await this.retrieve(e),Date.now()-o>n)throw new qt({message:`Giving up on waiting for file ${e} to finish processing after ${n} milliseconds.`});return i}};var On=class extends C{};var Mn=class extends C{run(e,r){return this._client.post("/fine_tuning/alpha/graders/run",{body:e,...r})}validate(e,r){return this._client.post("/fine_tuning/alpha/graders/validate",{body:e,...r})}};var Cr=class extends C{constructor(){super(...arguments),this.graders=new Mn(this._client)}};Cr.Graders=Mn;var Ln=class extends C{create(e,r,n){return this._client.getAPIList(A`/fine_tuning/checkpoints/${e}/permissions`,tt,{body:r,method:"post",...n})}retrieve(e,r={},n){return this._client.get(A`/fine_tuning/checkpoints/${e}/permissions`,{query:r,...n})}delete(e,r,n){let{fine_tuned_model_checkpoint:s}=r;return this._client.delete(A`/fine_tuning/checkpoints/${s}/permissions/${e}`,n)}};var Pr=class extends C{constructor(){super(...arguments),this.permissions=new Ln(this._client)}};Pr.Permissions=Ln;var Nn=class extends C{list(e,r={},n){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/checkpoints`,W,{query:r,...n})}};var Rr=class extends C{constructor(){super(...arguments),this.checkpoints=new Nn(this._client)}create(e,r){return this._client.post("/fine_tuning/jobs",{body:e,...r})}retrieve(e,r){return this._client.get(A`/fine_tuning/jobs/${e}`,r)}list(e={},r){return this._client.getAPIList("/fine_tuning/jobs",W,{query:e,...r})}cancel(e,r){return this._client.post(A`/fine_tuning/jobs/${e}/cancel`,r)}listEvents(e,r={},n){return this._client.getAPIList(A`/fine_tuning/jobs/${e}/events`,W,{query:r,...n})}pause(e,r){return this._client.post(A`/fine_tuning/jobs/${e}/pause`,r)}resume(e,r){return this._client.post(A`/fine_tuning/jobs/${e}/resume`,r)}};Rr.Checkpoints=Nn;var je=class extends C{constructor(){super(...arguments),this.methods=new On(this._client),this.jobs=new Rr(this._client),this.checkpoints=new Pr(this._client),this.alpha=new Cr(this._client)}};je.Methods=On;je.Jobs=Rr;je.Checkpoints=Pr;je.Alpha=Cr;var Dn=class extends C{};var Jt=class extends C{constructor(){super(...arguments),this.graderModels=new Dn(this._client)}};Jt.GraderModels=Dn;var Tr=class extends C{createVariation(e,r){return this._client.post("/images/variations",ve({body:e,...r},this._client))}edit(e,r){return this._client.post("/images/edits",ve({body:e,...r},this._client))}generate(e,r){return this._client.post("/images/generations",{body:e,...r})}};var Ir=class extends C{retrieve(e,r){return this._client.get(A`/models/${e}`,r)}list(e){return this._client.getAPIList("/models",tt,e)}delete(e,r){return this._client.delete(A`/models/${e}`,r)}};var kr=class extends C{create(e,r){return this._client.post("/moderations",{body:e,...r})}};function zd(t,e){return!e||!jb(e)?{...t,output_parsed:null,output:t.output.map(r=>r.type==="function_call"?{...r,parsed_arguments:null}:r.type==="message"?{...r,content:r.content.map(n=>({...n,parsed:null}))}:r)}:gc(t,e)}function gc(t,e){let r=t.output.map(s=>{if(s.type==="function_call")return{...s,parsed_arguments:Kb(e,s)};if(s.type==="message"){let o=s.content.map(i=>i.type==="output_text"?{...i,parsed:Hb(e,i.text)}:i);return{...s,content:o}}return s}),n=Object.assign({},t,{output:r});return Object.getOwnPropertyDescriptor(t,"output_text")||yc(n),Object.defineProperty(n,"output_parsed",{enumerable:!0,get(){for(let s of n.output)if(s.type==="message"){for(let o of s.content)if(o.type==="output_text"&&o.parsed!==null)return o.parsed}return null}}),n}function Hb(t,e){var r,n,s,o;return((n=(r=t.text)==null?void 0:r.format)==null?void 0:n.type)!=="json_schema"?null:"$parseRaw"in((s=t.text)==null?void 0:s.format)?((o=t.text)==null?void 0:o.format).$parseRaw(e):JSON.parse(e)}function jb(t){var e;return!!Ks((e=t.text)==null?void 0:e.format)}function Wb(t){return(t==null?void 0:t.$brand)==="auto-parseable-tool"}function Vb(t,e){return t.find(r=>r.type==="function"&&r.name===e)}function Kb(t,e){var n;let r=Vb((n=t.tools)!=null?n:[],e.name);return{...e,...e,parsed_arguments:Wb(r)?r.$parseRaw(e.arguments):r!=null&&r.strict?JSON.parse(e.arguments):null}}function yc(t){let e=[];for(let r of t.output)if(r.type==="message")for(let n of r.content)n.type==="output_text"&&e.push(n.text);t.output_text=e.join("")}var Bn,Ii,zt,ki,Xd,Yd,Qd,Zd,Oi=class t extends $t{constructor(e){super(),Bn.add(this),Ii.set(this,void 0),zt.set(this,void 0),ki.set(this,void 0),N(this,Ii,e,"f")}static createResponse(e,r,n){let s=new t(r);return s._run(()=>s._createOrRetrieveResponse(e,r,{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}async _createOrRetrieveResponse(e,r,n){var a,c;let s=n==null?void 0:n.signal;s&&(s.aborted&&this.controller.abort(),s.addEventListener("abort",()=>this.controller.abort())),b(this,Bn,"m",Xd).call(this);let o,i=null;"response_id"in r?(o=await e.responses.retrieve(r.response_id,{stream:!0},{...n,signal:this.controller.signal,stream:!0}),i=(a=r.starting_after)!=null?a:null):o=await e.responses.create({...r,stream:!0},{...n,signal:this.controller.signal}),this._connected();for await(let l of o)b(this,Bn,"m",Yd).call(this,l,i);if((c=o.controller.signal)!=null&&c.aborted)throw new X;return b(this,Bn,"m",Qd).call(this)}[(Ii=new WeakMap,zt=new WeakMap,ki=new WeakMap,Bn=new WeakSet,Xd=function(){this.ended||N(this,zt,void 0,"f")},Yd=function(r,n){if(this.ended)return;let s=(i,a)=>{(n==null||a.sequence_number>n)&&this._emit(i,a)},o=b(this,Bn,"m",Zd).call(this,r);switch(s("event",r),r.type){case"response.output_text.delta":{let i=o.output[r.output_index];if(!i)throw new T(`missing output at index ${r.output_index}`);if(i.type==="message"){let a=i.content[r.content_index];if(!a)throw new T(`missing content at index ${r.content_index}`);if(a.type!=="output_text")throw new T(`expected content to be 'output_text', got ${a.type}`);s("response.output_text.delta",{...r,snapshot:a.text})}break}case"response.function_call_arguments.delta":{let i=o.output[r.output_index];if(!i)throw new T(`missing output at index ${r.output_index}`);i.type==="function_call"&&s("response.function_call_arguments.delta",{...r,snapshot:i.arguments});break}default:s(r.type,r);break}},Qd=function(){if(this.ended)throw new T("stream has ended, this shouldn't happen");let r=b(this,zt,"f");if(!r)throw new T("request ended without sending any events");N(this,zt,void 0,"f");let n=Gb(r,b(this,Ii,"f"));return N(this,ki,n,"f"),n},Zd=function(r){let n=b(this,zt,"f");if(!n){if(r.type!=="response.created")throw new T(`When snapshot hasn't been set yet, expected 'response.created' event, got ${r.type}`);return n=N(this,zt,r.response,"f"),n}switch(r.type){case"response.output_item.added":{n.output.push(r.item);break}case"response.content_part.added":{let s=n.output[r.output_index];if(!s)throw new T(`missing output at index ${r.output_index}`);s.type==="message"&&s.content.push(r.part);break}case"response.output_text.delta":{let s=n.output[r.output_index];if(!s)throw new T(`missing output at index ${r.output_index}`);if(s.type==="message"){let o=s.content[r.content_index];if(!o)throw new T(`missing content at index ${r.content_index}`);if(o.type!=="output_text")throw new T(`expected content to be 'output_text', got ${o.type}`);o.text+=r.delta}break}case"response.function_call_arguments.delta":{let s=n.output[r.output_index];if(!s)throw new T(`missing output at index ${r.output_index}`);s.type==="function_call"&&(s.arguments+=r.delta);break}case"response.completed":{N(this,zt,r.response,"f");break}}return n},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("event",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}async finalResponse(){await this.done();let e=b(this,ki,"f");if(!e)throw new T("stream ended without producing a ChatCompletion");return e}};function Gb(t,e){return zd(t,e)}var Fn=class extends C{list(e,r={},n){return this._client.getAPIList(A`/responses/${e}/input_items`,W,{query:r,...n})}};var Xt=class extends C{constructor(){super(...arguments),this.inputItems=new Fn(this._client)}create(e,r){var n;return this._client.post("/responses",{body:e,...r,stream:(n=e.stream)!=null?n:!1})._thenUnwrap(s=>("object"in s&&s.object==="response"&&yc(s),s))}retrieve(e,r={},n){var s;return this._client.get(A`/responses/${e}`,{query:r,...n,stream:(s=r==null?void 0:r.stream)!=null?s:!1})}delete(e,r){return this._client.delete(A`/responses/${e}`,{...r,headers:I([{Accept:"*/*"},r==null?void 0:r.headers])})}parse(e,r){return this._client.responses.create(e,r)._thenUnwrap(n=>gc(n,e))}stream(e,r){return Oi.createResponse(this._client,e,r)}cancel(e,r){return this._client.post(A`/responses/${e}/cancel`,r)}};Xt.InputItems=Fn;var qn=class extends C{create(e,r,n){return this._client.post(A`/uploads/${e}/parts`,ve({body:r,...n},this._client))}};var Yt=class extends C{constructor(){super(...arguments),this.parts=new qn(this._client)}create(e,r){return this._client.post("/uploads",{body:e,...r})}cancel(e,r){return this._client.post(A`/uploads/${e}/cancel`,r)}complete(e,r,n){return this._client.post(A`/uploads/${e}/complete`,{body:r,...n})}};Yt.Parts=qn;var eh=async t=>{let e=await Promise.allSettled(t),r=e.filter(s=>s.status==="rejected");if(r.length){for(let s of r)console.error(s.reason);throw new Error(`${r.length} promise(s) failed - see the above errors`)}let n=[];for(let s of e)s.status==="fulfilled"&&n.push(s.value);return n};var Un=class extends C{create(e,r,n){return this._client.post(A`/vector_stores/${e}/file_batches`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,r,n){let{vector_store_id:s}=r;return this._client.get(A`/vector_stores/${s}/file_batches/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}cancel(e,r,n){let{vector_store_id:s}=r;return this._client.post(A`/vector_stores/${s}/file_batches/${e}/cancel`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,r,n){let s=await this.create(e,r);return await this.poll(e,s.id,n)}listFiles(e,r,n){let{vector_store_id:s,...o}=r;return this._client.getAPIList(A`/vector_stores/${s}/file_batches/${e}/files`,W,{query:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async poll(e,r,n){var o,i;let s=I([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":(i=(o=n==null?void 0:n.pollIntervalMs)==null?void 0:o.toString())!=null?i:void 0}]);for(;;){let{data:a,response:c}=await this.retrieve(r,{vector_store_id:e},{...n,headers:s}).withResponse();switch(a.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{let f=c.headers.get("openai-poll-after-ms");if(f){let u=parseInt(f);isNaN(u)||(l=u)}}await Ye(l);break;case"failed":case"cancelled":case"completed":return a}}}async uploadAndPoll(e,{files:r,fileIds:n=[]},s){var d;if(r==null||r.length==0)throw new Error("No `files` provided to process. If you've already uploaded files you should use `.createAndPoll()` instead");let o=(d=s==null?void 0:s.maxConcurrency)!=null?d:5,i=Math.min(o,r.length),a=this._client,c=r.values(),l=[...n];async function f(h){for(let p of h){let y=await a.files.create({file:p,purpose:"assistants"},s);l.push(y.id)}}let u=Array(i).fill(c).map(f);return await eh(u),await this.createAndPoll(e,{file_ids:l})}};var $n=class extends C{create(e,r,n){return this._client.post(A`/vector_stores/${e}/files`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}retrieve(e,r,n){let{vector_store_id:s}=r;return this._client.get(A`/vector_stores/${s}/files/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}update(e,r,n){let{vector_store_id:s,...o}=r;return this._client.post(A`/vector_stores/${s}/files/${e}`,{body:o,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e,r={},n){return this._client.getAPIList(A`/vector_stores/${e}/files`,W,{query:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}delete(e,r,n){let{vector_store_id:s}=r;return this._client.delete(A`/vector_stores/${s}/files/${e}`,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}async createAndPoll(e,r,n){let s=await this.create(e,r,n);return await this.poll(e,s.id,n)}async poll(e,r,n){var o,i;let s=I([n==null?void 0:n.headers,{"X-Stainless-Poll-Helper":"true","X-Stainless-Custom-Poll-Interval":(i=(o=n==null?void 0:n.pollIntervalMs)==null?void 0:o.toString())!=null?i:void 0}]);for(;;){let a=await this.retrieve(r,{vector_store_id:e},{...n,headers:s}).withResponse(),c=a.data;switch(c.status){case"in_progress":let l=5e3;if(n!=null&&n.pollIntervalMs)l=n.pollIntervalMs;else{let f=a.response.headers.get("openai-poll-after-ms");if(f){let u=parseInt(f);isNaN(u)||(l=u)}}await Ye(l);break;case"failed":case"completed":return c}}}async upload(e,r,n){let s=await this._client.files.create({file:r,purpose:"assistants"},n);return this.create(e,{file_id:s.id},n)}async uploadAndPoll(e,r,n){let s=await this.upload(e,r,n);return await this.poll(e,s.id,n)}content(e,r,n){let{vector_store_id:s}=r;return this._client.getAPIList(A`/vector_stores/${s}/files/${e}/content`,tt,{...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};var xt=class extends C{constructor(){super(...arguments),this.files=new $n(this._client),this.fileBatches=new Un(this._client)}create(e,r){return this._client.post("/vector_stores",{body:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}retrieve(e,r){return this._client.get(A`/vector_stores/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}update(e,r,n){return this._client.post(A`/vector_stores/${e}`,{body:r,...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}list(e={},r){return this._client.getAPIList("/vector_stores",W,{query:e,...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}delete(e,r){return this._client.delete(A`/vector_stores/${e}`,{...r,headers:I([{"OpenAI-Beta":"assistants=v2"},r==null?void 0:r.headers])})}search(e,r,n){return this._client.getAPIList(A`/vector_stores/${e}/search`,tt,{body:r,method:"post",...n,headers:I([{"OpenAI-Beta":"assistants=v2"},n==null?void 0:n.headers])})}};xt.Files=$n;xt.FileBatches=Un;var bc,Mi,D=class{constructor({baseURL:e=nt("OPENAI_BASE_URL"),apiKey:r=nt("OPENAI_API_KEY"),organization:n=(i=>(i=nt("OPENAI_ORG_ID"))!=null?i:null)(),project:s=(a=>(a=nt("OPENAI_PROJECT_ID"))!=null?a:null)(),...o}={}){var f,u,d,h,p,y;if(Mi.set(this,void 0),this.completions=new Sr(this),this.chat=new jt(this),this.embeddings=new xr(this),this.files=new vr(this),this.images=new Tr(this),this.audio=new rt(this),this.moderations=new kr(this),this.models=new Ir(this),this.fineTuning=new je(this),this.graders=new Jt(this),this.vectorStores=new xt(this),this.beta=new ot(this),this.batches=new gr(this),this.uploads=new Yt(this),this.responses=new Xt(this),this.evals=new Gt(this),this.containers=new Kt(this),r===void 0)throw new T("The OPENAI_API_KEY environment variable is missing or empty; either provide it, or instantiate the OpenAI client with an apiKey option, like new OpenAI({ apiKey: 'My API Key' }).");let c={apiKey:r,organization:n,project:s,...o,baseURL:e||"https://api.openai.com/v1"};if(!c.dangerouslyAllowBrowser&&gd())throw new T(`It looks like you're running in a browser-like environment.
This is disabled by default, as it risks exposing your secret API credentials to attackers.
If you understand the risks and have appropriate mitigations in place,
you can set the \`dangerouslyAllowBrowser\` option to \`true\`, e.g.,
new OpenAI({ apiKey, dangerouslyAllowBrowser: true });
https://help.openai.com/en/articles/5112595-best-practices-for-api-key-safety
`);this.baseURL=c.baseURL,this.timeout=(f=c.timeout)!=null?f:bc.DEFAULT_TIMEOUT,this.logger=(u=c.logger)!=null?u:console;let l="warn";this.logLevel=l,this.logLevel=(h=(d=ql(c.logLevel,"ClientOptions.logLevel",this))!=null?d:ql(nt("OPENAI_LOG"),"process.env['OPENAI_LOG']",this))!=null?h:l,this.fetchOptions=c.fetchOptions,this.maxRetries=(p=c.maxRetries)!=null?p:2,this.fetch=(y=c.fetch)!=null?y:bd(),N(this,Mi,_d,"f"),this._options=c,this.apiKey=r,this.organization=n,this.project=s}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetchOptions:this.fetchOptions,apiKey:this.apiKey,organization:this.organization,project:this.project,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){}authHeaders(e){return I([{Authorization:`Bearer ${this.apiKey}`}])}stringifyQuery(e){return Kl(e,{arrayFormat:"brackets"})}getUserAgent(){return`${this.constructor.name}/JS ${Ut}`}defaultIdempotencyKey(){return`stainless-node-retry-${Fl()}`}makeStatusError(e,r,n,s){return te.generate(e,r,n,s)}buildURL(e,r){let n=ad(e)?new URL(e):new URL(this.baseURL+(this.baseURL.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),s=this.defaultQuery();return cd(s)||(r={...s,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(n.search=this.stringifyQuery(r)),n.toString()}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:r,...s})))}request(e,r=null){return new dr(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){var S,_,v;let s=await e,o=(S=s.maxRetries)!=null?S:this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:c}=this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=n===void 0?"":`, retryOf: ${n}`,u=Date.now();if(re(this).debug(`[${l}] sending request`,bt({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),(_=s.signal)!=null&&_.aborted)throw new X;let d=new AbortController,h=await this.fetchWithTimeout(a,i,c,d).catch(Ns),p=Date.now();if(h instanceof Error){let P=`retrying, ${r} attempts remaining`;if((v=s.signal)!=null&&v.aborted)throw new X;let E=Ls(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return re(this).info(`[${l}] connection ${E?"timed out":"failed"} - ${P}`),re(this).debug(`[${l}] connection ${E?"timed out":"failed"} (${P})`,bt({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),this.retryRequest(s,r,n!=null?n:l);throw re(this).info(`[${l}] connection ${E?"timed out":"failed"} - error; no more retries left`),re(this).debug(`[${l}] connection ${E?"timed out":"failed"} (error; no more retries left)`,bt({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),E?new qt:new Ft({cause:h})}let y=[...h.headers.entries()].filter(([P])=>P==="x-request-id").map(([P,E])=>", "+P+": "+JSON.stringify(E)).join(""),g=`[${l}${f}${y}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){let P=this.shouldRetry(h);if(r&&P){let F=`retrying, ${r} attempts remaining`;return await wd(h.body),re(this).info(`${g} - ${F}`),re(this).debug(`[${l}] response error (${F})`,bt({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(s,r,n!=null?n:l,h.headers)}let E=P?"error; no more retries left":"error; not retryable";re(this).info(`${g} - ${E}`);let R=await h.text().catch(F=>Ns(F).message),k=dd(R),M=k?void 0:R;throw re(this).debug(`[${l}] response error (${E})`,bt({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:M,durationMs:Date.now()-u})),this.makeStatusError(h.status,k,M,h.headers)}return re(this).info(g),re(this).debug(`[${l}] response start`,bt({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:s,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:u}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new Us(this,n,e)}async fetchWithTimeout(e,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let c=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...a};i&&(f.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(c)}}shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,s){var c;let o,i=s==null?void 0:s.get("retry-after-ms");if(i){let l=parseFloat(i);Number.isNaN(l)||(o=l)}let a=s==null?void 0:s.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=(c=e.maxRetries)!=null?c:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await Ye(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}buildRequest(e,{retryCount:r=0}={}){var d,h,p;let n={...e},{method:s,path:o,query:i}=n,a=this.buildURL(o,i);"timeout"in n&&fd("timeout",n.timeout),n.timeout=(d=n.timeout)!=null?d:this.timeout;let{bodyHeaders:c,body:l}=this.buildBody({options:n}),f=this.buildHeaders({options:e,method:s,bodyHeaders:c,retryCount:r});return{req:{method:s,headers:f,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&l instanceof globalThis.ReadableStream&&{duplex:"half"},...l&&{body:l},...(h=this.fetchOptions)!=null?h:{},...(p=n.fetchOptions)!=null?p:{}},url:a,timeout:n.timeout}}buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=I([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...yd(),"OpenAI-Organization":this.organization,"OpenAI-Project":this.project},this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=I([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:ui(e)}:b(this,Mi,"f").call(this,{body:e,headers:n})}};bc=D,Mi=new WeakMap;D.OpenAI=bc;D.DEFAULT_TIMEOUT=6e5;D.OpenAIError=T;D.APIError=te;D.APIConnectionError=Ft;D.APIConnectionTimeoutError=qt;D.APIUserAbortError=X;D.NotFoundError=an;D.ConflictError=ln;D.RateLimitError=un;D.BadRequestError=nn;D.AuthenticationError=sn;D.InternalServerError=fn;D.PermissionDeniedError=on;D.UnprocessableEntityError=cn;D.toFile=gi;D.Completions=Sr;D.Chat=jt;D.Embeddings=xr;D.Files=vr;D.Images=Tr;D.Audio=rt;D.Moderations=kr;D.Models=Ir;D.FineTuning=je;D.Graders=Jt;D.VectorStores=xt;D.Beta=ot;D.Batches=gr;D.Uploads=Yt;D.Responses=Xt;D.Evals=Gt;D.Containers=Kt;var Zs=class extends D{constructor({baseURL:e=nt("OPENAI_BASE_URL"),apiKey:r=nt("AZURE_OPENAI_API_KEY"),apiVersion:n=nt("OPENAI_API_VERSION"),endpoint:s,deployment:o,azureADTokenProvider:i,dangerouslyAllowBrowser:a,...c}={}){if(!n)throw new T("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 i=="function"&&(a=!0),!i&&!r)throw new T("Missing credentials. Please pass one of `apiKey` and `azureADTokenProvider`, or set the `AZURE_OPENAI_API_KEY` environment variable.");if(i&&r)throw new T("The `apiKey` and `azureADTokenProvider` arguments are mutually exclusive; only one can be passed at a time.");if(r!=null||(r=th),c.defaultQuery={...c.defaultQuery,"api-version":n},e){if(s)throw new T("baseURL and endpoint are mutually exclusive")}else{if(s||(s=process.env.AZURE_OPENAI_ENDPOINT),!s)throw new T("Must provide one of the `baseURL` or `endpoint` arguments, or the `AZURE_OPENAI_ENDPOINT` environment variable");e=`${s}/openai`}super({apiKey:r,baseURL:e,...c,...a!==void 0?{dangerouslyAllowBrowser:a}:{}}),this.apiVersion="",this._azureADTokenProvider=i,this.apiVersion=n,this.deploymentName=o}buildRequest(e,r={}){var n;if(Zb.has(e.path)&&e.method==="post"&&e.body!==void 0){if(!pn(e.body))throw new Error("Expected request body to be an object");let s=this.deploymentName||e.body.model||((n=e.__metadata)==null?void 0:n.model);s!==void 0&&!this.baseURL.includes("/deployments")&&(e.path=`/deployments/${s}${e.path}`)}return super.buildRequest(e,r)}async _getAzureADToken(){if(typeof this._azureADTokenProvider=="function"){let e=await this._azureADTokenProvider();if(!e||typeof e!="string")throw new T(`Expected 'azureADTokenProvider' argument to return a string but it returned ${e}`);return e}}authHeaders(e){}async prepareOptions(e){if(e.headers=I([e.headers]),e.headers.values.get("Authorization")||e.headers.values.get("api-key"))return super.prepareOptions(e);let r=await this._getAzureADToken();if(r)e.headers.values.set("Authorization",`Bearer ${r}`);else if(this.apiKey!==th)e.headers.values.set("api-key",this.apiKey);else throw new T("Unable to handle auth");return super.prepareOptions(e)}},Zb=new Set(["/completions","/chat/completions","/embeddings","/audio/transcriptions","/audio/translations","/audio/speech","/images/generations","/batches","/images/edits"]),th="<Missing Key>";var Or=t=>{var n;let e=((n=t.split(".").pop())==null?void 0:n.toLowerCase())||"";return{png:"image/png",jpg:"image/jpeg",jpeg:"image/jpeg",gif:"image/gif",webp:"image/webp",svg:"image/svg+xml",bmp:"image/bmp",ico:"image/x-icon",pdf:"application/pdf",doc:"application/msword",docx:"application/vnd.openxmlformats-officedocument.wordprocessingml.document",xls:"application/vnd.ms-excel",xlsx:"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",ppt:"application/vnd.ms-powerpoint",pptx:"application/vnd.openxmlformats-officedocument.presentationml.presentation",txt:"text/plain",html:"text/html",css:"text/css",js:"application/javascript",json:"application/json",xml:"application/xml",md:"text/markdown",mp3:"audio/mpeg",wav:"audio/wav",ogg:"audio/ogg",flac:"audio/flac",m4a:"audio/mp4",mp4:"video/mp4",avi:"video/x-msvideo",mov:"video/quicktime",wmv:"video/x-ms-wmv",webm:"video/webm"}[e]||"application/octet-stream"},it=`
> [!quote]-
> `,at=`
`,Mr=t=>{let e="",r=new Uint8Array(t),n=r.byteLength;for(let s=0;s<n;s++)e+=String.fromCharCode(r[s]);return window.btoa(e)},Qt=async(t,e)=>{let r=Or(t.link);if(["image/png","image/jpeg","image/gif","image/webp"].includes(r)===!1)throw new Error(m("Only PNG, JPEG, GIF, and WebP images are supported."));let n=await e(t),s=Mr(n);return{type:"image_url",image_url:{url:`data:${r};base64,${s}`}}},Hn=t=>{switch(t){case"Text Generation":return"\u270D\uFE0F";case"Image Vision":return"\u{1F441}\uFE0F";case"PDF Vision":return"\u{1F4C4}";case"Image Generation":return"\u{1F3A8}";case"Image Editing":return"\u270F\uFE0F";case"Web Search":return"\u{1F50D}";case"Reasoning":return"\u{1F9E0}"}};var ew=t=>async function*(e,r,n){var S,_;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,model:c,endpoint:l,apiVersion:f,...u}=i;if(!a)throw new Error(m("API key is required"));let d=new Zs({endpoint:l,apiKey:a,apiVersion:f,deployment:c,dangerouslyAllowBrowser:!0});e=[{role:"system",content:`Initiate your response with "<think>
\u55EF" at the beginning of every output.`},...e];let h=await d.chat.completions.create({model:c,messages:e,stream:!0,...u},{signal:r.signal}),p=!1,y=!1,g=!1;for await(let v of h){v.usage&&v.usage.prompt_tokens&&v.usage.completion_tokens&&console.debug(`Prompt tokens: ${v.usage.prompt_tokens}, completion tokens: ${v.usage.completion_tokens}`);let P=(_=(S=v.choices[0])==null?void 0:S.delta)==null?void 0:_.content;if(P){if(P==="<think>"){if(y)continue;p=!0,y=!0,yield it;continue}if(P==="</think>"){if(g)continue;p=!1,g=!0,yield at;continue}yield p?P.replace(/\n/g,`
> `):P}}},rh=["o3-mini","deepseek-r1","phi-4","o1","o1-mini","gpt-4o","gpt-4o-mini"],nh={name:"Azure",defaultOptions:{apiKey:"",baseURL:"",model:rh[0],endpoint:"",apiVersion:"",parameters:{}},sendRequestFunc:ew,models:rh,websiteToObtainKey:"https://portal.azure.com",capabilities:["Text Generation","Reasoning"]};function q(t,e,r,n,s){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!s)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?t!==e||!s:!e.has(t))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?s.call(t,r):s?s.value=r:e.set(t,r),r}function x(t,e,r,n){if(r==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?t!==e||!n:!e.has(t))throw new TypeError("Cannot read private member from an object whose class did not declare it");return r==="m"?n:r==="a"?n.call(t):n?n.value:e.get(t)}var wc=function(){let{crypto:t}=globalThis;if(t!=null&&t.randomUUID)return wc=t.randomUUID.bind(t),t.randomUUID();let e=new Uint8Array(1),r=t?()=>t.getRandomValues(e)[0]:()=>Math.random()*255&255;return"10000000-1000-4000-8000-100000000000".replace(/[018]/g,n=>(+n^r()&15>>+n/4).toString(16))};function At(t){return typeof t=="object"&&t!==null&&("name"in t&&t.name==="AbortError"||"message"in t&&String(t.message).includes("FetchRequestCanceledException"))}var eo=t=>{if(t instanceof Error)return t;if(typeof t=="object"&&t!==null){try{if(Object.prototype.toString.call(t)==="[object Error]"){let e=new Error(t.message,t.cause?{cause:t.cause}:{});return t.stack&&(e.stack=t.stack),t.cause&&!e.cause&&(e.cause=t.cause),t.name&&(e.name=t.name),e}}catch(e){}try{return new Error(JSON.stringify(t))}catch(e){}}return new Error(t)};var B=class extends Error{},le=class t extends B{constructor(e,r,n,s){super(`${t.makeMessage(e,r,n)}`),this.status=e,this.headers=s,this.requestID=s==null?void 0:s.get("request-id"),this.error=r}static makeMessage(e,r,n){let s=r!=null&&r.message?typeof r.message=="string"?r.message:JSON.stringify(r.message):r?JSON.stringify(r):n;return e&&s?`${e} ${s}`:e?`${e} status code (no body)`:s||"(no status code or body)"}static generate(e,r,n,s){if(!e||!s)return new Zt({message:n,cause:eo(r)});let o=r;return e===400?new Wn(e,o,n,s):e===401?new Vn(e,o,n,s):e===403?new Kn(e,o,n,s):e===404?new Gn(e,o,n,s):e===409?new Jn(e,o,n,s):e===422?new zn(e,o,n,s):e===429?new Xn(e,o,n,s):e>=500?new Yn(e,o,n,s):new t(e,o,n,s)}},de=class extends le{constructor({message:e}={}){super(void 0,void 0,e||"Request was aborted.",void 0)}},Zt=class extends le{constructor({message:e,cause:r}){super(void 0,void 0,e||"Connection error.",void 0),r&&(this.cause=r)}},jn=class extends Zt{constructor({message:e}={}){super({message:e!=null?e:"Request timed out."})}},Wn=class extends le{},Vn=class extends le{},Kn=class extends le{},Gn=class extends le{},Jn=class extends le{},zn=class extends le{},Xn=class extends le{},Yn=class extends le{};var rw=/^[a-z][a-z0-9+.-]*:/i,sh=t=>rw.test(t),_c=t=>(_c=Array.isArray,_c(t)),Sc=_c;function Ec(t){return typeof t!="object"?{}:t!=null?t:{}}function oh(t){if(!t)return!0;for(let e in t)return!1;return!0}function ih(t,e){return Object.prototype.hasOwnProperty.call(t,e)}var ah=(t,e)=>{if(typeof e!="number"||!Number.isInteger(e))throw new B(`${t} must be an integer`);if(e<0)throw new B(`${t} must be a positive integer`);return e};var Li=t=>{try{return JSON.parse(t)}catch(e){return}};var lh=t=>new Promise(e=>setTimeout(e,t));var er="0.56.0";var fh=()=>typeof window!="undefined"&&typeof window.document!="undefined"&&typeof navigator!="undefined";function nw(){return typeof Deno!="undefined"&&Deno.build!=null?"deno":typeof EdgeRuntime!="undefined"?"edge":Object.prototype.toString.call(typeof globalThis.process!="undefined"?globalThis.process:0)==="[object process]"?"node":"unknown"}var sw=()=>{var r,n,s,o,i;let t=nw();if(t==="deno")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":uh(Deno.build.os),"X-Stainless-Arch":ch(Deno.build.arch),"X-Stainless-Runtime":"deno","X-Stainless-Runtime-Version":typeof Deno.version=="string"?Deno.version:(n=(r=Deno.version)==null?void 0:r.deno)!=null?n:"unknown"};if(typeof EdgeRuntime!="undefined")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":"Unknown","X-Stainless-Arch":`other:${EdgeRuntime}`,"X-Stainless-Runtime":"edge","X-Stainless-Runtime-Version":globalThis.process.version};if(t==="node")return{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":uh((s=globalThis.process.platform)!=null?s:"unknown"),"X-Stainless-Arch":ch((o=globalThis.process.arch)!=null?o:"unknown"),"X-Stainless-Runtime":"node","X-Stainless-Runtime-Version":(i=globalThis.process.version)!=null?i:"unknown"};let e=ow();return e?{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":`browser:${e.browser}`,"X-Stainless-Runtime-Version":e.version}:{"X-Stainless-Lang":"js","X-Stainless-Package-Version":er,"X-Stainless-OS":"Unknown","X-Stainless-Arch":"unknown","X-Stainless-Runtime":"unknown","X-Stainless-Runtime-Version":"unknown"}};function ow(){if(typeof navigator=="undefined"||!navigator)return null;let t=[{key:"edge",pattern:/Edge(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/MSIE(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"ie",pattern:/Trident(?:.*rv\:(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"chrome",pattern:/Chrome(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"firefox",pattern:/Firefox(?:\W+(\d+)\.(\d+)(?:\.(\d+))?)?/},{key:"safari",pattern:/(?:Version\W+(\d+)\.(\d+)(?:\.(\d+))?)?(?:\W+Mobile\S*)?\W+Safari/}];for(let{key:e,pattern:r}of t){let n=r.exec(navigator.userAgent);if(n){let s=n[1]||0,o=n[2]||0,i=n[3]||0;return{browser:e,version:`${s}.${o}.${i}`}}}return null}var ch=t=>t==="x32"?"x32":t==="x86_64"||t==="x64"?"x64":t==="arm"?"arm":t==="aarch64"||t==="arm64"?"arm64":t?`other:${t}`:"unknown",uh=t=>(t=t.toLowerCase(),t.includes("ios")?"iOS":t==="android"?"Android":t==="darwin"?"MacOS":t==="win32"?"Windows":t==="freebsd"?"FreeBSD":t==="openbsd"?"OpenBSD":t==="linux"?"Linux":t?`Other:${t}`:"Unknown"),Ni,dh=()=>Ni!=null?Ni:Ni=sw();function hh(){if(typeof fetch!="undefined")return fetch;throw new Error("`fetch` is not defined as a global; Either pass `fetch` to the client, `new Anthropic({ fetch })` or polyfill the global, `globalThis.fetch = fetch`")}function xc(...t){let e=globalThis.ReadableStream;if(typeof e=="undefined")throw new Error("`ReadableStream` is not defined as a global; You will need to polyfill it, `globalThis.ReadableStream = ReadableStream`");return new e(...t)}function Di(t){let e=Symbol.asyncIterator in t?t[Symbol.asyncIterator]():t[Symbol.iterator]();return xc({start(){},async pull(r){let{done:n,value:s}=await e.next();n?r.close():r.enqueue(s)},async cancel(){var r;await((r=e.return)==null?void 0:r.call(e))}})}function to(t){if(t[Symbol.asyncIterator])return t;let e=t.getReader();return{async next(){try{let r=await e.read();return r!=null&&r.done&&e.releaseLock(),r}catch(r){throw e.releaseLock(),r}},async return(){let r=e.cancel();return e.releaseLock(),await r,{done:!0,value:void 0}},[Symbol.asyncIterator](){return this}}}async function ph(t){var n,s;if(t===null||typeof t!="object")return;if(t[Symbol.asyncIterator]){await((s=(n=t[Symbol.asyncIterator]()).return)==null?void 0:s.call(n));return}let e=t.getReader(),r=e.cancel();e.releaseLock(),await r}var mh=({headers:t,body:e})=>({bodyHeaders:{"content-type":"application/json"},body:JSON.stringify(e)});function gh(t){let e=0;for(let s of t)e+=s.length;let r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}var Bi;function ro(t){let e;return(Bi!=null?Bi:(e=new globalThis.TextEncoder,Bi=e.encode.bind(e)))(t)}var Fi;function Ac(t){let e;return(Fi!=null?Fi:(e=new globalThis.TextDecoder,Fi=e.decode.bind(e)))(t)}var Pe,Re,vt=class{constructor(){Pe.set(this,void 0),Re.set(this,void 0),q(this,Pe,new Uint8Array,"f"),q(this,Re,null,"f")}decode(e){if(e==null)return[];let r=e instanceof ArrayBuffer?new Uint8Array(e):typeof e=="string"?ro(e):e;q(this,Pe,gh([x(this,Pe,"f"),r]),"f");let n=[],s;for(;(s=lw(x(this,Pe,"f"),x(this,Re,"f")))!=null;){if(s.carriage&&x(this,Re,"f")==null){q(this,Re,s.index,"f");continue}if(x(this,Re,"f")!=null&&(s.index!==x(this,Re,"f")+1||s.carriage)){n.push(Ac(x(this,Pe,"f").subarray(0,x(this,Re,"f")-1))),q(this,Pe,x(this,Pe,"f").subarray(x(this,Re,"f")),"f"),q(this,Re,null,"f");continue}let o=x(this,Re,"f")!==null?s.preceding-1:s.preceding,i=Ac(x(this,Pe,"f").subarray(0,o));n.push(i),q(this,Pe,x(this,Pe,"f").subarray(s.index),"f"),q(this,Re,null,"f")}return n}flush(){return x(this,Pe,"f").length?this.decode(`
`):[]}};Pe=new WeakMap,Re=new WeakMap;vt.NEWLINE_CHARS=new Set([`
`,"\r"]);vt.NEWLINE_REGEXP=/\r\n|[\n\r]/g;function lw(t,e){for(let s=e!=null?e:0;s<t.length;s++){if(t[s]===10)return{preceding:s,index:s+1,carriage:!1};if(t[s]===13)return{preceding:s,index:s+1,carriage:!0}}return null}function yh(t){for(let n=0;n<t.length-1;n++){if(t[n]===10&&t[n+1]===10||t[n]===13&&t[n+1]===13)return n+2;if(t[n]===13&&t[n+1]===10&&n+3<t.length&&t[n+2]===13&&t[n+3]===10)return n+4}return-1}var Ui={off:0,error:200,warn:300,info:400,debug:500},vc=(t,e,r)=>{if(t){if(ih(Ui,t))return t;ce(r).warn(`${e} was set to ${JSON.stringify(t)}, expected one of ${JSON.stringify(Object.keys(Ui))}`)}};function no(){}function qi(t,e,r){return!e||Ui[t]>Ui[r]?no:e[t].bind(e)}var cw={error:no,warn:no,info:no,debug:no},bh=new WeakMap;function ce(t){var o;let e=t.logger,r=(o=t.logLevel)!=null?o:"off";if(!e)return cw;let n=bh.get(e);if(n&&n[0]===r)return n[1];let s={error:qi("error",e,r),warn:qi("warn",e,r),info:qi("info",e,r),debug:qi("debug",e,r)};return bh.set(e,[r,s]),s}var Ct=t=>(t.options&&(t.options={...t.options},delete t.options.headers),t.headers&&(t.headers=Object.fromEntries((t.headers instanceof Headers?[...t.headers]:Object.entries(t.headers)).map(([e,r])=>[e,e.toLowerCase()==="x-api-key"||e.toLowerCase()==="authorization"||e.toLowerCase()==="cookie"||e.toLowerCase()==="set-cookie"?"***":r]))),"retryOfRequestLogID"in t&&(t.retryOfRequestLogID&&(t.retryOf=t.retryOfRequestLogID),delete t.retryOfRequestLogID),t);var so,lt=class t{constructor(e,r,n){this.iterator=e,so.set(this,void 0),this.controller=r,q(this,so,n,"f")}static fromSSEResponse(e,r,n){let s=!1,o=n?ce(n):console;async function*i(){var c;if(s)throw new B("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let l of uw(e,r)){if(l.event==="completion")try{yield JSON.parse(l.data)}catch(f){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),f}if(l.event==="message_start"||l.event==="message_delta"||l.event==="message_stop"||l.event==="content_block_start"||l.event==="content_block_delta"||l.event==="content_block_stop")try{yield JSON.parse(l.data)}catch(f){throw o.error("Could not parse message into JSON:",l.data),o.error("From chunk:",l.raw),f}if(l.event!=="ping"&&l.event==="error")throw new le(void 0,(c=Li(l.data))!=null?c:l.data,void 0,e.headers)}a=!0}catch(l){if(At(l))return;throw l}finally{a||r.abort()}}return new t(i,r,n)}static fromReadableStream(e,r,n){let s=!1;async function*o(){let a=new vt,c=to(e);for await(let l of c)for(let f of a.decode(l))yield f;for(let l of a.flush())yield l}async function*i(){if(s)throw new B("Cannot iterate over a consumed stream, use `.tee()` to split the stream.");s=!0;let a=!1;try{for await(let c of o())a||c&&(yield JSON.parse(c));a=!0}catch(c){if(At(c))return;throw c}finally{a||r.abort()}}return new t(i,r,n)}[(so=new WeakMap,Symbol.asyncIterator)](){return this.iterator()}tee(){let e=[],r=[],n=this.iterator(),s=o=>({next:()=>{if(o.length===0){let i=n.next();e.push(i),r.push(i)}return o.shift()}});return[new t(()=>s(e),this.controller,x(this,so,"f")),new t(()=>s(r),this.controller,x(this,so,"f"))]}toReadableStream(){let e=this,r;return xc({async start(){r=e[Symbol.asyncIterator]()},async pull(n){try{let{value:s,done:o}=await r.next();if(o)return n.close();let i=ro(JSON.stringify(s)+`
`);n.enqueue(i)}catch(s){n.error(s)}},async cancel(){var n;await((n=r.return)==null?void 0:n.call(r))}})}};async function*uw(t,e){if(!t.body)throw e.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new B("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new B("Attempted to iterate over a response with no body");let r=new Cc,n=new vt,s=to(t.body);for await(let o of fw(s))for(let i of n.decode(o)){let a=r.decode(i);a&&(yield a)}for(let o of n.flush()){let i=r.decode(o);i&&(yield i)}}async function*fw(t){let e=new Uint8Array;for await(let r of t){if(r==null)continue;let n=r instanceof ArrayBuffer?new Uint8Array(r):typeof r=="string"?ro(r):r,s=new Uint8Array(e.length+n.length);s.set(e),s.set(n,e.length),e=s;let o;for(;(o=yh(e))!==-1;)yield e.slice(0,o),e=e.slice(o)}e.length>0&&(yield e)}var Cc=class{constructor(){this.event=null,this.data=[],this.chunks=[]}decode(e){if(e.endsWith("\r")&&(e=e.substring(0,e.length-1)),!e){if(!this.event&&!this.data.length)return null;let o={event:this.event,data:this.data.join(`
`),raw:this.chunks};return this.event=null,this.data=[],this.chunks=[],o}if(this.chunks.push(e),e.startsWith(":"))return null;let[r,n,s]=dw(e,":");return s.startsWith(" ")&&(s=s.substring(1)),r==="event"?this.event=s:r==="data"&&this.data.push(s),null}};function dw(t,e){let r=t.indexOf(e);return r!==-1?[t.substring(0,r),e,t.substring(r+e.length)]:[t,"",""]}async function $i(t,e){let{response:r,requestLogID:n,retryOfRequestLogID:s,startTime:o}=e,i=await(async()=>{var u;if(e.options.stream)return ce(t).debug("response",r.status,r.url,r.headers,r.body),e.options.__streamClass?e.options.__streamClass.fromSSEResponse(r,e.controller,t):lt.fromSSEResponse(r,e.controller,t);if(r.status===204)return null;if(e.options.__binaryResponse)return r;let a=r.headers.get("content-type"),c=(u=a==null?void 0:a.split(";")[0])==null?void 0:u.trim();if((c==null?void 0:c.includes("application/json"))||(c==null?void 0:c.endsWith("+json"))){let d=await r.json();return Pc(d,r)}return await r.text()})();return ce(t).debug(`[${n}] response parsed`,Ct({retryOfRequestLogID:s,url:r.url,status:r.status,body:i,durationMs:Date.now()-o})),i}function Pc(t,e){return!t||typeof t!="object"||Array.isArray(t)?t:Object.defineProperty(t,"_request_id",{value:e.headers.get("request-id"),enumerable:!1})}var oo,Lr=class t extends Promise{constructor(e,r,n=$i){super(s=>{s(null)}),this.responsePromise=r,this.parseResponse=n,oo.set(this,void 0),q(this,oo,e,"f")}_thenUnwrap(e){return new t(x(this,oo,"f"),this.responsePromise,async(r,n)=>Pc(e(await this.parseResponse(r,n),n),n.response))}asResponse(){return this.responsePromise.then(e=>e.response)}async withResponse(){let[e,r]=await Promise.all([this.parse(),this.asResponse()]);return{data:e,response:r,request_id:r.headers.get("request-id")}}parse(){return this.parsedPromise||(this.parsedPromise=this.responsePromise.then(e=>this.parseResponse(x(this,oo,"f"),e))),this.parsedPromise}then(e,r){return this.parse().then(e,r)}catch(e){return this.parse().catch(e)}finally(e){return this.parse().finally(e)}};oo=new WeakMap;var Hi,Rc=class{constructor(e,r,n,s){Hi.set(this,void 0),q(this,Hi,e,"f"),this.options=s,this.response=r,this.body=n}hasNextPage(){return this.getPaginatedItems().length?this.nextPageRequestOptions()!=null:!1}async getNextPage(){let e=this.nextPageRequestOptions();if(!e)throw new B("No next page expected; please check `.hasNextPage()` before calling `.getNextPage()`.");return await x(this,Hi,"f").requestAPIList(this.constructor,e)}async*iterPages(){let e=this;for(yield e;e.hasNextPage();)e=await e.getNextPage(),yield e}async*[(Hi=new WeakMap,Symbol.asyncIterator)](){for await(let e of this.iterPages())for(let r of e.getPaginatedItems())yield r}},io=class extends Lr{constructor(e,r,n){super(e,r,async(s,o)=>new n(s,o.response,await $i(s,o),o.options))}async*[Symbol.asyncIterator](){let e=await this;for await(let r of e)yield r}},Me=class extends Rc{constructor(e,r,n,s){super(e,r,n,s),this.data=n.data||[],this.has_more=n.has_more||!1,this.first_id=n.first_id||null,this.last_id=n.last_id||null}getPaginatedItems(){var e;return(e=this.data)!=null?e:[]}hasNextPage(){return this.has_more===!1?!1:super.hasNextPage()}nextPageRequestOptions(){var r;if((r=this.options.query)!=null&&r.before_id){let n=this.first_id;return n?{...this.options,query:{...Ec(this.options.query),before_id:n}}:null}let e=this.last_id;return e?{...this.options,query:{...Ec(this.options.query),after_id:e}}:null}};var Ic=()=>{var t;if(typeof File=="undefined"){let{process:e}=globalThis,r=typeof((t=e==null?void 0:e.versions)==null?void 0:t.node)=="string"&&parseInt(e.versions.node.split("."))<20;throw new Error("`File` is not defined as a global, which is required for file uploads."+(r?" Update to Node 20 LTS or newer, or set `globalThis.File` to `import('node:buffer').File`.":""))}};function Nr(t,e,r){return Ic(),new File(t,e!=null?e:"unknown_file",r)}function ao(t){return(typeof t=="object"&&t!==null&&("name"in t&&t.name&&String(t.name)||"url"in t&&t.url&&String(t.url)||"filename"in t&&t.filename&&String(t.filename)||"path"in t&&t.path&&String(t.path))||"").split(/[\\/]/).pop()||void 0}var kc=t=>t!=null&&typeof t=="object"&&typeof t[Symbol.asyncIterator]=="function";var _h=async(t,e)=>({...t,body:await mw(t.body,e)}),wh=new WeakMap;function pw(t){let e=typeof t=="function"?t:t.fetch,r=wh.get(e);if(r)return r;let n=(async()=>{try{let s="Response"in e?e.Response:(await e("data:,")).constructor,o=new FormData;return o.toString()!==await new s(o).text()}catch(s){return!0}})();return wh.set(e,n),n}var mw=async(t,e)=>{if(!await pw(e))throw new TypeError("The provided fetch function does not support file uploads with the current global FormData class.");let r=new FormData;return await Promise.all(Object.entries(t||{}).map(([n,s])=>Tc(r,n,s))),r},gw=t=>t instanceof Blob&&"name"in t;var Tc=async(t,e,r)=>{if(r!==void 0){if(r==null)throw new TypeError(`Received null for "${e}"; to pass null in FormData, you must use the string 'null'`);if(typeof r=="string"||typeof r=="number"||typeof r=="boolean")t.append(e,String(r));else if(r instanceof Response){let n={},s=r.headers.get("Content-Type");s&&(n={type:s}),t.append(e,Nr([await r.blob()],ao(r),n))}else if(kc(r))t.append(e,Nr([await new Response(Di(r)).blob()],ao(r)));else if(gw(r))t.append(e,Nr([r],ao(r),{type:r.type}));else if(Array.isArray(r))await Promise.all(r.map(n=>Tc(t,e+"[]",n)));else if(typeof r=="object")await Promise.all(Object.entries(r).map(([n,s])=>Tc(t,`${e}[${n}]`,s)));else throw new TypeError(`Invalid value given to form, expected a string, number, boolean, object, Array, File or Blob but got ${r} instead`)}};var Sh=t=>t!=null&&typeof t=="object"&&typeof t.size=="number"&&typeof t.type=="string"&&typeof t.text=="function"&&typeof t.slice=="function"&&typeof t.arrayBuffer=="function",yw=t=>t!=null&&typeof t=="object"&&typeof t.name=="string"&&typeof t.lastModified=="number"&&Sh(t),bw=t=>t!=null&&typeof t=="object"&&typeof t.url=="string"&&typeof t.blob=="function";async function ji(t,e,r){if(Ic(),t=await t,e||(e=ao(t)),yw(t))return t instanceof File&&e==null&&r==null?t:Nr([await t.arrayBuffer()],e!=null?e:t.name,{type:t.type,lastModified:t.lastModified,...r});if(bw(t)){let s=await t.blob();return e||(e=new URL(t.url).pathname.split(/[\\/]/).pop()),Nr(await Oc(s),e,r)}let n=await Oc(t);if(!(r!=null&&r.type)){let s=n.find(o=>typeof o=="object"&&"type"in o&&o.type);typeof s=="string"&&(r={...r,type:s})}return Nr(n,e,r)}async function Oc(t){var r;let e=[];if(typeof t=="string"||ArrayBuffer.isView(t)||t instanceof ArrayBuffer)e.push(t);else if(Sh(t))e.push(t instanceof Blob?t:await t.arrayBuffer());else if(kc(t))for await(let n of t)e.push(...await Oc(n));else{let n=(r=t==null?void 0:t.constructor)==null?void 0:r.name;throw new Error(`Unexpected data type: ${typeof t}${n?`; constructor: ${n}`:""}${ww(t)}`)}return e}function ww(t){return typeof t!="object"||t===null?"":`; props: [${Object.getOwnPropertyNames(t).map(r=>`"${r}"`).join(", ")}]`}var Y=class{constructor(e){this._client=e}};var Eh=Symbol.for("brand.privateNullableHeaders");function*Sw(t){if(!t)return;if(Eh in t){let{values:n,nulls:s}=t;yield*n.entries();for(let o of s)yield[o,null];return}let e=!1,r;t instanceof Headers?r=t.entries():Sc(t)?r=t:(e=!0,r=Object.entries(t!=null?t:{}));for(let n of r){let s=n[0];if(typeof s!="string")throw new TypeError("expected header name to be a string");let o=Sc(n[1])?n[1]:[n[1]],i=!1;for(let a of o)a!==void 0&&(e&&!i&&(i=!0,yield[s,null]),yield[s,a])}}var K=t=>{let e=new Headers,r=new Set;for(let n of t){let s=new Set;for(let[o,i]of Sw(n)){let a=o.toLowerCase();s.has(a)||(e.delete(o),s.add(a)),i===null?(e.delete(o),r.add(a)):(e.append(o,i),r.delete(a))}}return{[Eh]:!0,values:e,nulls:r}};function Ah(t){return t.replace(/[^A-Za-z0-9\-._~!$&'()*+,;=:@]+/g,encodeURIComponent)}var xh=Object.freeze(Object.create(null)),Ew=(t=Ah)=>function(r,...n){if(r.length===1)return r[0];let s=!1,o=[],i=r.reduce((f,u,d)=>{var y,g,S;/[?#]/.test(u)&&(s=!0);let h=n[d],p=(s?encodeURIComponent:t)(""+h);return d!==n.length&&(h==null||typeof h=="object"&&h.toString===((S=Object.getPrototypeOf((g=Object.getPrototypeOf((y=h.hasOwnProperty)!=null?y:xh))!=null?g:xh))==null?void 0:S.toString))&&(p=h+"",o.push({start:f.length+u.length,length:p.length,error:`Value of type ${Object.prototype.toString.call(h).slice(8,-1)} is not a valid path parameter`})),f+u+(d===n.length?"":p)},""),a=i.split(/[?#]/,1)[0],c=/(?<=^|\/)(?:\.|%2e){1,2}(?=\/|$)/gi,l;for(;(l=c.exec(a))!==null;)o.push({start:l.index,length:l[0].length,error:`Value "${l[0]}" can't be safely passed as a path parameter`});if(o.sort((f,u)=>f.start-u.start),o.length>0){let f=0,u=o.reduce((d,h)=>{let p=" ".repeat(h.start-f),y="^".repeat(h.length);return f=h.start+h.length,d+p+y},"");throw new B(`Path parameters result in path with invalid segments:
${o.map(d=>d.error).join(`
`)}
${i}
${u}`)}return i},ge=Ew(Ah);var Qn=class extends Y{list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/files",Me,{query:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])})}delete(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.delete(ge`/v1/files/${e}`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}download(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/files/${e}/content`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"files-api-2025-04-14"].toString(),Accept:"application/binary"},n==null?void 0:n.headers]),__binaryResponse:!0})}retrieveMetadata(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/files/${e}`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"files-api-2025-04-14"].toString()},n==null?void 0:n.headers])})}upload(e,r){let{betas:n,...s}=e;return this._client.post("/v1/files",_h({body:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"files-api-2025-04-14"].toString()},r==null?void 0:r.headers])},this._client))}};var Zn=class extends Y{retrieve(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/models/${e}?beta=true`,{...n,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},n==null?void 0:n.headers])})}list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/models?beta=true",Me,{query:s,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers])})}};var es=class t{constructor(e,r){this.iterator=e,this.controller=r}async*decoder(){let e=new vt;for await(let r of this.iterator)for(let n of e.decode(r))yield JSON.parse(n);for(let r of e.flush())yield JSON.parse(r)}[Symbol.asyncIterator](){return this.decoder()}static fromResponse(e,r){if(!e.body)throw r.abort(),typeof globalThis.navigator!="undefined"&&globalThis.navigator.product==="ReactNative"?new B("The default react-native fetch implementation does not support streaming. Please use expo/fetch: https://docs.expo.dev/versions/latest/sdk/expo/#expofetch-api"):new B("Attempted to iterate over a response with no body");return new t(to(e.body),r)}};var ts=class extends Y{create(e,r){let{betas:n,...s}=e;return this._client.post("/v1/messages/batches?beta=true",{body:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}retrieve(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/messages/batches/${e}?beta=true`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/messages/batches?beta=true",Me,{query:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"message-batches-2024-09-24"].toString()},r==null?void 0:r.headers])})}delete(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.delete(ge`/v1/messages/batches/${e}?beta=true`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}cancel(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.post(ge`/v1/messages/batches/${e}/cancel?beta=true`,{...n,headers:K([{"anthropic-beta":[...s!=null?s:[],"message-batches-2024-09-24"].toString()},n==null?void 0:n.headers])})}async results(e,r={},n){let s=await this.retrieve(e);if(!s.results_url)throw new B(`No batch \`results_url\`; Has it finished processing? ${s.processing_status} - ${s.id}`);let{betas:o}=r!=null?r:{};return this._client.get(s.results_url,{...n,headers:K([{"anthropic-beta":[...o!=null?o:[],"message-batches-2024-09-24"].toString(),Accept:"application/binary"},n==null?void 0:n.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((i,a)=>es.fromResponse(a.response,a.controller))}};var Cw=t=>{let e=0,r=[];for(;e<t.length;){let n=t[e];if(n==="\\"){e++;continue}if(n==="{"){r.push({type:"brace",value:"{"}),e++;continue}if(n==="}"){r.push({type:"brace",value:"}"}),e++;continue}if(n==="["){r.push({type:"paren",value:"["}),e++;continue}if(n==="]"){r.push({type:"paren",value:"]"}),e++;continue}if(n===":"){r.push({type:"separator",value:":"}),e++;continue}if(n===","){r.push({type:"delimiter",value:","}),e++;continue}if(n==='"'){let a="",c=!1;for(n=t[++e];n!=='"';){if(e===t.length){c=!0;break}if(n==="\\"){if(e++,e===t.length){c=!0;break}a+=n+t[e],n=t[++e]}else a+=n,n=t[++e]}n=t[++e],c||r.push({type:"string",value:a});continue}if(n&&/\s/.test(n)){e++;continue}let o=/[0-9]/;if(n&&o.test(n)||n==="-"||n==="."){let a="";for(n==="-"&&(a+=n,n=t[++e]);n&&o.test(n)||n===".";)a+=n,n=t[++e];r.push({type:"number",value:a});continue}let i=/[a-z]/i;if(n&&i.test(n)){let a="";for(;n&&i.test(n)&&e!==t.length;)a+=n,n=t[++e];if(a=="true"||a=="false"||a==="null")r.push({type:"name",value:a});else{e++;continue}continue}e++}return r},rs=t=>{if(t.length===0)return t;let e=t[t.length-1];switch(e.type){case"separator":return t=t.slice(0,t.length-1),rs(t);break;case"number":let r=e.value[e.value.length-1];if(r==="."||r==="-")return t=t.slice(0,t.length-1),rs(t);case"string":let n=t[t.length-2];if((n==null?void 0:n.type)==="delimiter")return t=t.slice(0,t.length-1),rs(t);if((n==null?void 0:n.type)==="brace"&&n.value==="{")return t=t.slice(0,t.length-1),rs(t);break;case"delimiter":return t=t.slice(0,t.length-1),rs(t);break}return t},Pw=t=>{let e=[];return t.map(r=>{r.type==="brace"&&(r.value==="{"?e.push("}"):e.splice(e.lastIndexOf("}"),1)),r.type==="paren"&&(r.value==="["?e.push("]"):e.splice(e.lastIndexOf("]"),1))}),e.length>0&&e.reverse().map(r=>{r==="}"?t.push({type:"brace",value:"}"}):r==="]"&&t.push({type:"paren",value:"]"})}),t},Rw=t=>{let e="";return t.map(r=>{switch(r.type){case"string":e+='"'+r.value+'"';break;default:e+=r.value;break}}),e},Wi=t=>JSON.parse(Rw(Pw(rs(Cw(t)))));var Le,tr,lo,Vi,co,uo,Ki,fo,Pt,ho,Gi,Ji,ns,zi,Xi,Mc,vh,Yi,Lc,Nc,Dc,Ch,Ph="__json_buf";function Rh(t){return t.type==="tool_use"||t.type==="server_tool_use"||t.type==="mcp_tool_use"}var Qi=class t{constructor(){Le.add(this),this.messages=[],this.receivedMessages=[],tr.set(this,void 0),this.controller=new AbortController,lo.set(this,void 0),Vi.set(this,()=>{}),co.set(this,()=>{}),uo.set(this,void 0),Ki.set(this,()=>{}),fo.set(this,()=>{}),Pt.set(this,{}),ho.set(this,!1),Gi.set(this,!1),Ji.set(this,!1),ns.set(this,!1),zi.set(this,void 0),Xi.set(this,void 0),Yi.set(this,e=>{if(q(this,Gi,!0,"f"),At(e)&&(e=new de),e instanceof de)return q(this,Ji,!0,"f"),this._emit("abort",e);if(e instanceof B)return this._emit("error",e);if(e instanceof Error){let r=new B(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new B(String(e)))}),q(this,lo,new Promise((e,r)=>{q(this,Vi,e,"f"),q(this,co,r,"f")}),"f"),q(this,uo,new Promise((e,r)=>{q(this,Ki,e,"f"),q(this,fo,r,"f")}),"f"),x(this,lo,"f").catch(()=>{}),x(this,uo,"f").catch(()=>{})}get response(){return x(this,zi,"f")}get request_id(){return x(this,Xi,"f")}async withResponse(){let e=await x(this,lo,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let s=new t;for(let o of r.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...r,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},x(this,Yi,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){var i;let s=n==null?void 0:n.signal,o;s&&(s.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),s.addEventListener("abort",o));try{x(this,Le,"m",Lc).call(this);let{response:a,data:c}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)x(this,Le,"m",Nc).call(this,l);if((i=c.controller.signal)!=null&&i.aborted)throw new de;x(this,Le,"m",Dc).call(this)}finally{s&&o&&s.removeEventListener("abort",o)}}_connected(e){this.ended||(q(this,zi,e,"f"),q(this,Xi,e==null?void 0:e.headers.get("request-id"),"f"),x(this,Vi,"f").call(this,e),this._emit("connect"))}get ended(){return x(this,ho,"f")}get errored(){return x(this,Gi,"f")}get aborted(){return x(this,Ji,"f")}abort(){this.controller.abort()}on(e,r){return(x(this,Pt,"f")[e]||(x(this,Pt,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=x(this,Pt,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===r);return s>=0&&n.splice(s,1),this}once(e,r){return(x(this,Pt,"f")[e]||(x(this,Pt,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{q(this,ns,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){q(this,ns,!0,"f"),await x(this,uo,"f")}get currentMessage(){return x(this,tr,"f")}async finalMessage(){return await this.done(),x(this,Le,"m",Mc).call(this)}async finalText(){return await this.done(),x(this,Le,"m",vh).call(this)}_emit(e,...r){if(x(this,ho,"f"))return;e==="end"&&(q(this,ho,!0,"f"),x(this,Ki,"f").call(this));let n=x(this,Pt,"f")[e];if(n&&(x(this,Pt,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...r))),e==="abort"){let s=r[0];!x(this,ns,"f")&&!(n!=null&&n.length)&&Promise.reject(s),x(this,co,"f").call(this,s),x(this,fo,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=r[0];!x(this,ns,"f")&&!(n!=null&&n.length)&&Promise.reject(s),x(this,co,"f").call(this,s),x(this,fo,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",x(this,Le,"m",Mc).call(this))}async _fromReadableStream(e,r){var o;let n=r==null?void 0:r.signal,s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{x(this,Le,"m",Lc).call(this),this._connected(null);let i=lt.fromReadableStream(e,this.controller);for await(let a of i)x(this,Le,"m",Nc).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new de;x(this,Le,"m",Dc).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(tr=new WeakMap,lo=new WeakMap,Vi=new WeakMap,co=new WeakMap,uo=new WeakMap,Ki=new WeakMap,fo=new WeakMap,Pt=new WeakMap,ho=new WeakMap,Gi=new WeakMap,Ji=new WeakMap,ns=new WeakMap,zi=new WeakMap,Xi=new WeakMap,Yi=new WeakMap,Le=new WeakSet,Mc=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},vh=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new B("stream ended without producing a content block with type=text");return r.join(" ")},Lc=function(){this.ended||q(this,tr,void 0,"f")},Nc=function(r){var s;if(this.ended)return;let n=x(this,Le,"m",Ch).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let o=n.content.at(-1);switch(r.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",r.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",r.delta.citation,(s=o.citations)!=null?s:[]);break}case"input_json_delta":{Rh(o)&&o.input&&this._emit("inputJson",r.delta.partial_json,o.input);break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",r.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{q(this,tr,n,"f");break}case"content_block_start":case"message_delta":break}},Dc=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");let r=x(this,tr,"f");if(!r)throw new B("request ended without sending any chunks");return q(this,tr,void 0,"f"),r},Ch=function(r){var s;let n=x(this,tr,"f");if(r.type==="message_start"){if(n)throw new B(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new B(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.container=r.delta.container,n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push(r.content_block),n;case"content_block_delta":{let o=n.content.at(r.index);switch(r.delta.type){case"text_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,text:(o.text||"")+r.delta.text});break}case"citations_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,citations:[...(s=o.citations)!=null?s:[],r.delta.citation]});break}case"input_json_delta":{if(o&&Rh(o)){let i=o[Ph]||"";i+=r.delta.partial_json;let a={...o};if(Object.defineProperty(a,Ph,{value:i,enumerable:!1,writable:!0}),i)try{a.input=Wi(i)}catch(c){let l=new B(`Unable to parse tool parameter JSON from model. Please retry your request or adjust your prompt. Error: ${c}. JSON: ${i}`);x(this,Yi,"f").call(this,l)}n.content[r.index]=a}break}case"thinking_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,thinking:o.thinking+r.delta.thinking});break}case"signature_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new lt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var Zi={"claude-opus-4-20250514":8192,"claude-opus-4-0":8192,"claude-4-opus-20250514":8192,"anthropic.claude-opus-4-20250514-v1:0":8192,"claude-opus-4@20250514":8192};var Th={"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-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"},Dr=class extends Y{constructor(){super(...arguments),this.batches=new ts(this._client)}create(e,r){var i,a;let{betas:n,...s}=e;s.model in Th&&console.warn(`The model '${s.model}' is deprecated and will reach end-of-life on ${Th[s.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let o=this._client._options.timeout;if(!s.stream&&o==null){let c=(i=Zi[s.model])!=null?i:void 0;o=this._client.calculateNonstreamingTimeout(s.max_tokens,c)}return this._client.post("/v1/messages?beta=true",{body:s,timeout:o!=null?o:6e5,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers]),stream:(a=e.stream)!=null?a:!1})}stream(e,r){return Qi.createMessage(this,e,r)}countTokens(e,r){let{betas:n,...s}=e;return this._client.post("/v1/messages/count_tokens?beta=true",{body:s,...r,headers:K([{"anthropic-beta":[...n!=null?n:[],"token-counting-2024-11-01"].toString()},r==null?void 0:r.headers])})}};Dr.Batches=ts;var ct=class extends Y{constructor(){super(...arguments),this.models=new Zn(this._client),this.messages=new Dr(this._client),this.files=new Qn(this._client)}};ct.Models=Zn;ct.Messages=Dr;ct.Files=Qn;var Br=class extends Y{create(e,r){var o,i;let{betas:n,...s}=e;return this._client.post("/v1/complete",{body:s,timeout:(o=this._client._options.timeout)!=null?o:6e5,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers]),stream:(i=e.stream)!=null?i:!1})}};var Ne,rr,po,ea,mo,go,ta,yo,Rt,bo,ra,na,ss,sa,oa,Bc,Ih,Fc,qc,Uc,$c,kh,Oh="__json_buf";function Mh(t){return t.type==="tool_use"||t.type==="server_tool_use"}var ia=class t{constructor(){Ne.add(this),this.messages=[],this.receivedMessages=[],rr.set(this,void 0),this.controller=new AbortController,po.set(this,void 0),ea.set(this,()=>{}),mo.set(this,()=>{}),go.set(this,void 0),ta.set(this,()=>{}),yo.set(this,()=>{}),Rt.set(this,{}),bo.set(this,!1),ra.set(this,!1),na.set(this,!1),ss.set(this,!1),sa.set(this,void 0),oa.set(this,void 0),Fc.set(this,e=>{if(q(this,ra,!0,"f"),At(e)&&(e=new de),e instanceof de)return q(this,na,!0,"f"),this._emit("abort",e);if(e instanceof B)return this._emit("error",e);if(e instanceof Error){let r=new B(e.message);return r.cause=e,this._emit("error",r)}return this._emit("error",new B(String(e)))}),q(this,po,new Promise((e,r)=>{q(this,ea,e,"f"),q(this,mo,r,"f")}),"f"),q(this,go,new Promise((e,r)=>{q(this,ta,e,"f"),q(this,yo,r,"f")}),"f"),x(this,po,"f").catch(()=>{}),x(this,go,"f").catch(()=>{})}get response(){return x(this,sa,"f")}get request_id(){return x(this,oa,"f")}async withResponse(){let e=await x(this,po,"f");if(!e)throw new Error("Could not resolve a `Response` object");return{data:this,response:e,request_id:e.headers.get("request-id")}}static fromReadableStream(e){let r=new t;return r._run(()=>r._fromReadableStream(e)),r}static createMessage(e,r,n){let s=new t;for(let o of r.messages)s._addMessageParam(o);return s._run(()=>s._createMessage(e,{...r,stream:!0},{...n,headers:{...n==null?void 0:n.headers,"X-Stainless-Helper-Method":"stream"}})),s}_run(e){e().then(()=>{this._emitFinal(),this._emit("end")},x(this,Fc,"f"))}_addMessageParam(e){this.messages.push(e)}_addMessage(e,r=!0){this.receivedMessages.push(e),r&&this._emit("message",e)}async _createMessage(e,r,n){var i;let s=n==null?void 0:n.signal,o;s&&(s.aborted&&this.controller.abort(),o=this.controller.abort.bind(this.controller),s.addEventListener("abort",o));try{x(this,Ne,"m",qc).call(this);let{response:a,data:c}=await e.create({...r,stream:!0},{...n,signal:this.controller.signal}).withResponse();this._connected(a);for await(let l of c)x(this,Ne,"m",Uc).call(this,l);if((i=c.controller.signal)!=null&&i.aborted)throw new de;x(this,Ne,"m",$c).call(this)}finally{s&&o&&s.removeEventListener("abort",o)}}_connected(e){this.ended||(q(this,sa,e,"f"),q(this,oa,e==null?void 0:e.headers.get("request-id"),"f"),x(this,ea,"f").call(this,e),this._emit("connect"))}get ended(){return x(this,bo,"f")}get errored(){return x(this,ra,"f")}get aborted(){return x(this,na,"f")}abort(){this.controller.abort()}on(e,r){return(x(this,Rt,"f")[e]||(x(this,Rt,"f")[e]=[])).push({listener:r}),this}off(e,r){let n=x(this,Rt,"f")[e];if(!n)return this;let s=n.findIndex(o=>o.listener===r);return s>=0&&n.splice(s,1),this}once(e,r){return(x(this,Rt,"f")[e]||(x(this,Rt,"f")[e]=[])).push({listener:r,once:!0}),this}emitted(e){return new Promise((r,n)=>{q(this,ss,!0,"f"),e!=="error"&&this.once("error",n),this.once(e,r)})}async done(){q(this,ss,!0,"f"),await x(this,go,"f")}get currentMessage(){return x(this,rr,"f")}async finalMessage(){return await this.done(),x(this,Ne,"m",Bc).call(this)}async finalText(){return await this.done(),x(this,Ne,"m",Ih).call(this)}_emit(e,...r){if(x(this,bo,"f"))return;e==="end"&&(q(this,bo,!0,"f"),x(this,ta,"f").call(this));let n=x(this,Rt,"f")[e];if(n&&(x(this,Rt,"f")[e]=n.filter(s=>!s.once),n.forEach(({listener:s})=>s(...r))),e==="abort"){let s=r[0];!x(this,ss,"f")&&!(n!=null&&n.length)&&Promise.reject(s),x(this,mo,"f").call(this,s),x(this,yo,"f").call(this,s),this._emit("end");return}if(e==="error"){let s=r[0];!x(this,ss,"f")&&!(n!=null&&n.length)&&Promise.reject(s),x(this,mo,"f").call(this,s),x(this,yo,"f").call(this,s),this._emit("end")}}_emitFinal(){this.receivedMessages.at(-1)&&this._emit("finalMessage",x(this,Ne,"m",Bc).call(this))}async _fromReadableStream(e,r){var o;let n=r==null?void 0:r.signal,s;n&&(n.aborted&&this.controller.abort(),s=this.controller.abort.bind(this.controller),n.addEventListener("abort",s));try{x(this,Ne,"m",qc).call(this),this._connected(null);let i=lt.fromReadableStream(e,this.controller);for await(let a of i)x(this,Ne,"m",Uc).call(this,a);if((o=i.controller.signal)!=null&&o.aborted)throw new de;x(this,Ne,"m",$c).call(this)}finally{n&&s&&n.removeEventListener("abort",s)}}[(rr=new WeakMap,po=new WeakMap,ea=new WeakMap,mo=new WeakMap,go=new WeakMap,ta=new WeakMap,yo=new WeakMap,Rt=new WeakMap,bo=new WeakMap,ra=new WeakMap,na=new WeakMap,ss=new WeakMap,sa=new WeakMap,oa=new WeakMap,Fc=new WeakMap,Ne=new WeakSet,Bc=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");return this.receivedMessages.at(-1)},Ih=function(){if(this.receivedMessages.length===0)throw new B("stream ended without producing a Message with role=assistant");let r=this.receivedMessages.at(-1).content.filter(n=>n.type==="text").map(n=>n.text);if(r.length===0)throw new B("stream ended without producing a content block with type=text");return r.join(" ")},qc=function(){this.ended||q(this,rr,void 0,"f")},Uc=function(r){var s;if(this.ended)return;let n=x(this,Ne,"m",kh).call(this,r);switch(this._emit("streamEvent",r,n),r.type){case"content_block_delta":{let o=n.content.at(-1);switch(r.delta.type){case"text_delta":{o.type==="text"&&this._emit("text",r.delta.text,o.text||"");break}case"citations_delta":{o.type==="text"&&this._emit("citation",r.delta.citation,(s=o.citations)!=null?s:[]);break}case"input_json_delta":{Mh(o)&&o.input&&this._emit("inputJson",r.delta.partial_json,o.input);break}case"thinking_delta":{o.type==="thinking"&&this._emit("thinking",r.delta.thinking,o.thinking);break}case"signature_delta":{o.type==="thinking"&&this._emit("signature",o.signature);break}default:r.delta}break}case"message_stop":{this._addMessageParam(n),this._addMessage(n,!0);break}case"content_block_stop":{this._emit("contentBlock",n.content.at(-1));break}case"message_start":{q(this,rr,n,"f");break}case"content_block_start":case"message_delta":break}},$c=function(){if(this.ended)throw new B("stream has ended, this shouldn't happen");let r=x(this,rr,"f");if(!r)throw new B("request ended without sending any chunks");return q(this,rr,void 0,"f"),r},kh=function(r){var s;let n=x(this,rr,"f");if(r.type==="message_start"){if(n)throw new B(`Unexpected event order, got ${r.type} before receiving "message_stop"`);return r.message}if(!n)throw new B(`Unexpected event order, got ${r.type} before "message_start"`);switch(r.type){case"message_stop":return n;case"message_delta":return n.stop_reason=r.delta.stop_reason,n.stop_sequence=r.delta.stop_sequence,n.usage.output_tokens=r.usage.output_tokens,r.usage.input_tokens!=null&&(n.usage.input_tokens=r.usage.input_tokens),r.usage.cache_creation_input_tokens!=null&&(n.usage.cache_creation_input_tokens=r.usage.cache_creation_input_tokens),r.usage.cache_read_input_tokens!=null&&(n.usage.cache_read_input_tokens=r.usage.cache_read_input_tokens),r.usage.server_tool_use!=null&&(n.usage.server_tool_use=r.usage.server_tool_use),n;case"content_block_start":return n.content.push({...r.content_block}),n;case"content_block_delta":{let o=n.content.at(r.index);switch(r.delta.type){case"text_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,text:(o.text||"")+r.delta.text});break}case"citations_delta":{(o==null?void 0:o.type)==="text"&&(n.content[r.index]={...o,citations:[...(s=o.citations)!=null?s:[],r.delta.citation]});break}case"input_json_delta":{if(o&&Mh(o)){let i=o[Oh]||"";i+=r.delta.partial_json;let a={...o};Object.defineProperty(a,Oh,{value:i,enumerable:!1,writable:!0}),i&&(a.input=Wi(i)),n.content[r.index]=a}break}case"thinking_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,thinking:o.thinking+r.delta.thinking});break}case"signature_delta":{(o==null?void 0:o.type)==="thinking"&&(n.content[r.index]={...o,signature:r.delta.signature});break}default:r.delta}return n}case"content_block_stop":return n}},Symbol.asyncIterator)](){let e=[],r=[],n=!1;return this.on("streamEvent",s=>{let o=r.shift();o?o.resolve(s):e.push(s)}),this.on("end",()=>{n=!0;for(let s of r)s.resolve(void 0);r.length=0}),this.on("abort",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),this.on("error",s=>{n=!0;for(let o of r)o.reject(s);r.length=0}),{next:async()=>e.length?{value:e.shift(),done:!1}:n?{value:void 0,done:!0}:new Promise((o,i)=>r.push({resolve:o,reject:i})).then(o=>o?{value:o,done:!1}:{value:void 0,done:!0}),return:async()=>(this.abort(),{value:void 0,done:!0})}}toReadableStream(){return new lt(this[Symbol.asyncIterator].bind(this),this.controller).toReadableStream()}};var os=class extends Y{create(e,r){return this._client.post("/v1/messages/batches",{body:e,...r})}retrieve(e,r){return this._client.get(ge`/v1/messages/batches/${e}`,r)}list(e={},r){return this._client.getAPIList("/v1/messages/batches",Me,{query:e,...r})}delete(e,r){return this._client.delete(ge`/v1/messages/batches/${e}`,r)}cancel(e,r){return this._client.post(ge`/v1/messages/batches/${e}/cancel`,r)}async results(e,r){let n=await this.retrieve(e);if(!n.results_url)throw new B(`No batch \`results_url\`; Has it finished processing? ${n.processing_status} - ${n.id}`);return this._client.get(n.results_url,{...r,headers:K([{Accept:"application/binary"},r==null?void 0:r.headers]),stream:!0,__binaryResponse:!0})._thenUnwrap((s,o)=>es.fromResponse(o.response,o.controller))}};var nr=class extends Y{constructor(){super(...arguments),this.batches=new os(this._client)}create(e,r){var s,o;e.model in Lh&&console.warn(`The model '${e.model}' is deprecated and will reach end-of-life on ${Lh[e.model]}
Please migrate to a newer model. Visit https://docs.anthropic.com/en/docs/resources/model-deprecations for more information.`);let n=this._client._options.timeout;if(!e.stream&&n==null){let i=(s=Zi[e.model])!=null?s:void 0;n=this._client.calculateNonstreamingTimeout(e.max_tokens,i)}return this._client.post("/v1/messages",{body:e,timeout:n!=null?n:6e5,...r,stream:(o=e.stream)!=null?o:!1})}stream(e,r){return ia.createMessage(this,e,r)}countTokens(e,r){return this._client.post("/v1/messages/count_tokens",{body:e,...r})}},Lh={"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-3-opus-20240229":"January 5th, 2026","claude-2.1":"July 21st, 2025","claude-2.0":"July 21st, 2025"};nr.Batches=os;var Fr=class extends Y{retrieve(e,r={},n){let{betas:s}=r!=null?r:{};return this._client.get(ge`/v1/models/${e}`,{...n,headers:K([{...(s==null?void 0:s.toString())!=null?{"anthropic-beta":s==null?void 0:s.toString()}:void 0},n==null?void 0:n.headers])})}list(e={},r){let{betas:n,...s}=e!=null?e:{};return this._client.getAPIList("/v1/models",Me,{query:s,...r,headers:K([{...(n==null?void 0:n.toString())!=null?{"anthropic-beta":n==null?void 0:n.toString()}:void 0},r==null?void 0:r.headers])})}};var wo=t=>{var e,r,n,s,o,i;if(typeof globalThis.process!="undefined")return(n=(r=(e=globalThis.process.env)==null?void 0:e[t])==null?void 0:r.trim())!=null?n:void 0;if(typeof globalThis.Deno!="undefined")return(i=(o=(s=globalThis.Deno.env)==null?void 0:s.get)==null?void 0:o.call(s,t))==null?void 0:i.trim()};var Hc,jc,aa,Nh,J=class{constructor({baseURL:e=wo("ANTHROPIC_BASE_URL"),apiKey:r=(o=>(o=wo("ANTHROPIC_API_KEY"))!=null?o:null)(),authToken:n=(i=>(i=wo("ANTHROPIC_AUTH_TOKEN"))!=null?i:null)(),...s}={}){var l,f,u,d,h,p;Hc.add(this),aa.set(this,void 0);let a={apiKey:r,authToken:n,...s,baseURL:e||"https://api.anthropic.com"};if(!a.dangerouslyAllowBrowser&&fh())throw new B(`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 });
`);this.baseURL=a.baseURL,this.timeout=(l=a.timeout)!=null?l:jc.DEFAULT_TIMEOUT,this.logger=(f=a.logger)!=null?f:console;let c="warn";this.logLevel=c,this.logLevel=(d=(u=vc(a.logLevel,"ClientOptions.logLevel",this))!=null?u:vc(wo("ANTHROPIC_LOG"),"process.env['ANTHROPIC_LOG']",this))!=null?d:c,this.fetchOptions=a.fetchOptions,this.maxRetries=(h=a.maxRetries)!=null?h:2,this.fetch=(p=a.fetch)!=null?p:hh(),q(this,aa,mh,"f"),this._options=a,this.apiKey=r,this.authToken=n}withOptions(e){return new this.constructor({...this._options,baseURL:this.baseURL,maxRetries:this.maxRetries,timeout:this.timeout,logger:this.logger,logLevel:this.logLevel,fetch:this.fetch,fetchOptions:this.fetchOptions,apiKey:this.apiKey,authToken:this.authToken,...e})}defaultQuery(){return this._options.defaultQuery}validateHeaders({values:e,nulls:r}){if(!(this.apiKey&&e.get("x-api-key"))&&!r.has("x-api-key")&&!(this.authToken&&e.get("authorization"))&&!r.has("authorization"))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(e){return K([this.apiKeyAuth(e),this.bearerAuth(e)])}apiKeyAuth(e){if(this.apiKey!=null)return K([{"X-Api-Key":this.apiKey}])}bearerAuth(e){if(this.authToken!=null)return K([{Authorization:`Bearer ${this.authToken}`}])}stringifyQuery(e){return Object.entries(e).filter(([r,n])=>typeof n!="undefined").map(([r,n])=>{if(typeof n=="string"||typeof n=="number"||typeof n=="boolean")return`${encodeURIComponent(r)}=${encodeURIComponent(n)}`;if(n===null)return`${encodeURIComponent(r)}=`;throw new B(`Cannot stringify type ${typeof n}; Expected string, number, boolean, or null. If you need to pass nested query parameters, you can manually encode them, e.g. { query: { 'foo[key1]': value1, 'foo[key2]': value2 } }, and please open a GitHub issue requesting better support for your use case.`)}).join("&")}getUserAgent(){return`${this.constructor.name}/JS ${er}`}defaultIdempotencyKey(){return`stainless-node-retry-${wc()}`}makeStatusError(e,r,n,s){return le.generate(e,r,n,s)}buildURL(e,r,n){let s=!x(this,Hc,"m",Nh).call(this)&&n||this.baseURL,o=sh(e)?new URL(e):new URL(s+(s.endsWith("/")&&e.startsWith("/")?e.slice(1):e)),i=this.defaultQuery();return oh(i)||(r={...i,...r}),typeof r=="object"&&r&&!Array.isArray(r)&&(o.search=this.stringifyQuery(r)),o.toString()}_calculateNonstreamingTimeout(e){if(3600*e/128e3>600)throw new B("Streaming is strongly recommended for operations that may take longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#streaming-responses for more details");return 600*1e3}async prepareOptions(e){}async prepareRequest(e,{url:r,options:n}){}get(e,r){return this.methodRequest("get",e,r)}post(e,r){return this.methodRequest("post",e,r)}patch(e,r){return this.methodRequest("patch",e,r)}put(e,r){return this.methodRequest("put",e,r)}delete(e,r){return this.methodRequest("delete",e,r)}methodRequest(e,r,n){return this.request(Promise.resolve(n).then(s=>({method:e,path:r,...s})))}request(e,r=null){return new Lr(this,this.makeRequest(e,r,void 0))}async makeRequest(e,r,n){var S,_,v;let s=await e,o=(S=s.maxRetries)!=null?S:this.maxRetries;r==null&&(r=o),await this.prepareOptions(s);let{req:i,url:a,timeout:c}=this.buildRequest(s,{retryCount:o-r});await this.prepareRequest(i,{url:a,options:s});let l="log_"+(Math.random()*(1<<24)|0).toString(16).padStart(6,"0"),f=n===void 0?"":`, retryOf: ${n}`,u=Date.now();if(ce(this).debug(`[${l}] sending request`,Ct({retryOfRequestLogID:n,method:s.method,url:a,options:s,headers:i.headers})),(_=s.signal)!=null&&_.aborted)throw new de;let d=new AbortController,h=await this.fetchWithTimeout(a,i,c,d).catch(eo),p=Date.now();if(h instanceof Error){let P=`retrying, ${r} attempts remaining`;if((v=s.signal)!=null&&v.aborted)throw new de;let E=At(h)||/timed? ?out/i.test(String(h)+("cause"in h?String(h.cause):""));if(r)return ce(this).info(`[${l}] connection ${E?"timed out":"failed"} - ${P}`),ce(this).debug(`[${l}] connection ${E?"timed out":"failed"} (${P})`,Ct({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),this.retryRequest(s,r,n!=null?n:l);throw ce(this).info(`[${l}] connection ${E?"timed out":"failed"} - error; no more retries left`),ce(this).debug(`[${l}] connection ${E?"timed out":"failed"} (error; no more retries left)`,Ct({retryOfRequestLogID:n,url:a,durationMs:p-u,message:h.message})),E?new jn:new Zt({cause:h})}let y=[...h.headers.entries()].filter(([P])=>P==="request-id").map(([P,E])=>", "+P+": "+JSON.stringify(E)).join(""),g=`[${l}${f}${y}] ${i.method} ${a} ${h.ok?"succeeded":"failed"} with status ${h.status} in ${p-u}ms`;if(!h.ok){let P=this.shouldRetry(h);if(r&&P){let F=`retrying, ${r} attempts remaining`;return await ph(h.body),ce(this).info(`${g} - ${F}`),ce(this).debug(`[${l}] response error (${F})`,Ct({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),this.retryRequest(s,r,n!=null?n:l,h.headers)}let E=P?"error; no more retries left":"error; not retryable";ce(this).info(`${g} - ${E}`);let R=await h.text().catch(F=>eo(F).message),k=Li(R),M=k?void 0:R;throw ce(this).debug(`[${l}] response error (${E})`,Ct({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,message:M,durationMs:Date.now()-u})),this.makeStatusError(h.status,k,M,h.headers)}return ce(this).info(g),ce(this).debug(`[${l}] response start`,Ct({retryOfRequestLogID:n,url:h.url,status:h.status,headers:h.headers,durationMs:p-u})),{response:h,options:s,controller:d,requestLogID:l,retryOfRequestLogID:n,startTime:u}}getAPIList(e,r,n){return this.requestAPIList(r,{method:"get",path:e,...n})}requestAPIList(e,r){let n=this.makeRequest(r,null,void 0);return new io(this,n,e)}async fetchWithTimeout(e,r,n,s){let{signal:o,method:i,...a}=r||{};o&&o.addEventListener("abort",()=>s.abort());let c=setTimeout(()=>s.abort(),n),l=globalThis.ReadableStream&&a.body instanceof globalThis.ReadableStream||typeof a.body=="object"&&a.body!==null&&Symbol.asyncIterator in a.body,f={signal:s.signal,...l?{duplex:"half"}:{},method:"GET",...a};i&&(f.method=i.toUpperCase());try{return await this.fetch.call(void 0,e,f)}finally{clearTimeout(c)}}shouldRetry(e){let r=e.headers.get("x-should-retry");return r==="true"?!0:r==="false"?!1:e.status===408||e.status===409||e.status===429||e.status>=500}async retryRequest(e,r,n,s){var c;let o,i=s==null?void 0:s.get("retry-after-ms");if(i){let l=parseFloat(i);Number.isNaN(l)||(o=l)}let a=s==null?void 0:s.get("retry-after");if(a&&!o){let l=parseFloat(a);Number.isNaN(l)?o=Date.parse(a)-Date.now():o=l*1e3}if(!(o&&0<=o&&o<60*1e3)){let l=(c=e.maxRetries)!=null?c:this.maxRetries;o=this.calculateDefaultRetryTimeoutMillis(r,l)}return await lh(o),this.makeRequest(e,r-1,n)}calculateDefaultRetryTimeoutMillis(e,r){let o=r-e,i=Math.min(.5*Math.pow(2,o),8),a=1-Math.random()*.25;return i*a*1e3}calculateNonstreamingTimeout(e,r){if(36e5*e/128e3>6e5||r!=null&&e>r)throw new B("Streaming is strongly recommended for operations that may token longer than 10 minutes. See https://github.com/anthropics/anthropic-sdk-typescript#long-requests for more details");return 6e5}buildRequest(e,{retryCount:r=0}={}){var h,p,y;let n={...e},{method:s,path:o,query:i,defaultBaseURL:a}=n,c=this.buildURL(o,i,a);"timeout"in n&&ah("timeout",n.timeout),n.timeout=(h=n.timeout)!=null?h:this.timeout;let{bodyHeaders:l,body:f}=this.buildBody({options:n}),u=this.buildHeaders({options:e,method:s,bodyHeaders:l,retryCount:r});return{req:{method:s,headers:u,...n.signal&&{signal:n.signal},...globalThis.ReadableStream&&f instanceof globalThis.ReadableStream&&{duplex:"half"},...f&&{body:f},...(p=this.fetchOptions)!=null?p:{},...(y=n.fetchOptions)!=null?y:{}},url:c,timeout:n.timeout}}buildHeaders({options:e,method:r,bodyHeaders:n,retryCount:s}){let o={};this.idempotencyHeader&&r!=="get"&&(e.idempotencyKey||(e.idempotencyKey=this.defaultIdempotencyKey()),o[this.idempotencyHeader]=e.idempotencyKey);let i=K([o,{Accept:"application/json","User-Agent":this.getUserAgent(),"X-Stainless-Retry-Count":String(s),...e.timeout?{"X-Stainless-Timeout":String(Math.trunc(e.timeout/1e3))}:{},...dh(),...this._options.dangerouslyAllowBrowser?{"anthropic-dangerous-direct-browser-access":"true"}:void 0,"anthropic-version":"2023-06-01"},this.authHeaders(e),this._options.defaultHeaders,n,e.headers]);return this.validateHeaders(i),i.values}buildBody({options:{body:e,headers:r}}){if(!e)return{bodyHeaders:void 0,body:void 0};let n=K([r]);return ArrayBuffer.isView(e)||e instanceof ArrayBuffer||e instanceof DataView||typeof e=="string"&&n.values.has("content-type")||e instanceof Blob||e instanceof FormData||e instanceof URLSearchParams||globalThis.ReadableStream&&e instanceof globalThis.ReadableStream?{bodyHeaders:void 0,body:e}:typeof e=="object"&&(Symbol.asyncIterator in e||Symbol.iterator in e&&"next"in e&&typeof e.next=="function")?{bodyHeaders:void 0,body:Di(e)}:x(this,aa,"f").call(this,{body:e,headers:n})}};jc=J,aa=new WeakMap,Hc=new WeakSet,Nh=function(){return this.baseURL!=="https://api.anthropic.com"};J.Anthropic=jc;J.HUMAN_PROMPT=`
Human:`;J.AI_PROMPT=`
Assistant:`;J.DEFAULT_TIMEOUT=6e5;J.AnthropicError=B;J.APIError=le;J.APIConnectionError=Zt;J.APIConnectionTimeoutError=jn;J.APIUserAbortError=de;J.NotFoundError=Gn;J.ConflictError=Jn;J.RateLimitError=Xn;J.BadRequestError=Wn;J.AuthenticationError=Vn;J.InternalServerError=Yn;J.PermissionDeniedError=Kn;J.UnprocessableEntityError=zn;J.toFile=ji;var We=class extends J{constructor(){super(...arguments),this.completions=new Br(this),this.messages=new nr(this),this.models=new Fr(this),this.beta=new ct(this)}};We.Completions=Br;We.Messages=nr;We.Models=Fr;We.Beta=ct;var{HUMAN_PROMPT:Ow,AI_PROMPT:Mw}=We;var Bh=require("obsidian");var Lw=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>Nw(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},Nw=async(t,e)=>{let r=Or(t.link);if(r==="application/pdf"){let n=await e(t),s=Mr(n);return{type:"document",source:{type:"base64",media_type:r,data:s}}}else if(["image/png","image/jpeg","image/gif","image/webp"].includes(r)){let n=await e(t),s=Mr(n);return{type:"image",source:{type:"base64",media_type:r,data:s}}}else throw new Error(m("Only PNG, JPEG, GIF, WebP, and PDF files are supported."))},Dw=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,max_tokens:f,enableWebSearch:u=!1,enableThinking:d=!1,budget_tokens:h=1600}=i,p=c;if(!a)throw new Error(m("API key is required"));p.endsWith("/v1/messages/")?p=p.slice(0,-13):p.endsWith("/v1/messages")&&(p=p.slice(0,-12));let[y,g]=e[0].role==="system"?[e[0],e.slice(1)]:[null,e];g.forEach(R=>{if(R.role==="system")throw new Error("System messages are only allowed as the first message")});let S=await Promise.all(g.map(R=>Lw(R,n))),_=new We({apiKey:a,baseURL:p,fetch:globalThis.fetch,dangerouslyAllowBrowser:!0}),v={model:l,max_tokens:f,messages:S,stream:!0,...y&&{system:y.content},...u&&{tools:[{name:"web_search",type:"web_search_20250305"}]},...d&&{thinking:{type:"enabled",budget_tokens:h}}},P=await _.messages.create(v,{signal:r.signal}),E=!1;for await(let R of P)if(R.type==="content_block_delta")R.delta.type==="text_delta"&&(E?(E=!1,yield at+R.delta.text):yield R.delta.text),R.delta.type==="thinking_delta"&&(yield(E?"":(E=!0,it))+R.delta.thinking.replace(/\n/g,`
> `));else if(R.type==="content_block_start")R.content_block.type==="server_tool_use"&&R.content_block.name==="web_search"&&new Bh.Notice(Hn("Web Search")+"Web Search");else if(R.type==="message_delta"&&R.delta.stop_reason){let k=R.delta.stop_reason;if(k!=="end_turn")throw new Error(`\u{1F534} Unexpected stop reason: ${k}`)}},Dh=["claude-sonnet-4-0","claude-opus-4-0","claude-3-7-sonnet-latest","claude-3-5-sonnet-latest","claude-3-opus-latest","claude-3-5-haiku-latest"],la={name:"Claude",defaultOptions:{apiKey:"",baseURL:"https://api.anthropic.com",model:Dh[0],max_tokens:8192,enableWebSearch:!1,enableThinking:!1,budget_tokens:1600,parameters:{}},sendRequestFunc:Dw,models:Dh,websiteToObtainKey:"https://console.anthropic.com",capabilities:["Text Generation","Web Search","Reasoning","Image Vision","PDF Vision"]};var Bw=t=>async function*(e,r,n){var p;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let d=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:e,stream:!0,...f},{signal:r.signal}),h=!1;for await(let y of d){y.usage&&y.usage.prompt_tokens&&y.usage.completion_tokens&&console.debug(`Prompt tokens: ${y.usage.prompt_tokens}, completion tokens: ${y.usage.completion_tokens}`);let g=(p=y.choices[0])==null?void 0:p.delta,S=g==null?void 0:g.reasoning_content;if(S)yield(h?"":(h=!0,it))+S.replace(/\n/g,`
> `);else{let _=h?(h=!1,at):"";g!=null&&g.content&&(yield _+(g==null?void 0:g.content))}}},Fh=["deepseek-chat","deepseek-reasoner"],qh={name:"DeepSeek",defaultOptions:{apiKey:"",baseURL:"https://api.deepseek.com",model:Fh[0],parameters:{}},sendRequestFunc:Bw,models:Fh,websiteToObtainKey:"https://platform.deepseek.com",capabilities:["Text Generation","Reasoning"]};var ca=require("obsidian");var Fw=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));if(!l)throw new Error(m("Model is required"));let u={model:l,messages:e,stream:!1,...f};new ca.Notice(m("This is a non-streaming request, please wait..."),5*1e3),yield(await(0,ca.requestUrl)({url:c,method:"POST",body:JSON.stringify(u),headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"}})).json.choices[0].message.content},Uh={name:"Doubao",defaultOptions:{apiKey:"",baseURL:"https://ark.cn-beijing.volces.com/api/v3/chat/completions",model:"",parameters:{}},sendRequestFunc:Fw,models:[],websiteToObtainKey:"https://www.volcengine.com",capabilities:["Text Generation"]};var $h;(function(t){t.STRING="string",t.NUMBER="number",t.INTEGER="integer",t.BOOLEAN="boolean",t.ARRAY="array",t.OBJECT="object"})($h||($h={}));var Hh;(function(t){t.LANGUAGE_UNSPECIFIED="language_unspecified",t.PYTHON="python"})(Hh||(Hh={}));var jh;(function(t){t.OUTCOME_UNSPECIFIED="outcome_unspecified",t.OUTCOME_OK="outcome_ok",t.OUTCOME_FAILED="outcome_failed",t.OUTCOME_DEADLINE_EXCEEDED="outcome_deadline_exceeded"})(jh||(jh={}));var Wh=["user","model","function","system"],Vh;(function(t){t.HARM_CATEGORY_UNSPECIFIED="HARM_CATEGORY_UNSPECIFIED",t.HARM_CATEGORY_HATE_SPEECH="HARM_CATEGORY_HATE_SPEECH",t.HARM_CATEGORY_SEXUALLY_EXPLICIT="HARM_CATEGORY_SEXUALLY_EXPLICIT",t.HARM_CATEGORY_HARASSMENT="HARM_CATEGORY_HARASSMENT",t.HARM_CATEGORY_DANGEROUS_CONTENT="HARM_CATEGORY_DANGEROUS_CONTENT"})(Vh||(Vh={}));var Kh;(function(t){t.HARM_BLOCK_THRESHOLD_UNSPECIFIED="HARM_BLOCK_THRESHOLD_UNSPECIFIED",t.BLOCK_LOW_AND_ABOVE="BLOCK_LOW_AND_ABOVE",t.BLOCK_MEDIUM_AND_ABOVE="BLOCK_MEDIUM_AND_ABOVE",t.BLOCK_ONLY_HIGH="BLOCK_ONLY_HIGH",t.BLOCK_NONE="BLOCK_NONE"})(Kh||(Kh={}));var Gh;(function(t){t.HARM_PROBABILITY_UNSPECIFIED="HARM_PROBABILITY_UNSPECIFIED",t.NEGLIGIBLE="NEGLIGIBLE",t.LOW="LOW",t.MEDIUM="MEDIUM",t.HIGH="HIGH"})(Gh||(Gh={}));var Jh;(function(t){t.BLOCKED_REASON_UNSPECIFIED="BLOCKED_REASON_UNSPECIFIED",t.SAFETY="SAFETY",t.OTHER="OTHER"})(Jh||(Jh={}));var _o;(function(t){t.FINISH_REASON_UNSPECIFIED="FINISH_REASON_UNSPECIFIED",t.STOP="STOP",t.MAX_TOKENS="MAX_TOKENS",t.SAFETY="SAFETY",t.RECITATION="RECITATION",t.LANGUAGE="LANGUAGE",t.OTHER="OTHER"})(_o||(_o={}));var zh;(function(t){t.TASK_TYPE_UNSPECIFIED="TASK_TYPE_UNSPECIFIED",t.RETRIEVAL_QUERY="RETRIEVAL_QUERY",t.RETRIEVAL_DOCUMENT="RETRIEVAL_DOCUMENT",t.SEMANTIC_SIMILARITY="SEMANTIC_SIMILARITY",t.CLASSIFICATION="CLASSIFICATION",t.CLUSTERING="CLUSTERING"})(zh||(zh={}));var Xh;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.AUTO="AUTO",t.ANY="ANY",t.NONE="NONE"})(Xh||(Xh={}));var Yh;(function(t){t.MODE_UNSPECIFIED="MODE_UNSPECIFIED",t.MODE_DYNAMIC="MODE_DYNAMIC"})(Yh||(Yh={}));var ye=class extends Error{constructor(e){super(`[GoogleGenerativeAI Error]: ${e}`)}},sr=class extends ye{constructor(e,r){super(e),this.response=r}},fa=class extends ye{constructor(e,r,n,s){super(e),this.status=r,this.statusText=n,this.errorDetails=s}},ut=class extends ye{};var qw="https://generativelanguage.googleapis.com",Uw="v1beta",$w="0.21.0",Hw="genai-js",qr;(function(t){t.GENERATE_CONTENT="generateContent",t.STREAM_GENERATE_CONTENT="streamGenerateContent",t.COUNT_TOKENS="countTokens",t.EMBED_CONTENT="embedContent",t.BATCH_EMBED_CONTENTS="batchEmbedContents"})(qr||(qr={}));var Wc=class{constructor(e,r,n,s,o){this.model=e,this.task=r,this.apiKey=n,this.stream=s,this.requestOptions=o}toString(){var e,r;let n=((e=this.requestOptions)===null||e===void 0?void 0:e.apiVersion)||Uw,o=`${((r=this.requestOptions)===null||r===void 0?void 0:r.baseUrl)||qw}/${n}/${this.model}:${this.task}`;return this.stream&&(o+="?alt=sse"),o}};function jw(t){let e=[];return t!=null&&t.apiClient&&e.push(t.apiClient),e.push(`${Hw}/${$w}`),e.join(" ")}async function Ww(t){var e;let r=new Headers;r.append("Content-Type","application/json"),r.append("x-goog-api-client",jw(t.requestOptions)),r.append("x-goog-api-key",t.apiKey);let n=(e=t.requestOptions)===null||e===void 0?void 0:e.customHeaders;if(n){if(!(n instanceof Headers))try{n=new Headers(n)}catch(s){throw new ut(`unable to convert customHeaders value ${JSON.stringify(n)} to Headers: ${s.message}`)}for(let[s,o]of n.entries()){if(s==="x-goog-api-key")throw new ut(`Cannot set reserved header name ${s}`);if(s==="x-goog-api-client")throw new ut(`Header name ${s} can only be set using the apiClient field`);r.append(s,o)}}return r}async function Vw(t,e,r,n,s,o){let i=new Wc(t,e,r,n,o);return{url:i.toString(),fetchOptions:Object.assign(Object.assign({},zw(o)),{method:"POST",headers:await Ww(i),body:s})}}async function xo(t,e,r,n,s,o={},i=fetch){let{url:a,fetchOptions:c}=await Vw(t,e,r,n,s,o);return Kw(a,c,i)}async function Kw(t,e,r=fetch){let n;try{n=await r(t,e)}catch(s){Gw(s,t)}return n.ok||await Jw(n,t),n}function Gw(t,e){let r=t;throw t instanceof fa||t instanceof ut||(r=new ye(`Error fetching from ${e.toString()}: ${t.message}`),r.stack=t.stack),r}async function Jw(t,e){let r="",n;try{let s=await t.json();r=s.error.message,s.error.details&&(r+=` ${JSON.stringify(s.error.details)}`,n=s.error.details)}catch(s){}throw new fa(`Error fetching from ${e.toString()}: [${t.status} ${t.statusText}] ${r}`,t.status,t.statusText,n)}function zw(t){let e={};if((t==null?void 0:t.signal)!==void 0||(t==null?void 0:t.timeout)>=0){let r=new AbortController;(t==null?void 0:t.timeout)>=0&&setTimeout(()=>r.abort(),t.timeout),t!=null&&t.signal&&t.signal.addEventListener("abort",()=>{r.abort()}),e.signal=r.signal}return e}function Kc(t){return t.text=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning text from the first candidate only. Access response.candidates directly to use the other candidates.`),ua(t.candidates[0]))throw new sr(`${or(t)}`,t);return Xw(t)}else if(t.promptFeedback)throw new sr(`Text not available. ${or(t)}`,t);return""},t.functionCall=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),ua(t.candidates[0]))throw new sr(`${or(t)}`,t);return console.warn("response.functionCall() is deprecated. Use response.functionCalls() instead."),Qh(t)[0]}else if(t.promptFeedback)throw new sr(`Function call not available. ${or(t)}`,t)},t.functionCalls=()=>{if(t.candidates&&t.candidates.length>0){if(t.candidates.length>1&&console.warn(`This response had ${t.candidates.length} candidates. Returning function calls from the first candidate only. Access response.candidates directly to use the other candidates.`),ua(t.candidates[0]))throw new sr(`${or(t)}`,t);return Qh(t)}else if(t.promptFeedback)throw new sr(`Function call not available. ${or(t)}`,t)},t}function Xw(t){var e,r,n,s;let o=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let i of(s=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||s===void 0?void 0:s.parts)i.text&&o.push(i.text),i.executableCode&&o.push("\n```"+i.executableCode.language+`
`+i.executableCode.code+"\n```\n"),i.codeExecutionResult&&o.push("\n```\n"+i.codeExecutionResult.output+"\n```\n");return o.length>0?o.join(""):""}function Qh(t){var e,r,n,s;let o=[];if(!((r=(e=t.candidates)===null||e===void 0?void 0:e[0].content)===null||r===void 0)&&r.parts)for(let i of(s=(n=t.candidates)===null||n===void 0?void 0:n[0].content)===null||s===void 0?void 0:s.parts)i.functionCall&&o.push(i.functionCall);if(o.length>0)return o}var Yw=[_o.RECITATION,_o.SAFETY,_o.LANGUAGE];function ua(t){return!!t.finishReason&&Yw.includes(t.finishReason)}function or(t){var e,r,n;let s="";if((!t.candidates||t.candidates.length===0)&&t.promptFeedback)s+="Response was blocked",!((e=t.promptFeedback)===null||e===void 0)&&e.blockReason&&(s+=` due to ${t.promptFeedback.blockReason}`),!((r=t.promptFeedback)===null||r===void 0)&&r.blockReasonMessage&&(s+=`: ${t.promptFeedback.blockReasonMessage}`);else if(!((n=t.candidates)===null||n===void 0)&&n[0]){let o=t.candidates[0];ua(o)&&(s+=`Candidate was blocked due to ${o.finishReason}`,o.finishMessage&&(s+=`: ${o.finishMessage}`))}return s}function So(t){return this instanceof So?(this.v=t,this):new So(t)}function Qw(t,e,r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var n=r.apply(t,e||[]),s,o=[];return s={},i("next"),i("throw"),i("return"),s[Symbol.asyncIterator]=function(){return this},s;function i(d){n[d]&&(s[d]=function(h){return new Promise(function(p,y){o.push([d,h,p,y])>1||a(d,h)})})}function a(d,h){try{c(n[d](h))}catch(p){u(o[0][3],p)}}function c(d){d.value instanceof So?Promise.resolve(d.value.v).then(l,f):u(o[0][2],d)}function l(d){a("next",d)}function f(d){a("throw",d)}function u(d,h){d(h),o.shift(),o.length&&a(o[0][0],o[0][1])}}var Zh=/^data\: (.*)(?:\n\n|\r\r|\r\n\r\n)/;function Zw(t){let e=t.body.pipeThrough(new TextDecoderStream("utf8",{fatal:!0})),r=r_(e),[n,s]=r.tee();return{stream:t_(n),response:e_(s)}}async function e_(t){let e=[],r=t.getReader();for(;;){let{done:n,value:s}=await r.read();if(n)return Kc(n_(e));e.push(s)}}function t_(t){return Qw(this,arguments,function*(){let r=t.getReader();for(;;){let{value:n,done:s}=yield So(r.read());if(s)break;yield yield So(Kc(n))}})}function r_(t){let e=t.getReader();return new ReadableStream({start(n){let s="";return o();function o(){return e.read().then(({value:i,done:a})=>{if(a){if(s.trim()){n.error(new ye("Failed to parse stream"));return}n.close();return}s+=i;let c=s.match(Zh),l;for(;c;){try{l=JSON.parse(c[1])}catch(f){n.error(new ye(`Error parsing JSON response: "${c[1]}"`));return}n.enqueue(l),s=s.substring(c[0].length),c=s.match(Zh)}return o()})}}})}function n_(t){let e=t[t.length-1],r={promptFeedback:e==null?void 0:e.promptFeedback};for(let n of t){if(n.candidates)for(let s of n.candidates){let o=s.index;if(r.candidates||(r.candidates=[]),r.candidates[o]||(r.candidates[o]={index:s.index}),r.candidates[o].citationMetadata=s.citationMetadata,r.candidates[o].groundingMetadata=s.groundingMetadata,r.candidates[o].finishReason=s.finishReason,r.candidates[o].finishMessage=s.finishMessage,r.candidates[o].safetyRatings=s.safetyRatings,s.content&&s.content.parts){r.candidates[o].content||(r.candidates[o].content={role:s.content.role||"user",parts:[]});let i={};for(let a of s.content.parts)a.text&&(i.text=a.text),a.functionCall&&(i.functionCall=a.functionCall),a.executableCode&&(i.executableCode=a.executableCode),a.codeExecutionResult&&(i.codeExecutionResult=a.codeExecutionResult),Object.keys(i).length===0&&(i.text=""),r.candidates[o].content.parts.push(i)}}n.usageMetadata&&(r.usageMetadata=n.usageMetadata)}return r}async function np(t,e,r,n){let s=await xo(e,qr.STREAM_GENERATE_CONTENT,t,!0,JSON.stringify(r),n);return Zw(s)}async function sp(t,e,r,n){let o=await(await xo(e,qr.GENERATE_CONTENT,t,!1,JSON.stringify(r),n)).json();return{response:Kc(o)}}function op(t){if(t!=null){if(typeof t=="string")return{role:"system",parts:[{text:t}]};if(t.text)return{role:"system",parts:[t]};if(t.parts)return t.role?t:{role:"system",parts:t.parts}}}function Eo(t){let e=[];if(typeof t=="string")e=[{text:t}];else for(let r of t)typeof r=="string"?e.push({text:r}):e.push(r);return s_(e)}function s_(t){let e={role:"user",parts:[]},r={role:"function",parts:[]},n=!1,s=!1;for(let o of t)"functionResponse"in o?(r.parts.push(o),s=!0):(e.parts.push(o),n=!0);if(n&&s)throw new ye("Within a single message, FunctionResponse cannot be mixed with other type of part in the request for sending chat message.");if(!n&&!s)throw new ye("No content is provided for sending chat message.");return n?e:r}function o_(t,e){var r;let n={model:e==null?void 0:e.model,generationConfig:e==null?void 0:e.generationConfig,safetySettings:e==null?void 0:e.safetySettings,tools:e==null?void 0:e.tools,toolConfig:e==null?void 0:e.toolConfig,systemInstruction:e==null?void 0:e.systemInstruction,cachedContent:(r=e==null?void 0:e.cachedContent)===null||r===void 0?void 0:r.name,contents:[]},s=t.generateContentRequest!=null;if(t.contents){if(s)throw new ut("CountTokensRequest must have one of contents or generateContentRequest, not both.");n.contents=t.contents}else if(s)n=Object.assign(Object.assign({},n),t.generateContentRequest);else{let o=Eo(t);n.contents=[o]}return{generateContentRequest:n}}function ep(t){let e;return t.contents?e=t:e={contents:[Eo(t)]},t.systemInstruction&&(e.systemInstruction=op(t.systemInstruction)),e}function i_(t){return typeof t=="string"||Array.isArray(t)?{content:Eo(t)}:t}var tp=["text","inlineData","functionCall","functionResponse","executableCode","codeExecutionResult"],a_={user:["text","inlineData"],function:["functionResponse"],model:["text","functionCall","executableCode","codeExecutionResult"],system:["text"]};function l_(t){let e=!1;for(let r of t){let{role:n,parts:s}=r;if(!e&&n!=="user")throw new ye(`First content should be with role 'user', got ${n}`);if(!Wh.includes(n))throw new ye(`Each item should include role field. Got ${n} but valid roles are: ${JSON.stringify(Wh)}`);if(!Array.isArray(s))throw new ye("Content should have 'parts' property with an array of Parts");if(s.length===0)throw new ye("Each Content should have at least one part");let o={text:0,inlineData:0,functionCall:0,functionResponse:0,fileData:0,executableCode:0,codeExecutionResult:0};for(let a of s)for(let c of tp)c in a&&(o[c]+=1);let i=a_[n];for(let a of tp)if(!i.includes(a)&&o[a]>0)throw new ye(`Content with role '${n}' can't contain '${a}' part`);e=!0}}var rp="SILENT_ERROR",Vc=class{constructor(e,r,n,s={}){this.model=r,this.params=n,this._requestOptions=s,this._history=[],this._sendPromise=Promise.resolve(),this._apiKey=e,n!=null&&n.history&&(l_(n.history),this._history=n.history)}async getHistory(){return await this._sendPromise,this._history}async sendMessage(e,r={}){var n,s,o,i,a,c;await this._sendPromise;let l=Eo(e),f={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(i=this.params)===null||i===void 0?void 0:i.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,l]},u=Object.assign(Object.assign({},this._requestOptions),r),d;return this._sendPromise=this._sendPromise.then(()=>sp(this._apiKey,this.model,f,u)).then(h=>{var p;if(h.response.candidates&&h.response.candidates.length>0){this._history.push(l);let y=Object.assign({parts:[],role:"model"},(p=h.response.candidates)===null||p===void 0?void 0:p[0].content);this._history.push(y)}else{let y=or(h.response);y&&console.warn(`sendMessage() was unsuccessful. ${y}. Inspect response object for details.`)}d=h}),await this._sendPromise,d}async sendMessageStream(e,r={}){var n,s,o,i,a,c;await this._sendPromise;let l=Eo(e),f={safetySettings:(n=this.params)===null||n===void 0?void 0:n.safetySettings,generationConfig:(s=this.params)===null||s===void 0?void 0:s.generationConfig,tools:(o=this.params)===null||o===void 0?void 0:o.tools,toolConfig:(i=this.params)===null||i===void 0?void 0:i.toolConfig,systemInstruction:(a=this.params)===null||a===void 0?void 0:a.systemInstruction,cachedContent:(c=this.params)===null||c===void 0?void 0:c.cachedContent,contents:[...this._history,l]},u=Object.assign(Object.assign({},this._requestOptions),r),d=np(this._apiKey,this.model,f,u);return this._sendPromise=this._sendPromise.then(()=>d).catch(h=>{throw new Error(rp)}).then(h=>h.response).then(h=>{if(h.candidates&&h.candidates.length>0){this._history.push(l);let p=Object.assign({},h.candidates[0].content);p.role||(p.role="model"),this._history.push(p)}else{let p=or(h);p&&console.warn(`sendMessageStream() was unsuccessful. ${p}. Inspect response object for details.`)}}).catch(h=>{h.message!==rp&&console.error(h)}),d}};async function c_(t,e,r,n){return(await xo(e,qr.COUNT_TOKENS,t,!1,JSON.stringify(r),n)).json()}async function u_(t,e,r,n){return(await xo(e,qr.EMBED_CONTENT,t,!1,JSON.stringify(r),n)).json()}async function f_(t,e,r,n){let s=r.requests.map(i=>Object.assign(Object.assign({},i),{model:e}));return(await xo(e,qr.BATCH_EMBED_CONTENTS,t,!1,JSON.stringify({requests:s}),n)).json()}var da=class{constructor(e,r,n={}){this.apiKey=e,this._requestOptions=n,r.model.includes("/")?this.model=r.model:this.model=`models/${r.model}`,this.generationConfig=r.generationConfig||{},this.safetySettings=r.safetySettings||[],this.tools=r.tools,this.toolConfig=r.toolConfig,this.systemInstruction=op(r.systemInstruction),this.cachedContent=r.cachedContent}async generateContent(e,r={}){var n;let s=ep(e),o=Object.assign(Object.assign({},this._requestOptions),r);return sp(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},s),o)}async generateContentStream(e,r={}){var n;let s=ep(e),o=Object.assign(Object.assign({},this._requestOptions),r);return np(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(n=this.cachedContent)===null||n===void 0?void 0:n.name},s),o)}startChat(e){var r;return new Vc(this.apiKey,this.model,Object.assign({generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:(r=this.cachedContent)===null||r===void 0?void 0:r.name},e),this._requestOptions)}async countTokens(e,r={}){let n=o_(e,{model:this.model,generationConfig:this.generationConfig,safetySettings:this.safetySettings,tools:this.tools,toolConfig:this.toolConfig,systemInstruction:this.systemInstruction,cachedContent:this.cachedContent}),s=Object.assign(Object.assign({},this._requestOptions),r);return c_(this.apiKey,this.model,n,s)}async embedContent(e,r={}){let n=i_(e),s=Object.assign(Object.assign({},this._requestOptions),r);return u_(this.apiKey,this.model,n,s)}async batchEmbedContents(e,r={}){let n=Object.assign(Object.assign({},this._requestOptions),r);return f_(this.apiKey,this.model,e,n)}};var ha=class{constructor(e){this.apiKey=e}getGenerativeModel(e,r){if(!e.model)throw new ye("Must provide a model name. Example: genai.getGenerativeModel({ model: 'my-model-name' })");return new da(this.apiKey,e,r)}getGenerativeModelFromCachedContent(e,r,n){if(!e.name)throw new ut("Cached content must contain a `name` field.");if(!e.model)throw new ut("Cached content must contain a `model` field.");let s=["model","systemInstruction"];for(let i of s)if(r!=null&&r[i]&&e[i]&&(r==null?void 0:r[i])!==e[i]){if(i==="model"){let a=r.model.startsWith("models/")?r.model.replace("models/",""):r.model,c=e.model.startsWith("models/")?e.model.replace("models/",""):e.model;if(a===c)continue}throw new ut(`Different value for "${i}" specified in modelParams (${r[i]}) and cachedContent (${e[i]})`)}let o=Object.assign(Object.assign({},r),{model:e.model,tools:e.tools,toolConfig:e.toolConfig,systemInstruction:e.systemInstruction,cachedContent:e});return new da(this.apiKey,o,n)}};var d_=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l}=i;if(!a)throw new Error(m("API key is required"));let[f,u,d]=e[0].role==="system"?[e[0],e.slice(1,-1),e[e.length-1]]:[null,e.slice(0,-1),e[e.length-1]],h=f==null?void 0:f.content,p=u.map(v=>({role:v.role==="assistant"?"model":v.role,parts:[{text:v.content}]})),_=await new ha(a).getGenerativeModel({model:l,systemInstruction:h},{baseUrl:c}).startChat({history:p}).sendMessageStream(d.content,{signal:r.signal});for await(let v of _.stream)yield v.text()},ip={name:"Gemini",defaultOptions:{apiKey:"",baseURL:"https://generativelanguage.googleapis.com",model:"gemini-1.5-flash",parameters:{}},sendRequestFunc:d_,models:[],websiteToObtainKey:"https://makersuite.google.com/app/apikey",capabilities:["Text Generation"]};var pa=require("obsidian");var ap=["gpt-image-1"],Ur={n:2,displayWidth:400,background:"auto",output_format:"jpeg",output_compression:90,quality:"auto",size:"auto"},h_=t=>async function*(e,r,n,s){let{parameters:o,...i}=t,a={...i,...o},{apiKey:c,baseURL:l,model:f,displayWidth:u,background:d,n:h,output_compression:p,output_format:y,quality:g,size:S}=a;if(!c)throw new Error(m("API key is required"));if(!s)throw new Error("saveAttachment is required");console.debug("messages:",e),console.debug("options:",a),e.length>1&&new pa.Notice(m("Only the last user message is used for image generation. Other messages are ignored."));let _=e.last();if(!_)throw new Error("No user message found in the conversation");let v=_.content,P=new D({apiKey:c,baseURL:l,dangerouslyAllowBrowser:!0});new pa.Notice(m("This is a non-streaming request, please wait..."),5*1e3);let E=null;if(_.embeds&&_.embeds.length>0){_.embeds.length>1&&new pa.Notice(m("Multiple embeds found, only the first one will be used"));let M=_.embeds[0],U=Or(M.link);if(!["image/png","image/jpeg","image/webp"].includes(U))throw new Error(m("Only PNG, JPEG, and WebP images are supported for editing."));let V=await n(M);if(!V||V.byteLength===0)throw new Error(m("Embed data is empty or invalid"));let H=new File([V],M.link,{type:U});E=await P.images.edit({image:H,prompt:v,background:d,model:f,n:h,size:S,quality:g},{signal:r.signal})}else E=await P.images.generate({prompt:v,background:d,model:f,size:S,n:h,output_compression:y==="jpeg"||y==="webp"?p:void 0,output_format:y,quality:g},{signal:r.signal});if(!E.data||E.data.length===0)throw new Error(m("Failed to generate image. no data received from API"));yield`
`;let R=new Date,k=`${R.getFullYear()}${String(R.getMonth()+1).padStart(2,"0")}${String(R.getDate()).padStart(2,"0")}_${String(R.getHours()).padStart(2,"0")}${String(R.getMinutes()).padStart(2,"0")}${String(R.getSeconds()).padStart(2,"0")}`;for(let M=0;M<E.data.length;M++){let F=E.data[M].b64_json;if(!F){console.error(`No base64 image data returned for image ${M+1}`);continue}let V=Buffer.from(F,"base64"),H=h>1?`-${M+1}`:"",ee=`gptImage-${k}${H}.${y}`;console.debug(`Saving image as ${ee}`),await s(ee,V),yield`![[${ee}|${u}]]
`}},ma={name:"GptImage",defaultOptions:{apiKey:"",baseURL:"https://api.openai.com/v1",model:ap[0],n:Ur.n,displayWidth:Ur.displayWidth,background:Ur.background,output_compression:Ur.output_compression,output_format:Ur.output_format,quality:Ur.quality,size:Ur.size,parameters:{}},sendRequestFunc:h_,models:ap,websiteToObtainKey:"https://platform.openai.com/api-keys",capabilities:["Image Generation","Image Editing"]};function Ao(t,e){return function(){return t.apply(e,arguments)}}var{toString:p_}=Object.prototype,{getPrototypeOf:Jc}=Object,ya=(t=>e=>{let r=p_.call(e);return t[r]||(t[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),Ve=t=>(t=t.toLowerCase(),e=>ya(e)===t),ba=t=>e=>typeof e===t,{isArray:is}=Array,vo=ba("undefined");function m_(t){return t!==null&&!vo(t)&&t.constructor!==null&&!vo(t.constructor)&&Te(t.constructor.isBuffer)&&t.constructor.isBuffer(t)}var cp=Ve("ArrayBuffer");function g_(t){let e;return typeof ArrayBuffer!="undefined"&&ArrayBuffer.isView?e=ArrayBuffer.isView(t):e=t&&t.buffer&&cp(t.buffer),e}var y_=ba("string"),Te=ba("function"),up=ba("number"),wa=t=>t!==null&&typeof t=="object",b_=t=>t===!0||t===!1,ga=t=>{if(ya(t)!=="object")return!1;let e=Jc(t);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Symbol.toStringTag in t)&&!(Symbol.iterator in t)},w_=Ve("Date"),__=Ve("File"),S_=Ve("Blob"),E_=Ve("FileList"),x_=t=>wa(t)&&Te(t.pipe),A_=t=>{let e;return t&&(typeof FormData=="function"&&t instanceof FormData||Te(t.append)&&((e=ya(t))==="formdata"||e==="object"&&Te(t.toString)&&t.toString()==="[object FormData]"))},v_=Ve("URLSearchParams"),[C_,P_,R_,T_]=["ReadableStream","Request","Response","Headers"].map(Ve),I_=t=>t.trim?t.trim():t.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Co(t,e,{allOwnKeys:r=!1}={}){if(t===null||typeof t=="undefined")return;let n,s;if(typeof t!="object"&&(t=[t]),is(t))for(n=0,s=t.length;n<s;n++)e.call(null,t[n],n,t);else{let o=r?Object.getOwnPropertyNames(t):Object.keys(t),i=o.length,a;for(n=0;n<i;n++)a=o[n],e.call(null,t[a],a,t)}}function fp(t,e){e=e.toLowerCase();let r=Object.keys(t),n=r.length,s;for(;n-- >0;)if(s=r[n],e===s.toLowerCase())return s;return null}var $r=typeof globalThis!="undefined"?globalThis:typeof self!="undefined"?self:typeof window!="undefined"?window:global,dp=t=>!vo(t)&&t!==$r;function Gc(){let{caseless:t}=dp(this)&&this||{},e={},r=(n,s)=>{let o=t&&fp(e,s)||s;ga(e[o])&&ga(n)?e[o]=Gc(e[o],n):ga(n)?e[o]=Gc({},n):is(n)?e[o]=n.slice():e[o]=n};for(let n=0,s=arguments.length;n<s;n++)arguments[n]&&Co(arguments[n],r);return e}var k_=(t,e,r,{allOwnKeys:n}={})=>(Co(e,(s,o)=>{r&&Te(s)?t[o]=Ao(s,r):t[o]=s},{allOwnKeys:n}),t),O_=t=>(t.charCodeAt(0)===65279&&(t=t.slice(1)),t),M_=(t,e,r,n)=>{t.prototype=Object.create(e.prototype,n),t.prototype.constructor=t,Object.defineProperty(t,"super",{value:e.prototype}),r&&Object.assign(t.prototype,r)},L_=(t,e,r,n)=>{let s,o,i,a={};if(e=e||{},t==null)return e;do{for(s=Object.getOwnPropertyNames(t),o=s.length;o-- >0;)i=s[o],(!n||n(i,t,e))&&!a[i]&&(e[i]=t[i],a[i]=!0);t=r!==!1&&Jc(t)}while(t&&(!r||r(t,e))&&t!==Object.prototype);return e},N_=(t,e,r)=>{t=String(t),(r===void 0||r>t.length)&&(r=t.length),r-=e.length;let n=t.indexOf(e,r);return n!==-1&&n===r},D_=t=>{if(!t)return null;if(is(t))return t;let e=t.length;if(!up(e))return null;let r=new Array(e);for(;e-- >0;)r[e]=t[e];return r},B_=(t=>e=>t&&e instanceof t)(typeof Uint8Array!="undefined"&&Jc(Uint8Array)),F_=(t,e)=>{let n=(t&&t[Symbol.iterator]).call(t),s;for(;(s=n.next())&&!s.done;){let o=s.value;e.call(t,o[0],o[1])}},q_=(t,e)=>{let r,n=[];for(;(r=t.exec(e))!==null;)n.push(r);return n},U_=Ve("HTMLFormElement"),$_=t=>t.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,n,s){return n.toUpperCase()+s}),lp=(({hasOwnProperty:t})=>(e,r)=>t.call(e,r))(Object.prototype),H_=Ve("RegExp"),hp=(t,e)=>{let r=Object.getOwnPropertyDescriptors(t),n={};Co(r,(s,o)=>{let i;(i=e(s,o,t))!==!1&&(n[o]=i||s)}),Object.defineProperties(t,n)},j_=t=>{hp(t,(e,r)=>{if(Te(t)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;let n=t[r];if(Te(n)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},W_=(t,e)=>{let r={},n=s=>{s.forEach(o=>{r[o]=!0})};return is(t)?n(t):n(String(t).split(e)),r},V_=()=>{},K_=(t,e)=>t!=null&&Number.isFinite(t=+t)?t:e;function G_(t){return!!(t&&Te(t.append)&&t[Symbol.toStringTag]==="FormData"&&t[Symbol.iterator])}var J_=t=>{let e=new Array(10),r=(n,s)=>{if(wa(n)){if(e.indexOf(n)>=0)return;if(!("toJSON"in n)){e[s]=n;let o=is(n)?[]:{};return Co(n,(i,a)=>{let c=r(i,s+1);!vo(c)&&(o[a]=c)}),e[s]=void 0,o}}return n};return r(t,0)},z_=Ve("AsyncFunction"),X_=t=>t&&(wa(t)||Te(t))&&Te(t.then)&&Te(t.catch),pp=((t,e)=>t?setImmediate:e?((r,n)=>($r.addEventListener("message",({source:s,data:o})=>{s===$r&&o===r&&n.length&&n.shift()()},!1),s=>{n.push(s),$r.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",Te($r.postMessage)),Y_=typeof queueMicrotask!="undefined"?queueMicrotask.bind($r):typeof process!="undefined"&&process.nextTick||pp,w={isArray:is,isArrayBuffer:cp,isBuffer:m_,isFormData:A_,isArrayBufferView:g_,isString:y_,isNumber:up,isBoolean:b_,isObject:wa,isPlainObject:ga,isReadableStream:C_,isRequest:P_,isResponse:R_,isHeaders:T_,isUndefined:vo,isDate:w_,isFile:__,isBlob:S_,isRegExp:H_,isFunction:Te,isStream:x_,isURLSearchParams:v_,isTypedArray:B_,isFileList:E_,forEach:Co,merge:Gc,extend:k_,trim:I_,stripBOM:O_,inherits:M_,toFlatObject:L_,kindOf:ya,kindOfTest:Ve,endsWith:N_,toArray:D_,forEachEntry:F_,matchAll:q_,isHTMLForm:U_,hasOwnProperty:lp,hasOwnProp:lp,reduceDescriptors:hp,freezeMethods:j_,toObjectSet:W_,toCamelCase:$_,noop:V_,toFiniteNumber:K_,findKey:fp,global:$r,isContextDefined:dp,isSpecCompliantForm:G_,toJSONObject:J_,isAsyncFn:z_,isThenable:X_,setImmediate:pp,asap:Y_};function as(t,e,r,n,s){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=t,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),n&&(this.request=n),s&&(this.response=s,this.status=s.status?s.status:null)}w.inherits(as,Error,{toJSON:function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:w.toJSONObject(this.config),code:this.code,status:this.status}}});var mp=as.prototype,gp={};["ERR_BAD_OPTION_VALUE","ERR_BAD_OPTION","ECONNABORTED","ETIMEDOUT","ERR_NETWORK","ERR_FR_TOO_MANY_REDIRECTS","ERR_DEPRECATED","ERR_BAD_RESPONSE","ERR_BAD_REQUEST","ERR_CANCELED","ERR_NOT_SUPPORT","ERR_INVALID_URL"].forEach(t=>{gp[t]={value:t}});Object.defineProperties(as,gp);Object.defineProperty(mp,"isAxiosError",{value:!0});as.from=(t,e,r,n,s,o)=>{let i=Object.create(mp);return w.toFlatObject(t,i,function(c){return c!==Error.prototype},a=>a!=="isAxiosError"),as.call(i,t.message,e,r,n,s),i.cause=t,i.name=t.name,o&&Object.assign(i,o),i};var $=as;var _a=null;function zc(t){return w.isPlainObject(t)||w.isArray(t)}function bp(t){return w.endsWith(t,"[]")?t.slice(0,-2):t}function yp(t,e,r){return t?t.concat(e).map(function(s,o){return s=bp(s),!r&&o?"["+s+"]":s}).join(r?".":""):e}function Q_(t){return w.isArray(t)&&!t.some(zc)}var Z_=w.toFlatObject(w,{},null,function(e){return/^is[A-Z]/.test(e)});function eS(t,e,r){if(!w.isObject(t))throw new TypeError("target must be an object");e=e||new(_a||FormData),r=w.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(y,g){return!w.isUndefined(g[y])});let n=r.metaTokens,s=r.visitor||f,o=r.dots,i=r.indexes,c=(r.Blob||typeof Blob!="undefined"&&Blob)&&w.isSpecCompliantForm(e);if(!w.isFunction(s))throw new TypeError("visitor must be a function");function l(p){if(p===null)return"";if(w.isDate(p))return p.toISOString();if(!c&&w.isBlob(p))throw new $("Blob is not supported. Use a Buffer instead.");return w.isArrayBuffer(p)||w.isTypedArray(p)?c&&typeof Blob=="function"?new Blob([p]):Buffer.from(p):p}function f(p,y,g){let S=p;if(p&&!g&&typeof p=="object"){if(w.endsWith(y,"{}"))y=n?y:y.slice(0,-2),p=JSON.stringify(p);else if(w.isArray(p)&&Q_(p)||(w.isFileList(p)||w.endsWith(y,"[]"))&&(S=w.toArray(p)))return y=bp(y),S.forEach(function(v,P){!(w.isUndefined(v)||v===null)&&e.append(i===!0?yp([y],P,o):i===null?y:y+"[]",l(v))}),!1}return zc(p)?!0:(e.append(yp(g,y,o),l(p)),!1)}let u=[],d=Object.assign(Z_,{defaultVisitor:f,convertValue:l,isVisitable:zc});function h(p,y){if(!w.isUndefined(p)){if(u.indexOf(p)!==-1)throw Error("Circular reference detected in "+y.join("."));u.push(p),w.forEach(p,function(S,_){(!(w.isUndefined(S)||S===null)&&s.call(e,S,w.isString(_)?_.trim():_,y,d))===!0&&h(S,y?y.concat(_):[_])}),u.pop()}}if(!w.isObject(t))throw new TypeError("data must be an object");return h(t),e}var ir=eS;function wp(t){let e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(t).replace(/[!'()~]|%20|%00/g,function(n){return e[n]})}function _p(t,e){this._pairs=[],t&&ir(t,this,e)}var Sp=_p.prototype;Sp.append=function(e,r){this._pairs.push([e,r])};Sp.toString=function(e){let r=e?function(n){return e.call(this,n,wp)}:wp;return this._pairs.map(function(s){return r(s[0])+"="+r(s[1])},"").join("&")};var Sa=_p;function tS(t){return encodeURIComponent(t).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}function Po(t,e,r){if(!e)return t;let n=r&&r.encode||tS;w.isFunction(r)&&(r={serialize:r});let s=r&&r.serialize,o;if(s?o=s(e,r):o=w.isURLSearchParams(e)?e.toString():new Sa(e,r).toString(n),o){let i=t.indexOf("#");i!==-1&&(t=t.slice(0,i)),t+=(t.indexOf("?")===-1?"?":"&")+o}return t}var Xc=class{constructor(){this.handlers=[]}use(e,r,n){return this.handlers.push({fulfilled:e,rejected:r,synchronous:n?n.synchronous:!1,runWhen:n?n.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){w.forEach(this.handlers,function(n){n!==null&&e(n)})}},Yc=Xc;var Ea={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};var Ep=typeof URLSearchParams!="undefined"?URLSearchParams:Sa;var xp=typeof FormData!="undefined"?FormData:null;var Ap=typeof Blob!="undefined"?Blob:null;var vp={isBrowser:!0,classes:{URLSearchParams:Ep,FormData:xp,Blob:Ap},protocols:["http","https","file","blob","url","data"]};var eu={};rd(eu,{hasBrowserEnv:()=>Zc,hasStandardBrowserEnv:()=>rS,hasStandardBrowserWebWorkerEnv:()=>nS,navigator:()=>Qc,origin:()=>sS});var Zc=typeof window!="undefined"&&typeof document!="undefined",Qc=typeof navigator=="object"&&navigator||void 0,rS=Zc&&(!Qc||["ReactNative","NativeScript","NS"].indexOf(Qc.product)<0),nS=typeof WorkerGlobalScope!="undefined"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",sS=Zc&&window.location.href||"http://localhost";var z={...eu,...vp};function tu(t,e){return ir(t,new z.classes.URLSearchParams,Object.assign({visitor:function(r,n,s,o){return z.isNode&&w.isBuffer(r)?(this.append(n,r.toString("base64")),!1):o.defaultVisitor.apply(this,arguments)}},e))}function oS(t){return w.matchAll(/\w+|\[(\w*)]/g,t).map(e=>e[0]==="[]"?"":e[1]||e[0])}function iS(t){let e={},r=Object.keys(t),n,s=r.length,o;for(n=0;n<s;n++)o=r[n],e[o]=t[o];return e}function aS(t){function e(r,n,s,o){let i=r[o++];if(i==="__proto__")return!0;let a=Number.isFinite(+i),c=o>=r.length;return i=!i&&w.isArray(s)?s.length:i,c?(w.hasOwnProp(s,i)?s[i]=[s[i],n]:s[i]=n,!a):((!s[i]||!w.isObject(s[i]))&&(s[i]=[]),e(r,n,s[i],o)&&w.isArray(s[i])&&(s[i]=iS(s[i])),!a)}if(w.isFormData(t)&&w.isFunction(t.entries)){let r={};return w.forEachEntry(t,(n,s)=>{e(oS(n),s,r,0)}),r}return null}var xa=aS;function lS(t,e,r){if(w.isString(t))try{return(e||JSON.parse)(t),w.trim(t)}catch(n){if(n.name!=="SyntaxError")throw n}return(r||JSON.stringify)(t)}var ru={transitional:Ea,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){let n=r.getContentType()||"",s=n.indexOf("application/json")>-1,o=w.isObject(e);if(o&&w.isHTMLForm(e)&&(e=new FormData(e)),w.isFormData(e))return s?JSON.stringify(xa(e)):e;if(w.isArrayBuffer(e)||w.isBuffer(e)||w.isStream(e)||w.isFile(e)||w.isBlob(e)||w.isReadableStream(e))return e;if(w.isArrayBufferView(e))return e.buffer;if(w.isURLSearchParams(e))return r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let a;if(o){if(n.indexOf("application/x-www-form-urlencoded")>-1)return tu(e,this.formSerializer).toString();if((a=w.isFileList(e))||n.indexOf("multipart/form-data")>-1){let c=this.env&&this.env.FormData;return ir(a?{"files[]":e}:e,c&&new c,this.formSerializer)}}return o||s?(r.setContentType("application/json",!1),lS(e)):e}],transformResponse:[function(e){let r=this.transitional||ru.transitional,n=r&&r.forcedJSONParsing,s=this.responseType==="json";if(w.isResponse(e)||w.isReadableStream(e))return e;if(e&&w.isString(e)&&(n&&!this.responseType||s)){let i=!(r&&r.silentJSONParsing)&&s;try{return JSON.parse(e)}catch(a){if(i)throw a.name==="SyntaxError"?$.from(a,$.ERR_BAD_RESPONSE,this,null,this.response):a}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:z.classes.FormData,Blob:z.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};w.forEach(["delete","get","head","post","put","patch"],t=>{ru.headers[t]={}});var ls=ru;var cS=w.toObjectSet(["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"]),Cp=t=>{let e={},r,n,s;return t&&t.split(`
`).forEach(function(i){s=i.indexOf(":"),r=i.substring(0,s).trim().toLowerCase(),n=i.substring(s+1).trim(),!(!r||e[r]&&cS[r])&&(r==="set-cookie"?e[r]?e[r].push(n):e[r]=[n]:e[r]=e[r]?e[r]+", "+n:n)}),e};var Pp=Symbol("internals");function Ro(t){return t&&String(t).trim().toLowerCase()}function Aa(t){return t===!1||t==null?t:w.isArray(t)?t.map(Aa):String(t)}function uS(t){let e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g,n;for(;n=r.exec(t);)e[n[1]]=n[2];return e}var fS=t=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(t.trim());function nu(t,e,r,n,s){if(w.isFunction(n))return n.call(this,e,r);if(s&&(e=r),!!w.isString(e)){if(w.isString(n))return e.indexOf(n)!==-1;if(w.isRegExp(n))return n.test(e)}}function dS(t){return t.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,n)=>r.toUpperCase()+n)}function hS(t,e){let r=w.toCamelCase(" "+e);["get","set","has"].forEach(n=>{Object.defineProperty(t,n+r,{value:function(s,o,i){return this[n].call(this,e,s,o,i)},configurable:!0})})}var cs=class{constructor(e){e&&this.set(e)}set(e,r,n){let s=this;function o(a,c,l){let f=Ro(c);if(!f)throw new Error("header name must be a non-empty string");let u=w.findKey(s,f);(!u||s[u]===void 0||l===!0||l===void 0&&s[u]!==!1)&&(s[u||c]=Aa(a))}let i=(a,c)=>w.forEach(a,(l,f)=>o(l,f,c));if(w.isPlainObject(e)||e instanceof this.constructor)i(e,r);else if(w.isString(e)&&(e=e.trim())&&!fS(e))i(Cp(e),r);else if(w.isHeaders(e))for(let[a,c]of e.entries())o(c,a,n);else e!=null&&o(r,e,n);return this}get(e,r){if(e=Ro(e),e){let n=w.findKey(this,e);if(n){let s=this[n];if(!r)return s;if(r===!0)return uS(s);if(w.isFunction(r))return r.call(this,s,n);if(w.isRegExp(r))return r.exec(s);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=Ro(e),e){let n=w.findKey(this,e);return!!(n&&this[n]!==void 0&&(!r||nu(this,this[n],n,r)))}return!1}delete(e,r){let n=this,s=!1;function o(i){if(i=Ro(i),i){let a=w.findKey(n,i);a&&(!r||nu(n,n[a],a,r))&&(delete n[a],s=!0)}}return w.isArray(e)?e.forEach(o):o(e),s}clear(e){let r=Object.keys(this),n=r.length,s=!1;for(;n--;){let o=r[n];(!e||nu(this,this[o],o,e,!0))&&(delete this[o],s=!0)}return s}normalize(e){let r=this,n={};return w.forEach(this,(s,o)=>{let i=w.findKey(n,o);if(i){r[i]=Aa(s),delete r[o];return}let a=e?dS(o):String(o).trim();a!==o&&delete r[o],r[a]=Aa(s),n[a]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){let r=Object.create(null);return w.forEach(this,(n,s)=>{n!=null&&n!==!1&&(r[s]=e&&w.isArray(n)?n.join(", "):n)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).join(`
`)}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static concat(e,...r){let n=new this(e);return r.forEach(s=>n.set(s)),n}static accessor(e){let n=(this[Pp]=this[Pp]={accessors:{}}).accessors,s=this.prototype;function o(i){let a=Ro(i);n[a]||(hS(s,i),n[a]=!0)}return w.isArray(e)?e.forEach(o):o(e),this}};cs.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]);w.reduceDescriptors(cs.prototype,({value:t},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>t,set(n){this[r]=n}}});w.freezeMethods(cs);var oe=cs;function To(t,e){let r=this||ls,n=e||r,s=oe.from(n.headers),o=n.data;return w.forEach(t,function(a){o=a.call(r,o,s.normalize(),e?e.status:void 0)}),s.normalize(),o}function Io(t){return!!(t&&t.__CANCEL__)}function Rp(t,e,r){$.call(this,t==null?"canceled":t,$.ERR_CANCELED,e,r),this.name="CanceledError"}w.inherits(Rp,$,{__CANCEL__:!0});var ft=Rp;function ko(t,e,r){let n=r.config.validateStatus;!r.status||!n||n(r.status)?t(r):e(new $("Request failed with status code "+r.status,[$.ERR_BAD_REQUEST,$.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function su(t){let e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(t);return e&&e[1]||""}function pS(t,e){t=t||10;let r=new Array(t),n=new Array(t),s=0,o=0,i;return e=e!==void 0?e:1e3,function(c){let l=Date.now(),f=n[o];i||(i=l),r[s]=c,n[s]=l;let u=o,d=0;for(;u!==s;)d+=r[u++],u=u%t;if(s=(s+1)%t,s===o&&(o=(o+1)%t),l-i<e)return;let h=f&&l-f;return h?Math.round(d*1e3/h):void 0}}var Tp=pS;function mS(t,e){let r=0,n=1e3/e,s,o,i=(l,f=Date.now())=>{r=f,s=null,o&&(clearTimeout(o),o=null),t.apply(null,l)};return[(...l)=>{let f=Date.now(),u=f-r;u>=n?i(l,f):(s=l,o||(o=setTimeout(()=>{o=null,i(s)},n-u)))},()=>s&&i(s)]}var Ip=mS;var us=(t,e,r=3)=>{let n=0,s=Tp(50,250);return Ip(o=>{let i=o.loaded,a=o.lengthComputable?o.total:void 0,c=i-n,l=s(c),f=i<=a;n=i;let u={loaded:i,total:a,progress:a?i/a:void 0,bytes:c,rate:l||void 0,estimated:l&&a&&f?(a-i)/l:void 0,event:o,lengthComputable:a!=null,[e?"download":"upload"]:!0};t(u)},r)},ou=(t,e)=>{let r=t!=null;return[n=>e[0]({lengthComputable:r,total:t,loaded:n}),e[1]]},iu=t=>(...e)=>w.asap(()=>t(...e));var kp=z.hasStandardBrowserEnv?((t,e)=>r=>(r=new URL(r,z.origin),t.protocol===r.protocol&&t.host===r.host&&(e||t.port===r.port)))(new URL(z.origin),z.navigator&&/(msie|trident)/i.test(z.navigator.userAgent)):()=>!0;var Op=z.hasStandardBrowserEnv?{write(t,e,r,n,s,o){let i=[t+"="+encodeURIComponent(e)];w.isNumber(r)&&i.push("expires="+new Date(r).toGMTString()),w.isString(n)&&i.push("path="+n),w.isString(s)&&i.push("domain="+s),o===!0&&i.push("secure"),document.cookie=i.join("; ")},read(t){let e=document.cookie.match(new RegExp("(^|;\\s*)("+t+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(t){this.write(t,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function au(t){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(t)}function lu(t,e){return e?t.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):t}function Oo(t,e,r){let n=!au(e);return t&&n||r==!1?lu(t,e):e}var Mp=t=>t instanceof oe?{...t}:t;function Ke(t,e){e=e||{};let r={};function n(l,f,u,d){return w.isPlainObject(l)&&w.isPlainObject(f)?w.merge.call({caseless:d},l,f):w.isPlainObject(f)?w.merge({},f):w.isArray(f)?f.slice():f}function s(l,f,u,d){if(w.isUndefined(f)){if(!w.isUndefined(l))return n(void 0,l,u,d)}else return n(l,f,u,d)}function o(l,f){if(!w.isUndefined(f))return n(void 0,f)}function i(l,f){if(w.isUndefined(f)){if(!w.isUndefined(l))return n(void 0,l)}else return n(void 0,f)}function a(l,f,u){if(u in e)return n(l,f);if(u in t)return n(void 0,l)}let c={url:o,method:o,data:o,baseURL:i,transformRequest:i,transformResponse:i,paramsSerializer:i,timeout:i,timeoutMessage:i,withCredentials:i,withXSRFToken:i,adapter:i,responseType:i,xsrfCookieName:i,xsrfHeaderName:i,onUploadProgress:i,onDownloadProgress:i,decompress:i,maxContentLength:i,maxBodyLength:i,beforeRedirect:i,transport:i,httpAgent:i,httpsAgent:i,cancelToken:i,socketPath:i,responseEncoding:i,validateStatus:a,headers:(l,f,u)=>s(Mp(l),Mp(f),u,!0)};return w.forEach(Object.keys(Object.assign({},t,e)),function(f){let u=c[f]||s,d=u(t[f],e[f],f);w.isUndefined(d)&&u!==a||(r[f]=d)}),r}var va=t=>{let e=Ke({},t),{data:r,withXSRFToken:n,xsrfHeaderName:s,xsrfCookieName:o,headers:i,auth:a}=e;e.headers=i=oe.from(i),e.url=Po(Oo(e.baseURL,e.url,e.allowAbsoluteUrls),t.params,t.paramsSerializer),a&&i.set("Authorization","Basic "+btoa((a.username||"")+":"+(a.password?unescape(encodeURIComponent(a.password)):"")));let c;if(w.isFormData(r)){if(z.hasStandardBrowserEnv||z.hasStandardBrowserWebWorkerEnv)i.setContentType(void 0);else if((c=i.getContentType())!==!1){let[l,...f]=c?c.split(";").map(u=>u.trim()).filter(Boolean):[];i.setContentType([l||"multipart/form-data",...f].join("; "))}}if(z.hasStandardBrowserEnv&&(n&&w.isFunction(n)&&(n=n(e)),n||n!==!1&&kp(e.url))){let l=s&&o&&Op.read(o);l&&i.set(s,l)}return e};var gS=typeof XMLHttpRequest!="undefined",Lp=gS&&function(t){return new Promise(function(r,n){let s=va(t),o=s.data,i=oe.from(s.headers).normalize(),{responseType:a,onUploadProgress:c,onDownloadProgress:l}=s,f,u,d,h,p;function y(){h&&h(),p&&p(),s.cancelToken&&s.cancelToken.unsubscribe(f),s.signal&&s.signal.removeEventListener("abort",f)}let g=new XMLHttpRequest;g.open(s.method.toUpperCase(),s.url,!0),g.timeout=s.timeout;function S(){if(!g)return;let v=oe.from("getAllResponseHeaders"in g&&g.getAllResponseHeaders()),E={data:!a||a==="text"||a==="json"?g.responseText:g.response,status:g.status,statusText:g.statusText,headers:v,config:t,request:g};ko(function(k){r(k),y()},function(k){n(k),y()},E),g=null}"onloadend"in g?g.onloadend=S:g.onreadystatechange=function(){!g||g.readyState!==4||g.status===0&&!(g.responseURL&&g.responseURL.indexOf("file:")===0)||setTimeout(S)},g.onabort=function(){g&&(n(new $("Request aborted",$.ECONNABORTED,t,g)),g=null)},g.onerror=function(){n(new $("Network Error",$.ERR_NETWORK,t,g)),g=null},g.ontimeout=function(){let P=s.timeout?"timeout of "+s.timeout+"ms exceeded":"timeout exceeded",E=s.transitional||Ea;s.timeoutErrorMessage&&(P=s.timeoutErrorMessage),n(new $(P,E.clarifyTimeoutError?$.ETIMEDOUT:$.ECONNABORTED,t,g)),g=null},o===void 0&&i.setContentType(null),"setRequestHeader"in g&&w.forEach(i.toJSON(),function(P,E){g.setRequestHeader(E,P)}),w.isUndefined(s.withCredentials)||(g.withCredentials=!!s.withCredentials),a&&a!=="json"&&(g.responseType=s.responseType),l&&([d,p]=us(l,!0),g.addEventListener("progress",d)),c&&g.upload&&([u,h]=us(c),g.upload.addEventListener("progress",u),g.upload.addEventListener("loadend",h)),(s.cancelToken||s.signal)&&(f=v=>{g&&(n(!v||v.type?new ft(null,t,g):v),g.abort(),g=null)},s.cancelToken&&s.cancelToken.subscribe(f),s.signal&&(s.signal.aborted?f():s.signal.addEventListener("abort",f)));let _=su(s.url);if(_&&z.protocols.indexOf(_)===-1){n(new $("Unsupported protocol "+_+":",$.ERR_BAD_REQUEST,t));return}g.send(o||null)})};var yS=(t,e)=>{let{length:r}=t=t?t.filter(Boolean):[];if(e||r){let n=new AbortController,s,o=function(l){if(!s){s=!0,a();let f=l instanceof Error?l:this.reason;n.abort(f instanceof $?f:new ft(f instanceof Error?f.message:f))}},i=e&&setTimeout(()=>{i=null,o(new $(`timeout ${e} of ms exceeded`,$.ETIMEDOUT))},e),a=()=>{t&&(i&&clearTimeout(i),i=null,t.forEach(l=>{l.unsubscribe?l.unsubscribe(o):l.removeEventListener("abort",o)}),t=null)};t.forEach(l=>l.addEventListener("abort",o));let{signal:c}=n;return c.unsubscribe=()=>w.asap(a),c}},Np=yS;var bS=function*(t,e){let r=t.byteLength;if(!e||r<e){yield t;return}let n=0,s;for(;n<r;)s=n+e,yield t.slice(n,s),n=s},wS=async function*(t,e){for await(let r of _S(t))yield*bS(r,e)},_S=async function*(t){if(t[Symbol.asyncIterator]){yield*t;return}let e=t.getReader();try{for(;;){let{done:r,value:n}=await e.read();if(r)break;yield n}}finally{await e.cancel()}},cu=(t,e,r,n)=>{let s=wS(t,e),o=0,i,a=c=>{i||(i=!0,n&&n(c))};return new ReadableStream({async pull(c){try{let{done:l,value:f}=await s.next();if(l){a(),c.close();return}let u=f.byteLength;if(r){let d=o+=u;r(d)}c.enqueue(new Uint8Array(f))}catch(l){throw a(l),l}},cancel(c){return a(c),s.return()}},{highWaterMark:2})};var Pa=typeof fetch=="function"&&typeof Request=="function"&&typeof Response=="function",Bp=Pa&&typeof ReadableStream=="function",SS=Pa&&(typeof TextEncoder=="function"?(t=>e=>t.encode(e))(new TextEncoder):async t=>new Uint8Array(await new Response(t).arrayBuffer())),Fp=(t,...e)=>{try{return!!t(...e)}catch(r){return!1}},ES=Bp&&Fp(()=>{let t=!1,e=new Request(z.origin,{body:new ReadableStream,method:"POST",get duplex(){return t=!0,"half"}}).headers.has("Content-Type");return t&&!e}),Dp=64*1024,uu=Bp&&Fp(()=>w.isReadableStream(new Response("").body)),Ca={stream:uu&&(t=>t.body)};Pa&&(t=>{["text","arrayBuffer","blob","formData","stream"].forEach(e=>{!Ca[e]&&(Ca[e]=w.isFunction(t[e])?r=>r[e]():(r,n)=>{throw new $(`Response type '${e}' is not supported`,$.ERR_NOT_SUPPORT,n)})})})(new Response);var xS=async t=>{if(t==null)return 0;if(w.isBlob(t))return t.size;if(w.isSpecCompliantForm(t))return(await new Request(z.origin,{method:"POST",body:t}).arrayBuffer()).byteLength;if(w.isArrayBufferView(t)||w.isArrayBuffer(t))return t.byteLength;if(w.isURLSearchParams(t)&&(t=t+""),w.isString(t))return(await SS(t)).byteLength},AS=async(t,e)=>{let r=w.toFiniteNumber(t.getContentLength());return r==null?xS(e):r},qp=Pa&&(async t=>{let{url:e,method:r,data:n,signal:s,cancelToken:o,timeout:i,onDownloadProgress:a,onUploadProgress:c,responseType:l,headers:f,withCredentials:u="same-origin",fetchOptions:d}=va(t);l=l?(l+"").toLowerCase():"text";let h=Np([s,o&&o.toAbortSignal()],i),p,y=h&&h.unsubscribe&&(()=>{h.unsubscribe()}),g;try{if(c&&ES&&r!=="get"&&r!=="head"&&(g=await AS(f,n))!==0){let E=new Request(e,{method:"POST",body:n,duplex:"half"}),R;if(w.isFormData(n)&&(R=E.headers.get("content-type"))&&f.setContentType(R),E.body){let[k,M]=ou(g,us(iu(c)));n=cu(E.body,Dp,k,M)}}w.isString(u)||(u=u?"include":"omit");let S="credentials"in Request.prototype;p=new Request(e,{...d,signal:h,method:r.toUpperCase(),headers:f.normalize().toJSON(),body:n,duplex:"half",credentials:S?u:void 0});let _=await fetch(p),v=uu&&(l==="stream"||l==="response");if(uu&&(a||v&&y)){let E={};["status","statusText","headers"].forEach(U=>{E[U]=_[U]});let R=w.toFiniteNumber(_.headers.get("content-length")),[k,M]=a&&ou(R,us(iu(a),!0))||[];_=new Response(cu(_.body,Dp,k,()=>{M&&M(),y&&y()}),E)}l=l||"text";let P=await Ca[w.findKey(Ca,l)||"text"](_,t);return!v&&y&&y(),await new Promise((E,R)=>{ko(E,R,{data:P,headers:oe.from(_.headers),status:_.status,statusText:_.statusText,config:t,request:p})})}catch(S){throw y&&y(),S&&S.name==="TypeError"&&/fetch/i.test(S.message)?Object.assign(new $("Network Error",$.ERR_NETWORK,t,p),{cause:S.cause||S}):$.from(S,S&&S.code,t,p)}});var fu={http:_a,xhr:Lp,fetch:qp};w.forEach(fu,(t,e)=>{if(t){try{Object.defineProperty(t,"name",{value:e})}catch(r){}Object.defineProperty(t,"adapterName",{value:e})}});var Up=t=>`- ${t}`,vS=t=>w.isFunction(t)||t===null||t===!1,Ra={getAdapter:t=>{t=w.isArray(t)?t:[t];let{length:e}=t,r,n,s={};for(let o=0;o<e;o++){r=t[o];let i;if(n=r,!vS(r)&&(n=fu[(i=String(r)).toLowerCase()],n===void 0))throw new $(`Unknown adapter '${i}'`);if(n)break;s[i||"#"+o]=n}if(!n){let o=Object.entries(s).map(([a,c])=>`adapter ${a} `+(c===!1?"is not supported by the environment":"is not available in the build")),i=e?o.length>1?`since :
`+o.map(Up).join(`
`):" "+Up(o[0]):"as no adapter specified";throw new $("There is no suitable adapter to dispatch the request "+i,"ERR_NOT_SUPPORT")}return n},adapters:fu};function du(t){if(t.cancelToken&&t.cancelToken.throwIfRequested(),t.signal&&t.signal.aborted)throw new ft(null,t)}function Ta(t){return du(t),t.headers=oe.from(t.headers),t.data=To.call(t,t.transformRequest),["post","put","patch"].indexOf(t.method)!==-1&&t.headers.setContentType("application/x-www-form-urlencoded",!1),Ra.getAdapter(t.adapter||ls.adapter)(t).then(function(n){return du(t),n.data=To.call(t,t.transformResponse,n),n.headers=oe.from(n.headers),n},function(n){return Io(n)||(du(t),n&&n.response&&(n.response.data=To.call(t,t.transformResponse,n.response),n.response.headers=oe.from(n.response.headers))),Promise.reject(n)})}var Ia="1.8.3";var ka={};["object","boolean","number","function","string","symbol"].forEach((t,e)=>{ka[t]=function(n){return typeof n===t||"a"+(e<1?"n ":" ")+t}});var $p={};ka.transitional=function(e,r,n){function s(o,i){return"[Axios v"+Ia+"] Transitional option '"+o+"'"+i+(n?". "+n:"")}return(o,i,a)=>{if(e===!1)throw new $(s(i," has been removed"+(r?" in "+r:"")),$.ERR_DEPRECATED);return r&&!$p[i]&&($p[i]=!0,console.warn(s(i," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(o,i,a):!0}};ka.spelling=function(e){return(r,n)=>(console.warn(`${n} is likely a misspelling of ${e}`),!0)};function CS(t,e,r){if(typeof t!="object")throw new $("options must be an object",$.ERR_BAD_OPTION_VALUE);let n=Object.keys(t),s=n.length;for(;s-- >0;){let o=n[s],i=e[o];if(i){let a=t[o],c=a===void 0||i(a,o,t);if(c!==!0)throw new $("option "+o+" must be "+c,$.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new $("Unknown option "+o,$.ERR_BAD_OPTION)}}var Mo={assertOptions:CS,validators:ka};var dt=Mo.validators,fs=class{constructor(e){this.defaults=e,this.interceptors={request:new Yc,response:new Yc}}async request(e,r){try{return await this._request(e,r)}catch(n){if(n instanceof Error){let s={};Error.captureStackTrace?Error.captureStackTrace(s):s=new Error;let o=s.stack?s.stack.replace(/^.+\n/,""):"";try{n.stack?o&&!String(n.stack).endsWith(o.replace(/^.+\n.+\n/,""))&&(n.stack+=`
`+o):n.stack=o}catch(i){}}throw n}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=Ke(this.defaults,r);let{transitional:n,paramsSerializer:s,headers:o}=r;n!==void 0&&Mo.assertOptions(n,{silentJSONParsing:dt.transitional(dt.boolean),forcedJSONParsing:dt.transitional(dt.boolean),clarifyTimeoutError:dt.transitional(dt.boolean)},!1),s!=null&&(w.isFunction(s)?r.paramsSerializer={serialize:s}:Mo.assertOptions(s,{encode:dt.function,serialize:dt.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),Mo.assertOptions(r,{baseUrl:dt.spelling("baseURL"),withXsrfToken:dt.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let i=o&&w.merge(o.common,o[r.method]);o&&w.forEach(["delete","get","head","post","put","patch","common"],p=>{delete o[p]}),r.headers=oe.concat(i,o);let a=[],c=!0;this.interceptors.request.forEach(function(y){typeof y.runWhen=="function"&&y.runWhen(r)===!1||(c=c&&y.synchronous,a.unshift(y.fulfilled,y.rejected))});let l=[];this.interceptors.response.forEach(function(y){l.push(y.fulfilled,y.rejected)});let f,u=0,d;if(!c){let p=[Ta.bind(this),void 0];for(p.unshift.apply(p,a),p.push.apply(p,l),d=p.length,f=Promise.resolve(r);u<d;)f=f.then(p[u++],p[u++]);return f}d=a.length;let h=r;for(u=0;u<d;){let p=a[u++],y=a[u++];try{h=p(h)}catch(g){y.call(this,g);break}}try{f=Ta.call(this,h)}catch(p){return Promise.reject(p)}for(u=0,d=l.length;u<d;)f=f.then(l[u++],l[u++]);return f}getUri(e){e=Ke(this.defaults,e);let r=Oo(e.baseURL,e.url,e.allowAbsoluteUrls);return Po(r,e.params,e.paramsSerializer)}};w.forEach(["delete","get","head","options"],function(e){fs.prototype[e]=function(r,n){return this.request(Ke(n||{},{method:e,url:r,data:(n||{}).data}))}});w.forEach(["post","put","patch"],function(e){function r(n){return function(o,i,a){return this.request(Ke(a||{},{method:e,headers:n?{"Content-Type":"multipart/form-data"}:{},url:o,data:i}))}}fs.prototype[e]=r(),fs.prototype[e+"Form"]=r(!0)});var Lo=fs;var hu=class t{constructor(e){if(typeof e!="function")throw new TypeError("executor must be a function.");let r;this.promise=new Promise(function(o){r=o});let n=this;this.promise.then(s=>{if(!n._listeners)return;let o=n._listeners.length;for(;o-- >0;)n._listeners[o](s);n._listeners=null}),this.promise.then=s=>{let o,i=new Promise(a=>{n.subscribe(a),o=a}).then(s);return i.cancel=function(){n.unsubscribe(o)},i},e(function(o,i,a){n.reason||(n.reason=new ft(o,i,a),r(n.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;let r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){let e=new AbortController,r=n=>{e.abort(n)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new t(function(s){e=s}),cancel:e}}},Hp=hu;function pu(t){return function(r){return t.apply(null,r)}}function mu(t){return w.isObject(t)&&t.isAxiosError===!0}var gu={Continue:100,SwitchingProtocols:101,Processing:102,EarlyHints:103,Ok:200,Created:201,Accepted:202,NonAuthoritativeInformation:203,NoContent:204,ResetContent:205,PartialContent:206,MultiStatus:207,AlreadyReported:208,ImUsed:226,MultipleChoices:300,MovedPermanently:301,Found:302,SeeOther:303,NotModified:304,UseProxy:305,Unused:306,TemporaryRedirect:307,PermanentRedirect:308,BadRequest:400,Unauthorized:401,PaymentRequired:402,Forbidden:403,NotFound:404,MethodNotAllowed:405,NotAcceptable:406,ProxyAuthenticationRequired:407,RequestTimeout:408,Conflict:409,Gone:410,LengthRequired:411,PreconditionFailed:412,PayloadTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,Locked:423,FailedDependency:424,TooEarly:425,UpgradeRequired:426,PreconditionRequired:428,TooManyRequests:429,RequestHeaderFieldsTooLarge:431,UnavailableForLegalReasons:451,InternalServerError:500,NotImplemented:501,BadGateway:502,ServiceUnavailable:503,GatewayTimeout:504,HttpVersionNotSupported:505,VariantAlsoNegotiates:506,InsufficientStorage:507,LoopDetected:508,NotExtended:510,NetworkAuthenticationRequired:511};Object.entries(gu).forEach(([t,e])=>{gu[e]=t});var jp=gu;function Wp(t){let e=new Lo(t),r=Ao(Lo.prototype.request,e);return w.extend(r,Lo.prototype,e,{allOwnKeys:!0}),w.extend(r,e,null,{allOwnKeys:!0}),r.create=function(s){return Wp(Ke(t,s))},r}var Q=Wp(ls);Q.Axios=Lo;Q.CanceledError=ft;Q.CancelToken=Hp;Q.isCancel=Io;Q.VERSION=Ia;Q.toFormData=ir;Q.AxiosError=$;Q.Cancel=Q.CanceledError;Q.all=function(e){return Promise.all(e)};Q.spread=pu;Q.isAxiosError=mu;Q.mergeConfig=Ke;Q.AxiosHeaders=oe;Q.formToJSON=t=>xa(w.isHTMLForm(t)?new FormData(t):t);Q.getAdapter=Ra.getAdapter;Q.HttpStatusCode=jp;Q.default=Q;var ds=Q;var{Axios:zL,AxiosError:XL,CanceledError:YL,isCancel:QL,CancelToken:ZL,VERSION:eN,all:tN,Cancel:rN,isAxiosError:nN,spread:sN,toFormData:oN,AxiosHeaders:iN,HttpStatusCode:aN,formToJSON:lN,getAdapter:cN,mergeConfig:uN}=ds;var PS=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));if(!l)throw new Error(m("Model is required"));let u=await Promise.all(e.map(S=>RS(S,n))),d={model:l,messages:u,stream:!0,...f},p=(await ds.post(c,d,{headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},adapter:"fetch",responseType:"stream",withCredentials:!1,signal:r.signal})).data.pipeThrough(new TextDecoderStream).getReader(),y=!0,g=!1;for(;y;){let{done:S,value:_}=await p.read();if(S){y=!1;break}let v=_.split(`
`);for(let P of v){if(P.includes("data: [DONE]")){y=!1;break}let E=P.replace(/^data: /,"").trim();if(E){let R=JSON.parse(E);if(R.choices&&R.choices[0].delta){let k=R.choices[0].delta,M=k.reasoning_content;if(M)yield(g?"":(g=!0,it))+M.replace(/\n/g,`
> `);else{let U=g?(g=!1,at):"";k.content&&(yield U+k.content)}}}}}},RS=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>Qt(n,e))):[];return r.length===0?{role:t.role,content:t.content}:(t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r})},Oa={name:"Kimi",defaultOptions:{apiKey:"",baseURL:"https://api.moonshot.cn/v1/chat/completions",model:"",parameters:{}},sendRequestFunc:PS,models:[],websiteToObtainKey:"https://www.moonshot.cn",capabilities:["Text Generation","Image Vision","Reasoning"]};var he=typeof globalThis!="undefined"&&globalThis||typeof self!="undefined"&&self||typeof global!="undefined"&&global||{},_e={searchParams:"URLSearchParams"in he,iterable:"Symbol"in he&&"iterator"in Symbol,blob:"FileReader"in he&&"Blob"in he&&function(){try{return new Blob,!0}catch(t){return!1}}(),formData:"FormData"in he,arrayBuffer:"ArrayBuffer"in he};function TS(t){return t&&DataView.prototype.isPrototypeOf(t)}_e.arrayBuffer&&(Vp=["[object Int8Array]","[object Uint8Array]","[object Uint8ClampedArray]","[object Int16Array]","[object Uint16Array]","[object Int32Array]","[object Uint32Array]","[object Float32Array]","[object Float64Array]"],Gp=ArrayBuffer.isView||function(t){return t&&Vp.indexOf(Object.prototype.toString.call(t))>-1});var Vp,Gp;function hs(t){if(typeof t!="string"&&(t=String(t)),/[^a-z0-9\-#$%&'*+.^_`|~!]/i.test(t)||t==="")throw new TypeError('Invalid character in header field name: "'+t+'"');return t.toLowerCase()}function bu(t){return typeof t!="string"&&(t=String(t)),t}function wu(t){var e={next:function(){var r=t.shift();return{done:r===void 0,value:r}}};return _e.iterable&&(e[Symbol.iterator]=function(){return e}),e}function ie(t){this.map={},t instanceof ie?t.forEach(function(e,r){this.append(r,e)},this):Array.isArray(t)?t.forEach(function(e){if(e.length!=2)throw new TypeError("Headers constructor: expected name/value pair to be length 2, found"+e.length);this.append(e[0],e[1])},this):t&&Object.getOwnPropertyNames(t).forEach(function(e){this.append(e,t[e])},this)}ie.prototype.append=function(t,e){t=hs(t),e=bu(e);var r=this.map[t];this.map[t]=r?r+", "+e:e};ie.prototype.delete=function(t){delete this.map[hs(t)]};ie.prototype.get=function(t){return t=hs(t),this.has(t)?this.map[t]:null};ie.prototype.has=function(t){return this.map.hasOwnProperty(hs(t))};ie.prototype.set=function(t,e){this.map[hs(t)]=bu(e)};ie.prototype.forEach=function(t,e){for(var r in this.map)this.map.hasOwnProperty(r)&&t.call(e,this.map[r],r,this)};ie.prototype.keys=function(){var t=[];return this.forEach(function(e,r){t.push(r)}),wu(t)};ie.prototype.values=function(){var t=[];return this.forEach(function(e){t.push(e)}),wu(t)};ie.prototype.entries=function(){var t=[];return this.forEach(function(e,r){t.push([r,e])}),wu(t)};_e.iterable&&(ie.prototype[Symbol.iterator]=ie.prototype.entries);function yu(t){if(!t._noBody){if(t.bodyUsed)return Promise.reject(new TypeError("Already read"));t.bodyUsed=!0}}function Jp(t){return new Promise(function(e,r){t.onload=function(){e(t.result)},t.onerror=function(){r(t.error)}})}function IS(t){var e=new FileReader,r=Jp(e);return e.readAsArrayBuffer(t),r}function kS(t){var e=new FileReader,r=Jp(e),n=/charset=([A-Za-z0-9_-]+)/.exec(t.type),s=n?n[1]:"utf-8";return e.readAsText(t,s),r}function OS(t){for(var e=new Uint8Array(t),r=new Array(e.length),n=0;n<e.length;n++)r[n]=String.fromCharCode(e[n]);return r.join("")}function Kp(t){if(t.slice)return t.slice(0);var e=new Uint8Array(t.byteLength);return e.set(new Uint8Array(t)),e.buffer}function zp(){return this.bodyUsed=!1,this._initBody=function(t){this.bodyUsed=this.bodyUsed,this._bodyInit=t,t?typeof t=="string"?this._bodyText=t:_e.blob&&Blob.prototype.isPrototypeOf(t)?this._bodyBlob=t:_e.formData&&FormData.prototype.isPrototypeOf(t)?this._bodyFormData=t:_e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)?this._bodyText=t.toString():_e.arrayBuffer&&_e.blob&&TS(t)?(this._bodyArrayBuffer=Kp(t.buffer),this._bodyInit=new Blob([this._bodyArrayBuffer])):_e.arrayBuffer&&(ArrayBuffer.prototype.isPrototypeOf(t)||Gp(t))?this._bodyArrayBuffer=Kp(t):this._bodyText=t=Object.prototype.toString.call(t):(this._noBody=!0,this._bodyText=""),this.headers.get("content-type")||(typeof t=="string"?this.headers.set("content-type","text/plain;charset=UTF-8"):this._bodyBlob&&this._bodyBlob.type?this.headers.set("content-type",this._bodyBlob.type):_e.searchParams&&URLSearchParams.prototype.isPrototypeOf(t)&&this.headers.set("content-type","application/x-www-form-urlencoded;charset=UTF-8"))},_e.blob&&(this.blob=function(){var t=yu(this);if(t)return t;if(this._bodyBlob)return Promise.resolve(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(new Blob([this._bodyArrayBuffer]));if(this._bodyFormData)throw new Error("could not read FormData body as blob");return Promise.resolve(new Blob([this._bodyText]))}),this.arrayBuffer=function(){if(this._bodyArrayBuffer){var t=yu(this);return t||(ArrayBuffer.isView(this._bodyArrayBuffer)?Promise.resolve(this._bodyArrayBuffer.buffer.slice(this._bodyArrayBuffer.byteOffset,this._bodyArrayBuffer.byteOffset+this._bodyArrayBuffer.byteLength)):Promise.resolve(this._bodyArrayBuffer))}else{if(_e.blob)return this.blob().then(IS);throw new Error("could not read as ArrayBuffer")}},this.text=function(){var t=yu(this);if(t)return t;if(this._bodyBlob)return kS(this._bodyBlob);if(this._bodyArrayBuffer)return Promise.resolve(OS(this._bodyArrayBuffer));if(this._bodyFormData)throw new Error("could not read FormData body as text");return Promise.resolve(this._bodyText)},_e.formData&&(this.formData=function(){return this.text().then(NS)}),this.json=function(){return this.text().then(JSON.parse)},this}var MS=["CONNECT","DELETE","GET","HEAD","OPTIONS","PATCH","POST","PUT","TRACE"];function LS(t){var e=t.toUpperCase();return MS.indexOf(e)>-1?e:t}function jr(t,e){if(!(this instanceof jr))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');e=e||{};var r=e.body;if(t instanceof jr){if(t.bodyUsed)throw new TypeError("Already read");this.url=t.url,this.credentials=t.credentials,e.headers||(this.headers=new ie(t.headers)),this.method=t.method,this.mode=t.mode,this.signal=t.signal,!r&&t._bodyInit!=null&&(r=t._bodyInit,t.bodyUsed=!0)}else this.url=String(t);if(this.credentials=e.credentials||this.credentials||"same-origin",(e.headers||!this.headers)&&(this.headers=new ie(e.headers)),this.method=LS(e.method||this.method||"GET"),this.mode=e.mode||this.mode||null,this.signal=e.signal||this.signal||function(){if("AbortController"in he){var o=new AbortController;return o.signal}}(),this.referrer=null,(this.method==="GET"||this.method==="HEAD")&&r)throw new TypeError("Body not allowed for GET or HEAD requests");if(this._initBody(r),(this.method==="GET"||this.method==="HEAD")&&(e.cache==="no-store"||e.cache==="no-cache")){var n=/([?&])_=[^&]*/;if(n.test(this.url))this.url=this.url.replace(n,"$1_="+new Date().getTime());else{var s=/\?/;this.url+=(s.test(this.url)?"&":"?")+"_="+new Date().getTime()}}}jr.prototype.clone=function(){return new jr(this,{body:this._bodyInit})};function NS(t){var e=new FormData;return t.trim().split("&").forEach(function(r){if(r){var n=r.split("="),s=n.shift().replace(/\+/g," "),o=n.join("=").replace(/\+/g," ");e.append(decodeURIComponent(s),decodeURIComponent(o))}}),e}function DS(t){var e=new ie,r=t.replace(/\r?\n[\t ]+/g," ");return r.split("\r").map(function(n){return n.indexOf(`
`)===0?n.substr(1,n.length):n}).forEach(function(n){var s=n.split(":"),o=s.shift().trim();if(o){var i=s.join(":").trim();try{e.append(o,i)}catch(a){console.warn("Response "+a.message)}}}),e}zp.call(jr.prototype);function ht(t,e){if(!(this instanceof ht))throw new TypeError('Please use the "new" operator, this DOM object constructor cannot be called as a function.');if(e||(e={}),this.type="default",this.status=e.status===void 0?200:e.status,this.status<200||this.status>599)throw new RangeError("Failed to construct 'Response': The status provided (0) is outside the range [200, 599].");this.ok=this.status>=200&&this.status<300,this.statusText=e.statusText===void 0?"":""+e.statusText,this.headers=new ie(e.headers),this.url=e.url||"",this._initBody(t)}zp.call(ht.prototype);ht.prototype.clone=function(){return new ht(this._bodyInit,{status:this.status,statusText:this.statusText,headers:new ie(this.headers),url:this.url})};ht.error=function(){var t=new ht(null,{status:200,statusText:""});return t.ok=!1,t.status=0,t.type="error",t};var BS=[301,302,303,307,308];ht.redirect=function(t,e){if(BS.indexOf(e)===-1)throw new RangeError("Invalid status code");return new ht(null,{status:e,headers:{location:t}})};var Hr=he.DOMException;try{new Hr}catch(t){Hr=function(e,r){this.message=e,this.name=r;var n=Error(e);this.stack=n.stack},Hr.prototype=Object.create(Error.prototype),Hr.prototype.constructor=Hr}function Xp(t,e){return new Promise(function(r,n){var s=new jr(t,e);if(s.signal&&s.signal.aborted)return n(new Hr("Aborted","AbortError"));var o=new XMLHttpRequest;function i(){o.abort()}o.onload=function(){var l={statusText:o.statusText,headers:DS(o.getAllResponseHeaders()||"")};s.url.indexOf("file://")===0&&(o.status<200||o.status>599)?l.status=200:l.status=o.status,l.url="responseURL"in o?o.responseURL:l.headers.get("X-Request-URL");var f="response"in o?o.response:o.responseText;setTimeout(function(){r(new ht(f,l))},0)},o.onerror=function(){setTimeout(function(){n(new TypeError("Network request failed"))},0)},o.ontimeout=function(){setTimeout(function(){n(new TypeError("Network request timed out"))},0)},o.onabort=function(){setTimeout(function(){n(new Hr("Aborted","AbortError"))},0)};function a(l){try{return l===""&&he.location.href?he.location.href:l}catch(f){return l}}if(o.open(s.method,a(s.url),!0),s.credentials==="include"?o.withCredentials=!0:s.credentials==="omit"&&(o.withCredentials=!1),"responseType"in o&&(_e.blob?o.responseType="blob":_e.arrayBuffer&&(o.responseType="arraybuffer")),e&&typeof e.headers=="object"&&!(e.headers instanceof ie||he.Headers&&e.headers instanceof he.Headers)){var c=[];Object.getOwnPropertyNames(e.headers).forEach(function(l){c.push(hs(l)),o.setRequestHeader(l,bu(e.headers[l]))}),s.headers.forEach(function(l,f){c.indexOf(f)===-1&&o.setRequestHeader(f,l)})}else s.headers.forEach(function(l,f){o.setRequestHeader(f,l)});s.signal&&(s.signal.addEventListener("abort",i),o.onreadystatechange=function(){o.readyState===4&&s.signal.removeEventListener("abort",i)}),o.send(typeof s._bodyInit=="undefined"?null:s._bodyInit)})}Xp.polyfill=!0;he.fetch||(he.fetch=Xp,he.Headers=ie,he.Request=jr,he.Response=ht);var Qp="11434",Zp=`http://127.0.0.1:${Qp}`,FS="0.5.16",qS=Object.defineProperty,US=(t,e,r)=>e in t?qS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,_u=(t,e,r)=>(US(t,typeof e!="symbol"?e+"":e,r),r),Eu=class t extends Error{constructor(e,r){super(e),this.error=e,this.status_code=r,this.name="ResponseError",Error.captureStackTrace&&Error.captureStackTrace(this,t)}},xu=class{constructor(e,r,n){_u(this,"abortController"),_u(this,"itr"),_u(this,"doneCallback"),this.abortController=e,this.itr=r,this.doneCallback=n}abort(){this.abortController.abort()}async*[Symbol.asyncIterator](){for await(let e of this.itr){if("error"in e)throw new Error(e.error);if(yield e,e.done||e.status==="success"){this.doneCallback();return}}throw new Error("Did not receive done or success response in stream.")}},Au=async t=>{var n;if(t.ok)return;let e=`Error ${t.status}: ${t.statusText}`,r=null;if((n=t.headers.get("content-type"))!=null&&n.includes("application/json"))try{r=await t.json(),e=r.error||e}catch(s){console.log("Failed to parse error response as JSON")}else try{console.log("Getting text from response"),e=await t.text()||e}catch(s){console.log("Failed to get text from error response")}throw new Eu(e,t.status)};function $S(){var t;if(typeof window!="undefined"&&window.navigator){let e=navigator;return"userAgentData"in e&&((t=e.userAgentData)!=null&&t.platform)?`${e.userAgentData.platform.toLowerCase()} Browser/${navigator.userAgent};`:navigator.platform?`${navigator.platform.toLowerCase()} Browser/${navigator.userAgent};`:`unknown Browser/${navigator.userAgent};`}else if(typeof process!="undefined")return`${process.arch} ${process.platform} Node.js/${process.version}`;return""}function HS(t){if(t instanceof Headers){let e={};return t.forEach((r,n)=>{e[n]=r}),e}else return Array.isArray(t)?Object.fromEntries(t):t||{}}var vu=async(t,e,r={})=>{let n={"Content-Type":"application/json",Accept:"application/json","User-Agent":`ollama-js/${FS} (${$S()})`};r.headers=HS(r.headers);let s=Object.fromEntries(Object.entries(r.headers).filter(([o])=>!Object.keys(n).some(i=>i.toLowerCase()===o.toLowerCase())));return r.headers={...n,...s},t(e,r)},Yp=async(t,e,r)=>{let n=await vu(t,e,{headers:r==null?void 0:r.headers});return await Au(n),n},ps=async(t,e,r,n)=>{let o=(a=>a!==null&&typeof a=="object"&&!Array.isArray(a))(r)?JSON.stringify(r):r,i=await vu(t,e,{method:"POST",body:o,signal:n==null?void 0:n.signal,headers:n==null?void 0:n.headers});return await Au(i),i},jS=async(t,e,r,n)=>{let s=await vu(t,e,{method:"DELETE",body:JSON.stringify(r),headers:n==null?void 0:n.headers});return await Au(s),s},WS=async function*(t){var s;let e=new TextDecoder("utf-8"),r="",n=t.getReader();for(;;){let{done:o,value:i}=await n.read();if(o)break;r+=e.decode(i);let a=r.split(`
`);r=(s=a.pop())!=null?s:"";for(let c of a)try{yield JSON.parse(c)}catch(l){console.warn("invalid json: ",c)}}for(let o of r.split(`
`).filter(i=>i!==""))try{yield JSON.parse(o)}catch(i){console.warn("invalid json: ",o)}},VS=t=>{if(!t)return Zp;let e=t.includes("://");t.startsWith(":")&&(t=`http://127.0.0.1${t}`,e=!0),e||(t=`http://${t}`);let r=new URL(t),n=r.port;n||(e?n=r.protocol==="https:"?"443":"80":n=Qp);let s="";r.username&&(s=r.username,r.password&&(s+=`:${r.password}`),s+="@");let o=`${r.protocol}//${s}${r.hostname}:${n}${r.pathname}`;return o.endsWith("/")&&(o=o.slice(0,-1)),o},KS=Object.defineProperty,GS=(t,e,r)=>e in t?KS(t,e,{enumerable:!0,configurable:!0,writable:!0,value:r}):t[e]=r,Su=(t,e,r)=>(GS(t,typeof e!="symbol"?e+"":e,r),r),Cu=class{constructor(e){var r,n;Su(this,"config"),Su(this,"fetch"),Su(this,"ongoingStreamedRequests",[]),this.config={host:"",headers:e==null?void 0:e.headers},e!=null&&e.proxy||(this.config.host=VS((r=e==null?void 0:e.host)!=null?r:Zp)),this.fetch=(n=e==null?void 0:e.fetch)!=null?n:fetch}abort(){for(let e of this.ongoingStreamedRequests)e.abort();this.ongoingStreamedRequests.length=0}async processStreamableRequest(e,r){var o;r.stream=(o=r.stream)!=null?o:!1;let n=`${this.config.host}/api/${e}`;if(r.stream){let i=new AbortController,a=await ps(this.fetch,n,r,{signal:i.signal,headers:this.config.headers});if(!a.body)throw new Error("Missing body");let c=WS(a.body),l=new xu(i,c,()=>{let f=this.ongoingStreamedRequests.indexOf(l);f>-1&&this.ongoingStreamedRequests.splice(f,1)});return this.ongoingStreamedRequests.push(l),l}return await(await ps(this.fetch,n,r,{headers:this.config.headers})).json()}async encodeImage(e){if(typeof e!="string"){let r=new Uint8Array(e),n="",s=r.byteLength;for(let o=0;o<s;o++)n+=String.fromCharCode(r[o]);return btoa(n)}return e}async generate(e){return e.images&&(e.images=await Promise.all(e.images.map(this.encodeImage.bind(this)))),this.processStreamableRequest("generate",e)}async chat(e){if(e.messages)for(let r of e.messages)r.images&&(r.images=await Promise.all(r.images.map(this.encodeImage.bind(this))));return this.processStreamableRequest("chat",e)}async create(e){return this.processStreamableRequest("create",{...e})}async pull(e){return this.processStreamableRequest("pull",{name:e.model,stream:e.stream,insecure:e.insecure})}async push(e){return this.processStreamableRequest("push",{name:e.model,stream:e.stream,insecure:e.insecure})}async delete(e){return await jS(this.fetch,`${this.config.host}/api/delete`,{name:e.model},{headers:this.config.headers}),{status:"success"}}async copy(e){return await ps(this.fetch,`${this.config.host}/api/copy`,{...e},{headers:this.config.headers}),{status:"success"}}async list(){return await(await Yp(this.fetch,`${this.config.host}/api/tags`,{headers:this.config.headers})).json()}async show(e){return await(await ps(this.fetch,`${this.config.host}/api/show`,{...e},{headers:this.config.headers})).json()}async embed(e){return await(await ps(this.fetch,`${this.config.host}/api/embed`,{...e},{headers:this.config.headers})).json()}async embeddings(e){return await(await ps(this.fetch,`${this.config.host}/api/embeddings`,{...e},{headers:this.config.headers})).json()}async ps(){return await(await Yp(this.fetch,`${this.config.host}/api/ps`,{headers:this.config.headers})).json()}},wN=new Cu;var JS=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{baseURL:a,model:c,...l}=i,f=new Cu({host:a}),u=await f.chat({model:c,messages:e,stream:!0,...l});for await(let d of u){if(r.signal.aborted){f.abort();break}yield d.message.content}},Ma={name:"Ollama",defaultOptions:{apiKey:"",baseURL:"http://127.0.0.1:11434",model:"llama3.1",parameters:{}},sendRequestFunc:JS,models:[],websiteToObtainKey:"https://ollama.com",capabilities:["Text Generation"]};var zS=t=>async function*(e,r,n){var p,y;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let u=await Promise.all(e.map(g=>XS(g,n))),h=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:u,stream:!0,...f},{signal:r.signal});for await(let g of h){let S=(y=(p=g.choices[0])==null?void 0:p.delta)==null?void 0:y.content;S&&(yield S)}},XS=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>Qt(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},em={name:"OpenAI",defaultOptions:{apiKey:"",baseURL:"https://api.openai.com/v1",model:"gpt-4.1",parameters:{}},sendRequestFunc:zS,models:[],websiteToObtainKey:"https://platform.openai.com/api-keys",capabilities:["Text Generation","Image Vision"]};var YS=t=>async function*(e,r,n){var S;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));if(!l)throw new Error(m("Model is required"));let u=await Promise.all(e.map(_=>ZS(_,n))),d={model:l,messages:u,stream:!0,...f},p=(S=(await fetch(c,{method:"POST",headers:{Authorization:`Bearer ${a}`,"Content-Type":"application/json"},body:JSON.stringify(d),signal:r.signal})).body)==null?void 0:S.getReader();if(!p)throw new Error("Response body is not readable");let y=new TextDecoder,g="";try{for(;;){let{done:_,value:v}=await p.read();if(_)break;for(g+=y.decode(v,{stream:!0});;){let P=g.indexOf(`
`);if(P===-1)break;let E=g.slice(0,P).trim();if(g=g.slice(P+1),E.startsWith("data: ")){let R=E.slice(6);if(R==="[DONE]")break;try{let M=JSON.parse(R).choices[0].delta.content;M&&(yield M)}catch(k){}}}}}finally{p.cancel()}},QS=async(t,e)=>{let r=Or(t.link);if(["image/png","image/jpeg","image/gif","image/webp"].includes(r)){let n=await e(t),s=Mr(n);return{type:"image_url",image_url:{url:`data:${r};base64,${s}`}}}else if(r==="application/pdf"){let n=await e(t),s=Mr(n);return{type:"file",file:{filename:t.link,file_data:`data:${r};base64,${s}`}}}else throw new Error(m("Only PNG, JPEG, GIF, WebP, and PDF files are supported."))},ZS=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>QS(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},La={name:"OpenRouter",defaultOptions:{apiKey:"",baseURL:"https://openrouter.ai/api/v1/chat/completions",model:"",parameters:{}},sendRequestFunc:YS,models:[],websiteToObtainKey:"https://openrouter.ai",capabilities:["Text Generation","Image Vision","PDF Vision"]};var Wr=require("obsidian");var eE=async(t,e)=>{if(!t||!e)throw new Error("Invalid API key secret");let r={grant_type:"client_credentials",client_id:t,client_secret:e},n=new URLSearchParams(r).toString(),o=(await(0,Wr.requestUrl)(`https://aip.baidubce.com/oauth/2.0/token?${n}`)).json;return{accessToken:o.access_token,exp:Date.now()+o.expires_in,apiKey:t,apiSecret:e}},tE=async(t,e,r)=>{let n=Date.now();if(t&&t.apiKey===e&&t.apiSecret===r&&t.exp>n+180*1e3)return{isValid:!0,token:t};let s=await eE(e,r);return console.debug("create new token",s),{isValid:!1,token:s}},rE=(t,e)=>{let r=e.endsWith(`
`)||e.endsWith("\r"),n=e.split(/\r\n|[\n\r]/g);return n.length===1&&!r?(t.push(n[0]),[]):(t.length>0&&(n=[t.join("")+n[0],...n.slice(1)],t=[]),r||(t=[n.pop()||""]),n)},nE=t=>async function*(e,r,n){let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,apiSecret:c,baseURL:l,model:f,token:u,...d}=i;if(!a)throw new Error(m("API key is required"));if(!c)throw new Error(m("API secret is required"));if(!f)throw new Error(m("Model is required"));let{token:h}=await tE(u,a,c);if(t.token=h,Wr.Platform.isDesktopApp){let p={messages:e,stream:!0,...d},y=await ds.post(l+`/${f}?access_token=${h.accessToken}`,p,{headers:{"Content-Type":"application/json"},adapter:"fetch",responseType:"stream",withCredentials:!1,signal:r.signal}),g=[],S=new TextDecoder("utf-8");for await(let _ of y.data){let v=S.decode(Buffer.from(_)),P=rE(g,v);for(let E of P)if(E.startsWith("data: ")){let R=E.slice(6),M=JSON.parse(R).result;M&&(yield M)}}}else{let p={messages:e,stream:!1,...d};new Wr.Notice(m("This is a non-streaming request, please wait..."),5*1e3);let y=await(0,Wr.requestUrl)({url:l+`/${f}?access_token=${h.accessToken}`,method:"POST",body:JSON.stringify(p),headers:{"Content-Type":"application/json"}});console.debug("response",y.json),yield y.json.result}},tm=["ernie-4.0-8k-latest","ernie-4.0-turbo-8k","ernie-3.5-128k","ernie_speed","ernie-speed-128k","gemma_7b_it","yi_34b_chat","mixtral_8x7b_instruct","llama_2_70b"],rm={name:"QianFan",defaultOptions:{apiKey:"",apiSecret:"",baseURL:"https://aip.baidubce.com/rpc/2.0/ai_custom/v1/wenxinworkshop/chat",model:tm[0],parameters:{}},sendRequestFunc:nE,models:tm,websiteToObtainKey:"https://qianfan.cloud.baidu.com",capabilities:["Text Generation"]};var sE=t=>async function*(e,r,n){var p,y;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let u=await Promise.all(e.map(g=>oE(g,n))),h=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:u,stream:!0,...f},{signal:r.signal});for await(let g of h){let S=(y=(p=g.choices[0])==null?void 0:p.delta)==null?void 0:y.content;S&&(yield S)}},oE=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>Qt(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},nm=["qwen-turbo","qwen-plus","qwen-max","qwen-vl-max"],sm={name:"Qwen",defaultOptions:{apiKey:"",baseURL:"https://dashscope.aliyuncs.com/compatible-mode/v1",model:nm[0],parameters:{}},sendRequestFunc:sE,models:nm,websiteToObtainKey:"https://dashscope.console.aliyun.com",capabilities:["Text Generation","Image Vision"]};var iE=t=>async function*(e,r,n){var y;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,...f}=i;if(!a)throw new Error(m("API key is required"));let u=await Promise.all(e.map(g=>aE(g,n))),h=await new D({apiKey:a,baseURL:c,dangerouslyAllowBrowser:!0}).chat.completions.create({model:l,messages:u,stream:!0,...f},{signal:r.signal}),p=!1;for await(let g of h){let S=(y=g.choices[0])==null?void 0:y.delta,_=S==null?void 0:S.reasoning_content;if(_)yield(p?"":(p=!0,it))+_.replace(/\n/g,`
> `);else{let v=p?(p=!1,at):"";S!=null&&S.content&&(yield v+(S==null?void 0:S.content))}}},aE=async(t,e)=>{let r=t.embeds?await Promise.all(t.embeds.map(n=>Qt(n,e))):[];return t.content.trim()&&r.push({type:"text",text:t.content}),{role:t.role,content:r}},Na={name:"SiliconFlow",defaultOptions:{apiKey:"",baseURL:"https://api.siliconflow.cn/v1",model:"",parameters:{}},sendRequestFunc:iE,models:[],websiteToObtainKey:"https://siliconflow.cn",capabilities:["Text Generation","Image Vision","Reasoning"]};var ms=crypto,Da=t=>t instanceof CryptoKey;var Tt=new TextEncoder,No=new TextDecoder,HN=2**32;function om(...t){let e=t.reduce((s,{length:o})=>s+o,0),r=new Uint8Array(e),n=0;for(let s of t)r.set(s,n),n+=s.length;return r}var lE=t=>{let e=t;typeof e=="string"&&(e=Tt.encode(e));let r=32768,n=[];for(let s=0;s<e.length;s+=r)n.push(String.fromCharCode.apply(null,e.subarray(s,s+r)));return btoa(n.join(""))},Ba=t=>lE(t).replace(/=/g,"").replace(/\+/g,"-").replace(/\//g,"_"),cE=t=>{let e=atob(t),r=new Uint8Array(e.length);for(let n=0;n<e.length;n++)r[n]=e.charCodeAt(n);return r},Fa=t=>{let e=t;e instanceof Uint8Array&&(e=No.decode(e)),e=e.replace(/-/g,"+").replace(/_/g,"/").replace(/\s/g,"");try{return cE(e)}catch(r){throw new TypeError("The input to be decoded is not correctly encoded.")}};var pe=class extends Error{constructor(e,r){var n;super(e,r),this.code="ERR_JOSE_GENERIC",this.name=this.constructor.name,(n=Error.captureStackTrace)==null||n.call(Error,this,this.constructor)}};pe.code="ERR_JOSE_GENERIC";var Pu=class extends pe{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_CLAIM_VALIDATION_FAILED",this.claim=n,this.reason=s,this.payload=r}};Pu.code="ERR_JWT_CLAIM_VALIDATION_FAILED";var Ru=class extends pe{constructor(e,r,n="unspecified",s="unspecified"){super(e,{cause:{claim:n,reason:s,payload:r}}),this.code="ERR_JWT_EXPIRED",this.claim=n,this.reason=s,this.payload=r}};Ru.code="ERR_JWT_EXPIRED";var Tu=class extends pe{constructor(){super(...arguments),this.code="ERR_JOSE_ALG_NOT_ALLOWED"}};Tu.code="ERR_JOSE_ALG_NOT_ALLOWED";var De=class extends pe{constructor(){super(...arguments),this.code="ERR_JOSE_NOT_SUPPORTED"}};De.code="ERR_JOSE_NOT_SUPPORTED";var Iu=class extends pe{constructor(e="decryption operation failed",r){super(e,r),this.code="ERR_JWE_DECRYPTION_FAILED"}};Iu.code="ERR_JWE_DECRYPTION_FAILED";var ku=class extends pe{constructor(){super(...arguments),this.code="ERR_JWE_INVALID"}};ku.code="ERR_JWE_INVALID";var It=class extends pe{constructor(){super(...arguments),this.code="ERR_JWS_INVALID"}};It.code="ERR_JWS_INVALID";var Do=class extends pe{constructor(){super(...arguments),this.code="ERR_JWT_INVALID"}};Do.code="ERR_JWT_INVALID";var Ou=class extends pe{constructor(){super(...arguments),this.code="ERR_JWK_INVALID"}};Ou.code="ERR_JWK_INVALID";var Mu=class extends pe{constructor(){super(...arguments),this.code="ERR_JWKS_INVALID"}};Mu.code="ERR_JWKS_INVALID";var Lu=class extends pe{constructor(e="no applicable key found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_NO_MATCHING_KEY"}};Lu.code="ERR_JWKS_NO_MATCHING_KEY";var Nu=class extends pe{constructor(e="multiple matching keys found in the JSON Web Key Set",r){super(e,r),this.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS"}};Nu.code="ERR_JWKS_MULTIPLE_MATCHING_KEYS";var Du=class extends pe{constructor(e="request timed out",r){super(e,r),this.code="ERR_JWKS_TIMEOUT"}};Du.code="ERR_JWKS_TIMEOUT";var Bu=class extends pe{constructor(e="signature verification failed",r){super(e,r),this.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED"}};Bu.code="ERR_JWS_SIGNATURE_VERIFICATION_FAILED";function kt(t,e="algorithm.name"){return new TypeError(`CryptoKey does not support this operation, its ${e} must be ${t}`)}function qa(t,e){return t.name===e}function Fu(t){return parseInt(t.name.slice(4),10)}function uE(t){switch(t){case"ES256":return"P-256";case"ES384":return"P-384";case"ES512":return"P-521";default:throw new Error("unreachable")}}function fE(t,e){if(e.length&&!e.some(r=>t.usages.includes(r))){let r="CryptoKey does not support this operation, its usages must include ";if(e.length>2){let n=e.pop();r+=`one of ${e.join(", ")}, or ${n}.`}else e.length===2?r+=`one of ${e[0]} or ${e[1]}.`:r+=`${e[0]}.`;throw new TypeError(r)}}function im(t,e,...r){switch(e){case"HS256":case"HS384":case"HS512":{if(!qa(t.algorithm,"HMAC"))throw kt("HMAC");let n=parseInt(e.slice(2),10);if(Fu(t.algorithm.hash)!==n)throw kt(`SHA-${n}`,"algorithm.hash");break}case"RS256":case"RS384":case"RS512":{if(!qa(t.algorithm,"RSASSA-PKCS1-v1_5"))throw kt("RSASSA-PKCS1-v1_5");let n=parseInt(e.slice(2),10);if(Fu(t.algorithm.hash)!==n)throw kt(`SHA-${n}`,"algorithm.hash");break}case"PS256":case"PS384":case"PS512":{if(!qa(t.algorithm,"RSA-PSS"))throw kt("RSA-PSS");let n=parseInt(e.slice(2),10);if(Fu(t.algorithm.hash)!==n)throw kt(`SHA-${n}`,"algorithm.hash");break}case"EdDSA":{if(t.algorithm.name!=="Ed25519"&&t.algorithm.name!=="Ed448")throw kt("Ed25519 or Ed448");break}case"ES256":case"ES384":case"ES512":{if(!qa(t.algorithm,"ECDSA"))throw kt("ECDSA");let n=uE(e);if(t.algorithm.namedCurve!==n)throw kt(n,"algorithm.namedCurve");break}default:throw new TypeError("CryptoKey does not support this operation")}fE(t,r)}function am(t,e,...r){var n;if(r=r.filter(Boolean),r.length>2){let s=r.pop();t+=`one of type ${r.join(", ")}, or ${s}.`}else r.length===2?t+=`one of type ${r[0]} or ${r[1]}.`:t+=`of type ${r[0]}.`;return e==null?t+=` Received ${e}`:typeof e=="function"&&e.name?t+=` Received function ${e.name}`:typeof e=="object"&&e!=null&&(n=e.constructor)!=null&&n.name&&(t+=` Received an instance of ${e.constructor.name}`),t}var qu=(t,...e)=>am("Key must be ",t,...e);function Uu(t,e,...r){return am(`Key for the ${t} algorithm must be `,e,...r)}var $u=t=>Da(t)?!0:(t==null?void 0:t[Symbol.toStringTag])==="KeyObject",gs=["CryptoKey"];var dE=(...t)=>{let e=t.filter(Boolean);if(e.length===0||e.length===1)return!0;let r;for(let n of e){let s=Object.keys(n);if(!r||r.size===0){r=new Set(s);continue}for(let o of s){if(r.has(o))return!1;r.add(o)}}return!0},lm=dE;function hE(t){return typeof t=="object"&&t!==null}function Bo(t){if(!hE(t)||Object.prototype.toString.call(t)!=="[object Object]")return!1;if(Object.getPrototypeOf(t)===null)return!0;let e=t;for(;Object.getPrototypeOf(e)!==null;)e=Object.getPrototypeOf(e);return Object.getPrototypeOf(t)===e}var cm=(t,e)=>{if(t.startsWith("RS")||t.startsWith("PS")){let{modulusLength:r}=e.algorithm;if(typeof r!="number"||r<2048)throw new TypeError(`${t} requires key modulusLength to be 2048 bits or larger`)}};function Vr(t){return Bo(t)&&typeof t.kty=="string"}function um(t){return t.kty!=="oct"&&typeof t.d=="string"}function fm(t){return t.kty!=="oct"&&typeof t.d=="undefined"}function dm(t){return Vr(t)&&t.kty==="oct"&&typeof t.k=="string"}function mE(t){let e,r;switch(t.kty){case"RSA":{switch(t.alg){case"PS256":case"PS384":case"PS512":e={name:"RSA-PSS",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RS256":case"RS384":case"RS512":e={name:"RSASSA-PKCS1-v1_5",hash:`SHA-${t.alg.slice(-3)}`},r=t.d?["sign"]:["verify"];break;case"RSA-OAEP":case"RSA-OAEP-256":case"RSA-OAEP-384":case"RSA-OAEP-512":e={name:"RSA-OAEP",hash:`SHA-${parseInt(t.alg.slice(-3),10)||1}`},r=t.d?["decrypt","unwrapKey"]:["encrypt","wrapKey"];break;default:throw new De('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"EC":{switch(t.alg){case"ES256":e={name:"ECDSA",namedCurve:"P-256"},r=t.d?["sign"]:["verify"];break;case"ES384":e={name:"ECDSA",namedCurve:"P-384"},r=t.d?["sign"]:["verify"];break;case"ES512":e={name:"ECDSA",namedCurve:"P-521"},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:"ECDH",namedCurve:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new De('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}case"OKP":{switch(t.alg){case"EdDSA":e={name:t.crv},r=t.d?["sign"]:["verify"];break;case"ECDH-ES":case"ECDH-ES+A128KW":case"ECDH-ES+A192KW":case"ECDH-ES+A256KW":e={name:t.crv},r=t.d?["deriveBits"]:[];break;default:throw new De('Invalid or unsupported JWK "alg" (Algorithm) Parameter value')}break}default:throw new De('Invalid or unsupported JWK "kty" (Key Type) Parameter value')}return{algorithm:e,keyUsages:r}}var gE=async t=>{var o,i;if(!t.alg)throw new TypeError('"alg" argument is required when "jwk.alg" is not present');let{algorithm:e,keyUsages:r}=mE(t),n=[e,(o=t.ext)!=null?o:!1,(i=t.key_ops)!=null?i:r],s={...t};return delete s.alg,delete s.use,ms.subtle.importKey("jwk",s,...n)},hm=gE;var pm=t=>Fa(t),ys,bs,mm=t=>(t==null?void 0:t[Symbol.toStringTag])==="KeyObject",Ua=async(t,e,r,n,s=!1)=>{let o=t.get(e);if(o!=null&&o[n])return o[n];let i=await hm({...r,alg:n});return s&&Object.freeze(e),o?o[n]=i:t.set(e,{[n]:i}),i},yE=(t,e)=>{if(mm(t)){let r=t.export({format:"jwk"});return delete r.d,delete r.dp,delete r.dq,delete r.p,delete r.q,delete r.qi,r.k?pm(r.k):(bs||(bs=new WeakMap),Ua(bs,t,r,e))}return Vr(t)?t.k?Fa(t.k):(bs||(bs=new WeakMap),Ua(bs,t,t,e,!0)):t},bE=(t,e)=>{if(mm(t)){let r=t.export({format:"jwk"});return r.k?pm(r.k):(ys||(ys=new WeakMap),Ua(ys,t,r,e))}return Vr(t)?t.k?Fa(t.k):(ys||(ys=new WeakMap),Ua(ys,t,t,e,!0)):t},Hu={normalizePublicKey:yE,normalizePrivateKey:bE};var ws=t=>t==null?void 0:t[Symbol.toStringTag],ju=(t,e,r)=>{var n,s;if(e.use!==void 0&&e.use!=="sig")throw new TypeError("Invalid key for this operation, when present its use must be sig");if(e.key_ops!==void 0&&((s=(n=e.key_ops).includes)==null?void 0:s.call(n,r))!==!0)throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${r}`);if(e.alg!==void 0&&e.alg!==t)throw new TypeError(`Invalid key for this operation, when present its alg must be ${t}`);return!0},wE=(t,e,r,n)=>{if(!(e instanceof Uint8Array)){if(n&&Vr(e)){if(dm(e)&&ju(t,e,r))return;throw new TypeError('JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present')}if(!$u(e))throw new TypeError(Uu(t,e,...gs,"Uint8Array",n?"JSON Web Key":null));if(e.type!=="secret")throw new TypeError(`${ws(e)} instances for symmetric algorithms must be of type "secret"`)}},_E=(t,e,r,n)=>{if(n&&Vr(e))switch(r){case"sign":if(um(e)&&ju(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a private JWK");case"verify":if(fm(e)&&ju(t,e,r))return;throw new TypeError("JSON Web Key for this operation be a public JWK")}if(!$u(e))throw new TypeError(Uu(t,e,...gs,n?"JSON Web Key":null));if(e.type==="secret")throw new TypeError(`${ws(e)} instances for asymmetric algorithms must not be of type "secret"`);if(r==="sign"&&e.type==="public")throw new TypeError(`${ws(e)} instances for asymmetric algorithm signing must be of type "private"`);if(r==="decrypt"&&e.type==="public")throw new TypeError(`${ws(e)} instances for asymmetric algorithm decryption must be of type "private"`);if(e.algorithm&&r==="verify"&&e.type==="private")throw new TypeError(`${ws(e)} instances for asymmetric algorithm verifying must be of type "public"`);if(e.algorithm&&r==="encrypt"&&e.type==="private")throw new TypeError(`${ws(e)} instances for asymmetric algorithm encryption must be of type "public"`)};function gm(t,e,r,n){e.startsWith("HS")||e==="dir"||e.startsWith("PBES2")||/^A\d{3}(?:GCM)?KW$/.test(e)?wE(e,r,n,t):_E(e,r,n,t)}var u3=gm.bind(void 0,!1),ym=gm.bind(void 0,!0);function SE(t,e,r,n,s){if(s.crit!==void 0&&(n==null?void 0:n.crit)===void 0)throw new t('"crit" (Critical) Header Parameter MUST be integrity protected');if(!n||n.crit===void 0)return new Set;if(!Array.isArray(n.crit)||n.crit.length===0||n.crit.some(i=>typeof i!="string"||i.length===0))throw new t('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');let o;r!==void 0?o=new Map([...Object.entries(r),...e.entries()]):o=e;for(let i of n.crit){if(!o.has(i))throw new De(`Extension Header Parameter "${i}" is not recognized`);if(s[i]===void 0)throw new t(`Extension Header Parameter "${i}" is missing`);if(o.get(i)&&n[i]===void 0)throw new t(`Extension Header Parameter "${i}" MUST be integrity protected`)}return new Set(n.crit)}var bm=SE;function Wu(t,e){let r=`SHA-${t.slice(-3)}`;switch(t){case"HS256":case"HS384":case"HS512":return{hash:r,name:"HMAC"};case"PS256":case"PS384":case"PS512":return{hash:r,name:"RSA-PSS",saltLength:t.slice(-3)>>3};case"RS256":case"RS384":case"RS512":return{hash:r,name:"RSASSA-PKCS1-v1_5"};case"ES256":case"ES384":case"ES512":return{hash:r,name:"ECDSA",namedCurve:e.namedCurve};case"EdDSA":return{name:e.name};default:throw new De(`alg ${t} is not supported either by JOSE or your javascript runtime`)}}async function Vu(t,e,r){if(r==="sign"&&(e=await Hu.normalizePrivateKey(e,t)),r==="verify"&&(e=await Hu.normalizePublicKey(e,t)),Da(e))return im(e,t,r),e;if(e instanceof Uint8Array){if(!t.startsWith("HS"))throw new TypeError(qu(e,...gs));return ms.subtle.importKey("raw",e,{hash:`SHA-${t.slice(-3)}`,name:"HMAC"},!1,[r])}throw new TypeError(qu(e,...gs,"Uint8Array","JSON Web Key"))}var ar=t=>Math.floor(t.getTime()/1e3);var EE=/^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i,$a=t=>{let e=EE.exec(t);if(!e||e[4]&&e[1])throw new TypeError("Invalid time period format");let r=parseFloat(e[2]),n=e[3].toLowerCase(),s;switch(n){case"sec":case"secs":case"second":case"seconds":case"s":s=Math.round(r);break;case"minute":case"minutes":case"min":case"mins":case"m":s=Math.round(r*60);break;case"hour":case"hours":case"hr":case"hrs":case"h":s=Math.round(r*3600);break;case"day":case"days":case"d":s=Math.round(r*86400);break;case"week":case"weeks":case"w":s=Math.round(r*604800);break;default:s=Math.round(r*31557600);break}return e[1]==="-"||e[4]==="ago"?-s:s};var xE=async(t,e,r)=>{let n=await Vu(t,e,"sign");cm(t,n);let s=await ms.subtle.sign(Wu(t,n.algorithm),n,r);return new Uint8Array(s)},wm=xE;var Ha=class{constructor(e){if(!(e instanceof Uint8Array))throw new TypeError("payload must be an instance of Uint8Array");this._payload=e}setProtectedHeader(e){if(this._protectedHeader)throw new TypeError("setProtectedHeader can only be called once");return this._protectedHeader=e,this}setUnprotectedHeader(e){if(this._unprotectedHeader)throw new TypeError("setUnprotectedHeader can only be called once");return this._unprotectedHeader=e,this}async sign(e,r){if(!this._protectedHeader&&!this._unprotectedHeader)throw new It("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");if(!lm(this._protectedHeader,this._unprotectedHeader))throw new It("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");let n={...this._protectedHeader,...this._unprotectedHeader},s=bm(It,new Map([["b64",!0]]),r==null?void 0:r.crit,this._protectedHeader,n),o=!0;if(s.has("b64")&&(o=this._protectedHeader.b64,typeof o!="boolean"))throw new It('The "b64" (base64url-encode payload) Header Parameter must be a boolean');let{alg:i}=n;if(typeof i!="string"||!i)throw new It('JWS "alg" (Algorithm) Header Parameter missing or invalid');ym(i,e,"sign");let a=this._payload;o&&(a=Tt.encode(Ba(a)));let c;this._protectedHeader?c=Tt.encode(Ba(JSON.stringify(this._protectedHeader))):c=Tt.encode("");let l=om(c,Tt.encode("."),a),f=await wm(i,e,l),u={signature:Ba(f),payload:""};return o&&(u.payload=No.decode(a)),this._unprotectedHeader&&(u.header=this._unprotectedHeader),this._protectedHeader&&(u.protected=No.decode(c)),u}};var ja=class{constructor(e){this._flattened=new Ha(e)}setProtectedHeader(e){return this._flattened.setProtectedHeader(e),this}async sign(e,r){let n=await this._flattened.sign(e,r);if(n.payload===void 0)throw new TypeError("use the flattened module for creating JWS with b64: false");return`${n.protected}.${n.payload}.${n.signature}`}};function Kr(t,e){if(!Number.isFinite(e))throw new TypeError(`Invalid ${t} input`);return e}var Wa=class{constructor(e={}){if(!Bo(e))throw new TypeError("JWT Claims Set MUST be an object");this._payload=e}setIssuer(e){return this._payload={...this._payload,iss:e},this}setSubject(e){return this._payload={...this._payload,sub:e},this}setAudience(e){return this._payload={...this._payload,aud:e},this}setJti(e){return this._payload={...this._payload,jti:e},this}setNotBefore(e){return typeof e=="number"?this._payload={...this._payload,nbf:Kr("setNotBefore",e)}:e instanceof Date?this._payload={...this._payload,nbf:Kr("setNotBefore",ar(e))}:this._payload={...this._payload,nbf:ar(new Date)+$a(e)},this}setExpirationTime(e){return typeof e=="number"?this._payload={...this._payload,exp:Kr("setExpirationTime",e)}:e instanceof Date?this._payload={...this._payload,exp:Kr("setExpirationTime",ar(e))}:this._payload={...this._payload,exp:ar(new Date)+$a(e)},this}setIssuedAt(e){return typeof e=="undefined"?this._payload={...this._payload,iat:ar(new Date)}:e instanceof Date?this._payload={...this._payload,iat:Kr("setIssuedAt",ar(e))}:typeof e=="string"?this._payload={...this._payload,iat:Kr("setIssuedAt",ar(new Date)+$a(e))}:this._payload={...this._payload,iat:Kr("setIssuedAt",e)},this}};var Fo=class extends Wa{setProtectedHeader(e){return this._protectedHeader=e,this}async sign(e,r){var s;let n=new ja(Tt.encode(JSON.stringify(this._payload)));if(n.setProtectedHeader(this._protectedHeader),Array.isArray((s=this._protectedHeader)==null?void 0:s.crit)&&this._protectedHeader.crit.includes("b64")&&this._protectedHeader.b64===!1)throw new Do("JWTs MUST NOT use unencoded payload");return n.sign(e,r)}};var vE=t=>async function*(e,r,n){var _,v;let{parameters:s,...o}=t,i={...o,...s},{apiKey:a,baseURL:c,model:l,token:f,tokenExpireInMinutes:u,enableWebSearch:d,...h}=i;if(!a)throw new Error(m("API key is required"));console.debug("zhipu options",{baseURL:c,apiKey:a,model:l,currentToken:f,tokenExpireInMinutes:u,enableWebSearch:d});let{token:p}=await PE(f,a,u);t.token=p;let y=new D({apiKey:p.id,baseURL:c,dangerouslyAllowBrowser:!0}),g=d?[{type:"web_search",web_search:{enable:!0}}]:[],S=await y.chat.completions.create({model:l,messages:e,stream:!0,tools:g,...h},{signal:r.signal});for await(let P of S){let E=(v=(_=P.choices[0])==null?void 0:_.delta)==null?void 0:v.content;E&&(yield E)}},CE=async(t,e)=>{let[r,n]=t.split(".");if(!r||!n)throw new Error('Invalid API key secret, must be in the format "apiKey.apiSecret"');let s=Date.now(),o={api_key:r,exp:s+e*60*1e3,timestamp:s};return{id:await new Fo({...o}).setProtectedHeader({alg:"HS256",sign_type:"SIGN"}).sign(new TextEncoder().encode(n)),exp:o.exp,apiKeySecret:t}},PE=async(t,e,r)=>{let n=Date.now();if(t&&t.apiKeySecret===e&&t.exp>n+180*1e3)return{isValid:!0,token:t};let s=await CE(e,r);return console.debug("create new token",s),{isValid:!1,token:s}},_m=["glm-4-plus","glm-4-air","glm-4-airx","glm-4-long","glm-4-flash","glm-4-flashx"],Sm={name:"Zhipu",defaultOptions:{apiKey:"",baseURL:"https://open.bigmodel.cn/api/paas/v4/",model:_m[0],tokenExpireInMinutes:1440,enableWebSearch:!1,parameters:{}},sendRequestFunc:vE,models:_m,websiteToObtainKey:"https://open.bigmodel.cn/",capabilities:["Text Generation","Web Search"]};var Be="Tars",pt={editorStatus:{isTextInserting:!1},providers:[],systemTags:["System","\u7CFB\u7EDF"],newChatTags:["NewChat","\u65B0\u5BF9\u8BDD"],userTags:["User","\u6211"],roleEmojis:{assistant:"\u2728",system:"\u{1F527}",newChat:"\u{1F680}",user:"\u{1F4AC}"},promptTemplates:[],enableInternalLink:!0,enableInternalLinkForAssistantMsg:!1,answerDelayInMilliseconds:2e3,confirmRegenerate:!0,enableTagSuggest:!0,tagSuggestMaxLineLength:20,enableExportToJSONL:!1,enableReplaceTag:!1,enableDefaultSystemMsg:!1,defaultSystemMsg:"",enableStreamLog:!1},qo=[em,nh,la,qh,Uh,ip,ma,Oa,Ma,La,rm,sm,Na,Sm];var xm=(t,e)=>async function*(r,n,s,o){let i=Date.now(),a=[];try{for await(let c of t(r,n,s,o)){let l=Date.now();a.push({text:c,time:l-i}),yield c}}finally{let c=r[r.length-1],l=/[<>:"/\\|?*\u0000-\u001F\u007F-\u009F]/g,f=c.content.slice(0,20).replace(l,"").trim()||"untitled",u=(0,Em.normalizePath)(`${Be}/${RE(new Date)}-${f}.json`),d={lastMsg:r[r.length-1].content.trim(),createdAt:new Date().toISOString(),texts:a};await e(u,JSON.stringify(d,null,2)),console.debug("Response logged to:",u)}},RE=t=>{let e=a=>a.toString().padStart(2,"0"),r=t.getFullYear().toString().slice(-2),n=e(t.getMonth()+1),s=e(t.getDate()),o=e(t.getHours()),i=e(t.getMinutes());return`${r}${n}${s}-${o}${i}`};var Am=["callout"],Ge=async(t,e)=>{var p,y;let r=t.workspace.getActiveFile();if(!r)throw new Error("No active file");let n=t.metadataCache,s=t.vault,o=await s.cachedRead(r),i=r.path,a=n.getFileCache(r);if(!a)throw new Error(m("Waiting for metadata to be ready. Please try again."));let c=((p=a.sections)==null?void 0:p.filter(g=>Am.includes(g.type)))||[],l=(a.tags||[]).filter(g=>!c.some(S=>S.position.start.offset<=g.position.start.offset&&g.position.end.offset<=S.position.end.offset)),f={newChatTags:e.newChatTags,userTags:e.userTags,assistantTags:e.providers.map(g=>g.tag),systemTags:e.systemTags,enableInternalLink:e.enableInternalLink,enableInternalLinkForAssistantMsg:e.enableInternalLinkForAssistantMsg,enableDefaultSystemMsg:e.enableDefaultSystemMsg,defaultSystemMsg:e.defaultSystemMsg,enableStreamLog:e.enableStreamLog},u=async(g,S)=>{let _=await t.fileManager.getAvailablePathForAttachment(g);await s.createBinary(_,S)},d=async g=>{let{path:S,subpath:_}=(0,Ot.parseLinktext)(g.link);console.debug("resolveEmbed path",S,"subpath",_);let v=n.getFirstLinkpathDest(S,i);if(v===null)throw new Error("LinkText broken: "+g.link.substring(0,20));return await s.readBinary(v)},h=async(g,S)=>{await s.create(g,S)};return{appMeta:n,vault:s,fileText:o,filePath:i,tags:l,sections:((y=a.sections)==null?void 0:y.filter(g=>!Am.includes(g.type)))||[],links:a.links,embeds:a.embeds,options:f,saveAttachment:u,resolveEmbed:d,createPlainText:h}},TE=async(t,e)=>{let{appMeta:r,vault:n,filePath:s}=t,{path:o,subpath:i}=(0,Ot.parseLinktext)(e);console.debug("path",o,"subpath",i);let a=r.getFirstLinkpathDest(o,s);if(a===null)throw new Error("LinkText broken: "+e.substring(0,20));let c=r.getFileCache(a);if(c===null)throw new Error(`No metadata found: ${o} ${i}`);let l=await n.cachedRead(a);if(i){let f=(0,Ot.resolveSubpath)(c,i);if(f===null)throw new Error(`no subpath data found: ${i}`);return l.substring(f.start.offset,f.end?f.end.offset:void 0)}else return l},vm=(t,e,r)=>{let{tags:n,sections:s,options:{userTags:o,assistantTags:i,systemTags:a}}=t,c=n.filter(u=>e<=u.position.start.offset&&u.position.end.offset<=r).map(u=>{let d=u.tag.slice(1).split("/")[0].toLowerCase(),h=o.some(p=>p.toLowerCase()===d)?"user":i.some(p=>p.toLowerCase()===d)?"assistant":a.some(p=>p.toLowerCase()===d)?"system":null;return h!=null?{tag:u.tag,role:h,lowerCaseTag:d,tagRange:[u.position.start.offset,u.position.end.offset],tagLine:u.position.start.line}:null}).filter(u=>u!==null);console.debug("roleMappedTags",c);let f=c.map((u,d)=>[u.tagRange[0],c[d+1]?c[d+1].tagRange[0]-1:r]).map((u,d)=>({...c[d],contentRange:[c[d].tagRange[1]+2,c[d+1]?c[d+1].tagRange[0]-1:r],sections:s.filter(h=>h.position.end.offset<=u[1]&&(h.position.start.offset<u[0]?h.position.end.offset>u[0]:!0)),line:[c[d].tagLine,c[d+1]?c[d+1].tagLine-1:1/0]}));return console.debug("taggedBlocks",f),f},IE=async(t,e,r,n)=>{let{fileText:s,links:o=[],embeds:i=[],options:{enableInternalLink:a,enableInternalLinkForAssistantMsg:c}}=t,l=e.position.start.offset<=r[0]?r[0]:e.position.start.offset,f=e.position.end.offset,u=o.map(_=>({ref:_,type:"link"})),d=i.map(_=>({ref:_,type:"embed"})),p=[...u,...d].sort((_,v)=>_.ref.position.start.offset-v.ref.position.start.offset).filter(_=>l<=_.ref.position.start.offset&&_.ref.position.end.offset<=f),y=n==="assistant"?c:a,S=(await Promise.all(p.map(async _=>{let v=_.ref;return _.type==="link"?{referCache:v,text:y?await TE(t,v.link):v.original}:{referCache:v,text:""}}))).reduce((_,{referCache:v,text:P})=>({endOffset:v.position.end.offset,text:_.text+s.slice(_.endOffset,v.position.start.offset)+P}),{endOffset:l,text:""});return console.debug("accumulatedText",S),{text:S.text+s.slice(S.endOffset,f),range:[l,f]}},Cm=async(t,e)=>{let r=await Promise.all(e.sections.map(s=>IE(t,s,e.contentRange,e.role)));return console.debug("textRanges",r),r.map(s=>s.text).join(`
`).trim()},kE=(t,e)=>{var r;return(r=t.embeds)==null?void 0:r.filter(n=>e[0]<=n.position.start.offset&&n.position.end.offset<=e[1])},OE=async(t,e,r)=>{let{tags:n,options:{newChatTags:s}}=t,o=n.findLast(l=>s.some(f=>l.tag.slice(1).split("/")[0].toLowerCase()===f.toLowerCase())&&e<=l.position.start.offset&&l.position.end.offset<=r),i=o?o.position.end.offset:e,a=vm(t,i,r);return await Promise.all(a.map(async l=>{let f={...l,content:await Cm(t,l)},u=kE(t,l.contentRange);return u&&u.length>0&&(f.embeds=u),f}))},ME=(0,Ot.debounce)(t=>{t.isTextInserting=!1},1e3,!0),LE=(t,e,r,n)=>{r.isTextInserting=!0;let s=t.getCursor("to");n!==null&&(n.line!==s.line||n.ch!==s.ch)&&(s=n);let o=t.getLine(s.line);o.length>s.ch&&(s={line:s.line,ch:o.length});let i=e.split(`
`),a={line:s.line+i.length-1,ch:i.length===1?s.ch+e.length:i[i.length-1].length};return t.replaceRange(e,s),t.setCursor(a),ME(r),a},Pm=async t=>{let{tags:e,options:{newChatTags:r}}=t,o=[0,...e.filter(c=>r.some(l=>c.tag.slice(1).split("/")[0].toLowerCase()===l.toLowerCase())).flatMap(c=>[c.position.start.offset-1,c.position.end.offset+1]),1/0],i=o.filter((c,l)=>l%2===0).map((c,l)=>({startOffset:c,endOffset:o[l*2+1]}));return console.debug("ranges",i),(await Promise.all(i.map(async c=>{let l=vm(t,c.startOffset,c.endOffset);return Promise.all(l.map(async u=>({...u,content:await Cm(t,u)})))}))).filter(c=>c.length>0)},Rm=(t,e)=>{let{tags:r,sections:n,options:{systemTags:s,userTags:o,assistantTags:i}}=t,a=[...s,...o,...i],c=r.filter(y=>a.some(g=>y.tag.slice(1).split("/")[0].toLowerCase()===g.toLowerCase()));console.debug("msgTagsInMeta",c);let l=c.findLastIndex(y=>y.position.start.line<=e);if(l<0)return[-1,-1];console.debug("msgTag",c[l]);let f=c[l].position.end.offset+2,u=l+1,d=u<c.length?c[u].position.start.offset:1/0;console.debug("nextTag",c[u]);let h=n.findLast(y=>y.position.end.offset<=d&&y.position.start.line>=e);if(!h)return[-1,-1];let p=h.position.end.offset;return console.debug("startOff",f,"endOffset",p),[f,p]},NE=t=>`${(t/1e3).toFixed(2)}s`,DE=async(t,e,r)=>t.options.enableStreamLog?(await t.vault.adapter.exists((0,Ot.normalizePath)(Be))||await t.vault.createFolder(Be),console.debug("Using stream logging"),xm(e.sendRequestFunc(r.options),t.createPlainText)):e.sendRequestFunc(r.options),Gr=async(t,e,r,n,s,o,i)=>{var a;try{let c=qo.find(R=>R.name===r.vendor);if(!c)throw new Error("No vendor found "+r.vendor);let f=(await OE(t,0,n)).map(R=>R.embeds?{role:R.role,content:R.content,embeds:R.embeds}:{role:R.role,content:R.content});console.debug("messages",f);let u=f.last();if(!u||u.role!=="user"||u.content.trim().length===0)throw new Error(m("Please add a user message first, or wait for the user message to be parsed."));t.options.enableDefaultSystemMsg&&((a=f[0])==null?void 0:a.role)!=="system"&&t.options.defaultSystemMsg&&(f.unshift({role:"system",content:t.options.defaultSystemMsg}),console.debug("Default system message added:",t.options.defaultSystemMsg));let d=f.filter(R=>R.role==="assistant").length+1,h=await DE(t,c,r),p=new Date;s.setGeneratingStatus(d);let y="",g=i.getController(),S=null,_=null;for await(let R of h(f,g,t.resolveEmbed,t.saveAttachment))_==null&&(_=e.getCursor("to")),S=LE(e,R,o,S),y+=R,s.updateGeneratingProgress(y.length);let v=new Date,P=NE(v.getTime()-p.getTime()),E={round:d,characters:y.length,duration:P,model:r.options.model,vendor:r.vendor,startTime:p,endTime:v};if(s.setSuccessStatus(E),y.length===0)throw new Error(m("No text generated"));if(console.debug("\u2728 "+m("AI generate")+" \u2728 ",y),_){let R=e.getCursor("to"),k=e.getRange(_,R),M=BE(y);k!==M&&(console.debug("format text with leading breaks"),e.replaceRange(M,_,R))}if(g.signal.aborted)throw new DOMException("Operation was aborted","AbortError")}finally{i.cleanup()}},BE=t=>{let e=t.split(`
`)[0];return e.startsWith("#")||e.startsWith("```")?`
`+t:e.startsWith("| ")?`
`+t:t};var lr=require("obsidian");var mt=t=>`#${t} : `,Uo=t=>`#${t} `,FE=(t,e,r=!1)=>r?`
#${e}`:t==="newChat"?Uo(e):mt(e),qE=[" "," "," :"," \uFF1A"],Tm=t=>{let e=Math.max(0,...t.newChatTags.map(n=>n.length)),r=Math.max(0,...t.systemTags.map(n=>n.length),...t.userTags.map(n=>n.length),...t.providers.map(n=>n.tag.length));return 4+(e+1)+(r+2)},UE=t=>{let e=[],r=/[^\s#::]+/g,n;for(let s=0;s<3&&(n=r.exec(t),!!n);s++)e.push(n[0]);return e},$E=(t,e)=>t.line>=1&&e.getLine(t.line-1).trim().length>0,Va=class extends lr.EditorSuggest{constructor(e,r,n,s,o){super(e),this.app=e,this.settings=r,this.tagLowerCaseMap=n,this.statusBarManager=s,this.requestController=o}onTrigger(e,r,n){if(this.settings.editorStatus.isTextInserting||e.ch<1||e.ch>this.settings.tagSuggestMaxLineLength)return null;let s=r.getLine(e.line);if(s.length>e.ch)return null;let o=UE(s);if(o.length===0||o.length>=3)return null;let i=this.tagLowerCaseMap.get(o[0].toLowerCase());if(!i)return null;let a;if(o.length===2&&(a=this.tagLowerCaseMap.get(o[1].toLowerCase()),!a||i.role!=="newChat"))return null;let c=a||i,l=o.length===2?o[1]:o[0],f=s.indexOf(l),u=s.slice(f+l.length);if(u){if(c.role==="newChat")return null;if(!qE.includes(u))return null}let d=$E(e,r);return{start:{line:e.line,ch:f>0&&s[f-1]==="#"?f-1:f},end:{line:e.line,ch:e.ch},query:JSON.stringify({...c,replacement:FE(c.role,c.tag,d)})}}async getSuggestions(e){return[JSON.parse(e.query)]}renderSuggestion(e,r){if(e.replacement.includes(`
`)){r.createSpan({text:e.replacement});return}let n=this.settings.roleEmojis.assistant;switch(e.role){case"assistant":{r.createSpan({text:`${e.replacement} ${n} ${m("AI generate")} ${n} `});break}case"user":{r.createSpan({text:`${e.replacement} ${this.settings.roleEmojis.user} `});break}case"system":{r.createSpan({text:`${e.replacement} ${this.settings.roleEmojis.system} `});break}case"newChat":{r.createSpan({text:`${e.replacement} ${this.settings.roleEmojis.newChat} `});break}default:r.createSpan({text:e.replacement})}}async selectSuggestion(e,r){if(!this.context)return;let n=this.context.editor;if(n.replaceRange(e.replacement,this.context.start,this.context.end),e.role!=="assistant"||e.replacement.includes(`
`)){this.close();return}console.debug("element",e);try{let s=this.settings.providers.find(a=>a.tag===e.tag);if(!s)throw new Error("No provider found "+e.tag);let o=await Ge(this.app,this.settings),i=n.posToOffset(this.context.start);console.debug("endOffset",i),await Gr(o,n,s,i,this.statusBarManager,this.settings.editorStatus,this.requestController),new lr.Notice(m("Text generated successfully"))}catch(s){if(console.error("error",s),s.name==="AbortError"){this.statusBarManager.setCancelledStatus(),new lr.Notice(m("Generation cancelled"));return}this.statusBarManager.setErrorStatus(s),new lr.Notice(`\u{1F534} ${lr.Platform.isDesktopApp?m("Click status bar for error details. "):""}${s}`,10*1e3)}this.close()}};var Ku=`
`,HE=t=>{let e=t.listSelections();if(e.length===0)throw new Error("No selection");if(e.length>1)throw new Error("Multiple selections");return e[0]},_s=(t,e,r)=>{let n=Gu(t,e);return jE(t,e,n,r)},Gu=(t,e)=>{let r=HE(e);console.debug("anchor",r.anchor),console.debug("head",r.head);let n=e.getCursor(),{sections:s}=km(t);if(!s)return console.debug("No sections"),{from:{line:n.line,ch:0},to:{line:n.line,ch:e.getLine(n.line).length}};let o=e.posToOffset(r.anchor),i=e.posToOffset(r.head),[a,c]=o<i?[o,i]:[i,o],l=s.filter(f=>a<=f.position.end.offset&&f.position.start.offset<=c);return l.length===0?(console.debug("No overlapping sections"),{from:{line:n.line,ch:0},to:{line:n.line,ch:e.getLine(n.line).length}}):{from:{line:l[0].position.start.line,ch:l[0].position.start.col},to:{line:l[l.length-1].position.end.line,ch:l[l.length-1].position.end.col}}},Ss=(t,e)=>{let{from:r,to:n}=e;return t.getRange(r,n).trim().length===0},Es=(t,e,r)=>{let n=e.line,s="";return e.line>0&&t.getLine(e.line-1).trim().length>0?(s=`
`+r,n+=1):s=r,t.replaceRange(s,e,e),t.setSelection({line:n,ch:t.getLine(n).length}),n},xs=(t,e,r)=>{let{from:n,to:s}=e,o="",i=s.line;n.line>0&&t.getLine(n.line-1).trim().length>0&&n.ch===0?(o=`
`+r,i+=1):o=r,t.replaceRange(o,n,n),t.setSelection({line:i,ch:t.getLine(i).length})},Ka=(t,e,r,n)=>{let{to:s}=e;r&&(t.replaceRange("#"+n,r.from,r.to),t.setSelection({line:s.line,ch:t.getLine(s.line).length}))},jE=(t,e,r,n)=>{let{tags:s}=km(t);if(!s)return{tagContent:null,role:null,range:r,tagRange:null};let{from:o,to:i}=r,a=s.find(c=>e.posToOffset(o)<=c.position.start.offset&&c.position.end.offset<=e.posToOffset(i));if(a){let c=n.userTags,l=n.providers.map(p=>p.tag),f=n.systemTags,u=n.newChatTags,d=a.tag.slice(1).split("/")[0].toLowerCase();if(u.some(p=>p.toLowerCase()===d)){let p=s.find(y=>a.position.end.offset<=y.position.start.offset&&y.position.end.offset<=e.posToOffset(i));return p?{tagContent:p.tag.slice(1),role:Im(p,{userTags:c,assistantTags:l,systemTags:f,newChatTags:u}),range:{from:e.offsetToPos(a.position.end.offset+1),to:r.to},tagRange:{from:e.offsetToPos(p.position.start.offset),to:e.offsetToPos(p.position.end.offset)}}:{tagContent:a.tag.slice(1),role:null,range:{from:e.offsetToPos(a.position.end.offset+1),to:r.to},tagRange:{from:e.offsetToPos(a.position.start.offset),to:e.offsetToPos(a.position.end.offset)}}}return{tagContent:a.tag.slice(1),role:Im(a,{userTags:c,assistantTags:l,systemTags:f,newChatTags:u}),range:r,tagRange:{from:e.offsetToPos(a.position.start.offset),to:e.offsetToPos(a.position.end.offset)}}}else return{tagContent:null,role:null,range:r,tagRange:null}},Im=(t,e)=>{let{userTags:r,assistantTags:n,systemTags:s,newChatTags:o}=e,i=t.tag.slice(1).split("/")[0].toLowerCase();return r.some(c=>c.toLowerCase()===i)?"user":n.some(c=>c.toLowerCase()===i)?"assistant":s.some(c=>c.toLowerCase()===i)?"system":o.some(c=>c.toLowerCase()===i)?"newChat":null},km=t=>{let e=t.workspace.getActiveFile();if(!e)throw new Error("No active file");let r=t.metadataCache.getFileCache(e);if(!r)throw new Error(m("Waiting for metadata to be ready. Please try again."));let n=r.tags;return{sections:r.sections,tags:n}},$o=(t,e)=>{let r=t.getCursor("to"),n=e.split(`
`),s={line:r.line+n.length-1,ch:n.length===1?r.ch+e.length:n[n.length-1].length};return t.replaceRange(e,r),t.setCursor(s),s.line};var zu=({id:t,name:e,tag:r},n,s,o,i)=>({id:t,name:e,editorCallback:async(a,c)=>{try{let l=s.providers.find(g=>g.tag===r);if(!l){new Je.Notice(`Assistant ${r} not found`);return}let f=mt(s.userTags[0]),u=mt(r),{range:d,role:h,tagContent:p,tagRange:y}=_s(n,a,s);if(console.debug("asstTagCmd",{range:d,role:h,tagContent:p,tagRange:y}),Ss(a,d)){let g=Es(a,d.from,u),S=a.posToOffset({line:g,ch:0}),_=await Ge(n,s);await Gr(_,a,l,S,o,s.editorStatus,i);return}if(h===null){xs(a,d,f),a.setCursor({line:d.to.line,ch:a.getLine(d.to.line).length}),$o(a,Ku+`
`);let g=await WE(a,u,s.answerDelayInMilliseconds),S=a.posToOffset({line:g,ch:0}),_=await Ge(n,s);await Gr(_,a,l,S,o,s.editorStatus,i)}else if(h==="assistant")if(s.confirmRegenerate){let g=async()=>{await Om(n,s,o,i,a,l,d,u)};new Ju(n,g).open()}else await Om(n,s,o,i,a,l,d,u);else{a.setCursor({line:d.to.line,ch:a.getLine(d.to.line).length});let g=$o(a,Ku+`
`+u),S=a.posToOffset({line:g,ch:0}),_=await Ge(n,s);await Gr(_,a,l,S,o,s.editorStatus,i),new Je.Notice(m("Text generated successfully"))}}catch(l){if(console.error(l),l.name==="AbortError"){o.setCancelledStatus(),new Je.Notice(m("Generation cancelled"));return}o.setErrorStatus(l),new Je.Notice(`\u{1F534} ${Je.Platform.isDesktopApp?m("Click status bar for error details. "):""}${l}`,10*1e3)}}}),Om=async(t,e,r,n,s,o,i,a)=>{s.replaceRange(a,i.from,i.to),s.setCursor({line:i.from.line,ch:s.getLine(i.from.line).length});let c=s.posToOffset({line:i.from.line,ch:0}),l=await Ge(t,e);await Gr(l,s,o,c,r,e.editorStatus,n)},Ju=class extends Je.Modal{constructor(e,r){super(e),this.onConfirm=r}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:m("Regenerate?")}),e.createEl("p",{text:m("This will delete the current response content. You can configure this in settings to not require confirmation.")}),new Je.Setting(e).addButton(r=>r.setButtonText(m("Yes")).setCta().onClick(async()=>{this.close(),await this.onConfirm()}))}},WE=async(t,e,r)=>{let n=e.length-2;if(n<=0)throw new Error("mark length must be greater than 2");let s=Math.round(r/n),o=$o(t,e[0]+e[1]);for(let i=2;i<e.length;i++)await new Promise(a=>setTimeout(a,s)),o=$o(t,e[i]);return o};var As=require("obsidian");var Ga="export-to-jsonl",Ho=(t,e)=>({id:Ga,name:m("Export conversations to JSONL"),callback:async()=>{await VE(t,e)}}),VE=async(t,e)=>{var f,u,d;let r=await Ge(t,e),n=await Pm(r);console.debug("conversations",n);let s=[];try{s=n.map(KE)}catch(h){console.error("error",h),new As.Notice(`\u{1F534}${m("Error")}: ${h}`,10*1e3);return}if(s.length===0){new As.Notice(m("No conversation found"));return}let o=s.map(h=>JSON.stringify(h)).join(`
`),i=(u=(f=t.workspace.getActiveFile())==null?void 0:f.parent)==null?void 0:u.path,a=(d=t.workspace.getActiveFile())==null?void 0:d.basename,c=(0,As.normalizePath)(`${i}/${a}.jsonl`),l=t.vault.getFileByPath(c);l?await t.vault.process(l,h=>o):await t.vault.create(c,o),new As.Notice(m("Exported to the same directory, Obsidian does not display the JSONL format. Please open with another software."),5*1e3)},KE=t=>{var c,l;let e=t.slice();if(e.length<2)throw new Error("No conversation");let r=null;((c=e.first())==null?void 0:c.role)==="system"&&(r=(l=e.shift())==null?void 0:l.content);let n=[];for(;e.length>0;){let f=e.shift(),u=e.shift();if((f==null?void 0:f.role)!=="user"||(u==null?void 0:u.role)!=="assistant")throw new Error("Invalid message role");if((f==null?void 0:f.content.trim().length)===0||(u==null?void 0:u.content.trim().length)===0)throw new Error("Empty message content");n.push([f.content,u.content])}let s=n.pop();if(!s)throw new Error("No conversation");let[o,i]=s,a={system:r,query:o,response:i,history:n.length>0?n:null};return Object.fromEntries(Object.entries(a).filter(([f,u])=>u!=null))};var Ja=require("obsidian");var Xu=({id:t,name:e,tag:r})=>({id:t,name:e,editorCallback:async(n,s)=>{try{let o=n.getCursor(),i=Uo(r);n.replaceRange(i,o),n.setCursor(o.line,o.ch+i.length)}catch(o){console.error(o),new Ja.Notice(`\u{1F534} ${Ja.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${o}`,10*1e3)}}});var Jr=require("obsidian");var za="replace-tag",jo=t=>({id:za,name:m("Replace speaker with tag"),callback:async()=>{let e=t.workspace.getActiveFile();if(!e)return;let r=await t.vault.cachedRead(e),n=zE(r);if(n.length<1){new Jr.Notice(m("No speaker found"));return}console.debug("twoMostFrequentSpeakers",n);let s=n.map(o=>({original:o.name,count:o.count,newTag:GE(o.name)}));new Yu(t,s,async o=>{await t.vault.process(e,i=>XE(i,o))}).open()}}),GE=t=>t.trim().startsWith("#")?t:"#"+t.trim().replace(/\s(?!:)/g,"-"),Yu=class extends Jr.Modal{constructor(e,r,n){super(e),this.recommendTags=r,this.onSubmit=n}onOpen(){let{contentEl:e}=this;e.createEl("h2",{text:m("Replace speaker with tag")}),e.createEl("p",{text:m("Replace the names of the two most frequently occurring speakers with tag format.")});for(let r of this.recommendTags)new Jr.Setting(e).setName(r.original+` (${r.count})`).addText(n=>n.setPlaceholder(r.newTag).setValue(r.newTag).onChange(async s=>{r.newTag=s}));new Jr.Setting(e).addButton(r=>r.setButtonText(m("Replace")).setCta().onClick(async()=>{this.close(),await this.onSubmit(this.recommendTags)}))}},JE=t=>t.reduce((e,r)=>(e[r]=(e[r]||0)+1,e),{}),zE=t=>{let r=t.split(`
`).map(a=>a.match(/^([\u4e00-\u9fa5a-zA-Z0-9# ]+)([:|:]) /g)).flatMap(a=>a||[]);console.debug("allMatches",r);let n=JE(r),s=Object.entries(n).sort((a,c)=>c[1]-a[1]);console.debug("sortedMatchFrequencies",s);let[o,i]=s.slice(0,2);return!o||!i?[]:[{name:o[0],count:o[1]},{name:i[0],count:i[1]}]},XE=(t,e)=>(e.forEach(({original:r,newTag:n})=>{t=t.replace(new RegExp(`^${r}`,"g"),`${n}`).replace(new RegExp(`
${r}`,"g"),`
${n}`)}),t);var Mm=require("obsidian");var Qu=(t,e)=>({id:"select-message-at-cursor",name:m("Select message at cursor"),editorCallback:async(r,n)=>{let s=await Ge(t,e),o=r.getCursor("to").line,[i,a]=Rm(s,o);if(i===-1||a===-1){new Mm.Notice(m("No message found at cursor"));return}r.setSelection(r.offsetToPos(i),r.offsetToPos(a))}});var Wo=require("obsidian");var Zu=({id:t,name:e,tag:r},n,s)=>({id:t,name:e,editorCallback:async(o,i)=>{try{let a=mt(r),{range:c,role:l,tagContent:f,tagRange:u}=_s(n,o,s);if(console.debug("systemTagCmd",{range:c,role:l,tagContent:f,tagRange:u}),Ss(o,c))return Es(o,c.from,a);if(l===null)return xs(o,c,a);if(l==="system"){if(r!==f&&u)return Ka(o,c,u,r)}else o.setSelection(c.from,c.to),new Wo.Notice(`${m("Conversion failed. Selected sections is a")} ${m(l)} ${m("message")}`)}catch(a){console.error(a),new Wo.Notice(`\u{1F534} ${Wo.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${a}`,10*1e3)}}});var Xa=(t,e)=>`${t}#${e}`,YE=t=>{let[e,r]=t.split("#");return{type:e,tag:r}},ef=t=>{let e=t.newChatTags.map(o=>Xa("newChat",o)),r=t.systemTags.map(o=>Xa("system",o)),n=t.userTags.map(o=>Xa("user",o)),s=t.providers.map(o=>Xa("assistant",o.tag));return[...e,...r,...n,...s]},zr=t=>{let{type:e,tag:r}=YE(t);return{id:t,name:QE(e,r),tag:r,role:e}},QE=(t,e)=>t==="newChat"?Uo(e):mt(e);var Vo=require("obsidian");var tf=({id:t,name:e,tag:r},n,s)=>({id:t,name:e,editorCallback:async(o,i)=>{try{let a=mt(r),{range:c,role:l,tagContent:f,tagRange:u}=_s(n,o,s);if(console.debug("userTagCmd",{range:c,role:l,tagContent:f,tagRange:u}),Ss(o,c))return Es(o,c.from,a);if(l===null)return xs(o,c,a);if(l==="user"){if(r!==f&&u)return Ka(o,c,u,r)}else o.setSelection(c.from,c.to),new Vo.Notice(`${m("Conversion failed. Selected sections is a")} ${m(l)} ${m("message")}`)}catch(a){console.error(a),new Vo.Notice(`\u{1F534} ${Vo.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${a}`,10*1e3)}}});var Ay=Oy(wy()),$e=require("obsidian");var _y=require("obsidian");var Il=class extends _y.Modal{constructor(e,r){super(e),this.reporter=r}onOpen(){let{contentEl:e}=this;e.createEl("h1",{text:m("Syntax Error Report")});let r=this.reporter.join(`
`);e.createEl("textarea",{text:r,cls:"syntax-error-textarea",attr:{readonly:!0,rows:5}})}onClose(){let{contentEl:e}=this;e.empty()}};var Sy=async(t,e)=>{let r=t.vault.getFileByPath(e);if(!r)throw new Error("No prompt file found. "+e);let s=t.metadataCache.getFileCache(r);if(!s)throw new Error(m("Waiting for metadata to be ready. Please try again."));console.debug("sections",s.sections);let o=s.sections;if(!o)throw new Error("No sections found. "+e);let i=s.headings;if(!i)throw new Error("No headings found. "+e);let a=await t.vault.cachedRead(r),c=o.reduce((d,h)=>{if(h.type==="thematicBreak")return[...d,[]];let p=d.length-1;return d[p]=[...d[p],h],d},[[]]).filter(d=>d.length>0);console.debug("sectionGroups",c);let l=c.slice(1);console.debug("slides",l);let f=[],u=[];for(let d of l)try{let h=U0(d,i,a);if(f.some(p=>p.title===h.title))throw new Error(`${m("Duplicate title:")} ${h.title}`);f.push(h)}catch(h){u.push(h.message)}return console.debug("promptTemplates",f),console.debug("reporter",u),{promptTemplates:f,reporter:u}},U0=(t,e,r)=>{if(t.length<2)throw new Error(`Line ${t[0].position.start.line+1}, ${m("Expected at least 2 sections, heading and content")}`);if(t[0].type!=="heading")throw new Error(`Line ${t[0].position.start.line+1} - ${t[0].position.end.line+1}, ${m("Expected heading")}`);let n=e.find(l=>l.position.start.line===t[0].position.start.line);if(!n)throw new Error(`Line ${t[0].position.start.line+1}, ${m("Expected heading")}`);let s=n.heading.trim();if(!s)throw new Error(`Line ${n.position.start.line+1}, ${m("Expected heading")}`);let o=t[1].position.start.offset,i=t[t.length-1].position.end.offset,c=r.slice(o,i).trim();return{title:s,template:c}},Ey=(t,e)=>{let r=[],n=new Map;return t.forEach(s=>{n.set(s.title,s.template)}),e.forEach(s=>{let o=n.get(s.title);o!==void 0&&o!==s.template&&r.push(s)}),r};var oi=t=>`Prompt#${t.title}`,zf=t=>t.slice(t.indexOf("#")+1),Xf=(t,e,r,n)=>({id:"LoadTemplateFile",name:m("Load template file: ")+`${Be}/${m("promptFileName")}.md`,callback:async()=>{try{let s=(0,$e.normalizePath)(`${Be}/${m("promptFileName")}.md`);await $0(t)&&(await xy(t,s),await new Promise(l=>setTimeout(l,2e3)));let{promptTemplates:i,reporter:a}=await Sy(t,s),c=Ey(e.promptTemplates,i);c.length>0&&(console.debug("changed",c),new $e.Notice(m("Templates have been updated: ")+c.map(l=>l.title).join(", "))),e.promptTemplates=i,await r(),n(),a&&a.length>0&&(await xy(t,s),new Il(t,a).open())}catch(s){console.error(s),new $e.Notice(`\u{1F534} ${$e.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${s}`,10*1e3)}}}),$0=async t=>{let e=!1;await t.vault.adapter.exists((0,$e.normalizePath)(Be))||await t.vault.createFolder(Be);let r=(0,$e.normalizePath)(`${Be}/${m("promptFileName")}.md`);return await t.vault.adapter.exists(r)||(await t.vault.create(r,m("PRESET_PROMPT_TEMPLATES")),new $e.Notice(m("Create prompt template file")+` ${Be}/${m("promptFileName")}.md`),e=!0),e},xy=async(t,e)=>{var r;((r=t.workspace.getActiveFile())==null?void 0:r.path)!=e&&await t.workspace.openLinkText("",e,!0)},Yf=(t,e,r,n)=>({id:t,name:e,editorCallback:async(s,o)=>{try{let i=n.promptTemplates.find(f=>f.title===e);if(!i)throw new Error(`No template found. ${i}`);let a=Gu(r,s),{from:c,to:l}=a;s.setSelection(c,l),await new Promise(f=>setTimeout(f,500)),j0(s,i.template)}catch(i){console.error(i),new $e.Notice(`\u{1F534} ${$e.Platform.isDesktopApp?m("Check the developer console for error details. "):""}${i}`,10*1e3)}}}),H0=t=>{let e=t.listSelections();if(e.length===0)throw new Error("No selection");if(e.length>1)throw new Error("Multiple selections");return e[0]},j0=(t,e)=>{let r=t.getSelection(),s=Ay.default.compile(e,{strict:!1,noEscape:!0})({s:r}),o=s.includes(r)?s:r+s,{anchor:i,head:a}=H0(t);t.replaceRange(o,i,a)};var L=require("obsidian");var Qf=require("obsidian");var kl=class extends Qf.FuzzySuggestModal{constructor(e,r,n){super(e),this.models=r,this.onChoose=n}getItems(){return this.models}getItemText(e){return e}renderSuggestion(e,r){let n=e.item,s=0,o=r.createEl("div");for(let i of e.match.matches){let a=n.slice(s,i[0]),c=n.slice(i[0],i[0]+i[1]);o.createEl("span",{text:a}),o.createEl("span",{text:c,cls:"fuzzy-match-highlight"}),s=i[0]+i[1]}o.createEl("span",{text:n.slice(s)})}onChooseItem(e,r){this.onChoose(e)}},Ol=class extends Qf.FuzzySuggestModal{constructor(e,r,n){super(e),this.vendors=r,this.onChoose=n}getItems(){return this.vendors}getItemText(e){return e.name}renderSuggestion(e,r){let n=e.item.name,s=0,o=r.createEl("div");for(let a of e.match.matches){let c=n.slice(s,a[0]),l=n.slice(a[0],a[0]+a[1]);o.createEl("span",{text:c}),o.createEl("span",{text:l,cls:"fuzzy-match-highlight"}),s=a[0]+a[1]}o.createEl("span",{text:n.slice(s)});let i=r.createEl("div",{cls:"capability-tags-container"});e.item.capabilities.forEach(a=>{i.createEl("span",{text:`${Hn(a)} ${m(a)}`,cls:"capability-tag"})})}onChooseItem(e,r){this.onChoose(e)}};var Ml=class extends L.PluginSettingTab{constructor(r,n){super(r,n);this.createProviderSetting=(r,n,s=!1)=>{let o=qo.find(f=>f.name===n.vendor);if(!o)throw new Error("No vendor found "+n.vendor);let{containerEl:i}=this,a=i.createEl("details");a.createEl("summary",{text:vy(n.tag,o.name),cls:"tars-setting-h4"}),a.open=s;let c=m("Supported features")+" : "+o.capabilities.map(f=>`${Hn(f)} ${m(f)}`).join(" ");this.addTagSection(a,n,r,o.name);let l=K0[o.name];l?new L.Setting(a).setName(m("Model")).setDesc(c).addButton(f=>{f.setButtonText(n.options.model?n.options.model:m("Select the model to use")).onClick(async()=>{if(l.requiresApiKey&&!n.options.apiKey){new L.Notice(m("Please input API key first"));return}try{let u=await V0(l.url,l.requiresApiKey?n.options.apiKey:void 0),d=async h=>{n.options.model=h,await this.plugin.saveSettings(),f.setButtonText(h)};new kl(this.app,u,d).open()}catch(u){if(u instanceof Error){let d=u.message.toLowerCase();d.includes("401")||d.includes("unauthorized")?new L.Notice("\u{1F511} "+m("API key may be incorrect. Please check your API key.")):d.includes("403")||d.includes("forbidden")?new L.Notice("\u{1F6AB} "+m("Access denied. Please check your API permissions.")):new L.Notice("\u{1F534} "+u.message)}else new L.Notice("\u{1F534} "+String(u))}})}):o.models.length>0?this.addModelDropDownSection(a,n.options,o.models,c):this.addModelTextSection(a,n.options,c),o.name!==Ma.name&&this.addAPIkeySection(a,n.options,o.websiteToObtainKey?m("Obtain key from ")+o.websiteToObtainKey:""),"apiSecret"in n.options&&this.addAPISecretOptional(a,n.options),o.capabilities.includes("Web Search")&&new L.Setting(a).setName(m("Web search")).setDesc(m("Enable web search for AI")).addToggle(f=>{var u;return f.setValue((u=n.options.enableWebSearch)!=null?u:!1).onChange(async d=>{n.options.enableWebSearch=d,await this.plugin.saveSettings()})}),o.name===la.name&&this.addClaudeSections(a,n.options),o.name===ma.name&&this.addGptImageSections(a,n.options),this.addBaseURLSection(a,n.options,o.defaultOptions.baseURL),"endpoint"in n.options&&this.addEndpointOptional(a,n.options),"apiVersion"in n.options&&this.addApiVersionOptional(a,n.options),this.addParametersSection(a,n.options),new L.Setting(a).setName(m("Remove")+" "+o.name).addButton(f=>{f.setWarning().setButtonText(m("Remove")).onClick(async()=>{this.plugin.settings.providers.splice(r,1),await this.plugin.saveSettings(),this.display()})})};this.addTagSection=(r,n,s,o)=>new L.Setting(r).setName("\u2728 "+m("Assistant message tag")).setDesc(m("Tag used to trigger AI text generation")).addText(i=>i.setPlaceholder(o).setValue(n.tag).onChange(async a=>{let c=a.trim();if(c.length===0||!Cy(c))return;if(this.plugin.settings.providers.filter((u,d)=>d!==s).map(u=>u.tag.toLowerCase()).includes(c.toLowerCase())){new L.Notice(m("Keyword for tag must be unique"));return}n.tag=c;let f=r.querySelector("summary");f!=null&&(f.textContent=vy(n.tag,o)),await this.plugin.saveSettings()}));this.addBaseURLSection=(r,n,s)=>{let o=null;new L.Setting(r).setName("baseURL").setDesc(m("Default:")+" "+s).addExtraButton(i=>{i.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{n.baseURL=s,await this.plugin.saveSettings(),o&&(o.value=s)})}).addText(i=>{o=i.inputEl,i.setValue(n.baseURL).onChange(async a=>{n.baseURL=a,await this.plugin.saveSettings()})})};this.addAPIkeySection=(r,n,s="")=>new L.Setting(r).setName("API key").setDesc(s).addText(o=>o.setPlaceholder(m("Enter your key")).setValue(n.apiKey).onChange(async i=>{n.apiKey=i,await this.plugin.saveSettings()}));this.addAPISecretOptional=(r,n,s="")=>new L.Setting(r).setName("API Secret").setDesc(s).addText(o=>o.setPlaceholder("").setValue(n.apiSecret).onChange(async i=>{n.apiSecret=i,await this.plugin.saveSettings()}));this.addModelDropDownSection=(r,n,s,o)=>new L.Setting(r).setName(m("Model")).setDesc(o).addDropdown(i=>i.addOptions(s.reduce((a,c)=>(a[c]=c,a),{})).setValue(n.model).onChange(async a=>{n.model=a,await this.plugin.saveSettings()}));this.addModelTextSection=(r,n,s)=>new L.Setting(r).setName(m("Model")).setDesc(s).addText(o=>o.setPlaceholder("").setValue(n.model).onChange(async i=>{n.model=i,await this.plugin.saveSettings()}));this.addClaudeSections=(r,n)=>{new L.Setting(r).setName(m("Thinking")).setDesc(m("When enabled, Claude will show its reasoning process before giving the final answer.")).addToggle(s=>{var o;return s.setValue((o=n.enableThinking)!=null?o:!1).onChange(async i=>{n.enableThinking=i,await this.plugin.saveSettings()})}),new L.Setting(r).setName(m("Budget tokens for thinking")).setDesc(m("Must be \u22651024 and less than max_tokens")).addText(s=>s.setPlaceholder("").setValue(n.budget_tokens?n.budget_tokens.toString():"1600").onChange(async o=>{let i=parseInt(o);if(isNaN(i)){new L.Notice(m("Please enter a number"));return}if(i<1024){new L.Notice(m("Minimum value is 1024"));return}n.budget_tokens=i,await this.plugin.saveSettings()})),new L.Setting(r).setName("Max tokens").setDesc(m("Refer to the technical documentation")).addText(s=>s.setPlaceholder("").setValue(n.max_tokens.toString()).onChange(async o=>{let i=parseInt(o);if(isNaN(i)){new L.Notice(m("Please enter a number"));return}if(i<256){new L.Notice(m("Minimum value is 256"));return}n.max_tokens=i,await this.plugin.saveSettings()}))};this.addEndpointOptional=(r,n)=>new L.Setting(r).setName(m("Endpoint")).setDesc("e.g. https://docs-test-001.openai.azure.com/").addText(s=>s.setPlaceholder("").setValue(n.endpoint).onChange(async o=>{let i=o.trim();if(i.length===0)n.endpoint="",await this.plugin.saveSettings();else if(W0(i))n.endpoint=i,await this.plugin.saveSettings();else{new L.Notice(m("Invalid URL"));return}}));this.addApiVersionOptional=(r,n)=>new L.Setting(r).setName(m("API version")).setDesc("e.g. 2024-xx-xx-preview").addText(s=>s.setPlaceholder("").setValue(n.apiVersion).onChange(async o=>{n.apiVersion=o,await this.plugin.saveSettings()}));this.addParametersSection=(r,n)=>new L.Setting(r).setName(m("Override input parameters")).setDesc(m(`Developer feature, in JSON format. For example, if the model list doesn't have the model you want, enter {"model": "your desired model"}`)).addTextArea(s=>s.setPlaceholder("{}").setValue(JSON.stringify(n.parameters)).onChange(async o=>{try{if(o.trim()===""){n.parameters={},await this.plugin.saveSettings();return}n.parameters=JSON.parse(o),await this.plugin.saveSettings()}catch(i){return}}));this.addGptImageSections=(r,n)=>{new L.Setting(r).setName(m("Image Display Width")).setDesc(m("Example: 400px width would output as ![[image.jpg|400]]")).addSlider(s=>s.setLimits(200,800,100).setValue(n.displayWidth).setDynamicTooltip().onChange(async o=>{n.displayWidth=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Number of images")).setDesc(m("Number of images to generate (1-5)")).addSlider(s=>s.setLimits(1,5,1).setValue(n.n).setDynamicTooltip().onChange(async o=>{n.n=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Image size")).addDropdown(s=>s.addOptions({auto:"Auto","1024x1024":"1024x1024","1536x1024":"1536x1024 "+m("landscape"),"1024x1536":"1024x1536 "+m("portrait")}).setValue(n.size).onChange(async o=>{n.size=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Output format")).addDropdown(s=>s.addOptions({png:"PNG",jpeg:"JPEG",webp:"WEBP"}).setValue(n.output_format).onChange(async o=>{n.output_format=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Quality")).setDesc(m("Quality level for generated images. default: Auto")).addDropdown(s=>s.addOptions({auto:m("Auto"),high:m("High"),medium:m("Medium"),low:m("Low")}).setValue(n.quality).onChange(async o=>{n.quality=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Background")).setDesc(m("Background of the generated image. default: Auto")).addDropdown(s=>s.addOptions({auto:m("Auto"),transparent:m("Transparent"),opaque:m("Opaque")}).setValue(n.background).onChange(async o=>{n.background=o,await this.plugin.saveSettings()})),new L.Setting(r).setName(m("Output compression")).setDesc(m("Compression level of the output image, 10% - 100%. Only for webp or jpeg output format")).addSlider(s=>s.setLimits(10,100,10).setValue(n.output_compression).setDynamicTooltip().onChange(async o=>{n.output_compression=o,await this.plugin.saveSettings()}))};this.plugin=n}hide(){this.plugin.buildTagCommands()}display(r=!1){let{containerEl:n}=this;n.empty(),new L.Setting(n).setName(m("AI assistants")).setHeading(),new L.Setting(n).setName(m("New AI assistant")).setDesc(m("For those compatible with the OpenAI protocol, you can select OpenAI.")).addButton(f=>{f.setButtonText(m("Add AI Provider")).onClick(async()=>{let u=async d=>{let h=d.name,y=this.plugin.settings.providers.map(S=>S.tag).includes(h)?"":h,g=JSON.parse(JSON.stringify(d.defaultOptions));this.plugin.settings.providers.push({tag:y,vendor:d.name,options:g}),await this.plugin.saveSettings(),this.display(!0)};new Ol(this.app,qo,u).open()})}),this.plugin.settings.providers.length||new L.Setting(n).setDesc(m("Please add at least one AI assistant to start using the plugin."));for(let[f,u]of this.plugin.settings.providers.entries()){let d=f===this.plugin.settings.providers.length-1;this.createProviderSetting(f,u,d&&r)}n.createEl("br"),new L.Setting(n).setName(m("Message tags")).setDesc(m("Keywords for tags in the text box are separated by spaces")).setHeading();let s=null;new L.Setting(n).setName(this.plugin.settings.roleEmojis.newChat+" "+m("New chat tags")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.newChatTags=pt.newChatTags,await this.plugin.saveSettings(),s&&(s.value=this.plugin.settings.newChatTags.join(" "))})}).addText(f=>{s=f.inputEl,f.setPlaceholder(pt.newChatTags.join(" ")).setValue(this.plugin.settings.newChatTags.join(" ")).onChange(async u=>{let d=u.split(" ").filter(h=>h.length>0);Zf(d)&&(this.plugin.settings.newChatTags=d,await this.plugin.saveSettings())})});let o=null;new L.Setting(n).setName(this.plugin.settings.roleEmojis.user+" "+m("User message tags")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.userTags=pt.userTags,await this.plugin.saveSettings(),o&&(o.value=this.plugin.settings.userTags.join(" "))})}).addText(f=>{o=f.inputEl,f.setPlaceholder(pt.userTags.join(" ")).setValue(this.plugin.settings.userTags.join(" ")).onChange(async u=>{let d=u.split(" ").filter(h=>h.length>0);Zf(d)&&(this.plugin.settings.userTags=d,await this.plugin.saveSettings())})});let i=null;new L.Setting(n).setName(this.plugin.settings.roleEmojis.system+" "+m("System message tags")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.systemTags=pt.systemTags,await this.plugin.saveSettings(),i&&(i.value=this.plugin.settings.systemTags.join(" "))})}).addText(f=>{i=f.inputEl,f.setPlaceholder(pt.systemTags.join(" ")).setValue(this.plugin.settings.systemTags.join(" ")).onChange(async u=>{let d=u.split(" ").filter(h=>h.length>0);Zf(d)&&(this.plugin.settings.systemTags=d,await this.plugin.saveSettings())})}),n.createEl("br"),new L.Setting(n).setName(m("System message")).setHeading();let a=null;new L.Setting(n).setName(m("Enable default system message")).setDesc(m("Automatically add a system message when none exists in the conversation")).addToggle(f=>f.setValue(this.plugin.settings.enableDefaultSystemMsg).onChange(async u=>{this.plugin.settings.enableDefaultSystemMsg=u,await this.plugin.saveSettings(),a&&(a.disabled=!u)})),new L.Setting(n).setName(m("Default system message")).addTextArea(f=>{a=f.inputEl,f.setDisabled(!this.plugin.settings.enableDefaultSystemMsg).setValue(this.plugin.settings.defaultSystemMsg).onChange(async u=>{this.plugin.settings.defaultSystemMsg=u.trim(),await this.plugin.saveSettings()})}),n.createEl("br"),new L.Setting(n).setName(m("Confirm before regeneration")).setDesc(m("Confirm before replacing existing assistant responses when using assistant commands")).addToggle(f=>f.setValue(this.plugin.settings.confirmRegenerate).onChange(async u=>{this.plugin.settings.confirmRegenerate=u,await this.plugin.saveSettings()})),new L.Setting(n).setName(m("Internal links")).setDesc(m("Internal links in user and system messages will be replaced with their referenced content. When disabled, only the original text of the links will be used.")).addToggle(f=>f.setValue(this.plugin.settings.enableInternalLink).onChange(async u=>{this.plugin.settings.enableInternalLink=u,await this.plugin.saveSettings()})),n.createEl("br");let c=n.createEl("details");c.createEl("summary",{text:m("Advanced"),cls:"tars-setting-h4"}),new L.Setting(c).setName(m("Internal links for assistant messages")).setDesc(m("Replace internal links in assistant messages with their referenced content. Note: This feature is generally not recommended as assistant-generated content may contain non-existent links.")).addToggle(f=>{var u;return f.setValue((u=this.plugin.settings.enableInternalLinkForAssistantMsg)!=null?u:!1).onChange(async d=>{this.plugin.settings.enableInternalLinkForAssistantMsg=d,await this.plugin.saveSettings()})});let l=null;new L.Setting(c).setName(m("Delay before answer (Seconds)")).setDesc(m("If you encounter errors with missing user messages when executing assistant commands on selected text, it may be due to the need for more time to parse the messages. Please slightly increase the delay time.")).addExtraButton(f=>{f.setIcon("reset").setTooltip(m("Restore default")).onClick(async()=>{this.plugin.settings.answerDelayInMilliseconds=pt.answerDelayInMilliseconds,await this.plugin.saveSettings(),l&&(l.value=(this.plugin.settings.answerDelayInMilliseconds/1e3).toString())})}).addSlider(f=>{l=f.sliderEl,f.setLimits(1.5,4,.5).setValue(this.plugin.settings.answerDelayInMilliseconds/1e3).setDynamicTooltip().onChange(async u=>{this.plugin.settings.answerDelayInMilliseconds=Math.round(u*1e3),await this.plugin.saveSettings()})}),new L.Setting(c).setName(m("Replace tag Command")).setDesc(m("Replace the names of the two most frequently occurring speakers with tag format.")).addToggle(f=>f.setValue(this.plugin.settings.enableReplaceTag).onChange(async u=>{this.plugin.settings.enableReplaceTag=u,await this.plugin.saveSettings(),u?this.plugin.addCommand(jo(this.app)):this.plugin.removeCommand(za)})),new L.Setting(c).setName(m("Export to JSONL Command")).setDesc(m("Export conversations to JSONL")).addToggle(f=>f.setValue(this.plugin.settings.enableExportToJSONL).onChange(async u=>{this.plugin.settings.enableExportToJSONL=u,await this.plugin.saveSettings(),u?this.plugin.addCommand(Ho(this.app,this.plugin.settings)):this.plugin.removeCommand(Ga)})),new L.Setting(c).setName(m("Tag suggest")).setDesc(m("If you only use commands without needing tag suggestions, you can disable this feature. Changes will take effect after restarting the plugin.")).addToggle(f=>f.setValue(this.plugin.settings.enableTagSuggest).onChange(async u=>{this.plugin.settings.enableTagSuggest=u,await this.plugin.saveSettings()}))}},vy=(t,e)=>t===e?e:t+" ("+e+")",Cy=t=>t.includes("#")?(new L.Notice(m("Keyword for tag must not contain #")),!1):t.includes(" ")?(new L.Notice(m("Keyword for tag must not contain space")),!1):!0,Zf=t=>{if(t.length===0)return new L.Notice(m("At least one tag is required")),!1;for(let e of t)if(!Cy(e))return!1;return!0},W0=t=>{try{return new URL(t),!0}catch(e){return!1}},V0=async(t,e)=>(await(0,L.requestUrl)({url:t,headers:{...e&&{Authorization:`Bearer ${e}`},"Content-Type":"application/json"}})).json.data.map(s=>s.id),K0={[Na.name]:{url:"https://api.siliconflow.cn/v1/models?type=text&sub_type=chat",requiresApiKey:!0},[La.name]:{url:"https://openrouter.ai/api/v1/models",requiresApiKey:!1},[Oa.name]:{url:"https://api.moonshot.cn/v1/models",requiresApiKey:!0}};var rn=require("obsidian");var ed=class extends rn.Modal{constructor(r,n){super(r);this.stats=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:m("AI Generation Details")});let n=r.createDiv({cls:"generation-stats"});n.createEl("p",{text:`${m("Round")}: ${this.stats.round}`}),n.createEl("p",{text:`${m("Model")}: ${this.stats.model}`}),n.createEl("p",{text:`${m("Vendor")}: ${this.stats.vendor}`}),n.createEl("p",{text:`${m("Characters")}: ${this.stats.characters}`}),n.createEl("p",{text:`${m("Duration")}: ${this.stats.duration}`}),n.createEl("p",{text:`${m("Start Time")}: ${this.stats.startTime.toLocaleTimeString()}`}),n.createEl("p",{text:`${m("End Time")}: ${this.stats.endTime.toLocaleTimeString()}`})}onClose(){let{contentEl:r}=this;r.empty()}},td=class extends rn.Modal{constructor(r,n){super(r);this.error=n}onOpen(){let{contentEl:r}=this;r.createEl("h2",{text:m("Error Details")});let n=r.createDiv({cls:"error-details"});if(n.createEl("p",{text:`${m("Error Type")}: ${this.error.name||m("Unknown Error")}`}),n.createEl("p",{text:`${m("Error Message")}: ${this.error.message}`}),n.createEl("p",{text:`${m("Occurrence Time")}: ${this.error.timestamp.toLocaleString()}`}),this.error.stack){let s=n.createDiv({cls:"stack-trace"});s.createEl("h3",{text:m("Stack Trace")});let o=s.createEl("pre",{cls:"stack-trace-pre"});o.textContent=this.error.stack}if(rn.Platform.isDesktopApp){let o=r.createDiv({cls:"error-modal-buttons"}).createEl("button",{text:m("Copy Error Info")});o.onclick=()=>{navigator.clipboard.writeText(JSON.stringify(this.error,null,2)),new rn.Notice(m("Error info copied to clipboard"))}}}onClose(){let{contentEl:r}=this;r.empty()}},Ll=class{constructor(e,r){this.app=e;this.statusBarItem=r;this.autoHideTimer=null;this.state={type:"idle",content:{text:"Tars",tooltip:m("Tars AI assistant is ready")},timestamp:new Date},this.setupClickHandler(),this.refreshStatusBar()}setupClickHandler(){this.statusBarItem.addEventListener("click",()=>{this.state.data&&(this.state.type==="error"?new td(this.app,this.state.data).open():this.state.type==="success"&&new ed(this.app,this.state.data).open())}),this.statusBarItem.style.cursor="pointer",this.statusBarItem.style.transition="opacity 0.2s ease"}updateState(e){this.state={...this.state,...e,timestamp:new Date},this.refreshStatusBar()}refreshStatusBar(){let{content:e}=this.state;this.statusBarItem.setText(e.text),this.statusBarItem.setAttribute("title",e.tooltip)}setGeneratingStatus(e){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"generating",content:{text:`Round ${e}...`,tooltip:`${m("Generating round")} ${e} ${m("answer...")}`},data:void 0})}updateGeneratingProgress(e){this.state.type==="generating"&&this.updateState({content:{text:`Tars: ${e}${m("characters")}`,tooltip:`${m("Generating...")} ${e} ${m("characters")}`}})}setSuccessStatus(e){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"success",content:{text:`Tars: ${e.characters}${m("characters")} ${e.duration}`,tooltip:`${m("Round")} ${e.round} | ${e.characters}${m("characters")} | ${e.duration} | ${e.model}`},data:e})}setErrorStatus(e){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null);let r={message:e.message,name:e.name,stack:e.stack,timestamp:new Date};this.updateState({type:"error",content:{text:`\u{1F534} Tars: ${m("Error")}`,tooltip:`${m("Error")}: ${e.message}`},data:r}),this.autoHideTimer=setTimeout(()=>this.clearStatus(),1e3*60*2)}setCancelledStatus(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"idle",content:{text:`\u26A0\uFE0F Tars: ${m("Generation cancelled")}`,tooltip:m("Generation cancelled")},data:void 0}),this.autoHideTimer=setTimeout(()=>this.clearStatus(),1e3*60*1)}clearStatus(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null),this.updateState({type:"idle",content:{text:"Tars",tooltip:m("Tars AI assistant is ready")},data:void 0})}getState(){return{...this.state}}dispose(){this.autoHideTimer&&(clearTimeout(this.autoHideTimer),this.autoHideTimer=null)}};var Nl=class extends Bt.Plugin{constructor(){super(...arguments);this.tagCmdIds=[];this.promptCmdIds=[];this.tagLowerCaseMap=new Map;this.aborterInstance=null}async onload(){await this.loadSettings(),console.debug("loading Tars plugin...");let r=this.addStatusBarItem();this.statusBarManager=new Ll(this.app,r),this.buildTagCommands(!0),this.buildPromptCommands(!0),this.addCommand(Qu(this.app,this.settings)),this.addCommand(Xf(this.app,this.settings,()=>this.saveSettings(),()=>this.buildPromptCommands())),this.settings.editorStatus={isTextInserting:!1},this.settings.enableTagSuggest&&this.registerEditorSuggest(new Va(this.app,this.settings,this.tagLowerCaseMap,this.statusBarManager,this.getRequestController())),this.addCommand({id:"cancelGeneration",name:m("Cancel generation"),callback:async()=>{if(this.settings.editorStatus.isTextInserting=!1,this.aborterInstance===null){new Bt.Notice(m("No active generation to cancel"));return}if(this.aborterInstance.signal.aborted){new Bt.Notice(m("Generation already cancelled"));return}this.aborterInstance.abort()}}),this.settings.enableReplaceTag&&this.addCommand(jo(this.app)),this.settings.enableExportToJSONL&&this.addCommand(Ho(this.app,this.settings)),this.addSettingTab(new Ml(this.app,this))}onunload(){var r;(r=this.statusBarManager)==null||r.dispose()}addTagCommand(r){let n=zr(r);switch(n.role){case"newChat":this.addCommand(Xu(n));break;case"system":this.addCommand(Zu(n,this.app,this.settings));break;case"user":this.addCommand(tf(n,this.app,this.settings));break;case"assistant":this.addCommand(zu(n,this.app,this.settings,this.statusBarManager,this.getRequestController()));break;default:throw new Error("Unknown tag role")}}buildTagCommands(r=!1){this.settings.tagSuggestMaxLineLength=Tm(this.settings);let n=ef(this.settings),s=this.tagCmdIds.filter(c=>!n.includes(c));s.forEach(c=>{this.removeCommand(c);let{tag:l}=zr(c);this.tagLowerCaseMap.delete(l.toLowerCase())});let o=n.filter(c=>!this.tagCmdIds.includes(c));if(o.forEach(c=>{this.addTagCommand(c);let{role:l,tag:f}=zr(c);this.tagLowerCaseMap.set(f.toLowerCase(),{role:l,tag:f})}),this.tagCmdIds=n,r)return;let i=s.map(c=>zr(c).tag);i.length>0&&(console.debug("Removed commands",i),new Bt.Notice(`${m("Removed commands")}: ${i.join(", ")}`));let a=o.map(c=>zr(c).tag);a.length>0&&(console.debug("Added commands",a),new Bt.Notice(`${m("Added commands")}: ${a.join(", ")}`))}buildPromptCommands(r=!1){let n=this.settings.promptTemplates.map(oi),s=this.promptCmdIds.filter(c=>!n.includes(c));s.forEach(c=>this.removeCommand(c));let o=this.settings.promptTemplates.filter(c=>!this.promptCmdIds.includes(oi(c)));if(o.forEach(c=>{this.addCommand(Yf(oi(c),c.title,this.app,this.settings))}),this.promptCmdIds=n,r)return;let i=s.map(c=>zf(c));i.length>0&&(console.debug("Removed commands",i),new Bt.Notice(`${m("Removed commands")}: ${i.join(", ")}`));let a=o.map(c=>c.title);a.length>0&&(console.debug("Added commands",a),new Bt.Notice(`${m("Added commands")}: ${a.join(", ")}`))}getRequestController(){return{getController:()=>(this.aborterInstance||(this.aborterInstance=new AbortController),this.aborterInstance),cleanup:()=>{this.settings.editorStatus.isTextInserting=!1,this.aborterInstance=null}}}async loadSettings(){this.settings=Object.assign({},pt,await this.loadData())}async saveSettings(){await this.saveData(this.settings)}};
/*! Bundled license information:
@google/generative-ai/dist/index.mjs:
@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.
*)
*/
/* nosourcemap */