UNPKG

@thirdrocktechno/directus-extension-directusgpt

Version:

A DirectusGPT plugin for integrating AI-powered custom ChatBot with your Directus content.

1 lines 2.38 MB
"use strict";var n=require("http"),e=require("https"),a=require("url"),t=require("stream"),i=require("assert"),r=require("tty"),s=require("util"),o=require("os"),l=require("zlib"),c=require("path"),d=require("fs"),p=require("punycode"),u=require("events"),m=require("dns"),h=require("buffer"),g=require("http2"),f=require("tls"),v=require("net"),y=require("crypto");class b{}class w extends b{constructor(n){super(),Object.defineProperty(this,"alwaysVerbose",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreLLM",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreChain",{enumerable:!0,configurable:!0,writable:!0,value:!1}),Object.defineProperty(this,"ignoreAgent",{enumerable:!0,configurable:!0,writable:!0,value:!1}),n&&(this.alwaysVerbose=n.alwaysVerbose??this.alwaysVerbose,this.ignoreLLM=n.ignoreLLM??this.ignoreLLM,this.ignoreChain=n.ignoreChain??this.ignoreChain,this.ignoreAgent=n.ignoreAgent??this.ignoreAgent)}}class S extends w{setHandler(n){return this.setHandlers([n])}}class k extends S{constructor(){super(),Object.defineProperty(this,"handlers",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.handlers=[]}async handleLLMStart(n,e,a){await Promise.all(this.handlers.map((async t=>{if(!t.ignoreLLM&&(a||t.alwaysVerbose))try{await(t.handleLLMStart?.(n,e))}catch(n){console.error(`Error in handler ${t.constructor.name}, handleLLMStart: ${n}`)}})))}async handleLLMNewToken(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreLLM&&(e||a.alwaysVerbose))try{await(a.handleLLMNewToken?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleLLMNewToken: ${n}`)}})))}async handleLLMError(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreLLM&&(e||a.alwaysVerbose))try{await(a.handleLLMError?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleLLMError: ${n}`)}})))}async handleLLMEnd(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreLLM&&(e||a.alwaysVerbose))try{await(a.handleLLMEnd?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleLLMEnd: ${n}`)}})))}async handleChainStart(n,e,a){await Promise.all(this.handlers.map((async t=>{if(!t.ignoreChain&&(a||t.alwaysVerbose))try{await(t.handleChainStart?.(n,e))}catch(n){console.error(`Error in handler ${t.constructor.name}, handleChainStart: ${n}`)}})))}async handleChainError(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreChain&&(e||a.alwaysVerbose))try{await(a.handleChainError?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleChainError: ${n}`)}})))}async handleChainEnd(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreChain&&(e||a.alwaysVerbose))try{await(a.handleChainEnd?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleChainEnd: ${n}`)}})))}async handleToolStart(n,e,a){await Promise.all(this.handlers.map((async t=>{if(!t.ignoreAgent&&(a||t.alwaysVerbose))try{await(t.handleToolStart?.(n,e))}catch(n){console.error(`Error in handler ${t.constructor.name}, handleToolStart: ${n}`)}})))}async handleToolError(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreAgent&&(e||a.alwaysVerbose))try{await(a.handleToolError?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleToolError: ${n}`)}})))}async handleToolEnd(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreAgent&&(e||a.alwaysVerbose))try{await(a.handleToolEnd?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleToolEnd: ${n}`)}})))}async handleText(n,e){await Promise.all(this.handlers.map((async a=>{if(e||a.alwaysVerbose)try{await(a.handleText?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleText: ${n}`)}})))}async handleAgentAction(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreAgent&&(e||a.alwaysVerbose))try{await(a.handleAgentAction?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleAgentAction: ${n}`)}})))}async handleAgentEnd(n,e){await Promise.all(this.handlers.map((async a=>{if(!a.ignoreAgent&&(e||a.alwaysVerbose))try{await(a.handleAgentEnd?.(n))}catch(n){console.error(`Error in handler ${a.constructor.name}, handleAgentEnd: ${n}`)}})))}addHandler(n){this.handlers.push(n)}removeHandler(n){this.handlers=this.handlers.filter((e=>e!==n))}setHandlers(n){this.handlers=n}static fromHandlers(n){const e=new this;return e.addHandler(new class extends w{constructor(){super(),Object.defineProperty(this,"alwaysVerbose",{enumerable:!0,configurable:!0,writable:!0,value:!0}),Object.assign(this,n)}}),e}}class C extends w{async handleChainStart(n){console.log(`Entering new ${n.name} chain...`)}async handleChainEnd(n){console.log("Finished chain.")}async handleAgentAction(n){console.log(n.log)}async handleToolEnd(n){console.log(n)}async handleText(n){console.log(n)}async handleAgentEnd(n){console.log(n.log)}}class x extends w{constructor(){super(),Object.defineProperty(this,"session",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"stack",{enumerable:!0,configurable:!0,writable:!0,value:[]}),Object.defineProperty(this,"executionOrder",{enumerable:!0,configurable:!0,writable:!0,value:1}),this.alwaysVerbose=!0}async newSession(n){const e={start_time:Date.now(),name:n},a=await this.persistSession(e);return this.session=a,a}_addChildRun(n,e){if("llm"===e.type)n.child_llm_runs.push(e);else if("chain"===e.type)n.child_chain_runs.push(e);else{if("tool"!==e.type)throw new Error("Invalid run type");n.child_tool_runs.push(e)}}_startTrace(n){if(this.executionOrder+=1,this.stack.length>0){if("tool"!==this.stack.at(-1)?.type&&"chain"!==this.stack.at(-1)?.type)throw new Error("Nested run can only be logged for tool or chain");const e=this.stack.at(-1);this._addChildRun(e,n)}this.stack.push(n)}async _endTrace(){const n=this.stack.pop();0===this.stack.length&&n&&(this.executionOrder=1,await this.persistRun(n))}async handleLLMStart(n,e,a){void 0===this.session&&(this.session=await this.loadDefaultSession());const t={start_time:Date.now(),end_time:0,serialized:n,prompts:e,session_id:this.session.id,execution_order:this.executionOrder,type:"llm"};this._startTrace(t)}async handleLLMEnd(n,e){if(0===this.stack.length||"llm"!==this.stack.at(-1)?.type)throw new Error("No LLM run to end.");const a=this.stack.at(-1);a.end_time=Date.now(),a.response=n,await this._endTrace()}async handleLLMError(n,e){if(0===this.stack.length||"llm"!==this.stack.at(-1)?.type)throw new Error("No LLM run to end.");const a=this.stack.at(-1);a.end_time=Date.now(),a.error=n.message,await this._endTrace()}async handleChainStart(n,e,a){void 0===this.session&&(this.session=await this.loadDefaultSession());const t={start_time:Date.now(),end_time:0,serialized:n,inputs:e,session_id:this.session.id,execution_order:this.executionOrder,type:"chain",child_llm_runs:[],child_chain_runs:[],child_tool_runs:[]};this._startTrace(t)}async handleChainEnd(n,e){if(0===this.stack.length||"chain"!==this.stack.at(-1)?.type)throw new Error("No chain run to end.");const a=this.stack.at(-1);a.end_time=Date.now(),a.outputs=n,await this._endTrace()}async handleChainError(n,e){if(0===this.stack.length||"chain"!==this.stack.at(-1)?.type)throw new Error("No chain run to end.");const a=this.stack.at(-1);a.end_time=Date.now(),a.error=n.message,await this._endTrace()}async handleToolStart(n,e,a){void 0===this.session&&(this.session=await this.loadDefaultSession());const t={start_time:Date.now(),end_time:0,serialized:n,tool_input:e,session_id:this.session.id,execution_order:this.executionOrder,type:"tool",action:JSON.stringify(n),child_llm_runs:[],child_chain_runs:[],child_tool_runs:[]};this._startTrace(t)}async handleToolEnd(n,e){if(0===this.stack.length||"tool"!==this.stack.at(-1)?.type)throw new Error("No tool run to end");const a=this.stack.at(-1);a.end_time=Date.now(),a.output=n,await this._endTrace()}async handleToolError(n,e){if(0===this.stack.length||"tool"!==this.stack.at(-1)?.type)throw new Error("No tool run to end.");const a=this.stack.at(-1);a.end_time=Date.now(),a.error=n.message,await this._endTrace()}}class A extends x{constructor(){super(),Object.defineProperty(this,"endpoint",{enumerable:!0,configurable:!0,writable:!0,value:("undefined"!=typeof process?process.env.LANGCHAIN_ENDPOINT:void 0)||"http://localhost:8000"}),Object.defineProperty(this,"headers",{enumerable:!0,configurable:!0,writable:!0,value:{"Content-Type":"application/json"}}),"undefined"!=typeof process&&process.env.LANGCHAIN_API_KEY&&(this.headers["x-api-key"]=process.env.LANGCHAIN_API_KEY)}async persistRun(n){let e;e="llm"===n.type?`${this.endpoint}/llm-runs`:"chain"===n.type?`${this.endpoint}/chain-runs`:`${this.endpoint}/tool-runs`;const a=await fetch(e,{method:"POST",headers:this.headers,body:JSON.stringify(n)});a.ok||console.error(`Failed to persist run: ${a.status} ${a.statusText}`)}async persistSession(n){const e=`${this.endpoint}/sessions`,a=await fetch(e,{method:"POST",headers:this.headers,body:JSON.stringify(n)});return a.ok?{id:(await a.json()).id,...n}:(console.error(`Failed to persist session: ${a.status} ${a.statusText}, using default session.`),{id:1,...n})}async loadSession(n){const e=`${this.endpoint}/sessions?name=${n}`;return this._handleSessionResponse(e)}async loadDefaultSession(){const n=`${this.endpoint}/sessions?name=default`;return this._handleSessionResponse(n)}async _handleSessionResponse(n){const e=await fetch(n,{method:"GET",headers:this.headers});let a;if(!e.ok)return console.error(`Failed to load session: ${e.status} ${e.statusText}`),a={id:1,start_time:Date.now()},this.session=a,a;const t=await e.json();return 0===t.length?(a={id:1,start_time:Date.now()},this.session=a,a):([a]=t,this.session=a,a)}}class D extends k{constructor(){super()}static getInstance(){return D.instance||(D.instance=new D,D.instance.addHandler(new C),"undefined"!=typeof process&&"langchain"===process.env.LANGCHAIN_HANDLER&&D.instance.addHandler(new A)),D.instance}}class E{constructor(n){Object.defineProperty(this,"text",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"name",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.text=n}}class _ extends E{_getType(){return"human"}}class T extends E{_getType(){return"ai"}}class R extends E{_getType(){return"system"}}class P extends E{constructor(n,e){super(n),Object.defineProperty(this,"role",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.role=e}_getType(){return"generic"}}var O="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function M(n){return n&&n.__esModule&&Object.prototype.hasOwnProperty.call(n,"default")?n.default:n}function B(n){if(n.__esModule)return n;var e=n.default;if("function"==typeof e){var a=function n(){if(this instanceof n){var a=[null];return a.push.apply(a,arguments),new(Function.bind.apply(e,a))}return e.apply(this,arguments)};a.prototype=e.prototype}else a={};return Object.defineProperty(a,"__esModule",{value:!0}),Object.keys(n).forEach((function(e){var t=Object.getOwnPropertyDescriptor(n,e);Object.defineProperty(a,e,t.get?t:{enumerable:!0,get:function(){return n[e]}})})),a}var F={},N={},I=O&&O.__assign||function(){return I=Object.assign||function(n){for(var e,a=1,t=arguments.length;a<t;a++)for(var i in e=arguments[a])Object.prototype.hasOwnProperty.call(e,i)&&(n[i]=e[i]);return n},I.apply(this,arguments)};Object.defineProperty(N,"__esModule",{value:!0});var L={delayFirstAttempt:!1,jitter:"none",maxDelay:1/0,numOfAttempts:10,retry:function(){return!0},startingDelay:100,timeMultiple:2};N.getSanitizedOptions=function(n){var e=I(I({},L),n);return e.numOfAttempts<1&&(e.numOfAttempts=1),e};var j={},H={},G={},z={},q={};Object.defineProperty(q,"__esModule",{value:!0}),q.fullJitter=function(n){var e=Math.random()*n;return Math.round(e)};var U={};Object.defineProperty(U,"__esModule",{value:!0}),U.noJitter=function(n){return n},Object.defineProperty(z,"__esModule",{value:!0});var V=q,W=U;z.JitterFactory=function(n){return"full"===n.jitter?V.fullJitter:W.noJitter},Object.defineProperty(G,"__esModule",{value:!0});var K=z,J=function(){function n(n){this.options=n,this.attempt=0}return n.prototype.apply=function(){var n=this;return new Promise((function(e){return setTimeout(e,n.jitteredDelay)}))},n.prototype.setAttemptNumber=function(n){this.attempt=n},Object.defineProperty(n.prototype,"jitteredDelay",{get:function(){return K.JitterFactory(this.options)(this.delay)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"delay",{get:function(){var n=this.options.startingDelay,e=this.options.timeMultiple,a=this.numOfDelayedAttempts,t=n*Math.pow(e,a);return Math.min(t,this.options.maxDelay)},enumerable:!0,configurable:!0}),Object.defineProperty(n.prototype,"numOfDelayedAttempts",{get:function(){return this.attempt},enumerable:!0,configurable:!0}),n}();G.Delay=J;var $,Y=O&&O.__extends||($=function(n,e){return $=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,e){n.__proto__=e}||function(n,e){for(var a in e)e.hasOwnProperty(a)&&(n[a]=e[a])},$(n,e)},function(n,e){function a(){this.constructor=n}$(n,e),n.prototype=null===e?Object.create(e):(a.prototype=e.prototype,new a)}),Q=O&&O.__awaiter||function(n,e,a,t){return new(a||(a=Promise))((function(i,r){function s(n){try{l(t.next(n))}catch(n){r(n)}}function o(n){try{l(t.throw(n))}catch(n){r(n)}}function l(n){var e;n.done?i(n.value):(e=n.value,e instanceof a?e:new a((function(n){n(e)}))).then(s,o)}l((t=t.apply(n,e||[])).next())}))},X=O&&O.__generator||function(n,e){var a,t,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function o(r){return function(o){return function(r){if(a)throw new TypeError("Generator is already executing.");for(;s;)try{if(a=1,t&&(i=2&r[0]?t.return:r[0]?t.throw||((i=t.return)&&i.call(t),0):t.next)&&!(i=i.call(t,r[1])).done)return i;switch(t=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,t=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=e.call(n,s)}catch(n){r=[6,n],t=0}finally{a=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,o])}}};Object.defineProperty(H,"__esModule",{value:!0});var Z=function(n){function e(){return null!==n&&n.apply(this,arguments)||this}return Y(e,n),e.prototype.apply=function(){return Q(this,void 0,void 0,(function(){return X(this,(function(e){return[2,!!this.isFirstAttempt||n.prototype.apply.call(this)]}))}))},Object.defineProperty(e.prototype,"isFirstAttempt",{get:function(){return 0===this.attempt},enumerable:!0,configurable:!0}),Object.defineProperty(e.prototype,"numOfDelayedAttempts",{get:function(){return this.attempt-1},enumerable:!0,configurable:!0}),e}(G.Delay);H.SkipFirstDelay=Z;var nn={},en=O&&O.__extends||function(){var n=function(e,a){return n=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(n,e){n.__proto__=e}||function(n,e){for(var a in e)e.hasOwnProperty(a)&&(n[a]=e[a])},n(e,a)};return function(e,a){function t(){this.constructor=e}n(e,a),e.prototype=null===a?Object.create(a):(t.prototype=a.prototype,new t)}}();Object.defineProperty(nn,"__esModule",{value:!0});var an=function(n){function e(){return null!==n&&n.apply(this,arguments)||this}return en(e,n),e}(G.Delay);nn.AlwaysDelay=an,Object.defineProperty(j,"__esModule",{value:!0});var tn=H,rn=nn;j.DelayFactory=function(n,e){var a=function(n){if(!n.delayFirstAttempt)return new tn.SkipFirstDelay(n);return new rn.AlwaysDelay(n)}(n);return a.setAttemptNumber(e),a};var sn=O&&O.__awaiter||function(n,e,a,t){return new(a||(a=Promise))((function(i,r){function s(n){try{l(t.next(n))}catch(n){r(n)}}function o(n){try{l(t.throw(n))}catch(n){r(n)}}function l(n){var e;n.done?i(n.value):(e=n.value,e instanceof a?e:new a((function(n){n(e)}))).then(s,o)}l((t=t.apply(n,e||[])).next())}))},on=O&&O.__generator||function(n,e){var a,t,i,r,s={label:0,sent:function(){if(1&i[0])throw i[1];return i[1]},trys:[],ops:[]};return r={next:o(0),throw:o(1),return:o(2)},"function"==typeof Symbol&&(r[Symbol.iterator]=function(){return this}),r;function o(r){return function(o){return function(r){if(a)throw new TypeError("Generator is already executing.");for(;s;)try{if(a=1,t&&(i=2&r[0]?t.return:r[0]?t.throw||((i=t.return)&&i.call(t),0):t.next)&&!(i=i.call(t,r[1])).done)return i;switch(t=0,i&&(r=[2&r[0],i.value]),r[0]){case 0:case 1:i=r;break;case 4:return s.label++,{value:r[1],done:!1};case 5:s.label++,t=r[1],r=[0];continue;case 7:r=s.ops.pop(),s.trys.pop();continue;default:if(!(i=s.trys,(i=i.length>0&&i[i.length-1])||6!==r[0]&&2!==r[0])){s=0;continue}if(3===r[0]&&(!i||r[1]>i[0]&&r[1]<i[3])){s.label=r[1];break}if(6===r[0]&&s.label<i[1]){s.label=i[1],i=r;break}if(i&&s.label<i[2]){s.label=i[2],s.ops.push(r);break}i[2]&&s.ops.pop(),s.trys.pop();continue}r=e.call(n,s)}catch(n){r=[6,n],t=0}finally{a=i=0}if(5&r[0])throw r[1];return{value:r[0]?r[1]:void 0,done:!0}}([r,o])}}};Object.defineProperty(F,"__esModule",{value:!0});var ln=N,cn=j;var dn=F.backOff=function(n,e){return void 0===e&&(e={}),sn(this,void 0,void 0,(function(){var a;return on(this,(function(t){switch(t.label){case 0:return a=ln.getSanitizedOptions(e),[4,new pn(n,a).execute()];case 1:return[2,t.sent()]}}))}))},pn=function(){function n(n,e){this.request=n,this.options=e,this.attemptNumber=0}return n.prototype.execute=function(){return sn(this,void 0,void 0,(function(){var n;return on(this,(function(e){switch(e.label){case 0:if(this.attemptLimitReached)return[3,7];e.label=1;case 1:return e.trys.push([1,4,,6]),[4,this.applyDelay()];case 2:return e.sent(),[4,this.request()];case 3:return[2,e.sent()];case 4:return n=e.sent(),this.attemptNumber++,[4,this.options.retry(n,this.attemptNumber)];case 5:if(!e.sent()||this.attemptLimitReached)throw n;return[3,6];case 6:return[3,0];case 7:throw new Error("Something went wrong.")}}))}))},Object.defineProperty(n.prototype,"attemptLimitReached",{get:function(){return this.attemptNumber>=this.options.numOfAttempts},enumerable:!0,configurable:!0}),n.prototype.applyDelay=function(){return sn(this,void 0,void 0,(function(){return on(this,(function(n){switch(n.label){case 0:return[4,cn.DelayFactory(this.options,this.attemptNumber).apply()];case 1:return n.sent(),[2]}}))}))},n}(),un={},mn={exports:{}};!function(n){var e=Object.prototype.hasOwnProperty,a="~";function t(){}function i(n,e,a){this.fn=n,this.context=e,this.once=a||!1}function r(n,e,t,r,s){if("function"!=typeof t)throw new TypeError("The listener must be a function");var o=new i(t,r||n,s),l=a?a+e:e;return n._events[l]?n._events[l].fn?n._events[l]=[n._events[l],o]:n._events[l].push(o):(n._events[l]=o,n._eventsCount++),n}function s(n,e){0==--n._eventsCount?n._events=new t:delete n._events[e]}function o(){this._events=new t,this._eventsCount=0}Object.create&&(t.prototype=Object.create(null),(new t).__proto__||(a=!1)),o.prototype.eventNames=function(){var n,t,i=[];if(0===this._eventsCount)return i;for(t in n=this._events)e.call(n,t)&&i.push(a?t.slice(1):t);return Object.getOwnPropertySymbols?i.concat(Object.getOwnPropertySymbols(n)):i},o.prototype.listeners=function(n){var e=a?a+n:n,t=this._events[e];if(!t)return[];if(t.fn)return[t.fn];for(var i=0,r=t.length,s=new Array(r);i<r;i++)s[i]=t[i].fn;return s},o.prototype.listenerCount=function(n){var e=a?a+n:n,t=this._events[e];return t?t.fn?1:t.length:0},o.prototype.emit=function(n,e,t,i,r,s){var o=a?a+n:n;if(!this._events[o])return!1;var l,c,d=this._events[o],p=arguments.length;if(d.fn){switch(d.once&&this.removeListener(n,d.fn,void 0,!0),p){case 1:return d.fn.call(d.context),!0;case 2:return d.fn.call(d.context,e),!0;case 3:return d.fn.call(d.context,e,t),!0;case 4:return d.fn.call(d.context,e,t,i),!0;case 5:return d.fn.call(d.context,e,t,i,r),!0;case 6:return d.fn.call(d.context,e,t,i,r,s),!0}for(c=1,l=new Array(p-1);c<p;c++)l[c-1]=arguments[c];d.fn.apply(d.context,l)}else{var u,m=d.length;for(c=0;c<m;c++)switch(d[c].once&&this.removeListener(n,d[c].fn,void 0,!0),p){case 1:d[c].fn.call(d[c].context);break;case 2:d[c].fn.call(d[c].context,e);break;case 3:d[c].fn.call(d[c].context,e,t);break;case 4:d[c].fn.call(d[c].context,e,t,i);break;default:if(!l)for(u=1,l=new Array(p-1);u<p;u++)l[u-1]=arguments[u];d[c].fn.apply(d[c].context,l)}}return!0},o.prototype.on=function(n,e,a){return r(this,n,e,a,!1)},o.prototype.once=function(n,e,a){return r(this,n,e,a,!0)},o.prototype.removeListener=function(n,e,t,i){var r=a?a+n:n;if(!this._events[r])return this;if(!e)return s(this,r),this;var o=this._events[r];if(o.fn)o.fn!==e||i&&!o.once||t&&o.context!==t||s(this,r);else{for(var l=0,c=[],d=o.length;l<d;l++)(o[l].fn!==e||i&&!o[l].once||t&&o[l].context!==t)&&c.push(o[l]);c.length?this._events[r]=1===c.length?c[0]:c:s(this,r)}return this},o.prototype.removeAllListeners=function(n){var e;return n?(e=a?a+n:n,this._events[e]&&s(this,e)):(this._events=new t,this._eventsCount=0),this},o.prototype.off=o.prototype.removeListener,o.prototype.addListener=o.prototype.on,o.prefixed=a,o.EventEmitter=o,n.exports=o}(mn);var hn=mn.exports,gn={exports:{}};const fn=(n,e)=>(e=e||(()=>{}),n.then((n=>new Promise((n=>{n(e())})).then((()=>n))),(n=>new Promise((n=>{n(e())})).then((()=>{throw n})))));class vn extends Error{constructor(n){super(n),this.name="TimeoutError"}}const yn=(n,e,a)=>new Promise(((t,i)=>{if("number"!=typeof e||e<0)throw new TypeError("Expected `milliseconds` to be a positive number");if(e===1/0)return void t(n);const r=setTimeout((()=>{if("function"==typeof a){try{t(a())}catch(n){i(n)}return}const r=a instanceof Error?a:new vn("string"==typeof a?a:`Promise timed out after ${e} milliseconds`);"function"==typeof n.cancel&&n.cancel(),i(r)}),e);fn(n.then(t,i),(()=>{clearTimeout(r)}))}));gn.exports=yn,gn.exports.default=yn,gn.exports.TimeoutError=vn;var bn=gn.exports,wn={},Sn={};Object.defineProperty(Sn,"__esModule",{value:!0}),Sn.default=function(n,e,a){let t=0,i=n.length;for(;i>0;){const r=i/2|0;let s=t+r;a(n[s],e)<=0?(t=++s,i-=r+1):i=r}return t},Object.defineProperty(wn,"__esModule",{value:!0});const kn=Sn;wn.default=class{constructor(){this._queue=[]}enqueue(n,e){const a={priority:(e=Object.assign({priority:0},e)).priority,run:n};if(this.size&&this._queue[this.size-1].priority>=e.priority)return void this._queue.push(a);const t=kn.default(this._queue,a,((n,e)=>e.priority-n.priority));this._queue.splice(t,0,a)}dequeue(){const n=this._queue.shift();return null==n?void 0:n.run}filter(n){return this._queue.filter((e=>e.priority===n.priority)).map((n=>n.run))}get size(){return this._queue.length}},Object.defineProperty(un,"__esModule",{value:!0});const Cn=hn,xn=bn,An=wn,Dn=()=>{},En=new xn.TimeoutError;var _n=un.default=class extends Cn{constructor(n){var e,a,t,i;if(super(),this._intervalCount=0,this._intervalEnd=0,this._pendingCount=0,this._resolveEmpty=Dn,this._resolveIdle=Dn,!("number"==typeof(n=Object.assign({carryoverConcurrencyCount:!1,intervalCap:1/0,interval:0,concurrency:1/0,autoStart:!0,queueClass:An.default},n)).intervalCap&&n.intervalCap>=1))throw new TypeError(`Expected \`intervalCap\` to be a number from 1 and up, got \`${null!==(a=null===(e=n.intervalCap)||void 0===e?void 0:e.toString())&&void 0!==a?a:""}\` (${typeof n.intervalCap})`);if(void 0===n.interval||!(Number.isFinite(n.interval)&&n.interval>=0))throw new TypeError(`Expected \`interval\` to be a finite number >= 0, got \`${null!==(i=null===(t=n.interval)||void 0===t?void 0:t.toString())&&void 0!==i?i:""}\` (${typeof n.interval})`);this._carryoverConcurrencyCount=n.carryoverConcurrencyCount,this._isIntervalIgnored=n.intervalCap===1/0||0===n.interval,this._intervalCap=n.intervalCap,this._interval=n.interval,this._queue=new n.queueClass,this._queueClass=n.queueClass,this.concurrency=n.concurrency,this._timeout=n.timeout,this._throwOnTimeout=!0===n.throwOnTimeout,this._isPaused=!1===n.autoStart}get _doesIntervalAllowAnother(){return this._isIntervalIgnored||this._intervalCount<this._intervalCap}get _doesConcurrentAllowAnother(){return this._pendingCount<this._concurrency}_next(){this._pendingCount--,this._tryToStartAnother(),this.emit("next")}_resolvePromises(){this._resolveEmpty(),this._resolveEmpty=Dn,0===this._pendingCount&&(this._resolveIdle(),this._resolveIdle=Dn,this.emit("idle"))}_onResumeInterval(){this._onInterval(),this._initializeIntervalIfNeeded(),this._timeoutId=void 0}_isIntervalPaused(){const n=Date.now();if(void 0===this._intervalId){const e=this._intervalEnd-n;if(!(e<0))return void 0===this._timeoutId&&(this._timeoutId=setTimeout((()=>{this._onResumeInterval()}),e)),!0;this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0}return!1}_tryToStartAnother(){if(0===this._queue.size)return this._intervalId&&clearInterval(this._intervalId),this._intervalId=void 0,this._resolvePromises(),!1;if(!this._isPaused){const n=!this._isIntervalPaused();if(this._doesIntervalAllowAnother&&this._doesConcurrentAllowAnother){const e=this._queue.dequeue();return!!e&&(this.emit("active"),e(),n&&this._initializeIntervalIfNeeded(),!0)}}return!1}_initializeIntervalIfNeeded(){this._isIntervalIgnored||void 0!==this._intervalId||(this._intervalId=setInterval((()=>{this._onInterval()}),this._interval),this._intervalEnd=Date.now()+this._interval)}_onInterval(){0===this._intervalCount&&0===this._pendingCount&&this._intervalId&&(clearInterval(this._intervalId),this._intervalId=void 0),this._intervalCount=this._carryoverConcurrencyCount?this._pendingCount:0,this._processQueue()}_processQueue(){for(;this._tryToStartAnother(););}get concurrency(){return this._concurrency}set concurrency(n){if(!("number"==typeof n&&n>=1))throw new TypeError(`Expected \`concurrency\` to be a number from 1 and up, got \`${n}\` (${typeof n})`);this._concurrency=n,this._processQueue()}async add(n,e={}){return new Promise(((a,t)=>{this._queue.enqueue((async()=>{this._pendingCount++,this._intervalCount++;try{const i=void 0===this._timeout&&void 0===e.timeout?n():xn.default(Promise.resolve(n()),void 0===e.timeout?this._timeout:e.timeout,(()=>{(void 0===e.throwOnTimeout?this._throwOnTimeout:e.throwOnTimeout)&&t(En)}));a(await i)}catch(n){t(n)}this._next()}),e),this._tryToStartAnother(),this.emit("add")}))}async addAll(n,e){return Promise.all(n.map((async n=>this.add(n,e))))}start(){return this._isPaused?(this._isPaused=!1,this._processQueue(),this):this}pause(){this._isPaused=!0}clear(){this._queue=new this._queueClass}async onEmpty(){if(0!==this._queue.size)return new Promise((n=>{const e=this._resolveEmpty;this._resolveEmpty=()=>{e(),n()}}))}async onIdle(){if(0!==this._pendingCount||0!==this._queue.size)return new Promise((n=>{const e=this._resolveIdle;this._resolveIdle=()=>{e(),n()}}))}get size(){return this._queue.size}sizeBy(n){return this._queue.filter(n).length}get pending(){return this._pendingCount}get isPaused(){return this._isPaused}get timeout(){return this._timeout}set timeout(n){this._timeout=n}};class Tn{constructor(n){Object.defineProperty(this,"maxConcurrency",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"maxRetries",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"queue",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.maxConcurrency=n.maxConcurrency??1/0,this.maxRetries=n.maxRetries??6;const e="default"in _n?_n.default:_n;this.queue=new e({concurrency:this.maxConcurrency})}call(n,...e){return this.queue.add((()=>dn((()=>n(...e)),{numOfAttempts:this.maxRetries,jitter:"full"})),{throwOnTimeout:!0})}}const Rn=n=>n.startsWith("gpt-3.5-turbo-")?"gpt-3.5-turbo":n.startsWith("gpt-4-32k-")?"gpt-4-32k":n.startsWith("gpt-4-")?"gpt-4":n;class Pn{constructor(n){Object.defineProperty(this,"verbose",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"callbackManager",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"caller",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_encoding",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),Object.defineProperty(this,"_registry",{enumerable:!0,configurable:!0,writable:!0,value:void 0}),this.verbose=n.verbose??!!n.callbackManager,this.callbackManager=n.callbackManager??D.getInstance(),this.caller=new Tn(n??{})}async getNumTokens(n){if(!this._encoding){const{encoding_for_model:n}=await(async()=>{try{const{encoding_for_model:n}=await Promise.resolve().then((function(){return af}));return{encoding_for_model:n}}catch(n){throw console.log(n),new Error("Please install @dqbd/tiktoken as a dependency with, e.g. `yarn add @dqbd/tiktoken`")}})();this._encoding=n("modelName"in this?Rn(this.modelName):"gpt2"),this._registry=new FinalizationRegistry((n=>n.free())),this._registry.register(this,this._encoding)}return this._encoding.encode(n).length}_identifyingParams(){return{}}serialize(){return{...this._identifyingParams(),_type:this._llmType(),_model:this._modelType()}}static async deserialize(n){const{_type:e,_model:a,...t}=n;if(a&&"base_chat_model"!==a)throw new Error(`Cannot load LLM with model ${a}`);const i={openai:(await Promise.resolve().then((function(){return us}))).ChatOpenAI}[e];if(void 0===i)throw new Error(`Cannot load LLM with type ${e}`);return new i(t)}}class On extends Pn{constructor({...n}){super(n)}async generate(n,e){const a=[],t=[],i=n.map((n=>function(n,e="Human",a="AI"){const t=[];for(const i of n){let n;if("human"===i._getType())n=e;else if("ai"===i._getType())n=a;else if("system"===i._getType())n="System";else{if("generic"!==i._getType())throw new Error(`Got unsupported message type: ${i}`);n=i.role}t.push(`${n}: ${i.text}`)}return t.join("\n")}(n)));await this.callbackManager.handleLLMStart({name:this._llmType()},i,this.verbose);try{for(const i of n){const n=await this._generate(i,e);n.llmOutput&&t.push(n.llmOutput),a.push(n.generations)}}catch(n){throw await this.callbackManager.handleLLMError(n,this.verbose),n}const r={generations:a,llmOutput:t.length?this._combineLLMOutput?.(...t):void 0};return await this.callbackManager.handleLLMEnd(r,this.verbose),r}_modelType(){return"base_chat_model"}async generatePrompt(n,e){const a=n.map((n=>n.toChatMessages()));return this.generate(a,e)}async call(n,e){return(await this.generate([n],e)).generations[0][0].message}async callPrompt(n,e){const a=n.toChatMessages();return this.call(a,e)}}var Mn={},Bn={},Fn={exports:{}},Nn=function(n,e){return function(){for(var a=new Array(arguments.length),t=0;t<a.length;t++)a[t]=arguments[t];return n.apply(e,a)}},In=Nn,Ln=Object.prototype.toString;function jn(n){return Array.isArray(n)}function Hn(n){return void 0===n}function Gn(n){return"[object ArrayBuffer]"===Ln.call(n)}function zn(n){return null!==n&&"object"==typeof n}function qn(n){if("[object Object]"!==Ln.call(n))return!1;var e=Object.getPrototypeOf(n);return null===e||e===Object.prototype}function Un(n){return"[object Function]"===Ln.call(n)}function Vn(n,e){if(null!=n)if("object"!=typeof n&&(n=[n]),jn(n))for(var a=0,t=n.length;a<t;a++)e.call(null,n[a],a,n);else for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&e.call(null,n[i],i,n)}var Wn={isArray:jn,isArrayBuffer:Gn,isBuffer:function(n){return null!==n&&!Hn(n)&&null!==n.constructor&&!Hn(n.constructor)&&"function"==typeof n.constructor.isBuffer&&n.constructor.isBuffer(n)},isFormData:function(n){return"[object FormData]"===Ln.call(n)},isArrayBufferView:function(n){return"undefined"!=typeof ArrayBuffer&&ArrayBuffer.isView?ArrayBuffer.isView(n):n&&n.buffer&&Gn(n.buffer)},isString:function(n){return"string"==typeof n},isNumber:function(n){return"number"==typeof n},isObject:zn,isPlainObject:qn,isUndefined:Hn,isDate:function(n){return"[object Date]"===Ln.call(n)},isFile:function(n){return"[object File]"===Ln.call(n)},isBlob:function(n){return"[object Blob]"===Ln.call(n)},isFunction:Un,isStream:function(n){return zn(n)&&Un(n.pipe)},isURLSearchParams:function(n){return"[object URLSearchParams]"===Ln.call(n)},isStandardBrowserEnv:function(){return("undefined"==typeof navigator||"ReactNative"!==navigator.product&&"NativeScript"!==navigator.product&&"NS"!==navigator.product)&&("undefined"!=typeof window&&"undefined"!=typeof document)},forEach:Vn,merge:function n(){var e={};function a(a,t){qn(e[t])&&qn(a)?e[t]=n(e[t],a):qn(a)?e[t]=n({},a):jn(a)?e[t]=a.slice():e[t]=a}for(var t=0,i=arguments.length;t<i;t++)Vn(arguments[t],a);return e},extend:function(n,e,a){return Vn(e,(function(e,t){n[t]=a&&"function"==typeof e?In(e,a):e})),n},trim:function(n){return n.trim?n.trim():n.replace(/^\s+|\s+$/g,"")},stripBOM:function(n){return 65279===n.charCodeAt(0)&&(n=n.slice(1)),n}},Kn=Wn;function Jn(n){return encodeURIComponent(n).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+").replace(/%5B/gi,"[").replace(/%5D/gi,"]")}var $n=function(n,e,a){if(!e)return n;var t;if(a)t=a(e);else if(Kn.isURLSearchParams(e))t=e.toString();else{var i=[];Kn.forEach(e,(function(n,e){null!=n&&(Kn.isArray(n)?e+="[]":n=[n],Kn.forEach(n,(function(n){Kn.isDate(n)?n=n.toISOString():Kn.isObject(n)&&(n=JSON.stringify(n)),i.push(Jn(e)+"="+Jn(n))})))})),t=i.join("&")}if(t){var r=n.indexOf("#");-1!==r&&(n=n.slice(0,r)),n+=(-1===n.indexOf("?")?"?":"&")+t}return n},Yn=Wn;function Qn(){this.handlers=[]}Qn.prototype.use=function(n,e,a){return this.handlers.push({fulfilled:n,rejected:e,synchronous:!!a&&a.synchronous,runWhen:a?a.runWhen:null}),this.handlers.length-1},Qn.prototype.eject=function(n){this.handlers[n]&&(this.handlers[n]=null)},Qn.prototype.forEach=function(n){Yn.forEach(this.handlers,(function(e){null!==e&&n(e)}))};var Xn,Zn,ne,ee,ae,te,ie,re,se,oe,le,ce,de,pe,ue,me,he,ge,fe,ve,ye=Qn,be=Wn,we=function(n,e,a,t,i){return n.config=e,a&&(n.code=a),n.request=t,n.response=i,n.isAxiosError=!0,n.toJSON=function(){return{message:this.message,name:this.name,description:this.description,number:this.number,fileName:this.fileName,lineNumber:this.lineNumber,columnNumber:this.columnNumber,stack:this.stack,config:this.config,code:this.code,status:this.response&&this.response.status?this.response.status:null}},n},Se={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1};function ke(){if(Zn)return Xn;Zn=1;var n=we;return Xn=function(e,a,t,i,r){var s=new Error(e);return n(s,a,t,i,r)}}function Ce(){if(ee)return ne;ee=1;var n=ke();return ne=function(e,a,t){var i=t.config.validateStatus;t.status&&i&&!i(t.status)?a(n("Request failed with status code "+t.status,t.config,null,t.request,t)):e(t)}}function xe(){if(ce)return le;ce=1;var n=re?ie:(re=1,ie=function(n){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(n)}),e=oe?se:(oe=1,se=function(n,e){return e?n.replace(/\/+$/,"")+"/"+e.replace(/^\/+/,""):n});return le=function(a,t){return a&&!n(t)?e(a,t):t}}function Ae(){if(ge)return he;function n(n){this.message=n}return ge=1,n.prototype.toString=function(){return"Cancel"+(this.message?": "+this.message:"")},n.prototype.__CANCEL__=!0,he=n}function De(){if(ve)return fe;ve=1;var n=Wn,e=Ce(),a=function(){if(te)return ae;te=1;var n=Wn;return ae=n.isStandardBrowserEnv()?{write:function(e,a,t,i,r,s){var o=[];o.push(e+"="+encodeURIComponent(a)),n.isNumber(t)&&o.push("expires="+new Date(t).toGMTString()),n.isString(i)&&o.push("path="+i),n.isString(r)&&o.push("domain="+r),!0===s&&o.push("secure"),document.cookie=o.join("; ")},read:function(n){var e=document.cookie.match(new RegExp("(^|;\\s*)("+n+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove:function(n){this.write(n,"",Date.now()-864e5)}}:{write:function(){},read:function(){return null},remove:function(){}},ae}(),t=$n,i=xe(),r=function(){if(pe)return de;pe=1;var n=Wn,e=["age","authorization","content-length","content-type","etag","expires","from","host","if-modified-since","if-unmodified-since","last-modified","location","max-forwards","proxy-authorization","referer","retry-after","user-agent"];return de=function(a){var t,i,r,s={};return a?(n.forEach(a.split("\n"),(function(a){if(r=a.indexOf(":"),t=n.trim(a.substr(0,r)).toLowerCase(),i=n.trim(a.substr(r+1)),t){if(s[t]&&e.indexOf(t)>=0)return;s[t]="set-cookie"===t?(s[t]?s[t]:[]).concat([i]):s[t]?s[t]+", "+i:i}})),s):s},de}(),s=function(){if(me)return ue;me=1;var n=Wn;return ue=n.isStandardBrowserEnv()?function(){var e,a=/(msie|trident)/i.test(navigator.userAgent),t=document.createElement("a");function i(n){var e=n;return a&&(t.setAttribute("href",e),e=t.href),t.setAttribute("href",e),{href:t.href,protocol:t.protocol?t.protocol.replace(/:$/,""):"",host:t.host,search:t.search?t.search.replace(/^\?/,""):"",hash:t.hash?t.hash.replace(/^#/,""):"",hostname:t.hostname,port:t.port,pathname:"/"===t.pathname.charAt(0)?t.pathname:"/"+t.pathname}}return e=i(window.location.href),function(a){var t=n.isString(a)?i(a):a;return t.protocol===e.protocol&&t.host===e.host}}():function(){return!0}}(),o=ke(),l=Se,c=Ae();return fe=function(d){return new Promise((function(p,u){var m,h=d.data,g=d.headers,f=d.responseType;function v(){d.cancelToken&&d.cancelToken.unsubscribe(m),d.signal&&d.signal.removeEventListener("abort",m)}n.isFormData(h)&&delete g["Content-Type"];var y=new XMLHttpRequest;if(d.auth){var b=d.auth.username||"",w=d.auth.password?unescape(encodeURIComponent(d.auth.password)):"";g.Authorization="Basic "+btoa(b+":"+w)}var S=i(d.baseURL,d.url);function k(){if(y){var n="getAllResponseHeaders"in y?r(y.getAllResponseHeaders()):null,a={data:f&&"text"!==f&&"json"!==f?y.response:y.responseText,status:y.status,statusText:y.statusText,headers:n,config:d,request:y};e((function(n){p(n),v()}),(function(n){u(n),v()}),a),y=null}}if(y.open(d.method.toUpperCase(),t(S,d.params,d.paramsSerializer),!0),y.timeout=d.timeout,"onloadend"in y?y.onloadend=k:y.onreadystatechange=function(){y&&4===y.readyState&&(0!==y.status||y.responseURL&&0===y.responseURL.indexOf("file:"))&&setTimeout(k)},y.onabort=function(){y&&(u(o("Request aborted",d,"ECONNABORTED",y)),y=null)},y.onerror=function(){u(o("Network Error",d,null,y)),y=null},y.ontimeout=function(){var n=d.timeout?"timeout of "+d.timeout+"ms exceeded":"timeout exceeded",e=d.transitional||l;d.timeoutErrorMessage&&(n=d.timeoutErrorMessage),u(o(n,d,e.clarifyTimeoutError?"ETIMEDOUT":"ECONNABORTED",y)),y=null},n.isStandardBrowserEnv()){var C=(d.withCredentials||s(S))&&d.xsrfCookieName?a.read(d.xsrfCookieName):void 0;C&&(g[d.xsrfHeaderName]=C)}"setRequestHeader"in y&&n.forEach(g,(function(n,e){void 0===h&&"content-type"===e.toLowerCase()?delete g[e]:y.setRequestHeader(e,n)})),n.isUndefined(d.withCredentials)||(y.withCredentials=!!d.withCredentials),f&&"json"!==f&&(y.responseType=d.responseType),"function"==typeof d.onDownloadProgress&&y.addEventListener("progress",d.onDownloadProgress),"function"==typeof d.onUploadProgress&&y.upload&&y.upload.addEventListener("progress",d.onUploadProgress),(d.cancelToken||d.signal)&&(m=function(n){y&&(u(!n||n&&n.type?new c("canceled"):n),y.abort(),y=null)},d.cancelToken&&d.cancelToken.subscribe(m),d.signal&&(d.signal.aborted?m():d.signal.addEventListener("abort",m))),h||(h=null),y.send(h)}))},fe}var Ee,_e,Te,Re,Pe,Oe={exports:{}},Me={exports:{}},Be={exports:{}};function Fe(){if(_e)return Ee;_e=1;var n=1e3,e=60*n,a=60*e,t=24*a,i=7*t,r=365.25*t;function s(n,e,a,t){var i=e>=1.5*a;return Math.round(n/a)+" "+t+(i?"s":"")}return Ee=function(o,l){l=l||{};var c=typeof o;if("string"===c&&o.length>0)return function(s){if((s=String(s)).length>100)return;var o=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(s);if(!o)return;var l=parseFloat(o[1]);switch((o[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return l*r;case"weeks":case"week":case"w":return l*i;case"days":case"day":case"d":return l*t;case"hours":case"hour":case"hrs":case"hr":case"h":return l*a;case"minutes":case"minute":case"mins":case"min":case"m":return l*e;case"seconds":case"second":case"secs":case"sec":case"s":return l*n;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return l;default:return}}(o);if("number"===c&&isFinite(o))return l.long?function(i){var r=Math.abs(i);if(r>=t)return s(i,r,t,"day");if(r>=a)return s(i,r,a,"hour");if(r>=e)return s(i,r,e,"minute");if(r>=n)return s(i,r,n,"second");return i+" ms"}(o):function(i){var r=Math.abs(i);if(r>=t)return Math.round(i/t)+"d";if(r>=a)return Math.round(i/a)+"h";if(r>=e)return Math.round(i/e)+"m";if(r>=n)return Math.round(i/n)+"s";return i+"ms"}(o);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(o))},Ee}function Ne(){if(Re)return Te;return Re=1,Te=function(n){function e(n){let t,i,r,s=null;function o(...n){if(!o.enabled)return;const a=o,i=Number(new Date),r=i-(t||i);a.diff=r,a.prev=t,a.curr=i,t=i,n[0]=e.coerce(n[0]),"string"!=typeof n[0]&&n.unshift("%O");let s=0;n[0]=n[0].replace(/%([a-zA-Z%])/g,((t,i)=>{if("%%"===t)return"%";s++;const r=e.formatters[i];if("function"==typeof r){const e=n[s];t=r.call(a,e),n.splice(s,1),s--}return t})),e.formatArgs.call(a,n);(a.log||e.log).apply(a,n)}return o.namespace=n,o.useColors=e.useColors(),o.color=e.selectColor(n),o.extend=a,o.destroy=e.destroy,Object.defineProperty(o,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(i!==e.namespaces&&(i=e.namespaces,r=e.enabled(n)),r),set:n=>{s=n}}),"function"==typeof e.init&&e.init(o),o}function a(n,a){const t=e(this.namespace+(void 0===a?":":a)+n);return t.log=this.log,t}function t(n){return n.toString().substring(2,n.toString().length-2).replace(/\.\*\?$/,"*")}return e.debug=e,e.default=e,e.coerce=function(n){if(n instanceof Error)return n.stack||n.message;return n},e.disable=function(){const n=[...e.names.map(t),...e.skips.map(t).map((n=>"-"+n))].join(",");return e.enable(""),n},e.enable=function(n){let a;e.save(n),e.namespaces=n,e.names=[],e.skips=[];const t=("string"==typeof n?n:"").split(/[\s,]+/),i=t.length;for(a=0;a<i;a++)t[a]&&("-"===(n=t[a].replace(/\*/g,".*?"))[0]?e.skips.push(new RegExp("^"+n.slice(1)+"$")):e.names.push(new RegExp("^"+n+"$")))},e.enabled=function(n){if("*"===n[n.length-1])return!0;let a,t;for(a=0,t=e.skips.length;a<t;a++)if(e.skips[a].test(n))return!1;for(a=0,t=e.names.length;a<t;a++)if(e.names[a].test(n))return!0;return!1},e.humanize=Fe(),e.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(n).forEach((a=>{e[a]=n[a]})),e.names=[],e.skips=[],e.formatters={},e.selectColor=function(n){let a=0;for(let e=0;e<n.length;e++)a=(a<<5)-a+n.charCodeAt(e),a|=0;return e.colors[Math.abs(a)%e.colors.length]},e.enable(e.load()),e},Te}var Ie,Le,je,He,Ge,ze,qe,Ue,Ve,We,Ke,Je,$e,Ye={exports:{}};function Qe(){return Le?Ie:(Le=1,Ie=(n,e=process.argv)=>{const a=n.startsWith("-")?"":1===n.length?"-":"--",t=e.indexOf(a+n),i=e.indexOf("--");return-1!==t&&(-1===i||t<i)})}function Xe(){return Ge||(Ge=1,function(n,e){const a=r,t=s;e.init=function(n){n.inspectOpts={};const a=Object.keys(e.inspectOpts);for(let t=0;t<a.length;t++)n.inspectOpts[a[t]]=e.inspectOpts[a[t]]},e.log=function(...n){return process.stderr.write(t.format(...n)+"\n")},e.formatArgs=function(a){const{namespace:t,useColors:i}=this;if(i){const e=this.color,i="[3"+(e<8?e:"8;5;"+e),r=` ${i};1m${t} `;a[0]=r+a[0].split("\n").join("\n"+r),a.push(i+"m+"+n.exports.humanize(this.diff)+"")}else a[0]=function(){if(e.inspectOpts.hideDate)return"";return(new Date).toISOString()+" "}()+t+" "+a[0]},e.save=function(n){n?process.env.DEBUG=n:delete process.env.DEBUG},e.load=function(){return process.env.DEBUG},e.useColors=function(){return"colors"in e.inspectOpts?Boolean(e.inspectOpts.colors):a.isatty(process.stderr.fd)},e.destroy=t.deprecate((()=>{}),"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),e.colors=[6,2,3,4,5,1];try{const n=function(){if(He)return je;He=1;const n=o,e=r,a=Qe(),{env:t}=process;let i;function s(n){return 0!==n&&{level:n,hasBasic:!0,has256:n>=2,has16m:n>=3}}function l(e,r){if(0===i)return 0;if(a("color=16m")||a("color=full")||a("color=truecolor"))return 3;if(a("color=256"))return 2;if(e&&!r&&void 0===i)return 0;const s=i||0;if("dumb"===t.TERM)return s;if("win32"===process.platform){const e=n.release().split(".");return Number(e[0])>=10&&Number(e[2])>=10586?Number(e[2])>=14931?3:2:1}if("CI"in t)return["TRAVIS","CIRCLECI","APPVEYOR","GITLAB_CI","GITHUB_ACTIONS","BUILDKITE"].some((n=>n in t))||"codeship"===t.CI_NAME?1:s;if("TEAMCITY_VERSION"in t)return/^(9\.(0*[1-9]\d*)\.|\d{2,}\.)/.test(t.TEAMCITY_VERSION)?1:0;if("truecolor"===t.COLORTERM)return 3;if("TERM_PROGRAM"in t){const n=parseInt((t.TERM_PROGRAM_VERSION||"").split(".")[0],10);switch(t.TERM_PROGRAM){case"iTerm.app":return n>=3?3:2;case"Apple_Terminal":return 2}}return/-256(color)?$/i.test(t.TERM)?2:/^screen|^xterm|^vt100|^vt220|^rxvt|color|ansi|cygwin|linux/i.test(t.TERM)||"COLORTERM"in t?1:s}return a("no-color")||a("no-colors")||a("color=false")||a("color=never")?i=0:(a("color")||a("colors")||a("color=true")||a("color=always"))&&(i=1),"FORCE_COLOR"in t&&(i="true"===t.FORCE_COLOR?1:"false"===t.FORCE_COLOR?0:0===t.FORCE_COLOR.length?1:Math.min(parseInt(t.FORCE_COLOR,10),3)),je={supportsColor:function(n){return s(l(n,n&&n.isTTY))},stdout:s(l(!0,e.isatty(1))),stderr:s(l(!0,e.isatty(2)))}}();n&&(n.stderr||n).level>=2&&(e.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(n){}e.inspectOpts=Object.keys(process.env).filter((n=>/^debug_/i.test(n))).reduce(((n,e)=>{const a=e.substring(6).toLowerCase().replace(/_([a-z])/g,((n,e)=>e.toUpperCase()));let t=process.env[e];return t=!!/^(yes|on|true|enabled)$/i.test(t)||!/^(no|off|false|disabled)$/i.test(t)&&("null"===t?null:Number(t)),n[a]=t,n}),{}),n.exports=Ne()(e);const{formatters:i}=n.exports;i.o=function(n){return this.inspectOpts.colors=this.useColors,t.inspect(n,this.inspectOpts).split("\n").map((n=>n.trim())).join(" ")},i.O=function(n){return this.inspectOpts.colors=this.useColors,t.inspect(n,this.inspectOpts)}}(Ye,Ye.exports)),Ye.exports}function Ze(){return ze||(ze=1,"undefined"==typeof process||"renderer"===process.type||!0===process.browser||process.__nwjs?Me.exports=(Pe||(Pe=1,function(n,e){e.formatArgs=function(e){if(e[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+e[0]+(this.useColors?"%c ":" ")+"+"+n.exports.humanize(this.diff),!this.useColors)return;const a="color: "+this.color;e.splice(1,0,a,"color: inherit");let t=0,i=0;e[0].replace(/%[a-zA-Z%]/g,(n=>{"%%"!==n&&(t++,"%c"===n&&(i=t))})),e.splice(i,0,a)},e.save=function(n){try{n?e.storage.setItem("debug",n):e.storage.removeItem("debug")}catch(n){}},e.load=function(){let n;try{n=e.storage.getItem("debug")}catch(n){}return!n&&"undefined"!=typeof process&&"env"in process&&(n=process.env.DEBUG),n},e.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},e.storage=function(){try{return localStorage}catch(n){}}(),e.destroy=(()=>{let n=!1;return()=>{n||(n=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),e.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],e.log=console.debug||console.log||(()=>{}),n.exports=Ne()(e);const{formatters:a}=n.exports;a.j=function(n){try{return JSON.stringify(n)}catch(n){return"[UnexpectedJSONParseError]: "+n.message}}}(Be,Be.exports)),Be.exports):Me.exports=Xe()),Me.exports}function na(){if(Ve)return Oe.exports;Ve=1;var r=a,s=r.URL,o=n,l=e,c=t.Writable,d=i,p=function(){return Ue||(Ue=1,qe=function(){if(!n){try{n=Ze()("follow-redirects")}catch(n){}"function"!=typeof n&&(n=function(){})}n.apply(null,arguments)}),qe;var n}(),u=["abort","aborted","connect","error","socket","timeout"],m=Object.create(null);u.forEach((function(n){m[n]=function(e,a,t){this._redirectable.emit(n,e,a