vault backup: 2025-09-11 15:14:23
This commit is contained in:
1 parent
fdb964fa4f
commit
723acaffb6
15 files changed
+17567
-74
No files matched your search
Vendored
+198
@@ -0,0 +1,198 @@
|
||||
/*
|
||||
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={"&":"&","<":"<",">":">",'"':""","'":"'","`":"`","=":"="},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.callLine truncated
|
||||
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:
Line truncated
|
||||
`+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)Line truncated
|
||||
`])}),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
Line truncated
|
||||
|
||||
- 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":"\u52
Line truncated
|
||||
|
||||
- \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=="obje
Line truncated
|
||||
`):[]}};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 musLine truncated
|
||||
${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.contLine truncated
|
||||
\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_conte
Line truncated
|
||||
${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}/Line truncated
|
||||
|
||||
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-shou
Line truncated
|
||||
|
||||
> [!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":`broLine truncated
|
||||
`):[]}};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
Line truncated
|
||||
${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})Line truncated
|
||||
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"){l
Line truncated
|
||||
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.retryReque
Line truncated
|
||||
|
||||
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
Line truncated
|
||||
`+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){Line truncated
|
||||
`;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
Line truncated
|
||||
`).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 XMLH
Line truncated
|
||||
`+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,A
Line truncated
|
||||
`);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._bodyArrayBuffeLine truncated
|
||||
`)===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.fromEntrie
Line truncated
|
||||
`);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
Line truncated
|
||||
`);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
Line truncated
|
||||
|
||||
`).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);
Line truncated
|
||||
/*! 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 */
|
||||
Reference in new issue
Block a user